1bcbd26bfSFlorian Hahn //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2bcbd26bfSFlorian Hahn //
3bcbd26bfSFlorian Hahn // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4bcbd26bfSFlorian Hahn // See https://llvm.org/LICENSE.txt for license information.
5bcbd26bfSFlorian Hahn // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bcbd26bfSFlorian Hahn //
7bcbd26bfSFlorian Hahn //===----------------------------------------------------------------------===//
8bcbd26bfSFlorian Hahn //
9bcbd26bfSFlorian Hahn // This file contains the implementation of the scalar evolution expander,
10bcbd26bfSFlorian Hahn // which is used to generate the code corresponding to a given scalar evolution
11bcbd26bfSFlorian Hahn // expression.
12bcbd26bfSFlorian Hahn //
13bcbd26bfSFlorian Hahn //===----------------------------------------------------------------------===//
14bcbd26bfSFlorian Hahn 
15bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
16bcbd26bfSFlorian Hahn #include "llvm/ADT/STLExtras.h"
17bcbd26bfSFlorian Hahn #include "llvm/ADT/SmallSet.h"
18bcbd26bfSFlorian Hahn #include "llvm/Analysis/InstructionSimplify.h"
19bcbd26bfSFlorian Hahn #include "llvm/Analysis/LoopInfo.h"
20bcbd26bfSFlorian Hahn #include "llvm/Analysis/TargetTransformInfo.h"
218906a0feSPhilip Reames #include "llvm/Analysis/ValueTracking.h"
22bcbd26bfSFlorian Hahn #include "llvm/IR/DataLayout.h"
23bcbd26bfSFlorian Hahn #include "llvm/IR/Dominators.h"
24bcbd26bfSFlorian Hahn #include "llvm/IR/IntrinsicInst.h"
25bcbd26bfSFlorian Hahn #include "llvm/IR/PatternMatch.h"
26bcbd26bfSFlorian Hahn #include "llvm/Support/CommandLine.h"
27bcbd26bfSFlorian Hahn #include "llvm/Support/raw_ostream.h"
28f75564adSFlorian Hahn #include "llvm/Transforms/Utils/LoopUtils.h"
29bcbd26bfSFlorian Hahn 
301540da3bSNeil Henning #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
311540da3bSNeil Henning #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
321540da3bSNeil Henning #else
331540da3bSNeil Henning #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
341540da3bSNeil Henning #endif
351540da3bSNeil Henning 
36bcbd26bfSFlorian Hahn using namespace llvm;
37bcbd26bfSFlorian Hahn 
38bcbd26bfSFlorian Hahn cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
39bcbd26bfSFlorian Hahn     "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
40bcbd26bfSFlorian Hahn     cl::desc("When performing SCEV expansion only if it is cheap to do, this "
41bcbd26bfSFlorian Hahn              "controls the budget that is considered cheap (default = 4)"));
42bcbd26bfSFlorian Hahn 
43bcbd26bfSFlorian Hahn using namespace PatternMatch;
44bcbd26bfSFlorian Hahn 
45bcbd26bfSFlorian Hahn /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
46c70f0b9dSFlorian Hahn /// reusing an existing cast if a suitable one (= dominating IP) exists, or
47bcbd26bfSFlorian Hahn /// creating a new one.
ReuseOrCreateCast(Value * V,Type * Ty,Instruction::CastOps Op,BasicBlock::iterator IP)48bcbd26bfSFlorian Hahn Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
49bcbd26bfSFlorian Hahn                                        Instruction::CastOps Op,
50bcbd26bfSFlorian Hahn                                        BasicBlock::iterator IP) {
51bcbd26bfSFlorian Hahn   // This function must be called with the builder having a valid insertion
52bcbd26bfSFlorian Hahn   // point. It doesn't need to be the actual IP where the uses of the returned
53bcbd26bfSFlorian Hahn   // cast will be added, but it must dominate such IP.
54bcbd26bfSFlorian Hahn   // We use this precondition to produce a cast that will dominate all its
55bcbd26bfSFlorian Hahn   // uses. In particular, this is crucial for the case where the builder's
56bcbd26bfSFlorian Hahn   // insertion point *is* the point where we were asked to put the cast.
57bcbd26bfSFlorian Hahn   // Since we don't know the builder's insertion point is actually
58bcbd26bfSFlorian Hahn   // where the uses will be added (only that it dominates it), we are
59bcbd26bfSFlorian Hahn   // not allowed to move it.
60bcbd26bfSFlorian Hahn   BasicBlock::iterator BIP = Builder.GetInsertPoint();
61bcbd26bfSFlorian Hahn 
62d746fefbSRoman Lebedev   Value *Ret = nullptr;
63bcbd26bfSFlorian Hahn 
64bcbd26bfSFlorian Hahn   // Check to see if there is already a cast!
65c70f0b9dSFlorian Hahn   for (User *U : V->users()) {
66c70f0b9dSFlorian Hahn     if (U->getType() != Ty)
67c70f0b9dSFlorian Hahn       continue;
68c70f0b9dSFlorian Hahn     CastInst *CI = dyn_cast<CastInst>(U);
69c70f0b9dSFlorian Hahn     if (!CI || CI->getOpcode() != Op)
70c70f0b9dSFlorian Hahn       continue;
71c70f0b9dSFlorian Hahn 
7223817cbdSFlorian Hahn     // Found a suitable cast that is at IP or comes before IP. Use it. Note that
7323817cbdSFlorian Hahn     // the cast must also properly dominate the Builder's insertion point.
7423817cbdSFlorian Hahn     if (IP->getParent() == CI->getParent() && &*BIP != CI &&
75c70f0b9dSFlorian Hahn         (&*IP == CI || CI->comesBefore(&*IP))) {
76bcbd26bfSFlorian Hahn       Ret = CI;
77bcbd26bfSFlorian Hahn       break;
78bcbd26bfSFlorian Hahn     }
79c70f0b9dSFlorian Hahn   }
80bcbd26bfSFlorian Hahn 
81bcbd26bfSFlorian Hahn   // Create a new cast.
82c70f0b9dSFlorian Hahn   if (!Ret) {
83d746fefbSRoman Lebedev     SCEVInsertPointGuard Guard(Builder, this);
84d746fefbSRoman Lebedev     Builder.SetInsertPoint(&*IP);
85d746fefbSRoman Lebedev     Ret = Builder.CreateCast(Op, V, Ty, V->getName());
86c70f0b9dSFlorian Hahn   }
87bcbd26bfSFlorian Hahn 
88bcbd26bfSFlorian Hahn   // We assert at the end of the function since IP might point to an
89bcbd26bfSFlorian Hahn   // instruction with different dominance properties than a cast
90bcbd26bfSFlorian Hahn   // (an invoke for example) and not dominate BIP (but the cast does).
91d746fefbSRoman Lebedev   assert(!isa<Instruction>(Ret) ||
92d746fefbSRoman Lebedev          SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
93bcbd26bfSFlorian Hahn 
94bcbd26bfSFlorian Hahn   return Ret;
95bcbd26bfSFlorian Hahn }
96bcbd26bfSFlorian Hahn 
97c70f0b9dSFlorian Hahn BasicBlock::iterator
findInsertPointAfter(Instruction * I,Instruction * MustDominate) const98b8a37058SRoman Lebedev SCEVExpander::findInsertPointAfter(Instruction *I,
99b8a37058SRoman Lebedev                                    Instruction *MustDominate) const {
100bcbd26bfSFlorian Hahn   BasicBlock::iterator IP = ++I->getIterator();
101bcbd26bfSFlorian Hahn   if (auto *II = dyn_cast<InvokeInst>(I))
102bcbd26bfSFlorian Hahn     IP = II->getNormalDest()->begin();
103bcbd26bfSFlorian Hahn 
104bcbd26bfSFlorian Hahn   while (isa<PHINode>(IP))
105bcbd26bfSFlorian Hahn     ++IP;
106bcbd26bfSFlorian Hahn 
107bcbd26bfSFlorian Hahn   if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
108bcbd26bfSFlorian Hahn     ++IP;
109bcbd26bfSFlorian Hahn   } else if (isa<CatchSwitchInst>(IP)) {
110c70f0b9dSFlorian Hahn     IP = MustDominate->getParent()->getFirstInsertionPt();
111bcbd26bfSFlorian Hahn   } else {
112bcbd26bfSFlorian Hahn     assert(!IP->isEHPad() && "unexpected eh pad!");
113bcbd26bfSFlorian Hahn   }
114bcbd26bfSFlorian Hahn 
115c70f0b9dSFlorian Hahn   // Adjust insert point to be after instructions inserted by the expander, so
116c70f0b9dSFlorian Hahn   // we can re-use already inserted instructions. Avoid skipping past the
117c70f0b9dSFlorian Hahn   // original \p MustDominate, in case it is an inserted instruction.
118c70f0b9dSFlorian Hahn   while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
119c70f0b9dSFlorian Hahn     ++IP;
120c70f0b9dSFlorian Hahn 
121bcbd26bfSFlorian Hahn   return IP;
122bcbd26bfSFlorian Hahn }
123bcbd26bfSFlorian Hahn 
124b8a37058SRoman Lebedev BasicBlock::iterator
GetOptimalInsertionPointForCastOf(Value * V) const125b8a37058SRoman Lebedev SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
126b8a37058SRoman Lebedev   // Cast the argument at the beginning of the entry block, after
127b8a37058SRoman Lebedev   // any bitcasts of other arguments.
128b8a37058SRoman Lebedev   if (Argument *A = dyn_cast<Argument>(V)) {
129b8a37058SRoman Lebedev     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
130b8a37058SRoman Lebedev     while ((isa<BitCastInst>(IP) &&
131b8a37058SRoman Lebedev             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
132b8a37058SRoman Lebedev             cast<BitCastInst>(IP)->getOperand(0) != A) ||
133b8a37058SRoman Lebedev            isa<DbgInfoIntrinsic>(IP))
134b8a37058SRoman Lebedev       ++IP;
135b8a37058SRoman Lebedev     return IP;
136b8a37058SRoman Lebedev   }
137b8a37058SRoman Lebedev 
138b8a37058SRoman Lebedev   // Cast the instruction immediately after the instruction.
139442c408eSRoman Lebedev   if (Instruction *I = dyn_cast<Instruction>(V))
140b8a37058SRoman Lebedev     return findInsertPointAfter(I, &*Builder.GetInsertPoint());
141442c408eSRoman Lebedev 
142442c408eSRoman Lebedev   // Otherwise, this must be some kind of a constant,
143442c408eSRoman Lebedev   // so let's plop this cast into the function's entry block.
144442c408eSRoman Lebedev   assert(isa<Constant>(V) &&
145442c408eSRoman Lebedev          "Expected the cast argument to be a global/constant");
146442c408eSRoman Lebedev   return Builder.GetInsertBlock()
147442c408eSRoman Lebedev       ->getParent()
148442c408eSRoman Lebedev       ->getEntryBlock()
149442c408eSRoman Lebedev       .getFirstInsertionPt();
150b8a37058SRoman Lebedev }
151b8a37058SRoman Lebedev 
152bcbd26bfSFlorian Hahn /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
153bcbd26bfSFlorian Hahn /// which must be possible with a noop cast, doing what we can to share
154bcbd26bfSFlorian Hahn /// the casts.
InsertNoopCastOfTo(Value * V,Type * Ty)155bcbd26bfSFlorian Hahn Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
156bcbd26bfSFlorian Hahn   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
157bcbd26bfSFlorian Hahn   assert((Op == Instruction::BitCast ||
158bcbd26bfSFlorian Hahn           Op == Instruction::PtrToInt ||
159bcbd26bfSFlorian Hahn           Op == Instruction::IntToPtr) &&
160bcbd26bfSFlorian Hahn          "InsertNoopCastOfTo cannot perform non-noop casts!");
161bcbd26bfSFlorian Hahn   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
162bcbd26bfSFlorian Hahn          "InsertNoopCastOfTo cannot change sizes!");
163bcbd26bfSFlorian Hahn 
1641d8f2e52SFlorian Hahn   // inttoptr only works for integral pointers. For non-integral pointers, we
1651d8f2e52SFlorian Hahn   // can create a GEP on i8* null  with the integral value as index. Note that
1661d8f2e52SFlorian Hahn   // it is safe to use GEP of null instead of inttoptr here, because only
1671d8f2e52SFlorian Hahn   // expressions already based on a GEP of null should be converted to pointers
1681d8f2e52SFlorian Hahn   // during expansion.
169b7c91a9bSSimon Pilgrim   if (Op == Instruction::IntToPtr) {
170b7c91a9bSSimon Pilgrim     auto *PtrTy = cast<PointerType>(Ty);
171b7c91a9bSSimon Pilgrim     if (DL.isNonIntegralPointerType(PtrTy)) {
1721d8f2e52SFlorian Hahn       auto *Int8PtrTy = Builder.getInt8PtrTy(PtrTy->getAddressSpace());
173bec4e865SNikita Popov       assert(DL.getTypeAllocSize(Builder.getInt8Ty()) == 1 &&
1741d8f2e52SFlorian Hahn              "alloc size of i8 must by 1 byte for the GEP to be correct");
1751d8f2e52SFlorian Hahn       auto *GEP = Builder.CreateGEP(
1761d8f2e52SFlorian Hahn           Builder.getInt8Ty(), Constant::getNullValue(Int8PtrTy), V, "uglygep");
1771d8f2e52SFlorian Hahn       return Builder.CreateBitCast(GEP, Ty);
1781d8f2e52SFlorian Hahn     }
179b7c91a9bSSimon Pilgrim   }
180bcbd26bfSFlorian Hahn   // Short-circuit unnecessary bitcasts.
181bcbd26bfSFlorian Hahn   if (Op == Instruction::BitCast) {
182bcbd26bfSFlorian Hahn     if (V->getType() == Ty)
183bcbd26bfSFlorian Hahn       return V;
184bcbd26bfSFlorian Hahn     if (CastInst *CI = dyn_cast<CastInst>(V)) {
185bcbd26bfSFlorian Hahn       if (CI->getOperand(0)->getType() == Ty)
186bcbd26bfSFlorian Hahn         return CI->getOperand(0);
187bcbd26bfSFlorian Hahn     }
188bcbd26bfSFlorian Hahn   }
189bcbd26bfSFlorian Hahn   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
190bcbd26bfSFlorian Hahn   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
191bcbd26bfSFlorian Hahn       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
192bcbd26bfSFlorian Hahn     if (CastInst *CI = dyn_cast<CastInst>(V))
193bcbd26bfSFlorian Hahn       if ((CI->getOpcode() == Instruction::PtrToInt ||
194bcbd26bfSFlorian Hahn            CI->getOpcode() == Instruction::IntToPtr) &&
195bcbd26bfSFlorian Hahn           SE.getTypeSizeInBits(CI->getType()) ==
196bcbd26bfSFlorian Hahn           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
197bcbd26bfSFlorian Hahn         return CI->getOperand(0);
198bcbd26bfSFlorian Hahn     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
199bcbd26bfSFlorian Hahn       if ((CE->getOpcode() == Instruction::PtrToInt ||
200bcbd26bfSFlorian Hahn            CE->getOpcode() == Instruction::IntToPtr) &&
201bcbd26bfSFlorian Hahn           SE.getTypeSizeInBits(CE->getType()) ==
202bcbd26bfSFlorian Hahn           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
203bcbd26bfSFlorian Hahn         return CE->getOperand(0);
204bcbd26bfSFlorian Hahn   }
205bcbd26bfSFlorian Hahn 
206bcbd26bfSFlorian Hahn   // Fold a cast of a constant.
207bcbd26bfSFlorian Hahn   if (Constant *C = dyn_cast<Constant>(V))
208bcbd26bfSFlorian Hahn     return ConstantExpr::getCast(Op, C, Ty);
209bcbd26bfSFlorian Hahn 
210b8a37058SRoman Lebedev   // Try to reuse existing cast, or insert one.
211b8a37058SRoman Lebedev   return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
212bcbd26bfSFlorian Hahn }
213bcbd26bfSFlorian Hahn 
214bcbd26bfSFlorian Hahn /// InsertBinop - Insert the specified binary operator, doing a small amount
215bcbd26bfSFlorian Hahn /// of work to avoid inserting an obviously redundant operation, and hoisting
216bcbd26bfSFlorian Hahn /// to an outer loop when the opportunity is there and it is safe.
InsertBinop(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS,SCEV::NoWrapFlags Flags,bool IsSafeToHoist)217bcbd26bfSFlorian Hahn Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
218bcbd26bfSFlorian Hahn                                  Value *LHS, Value *RHS,
219bcbd26bfSFlorian Hahn                                  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
220bcbd26bfSFlorian Hahn   // Fold a binop with constant operands.
221bcbd26bfSFlorian Hahn   if (Constant *CLHS = dyn_cast<Constant>(LHS))
222bcbd26bfSFlorian Hahn     if (Constant *CRHS = dyn_cast<Constant>(RHS))
22332a76fc2SNikita Popov       if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
22432a76fc2SNikita Popov         return Res;
225bcbd26bfSFlorian Hahn 
226bcbd26bfSFlorian Hahn   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
227bcbd26bfSFlorian Hahn   unsigned ScanLimit = 6;
228bcbd26bfSFlorian Hahn   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
229bcbd26bfSFlorian Hahn   // Scanning starts from the last instruction before the insertion point.
230bcbd26bfSFlorian Hahn   BasicBlock::iterator IP = Builder.GetInsertPoint();
231bcbd26bfSFlorian Hahn   if (IP != BlockBegin) {
232bcbd26bfSFlorian Hahn     --IP;
233bcbd26bfSFlorian Hahn     for (; ScanLimit; --IP, --ScanLimit) {
234bcbd26bfSFlorian Hahn       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
235bcbd26bfSFlorian Hahn       // generated code.
236bcbd26bfSFlorian Hahn       if (isa<DbgInfoIntrinsic>(IP))
237bcbd26bfSFlorian Hahn         ScanLimit++;
238bcbd26bfSFlorian Hahn 
239bcbd26bfSFlorian Hahn       auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
240bcbd26bfSFlorian Hahn         // Ensure that no-wrap flags match.
241bcbd26bfSFlorian Hahn         if (isa<OverflowingBinaryOperator>(I)) {
242bcbd26bfSFlorian Hahn           if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
243bcbd26bfSFlorian Hahn             return true;
244bcbd26bfSFlorian Hahn           if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
245bcbd26bfSFlorian Hahn             return true;
246bcbd26bfSFlorian Hahn         }
247bcbd26bfSFlorian Hahn         // Conservatively, do not use any instruction which has any of exact
248bcbd26bfSFlorian Hahn         // flags installed.
249bcbd26bfSFlorian Hahn         if (isa<PossiblyExactOperator>(I) && I->isExact())
250bcbd26bfSFlorian Hahn           return true;
251bcbd26bfSFlorian Hahn         return false;
252bcbd26bfSFlorian Hahn       };
253bcbd26bfSFlorian Hahn       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
254bcbd26bfSFlorian Hahn           IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
255bcbd26bfSFlorian Hahn         return &*IP;
256bcbd26bfSFlorian Hahn       if (IP == BlockBegin) break;
257bcbd26bfSFlorian Hahn     }
258bcbd26bfSFlorian Hahn   }
259bcbd26bfSFlorian Hahn 
260bcbd26bfSFlorian Hahn   // Save the original insertion point so we can restore it when we're done.
261bcbd26bfSFlorian Hahn   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
262bcbd26bfSFlorian Hahn   SCEVInsertPointGuard Guard(Builder, this);
263bcbd26bfSFlorian Hahn 
264bcbd26bfSFlorian Hahn   if (IsSafeToHoist) {
265bcbd26bfSFlorian Hahn     // Move the insertion point out of as many loops as we can.
266bcbd26bfSFlorian Hahn     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
267bcbd26bfSFlorian Hahn       if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
268bcbd26bfSFlorian Hahn       BasicBlock *Preheader = L->getLoopPreheader();
269bcbd26bfSFlorian Hahn       if (!Preheader) break;
270bcbd26bfSFlorian Hahn 
271bcbd26bfSFlorian Hahn       // Ok, move up a level.
272bcbd26bfSFlorian Hahn       Builder.SetInsertPoint(Preheader->getTerminator());
273bcbd26bfSFlorian Hahn     }
274bcbd26bfSFlorian Hahn   }
275bcbd26bfSFlorian Hahn 
276bcbd26bfSFlorian Hahn   // If we haven't found this binop, insert it.
277f34dcf27SNikita Popov   // TODO: Use the Builder, which will make CreateBinOp below fold with
278f34dcf27SNikita Popov   // InstSimplifyFolder.
279f34dcf27SNikita Popov   Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS));
280bcbd26bfSFlorian Hahn   BO->setDebugLoc(Loc);
281bcbd26bfSFlorian Hahn   if (Flags & SCEV::FlagNUW)
282bcbd26bfSFlorian Hahn     BO->setHasNoUnsignedWrap();
283bcbd26bfSFlorian Hahn   if (Flags & SCEV::FlagNSW)
284bcbd26bfSFlorian Hahn     BO->setHasNoSignedWrap();
285bcbd26bfSFlorian Hahn 
286bcbd26bfSFlorian Hahn   return BO;
287bcbd26bfSFlorian Hahn }
288bcbd26bfSFlorian Hahn 
289bcbd26bfSFlorian Hahn /// FactorOutConstant - Test if S is divisible by Factor, using signed
290bcbd26bfSFlorian Hahn /// division. If so, update S with Factor divided out and return true.
291bcbd26bfSFlorian Hahn /// S need not be evenly divisible if a reasonable remainder can be
292bcbd26bfSFlorian Hahn /// computed.
FactorOutConstant(const SCEV * & S,const SCEV * & Remainder,const SCEV * Factor,ScalarEvolution & SE,const DataLayout & DL)293bcbd26bfSFlorian Hahn static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
294bcbd26bfSFlorian Hahn                               const SCEV *Factor, ScalarEvolution &SE,
295bcbd26bfSFlorian Hahn                               const DataLayout &DL) {
296bcbd26bfSFlorian Hahn   // Everything is divisible by one.
297bcbd26bfSFlorian Hahn   if (Factor->isOne())
298bcbd26bfSFlorian Hahn     return true;
299bcbd26bfSFlorian Hahn 
300bcbd26bfSFlorian Hahn   // x/x == 1.
301bcbd26bfSFlorian Hahn   if (S == Factor) {
302bcbd26bfSFlorian Hahn     S = SE.getConstant(S->getType(), 1);
303bcbd26bfSFlorian Hahn     return true;
304bcbd26bfSFlorian Hahn   }
305bcbd26bfSFlorian Hahn 
306bcbd26bfSFlorian Hahn   // For a Constant, check for a multiple of the given factor.
307bcbd26bfSFlorian Hahn   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
308bcbd26bfSFlorian Hahn     // 0/x == 0.
309bcbd26bfSFlorian Hahn     if (C->isZero())
310bcbd26bfSFlorian Hahn       return true;
311bcbd26bfSFlorian Hahn     // Check for divisibility.
312bcbd26bfSFlorian Hahn     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
313bcbd26bfSFlorian Hahn       ConstantInt *CI =
314bcbd26bfSFlorian Hahn           ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
315bcbd26bfSFlorian Hahn       // If the quotient is zero and the remainder is non-zero, reject
316bcbd26bfSFlorian Hahn       // the value at this scale. It will be considered for subsequent
317bcbd26bfSFlorian Hahn       // smaller scales.
318bcbd26bfSFlorian Hahn       if (!CI->isZero()) {
319bcbd26bfSFlorian Hahn         const SCEV *Div = SE.getConstant(CI);
320bcbd26bfSFlorian Hahn         S = Div;
321bcbd26bfSFlorian Hahn         Remainder = SE.getAddExpr(
322bcbd26bfSFlorian Hahn             Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
323bcbd26bfSFlorian Hahn         return true;
324bcbd26bfSFlorian Hahn       }
325bcbd26bfSFlorian Hahn     }
326bcbd26bfSFlorian Hahn   }
327bcbd26bfSFlorian Hahn 
328bcbd26bfSFlorian Hahn   // In a Mul, check if there is a constant operand which is a multiple
329bcbd26bfSFlorian Hahn   // of the given factor.
330bcbd26bfSFlorian Hahn   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
331bcbd26bfSFlorian Hahn     // Size is known, check if there is a constant operand which is a multiple
332bcbd26bfSFlorian Hahn     // of the given factor. If so, we can factor it.
333bd43f78cSHuihui Zhang     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor))
334bcbd26bfSFlorian Hahn       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
335bcbd26bfSFlorian Hahn         if (!C->getAPInt().srem(FC->getAPInt())) {
33616d20e25SKazu Hirata           SmallVector<const SCEV *, 4> NewMulOps(M->operands());
337bcbd26bfSFlorian Hahn           NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
338bcbd26bfSFlorian Hahn           S = SE.getMulExpr(NewMulOps);
339bcbd26bfSFlorian Hahn           return true;
340bcbd26bfSFlorian Hahn         }
341bcbd26bfSFlorian Hahn   }
342bcbd26bfSFlorian Hahn 
343bcbd26bfSFlorian Hahn   // In an AddRec, check if both start and step are divisible.
344bcbd26bfSFlorian Hahn   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
345bcbd26bfSFlorian Hahn     const SCEV *Step = A->getStepRecurrence(SE);
346bcbd26bfSFlorian Hahn     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
347bcbd26bfSFlorian Hahn     if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
348bcbd26bfSFlorian Hahn       return false;
349bcbd26bfSFlorian Hahn     if (!StepRem->isZero())
350bcbd26bfSFlorian Hahn       return false;
351bcbd26bfSFlorian Hahn     const SCEV *Start = A->getStart();
352bcbd26bfSFlorian Hahn     if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
353bcbd26bfSFlorian Hahn       return false;
354bcbd26bfSFlorian Hahn     S = SE.getAddRecExpr(Start, Step, A->getLoop(),
355bcbd26bfSFlorian Hahn                          A->getNoWrapFlags(SCEV::FlagNW));
356bcbd26bfSFlorian Hahn     return true;
357bcbd26bfSFlorian Hahn   }
358bcbd26bfSFlorian Hahn 
359bcbd26bfSFlorian Hahn   return false;
360bcbd26bfSFlorian Hahn }
361bcbd26bfSFlorian Hahn 
362bcbd26bfSFlorian Hahn /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
363bcbd26bfSFlorian Hahn /// is the number of SCEVAddRecExprs present, which are kept at the end of
364bcbd26bfSFlorian Hahn /// the list.
365bcbd26bfSFlorian Hahn ///
SimplifyAddOperands(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)366bcbd26bfSFlorian Hahn static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
367bcbd26bfSFlorian Hahn                                 Type *Ty,
368bcbd26bfSFlorian Hahn                                 ScalarEvolution &SE) {
369bcbd26bfSFlorian Hahn   unsigned NumAddRecs = 0;
370bcbd26bfSFlorian Hahn   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
371bcbd26bfSFlorian Hahn     ++NumAddRecs;
372bcbd26bfSFlorian Hahn   // Group Ops into non-addrecs and addrecs.
373bcbd26bfSFlorian Hahn   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
374bcbd26bfSFlorian Hahn   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
375bcbd26bfSFlorian Hahn   // Let ScalarEvolution sort and simplify the non-addrecs list.
376bcbd26bfSFlorian Hahn   const SCEV *Sum = NoAddRecs.empty() ?
377bcbd26bfSFlorian Hahn                     SE.getConstant(Ty, 0) :
378bcbd26bfSFlorian Hahn                     SE.getAddExpr(NoAddRecs);
379bcbd26bfSFlorian Hahn   // If it returned an add, use the operands. Otherwise it simplified
380bcbd26bfSFlorian Hahn   // the sum into a single value, so just use that.
381bcbd26bfSFlorian Hahn   Ops.clear();
382bcbd26bfSFlorian Hahn   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
383bcbd26bfSFlorian Hahn     Ops.append(Add->op_begin(), Add->op_end());
384bcbd26bfSFlorian Hahn   else if (!Sum->isZero())
385bcbd26bfSFlorian Hahn     Ops.push_back(Sum);
386bcbd26bfSFlorian Hahn   // Then append the addrecs.
387bcbd26bfSFlorian Hahn   Ops.append(AddRecs.begin(), AddRecs.end());
388bcbd26bfSFlorian Hahn }
389bcbd26bfSFlorian Hahn 
390bcbd26bfSFlorian Hahn /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
391bcbd26bfSFlorian Hahn /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
392bcbd26bfSFlorian Hahn /// This helps expose more opportunities for folding parts of the expressions
393bcbd26bfSFlorian Hahn /// into GEP indices.
394bcbd26bfSFlorian Hahn ///
SplitAddRecs(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)395bcbd26bfSFlorian Hahn static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
396bcbd26bfSFlorian Hahn                          Type *Ty,
397bcbd26bfSFlorian Hahn                          ScalarEvolution &SE) {
398bcbd26bfSFlorian Hahn   // Find the addrecs.
399bcbd26bfSFlorian Hahn   SmallVector<const SCEV *, 8> AddRecs;
400bcbd26bfSFlorian Hahn   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
401bcbd26bfSFlorian Hahn     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
402bcbd26bfSFlorian Hahn       const SCEV *Start = A->getStart();
403bcbd26bfSFlorian Hahn       if (Start->isZero()) break;
404bcbd26bfSFlorian Hahn       const SCEV *Zero = SE.getConstant(Ty, 0);
405bcbd26bfSFlorian Hahn       AddRecs.push_back(SE.getAddRecExpr(Zero,
406bcbd26bfSFlorian Hahn                                          A->getStepRecurrence(SE),
407bcbd26bfSFlorian Hahn                                          A->getLoop(),
408bcbd26bfSFlorian Hahn                                          A->getNoWrapFlags(SCEV::FlagNW)));
409bcbd26bfSFlorian Hahn       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
410bcbd26bfSFlorian Hahn         Ops[i] = Zero;
411bcbd26bfSFlorian Hahn         Ops.append(Add->op_begin(), Add->op_end());
412bcbd26bfSFlorian Hahn         e += Add->getNumOperands();
413bcbd26bfSFlorian Hahn       } else {
414bcbd26bfSFlorian Hahn         Ops[i] = Start;
415bcbd26bfSFlorian Hahn       }
416bcbd26bfSFlorian Hahn     }
417bcbd26bfSFlorian Hahn   if (!AddRecs.empty()) {
418bcbd26bfSFlorian Hahn     // Add the addrecs onto the end of the list.
419bcbd26bfSFlorian Hahn     Ops.append(AddRecs.begin(), AddRecs.end());
420bcbd26bfSFlorian Hahn     // Resort the operand list, moving any constants to the front.
421bcbd26bfSFlorian Hahn     SimplifyAddOperands(Ops, Ty, SE);
422bcbd26bfSFlorian Hahn   }
423bcbd26bfSFlorian Hahn }
424bcbd26bfSFlorian Hahn 
425bcbd26bfSFlorian Hahn /// expandAddToGEP - Expand an addition expression with a pointer type into
426bcbd26bfSFlorian Hahn /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
427bcbd26bfSFlorian Hahn /// BasicAliasAnalysis and other passes analyze the result. See the rules
428bcbd26bfSFlorian Hahn /// for getelementptr vs. inttoptr in
429bcbd26bfSFlorian Hahn /// http://llvm.org/docs/LangRef.html#pointeraliasing
430bcbd26bfSFlorian Hahn /// for details.
431bcbd26bfSFlorian Hahn ///
432bcbd26bfSFlorian Hahn /// Design note: The correctness of using getelementptr here depends on
433bcbd26bfSFlorian Hahn /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
434bcbd26bfSFlorian Hahn /// they may introduce pointer arithmetic which may not be safely converted
435bcbd26bfSFlorian Hahn /// into getelementptr.
436bcbd26bfSFlorian Hahn ///
437bcbd26bfSFlorian Hahn /// Design note: It might seem desirable for this function to be more
438bcbd26bfSFlorian Hahn /// loop-aware. If some of the indices are loop-invariant while others
439bcbd26bfSFlorian Hahn /// aren't, it might seem desirable to emit multiple GEPs, keeping the
440bcbd26bfSFlorian Hahn /// loop-invariant portions of the overall computation outside the loop.
441bcbd26bfSFlorian Hahn /// However, there are a few reasons this is not done here. Hoisting simple
442bcbd26bfSFlorian Hahn /// arithmetic is a low-level optimization that often isn't very
443bcbd26bfSFlorian Hahn /// important until late in the optimization process. In fact, passes
444bcbd26bfSFlorian Hahn /// like InstructionCombining will combine GEPs, even if it means
445bcbd26bfSFlorian Hahn /// pushing loop-invariant computation down into loops, so even if the
446bcbd26bfSFlorian Hahn /// GEPs were split here, the work would quickly be undone. The
447bcbd26bfSFlorian Hahn /// LoopStrengthReduction pass, which is usually run quite late (and
448bcbd26bfSFlorian Hahn /// after the last InstructionCombining pass), takes care of hoisting
449bcbd26bfSFlorian Hahn /// loop-invariant portions of expressions, after considering what
450bcbd26bfSFlorian Hahn /// can be folded using target addressing modes.
451bcbd26bfSFlorian Hahn ///
expandAddToGEP(const SCEV * const * op_begin,const SCEV * const * op_end,PointerType * PTy,Type * Ty,Value * V)452bcbd26bfSFlorian Hahn Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
453bcbd26bfSFlorian Hahn                                     const SCEV *const *op_end,
454bcbd26bfSFlorian Hahn                                     PointerType *PTy,
455bcbd26bfSFlorian Hahn                                     Type *Ty,
456bcbd26bfSFlorian Hahn                                     Value *V) {
457bcbd26bfSFlorian Hahn   SmallVector<Value *, 4> GepIndices;
458bcbd26bfSFlorian Hahn   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
459bcbd26bfSFlorian Hahn   bool AnyNonZeroIndices = false;
460bcbd26bfSFlorian Hahn 
461bcbd26bfSFlorian Hahn   // Split AddRecs up into parts as either of the parts may be usable
462bcbd26bfSFlorian Hahn   // without the other.
463bcbd26bfSFlorian Hahn   SplitAddRecs(Ops, Ty, SE);
464bcbd26bfSFlorian Hahn 
465bcbd26bfSFlorian Hahn   Type *IntIdxTy = DL.getIndexType(PTy);
466bcbd26bfSFlorian Hahn 
46784c15bc0SNikita Popov   // For opaque pointers, always generate i8 GEP.
46884c15bc0SNikita Popov   if (!PTy->isOpaque()) {
469bcbd26bfSFlorian Hahn     // Descend down the pointer's type and attempt to convert the other
470bcbd26bfSFlorian Hahn     // operands into GEP indices, at each level. The first index in a GEP
471bcbd26bfSFlorian Hahn     // indexes into the array implied by the pointer operand; the rest of
472bcbd26bfSFlorian Hahn     // the indices index into the element or field type selected by the
473bcbd26bfSFlorian Hahn     // preceding index.
474aa97bc11SNikita Popov     Type *ElTy = PTy->getNonOpaquePointerElementType();
475bcbd26bfSFlorian Hahn     for (;;) {
476bcbd26bfSFlorian Hahn       // If the scale size is not 0, attempt to factor out a scale for
477bcbd26bfSFlorian Hahn       // array indexing.
478bcbd26bfSFlorian Hahn       SmallVector<const SCEV *, 8> ScaledOps;
479bcbd26bfSFlorian Hahn       if (ElTy->isSized()) {
480bcbd26bfSFlorian Hahn         const SCEV *ElSize = SE.getSizeOfExpr(IntIdxTy, ElTy);
481bcbd26bfSFlorian Hahn         if (!ElSize->isZero()) {
482bcbd26bfSFlorian Hahn           SmallVector<const SCEV *, 8> NewOps;
483bcbd26bfSFlorian Hahn           for (const SCEV *Op : Ops) {
484bcbd26bfSFlorian Hahn             const SCEV *Remainder = SE.getConstant(Ty, 0);
485bcbd26bfSFlorian Hahn             if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
486bcbd26bfSFlorian Hahn               // Op now has ElSize factored out.
487bcbd26bfSFlorian Hahn               ScaledOps.push_back(Op);
488bcbd26bfSFlorian Hahn               if (!Remainder->isZero())
489bcbd26bfSFlorian Hahn                 NewOps.push_back(Remainder);
490bcbd26bfSFlorian Hahn               AnyNonZeroIndices = true;
491bcbd26bfSFlorian Hahn             } else {
49284c15bc0SNikita Popov               // The operand was not divisible, so add it to the list of
49384c15bc0SNikita Popov               // operands we'll scan next iteration.
494bcbd26bfSFlorian Hahn               NewOps.push_back(Op);
495bcbd26bfSFlorian Hahn             }
496bcbd26bfSFlorian Hahn           }
497bcbd26bfSFlorian Hahn           // If we made any changes, update Ops.
498bcbd26bfSFlorian Hahn           if (!ScaledOps.empty()) {
499bcbd26bfSFlorian Hahn             Ops = NewOps;
500bcbd26bfSFlorian Hahn             SimplifyAddOperands(Ops, Ty, SE);
501bcbd26bfSFlorian Hahn           }
502bcbd26bfSFlorian Hahn         }
503bcbd26bfSFlorian Hahn       }
504bcbd26bfSFlorian Hahn 
505bcbd26bfSFlorian Hahn       // Record the scaled array index for this level of the type. If
506bcbd26bfSFlorian Hahn       // we didn't find any operands that could be factored, tentatively
507bcbd26bfSFlorian Hahn       // assume that element zero was selected (since the zero offset
508bcbd26bfSFlorian Hahn       // would obviously be folded away).
509f75564adSFlorian Hahn       Value *Scaled =
510f75564adSFlorian Hahn           ScaledOps.empty()
511f75564adSFlorian Hahn               ? Constant::getNullValue(Ty)
512f75564adSFlorian Hahn               : expandCodeForImpl(SE.getAddExpr(ScaledOps), Ty, false);
513bcbd26bfSFlorian Hahn       GepIndices.push_back(Scaled);
514bcbd26bfSFlorian Hahn 
515bcbd26bfSFlorian Hahn       // Collect struct field index operands.
516bcbd26bfSFlorian Hahn       while (StructType *STy = dyn_cast<StructType>(ElTy)) {
517bcbd26bfSFlorian Hahn         bool FoundFieldNo = false;
518bcbd26bfSFlorian Hahn         // An empty struct has no fields.
519bcbd26bfSFlorian Hahn         if (STy->getNumElements() == 0) break;
520bcbd26bfSFlorian Hahn         // Field offsets are known. See if a constant offset falls within any of
521bcbd26bfSFlorian Hahn         // the struct fields.
522bcbd26bfSFlorian Hahn         if (Ops.empty())
523bcbd26bfSFlorian Hahn           break;
524bcbd26bfSFlorian Hahn         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
525bcbd26bfSFlorian Hahn           if (SE.getTypeSizeInBits(C->getType()) <= 64) {
526bcbd26bfSFlorian Hahn             const StructLayout &SL = *DL.getStructLayout(STy);
527bcbd26bfSFlorian Hahn             uint64_t FullOffset = C->getValue()->getZExtValue();
528bcbd26bfSFlorian Hahn             if (FullOffset < SL.getSizeInBytes()) {
529bcbd26bfSFlorian Hahn               unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
530bcbd26bfSFlorian Hahn               GepIndices.push_back(
531bcbd26bfSFlorian Hahn                   ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
532bcbd26bfSFlorian Hahn               ElTy = STy->getTypeAtIndex(ElIdx);
533bcbd26bfSFlorian Hahn               Ops[0] =
534bcbd26bfSFlorian Hahn                   SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
535bcbd26bfSFlorian Hahn               AnyNonZeroIndices = true;
536bcbd26bfSFlorian Hahn               FoundFieldNo = true;
537bcbd26bfSFlorian Hahn             }
538bcbd26bfSFlorian Hahn           }
539bcbd26bfSFlorian Hahn         // If no struct field offsets were found, tentatively assume that
540bcbd26bfSFlorian Hahn         // field zero was selected (since the zero offset would obviously
541bcbd26bfSFlorian Hahn         // be folded away).
542bcbd26bfSFlorian Hahn         if (!FoundFieldNo) {
543bcbd26bfSFlorian Hahn           ElTy = STy->getTypeAtIndex(0u);
544bcbd26bfSFlorian Hahn           GepIndices.push_back(
545bcbd26bfSFlorian Hahn             Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
546bcbd26bfSFlorian Hahn         }
547bcbd26bfSFlorian Hahn       }
548bcbd26bfSFlorian Hahn 
549bcbd26bfSFlorian Hahn       if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
550bcbd26bfSFlorian Hahn         ElTy = ATy->getElementType();
551bcbd26bfSFlorian Hahn       else
552bd43f78cSHuihui Zhang         // FIXME: Handle VectorType.
553bd43f78cSHuihui Zhang         // E.g., If ElTy is scalable vector, then ElSize is not a compile-time
554bd43f78cSHuihui Zhang         // constant, therefore can not be factored out. The generated IR is less
555bd43f78cSHuihui Zhang         // ideal with base 'V' cast to i8* and do ugly getelementptr over that.
556bcbd26bfSFlorian Hahn         break;
557bcbd26bfSFlorian Hahn     }
55884c15bc0SNikita Popov   }
559bcbd26bfSFlorian Hahn 
560bcbd26bfSFlorian Hahn   // If none of the operands were convertible to proper GEP indices, cast
561bcbd26bfSFlorian Hahn   // the base to i8* and do an ugly getelementptr with that. It's still
562bcbd26bfSFlorian Hahn   // better than ptrtoint+arithmetic+inttoptr at least.
563bcbd26bfSFlorian Hahn   if (!AnyNonZeroIndices) {
564bcbd26bfSFlorian Hahn     // Cast the base to i8*.
56584c15bc0SNikita Popov     if (!PTy->isOpaque())
566bcbd26bfSFlorian Hahn       V = InsertNoopCastOfTo(V,
567bcbd26bfSFlorian Hahn          Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
568bcbd26bfSFlorian Hahn 
569bcbd26bfSFlorian Hahn     assert(!isa<Instruction>(V) ||
570bcbd26bfSFlorian Hahn            SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
571bcbd26bfSFlorian Hahn 
572bcbd26bfSFlorian Hahn     // Expand the operands for a plain byte offset.
573f75564adSFlorian Hahn     Value *Idx = expandCodeForImpl(SE.getAddExpr(Ops), Ty, false);
574bcbd26bfSFlorian Hahn 
575bcbd26bfSFlorian Hahn     // Fold a GEP with constant operands.
576bcbd26bfSFlorian Hahn     if (Constant *CLHS = dyn_cast<Constant>(V))
577bcbd26bfSFlorian Hahn       if (Constant *CRHS = dyn_cast<Constant>(Idx))
578bcbd26bfSFlorian Hahn         return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
579bcbd26bfSFlorian Hahn                                               CLHS, CRHS);
580bcbd26bfSFlorian Hahn 
581bcbd26bfSFlorian Hahn     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
582bcbd26bfSFlorian Hahn     unsigned ScanLimit = 6;
583bcbd26bfSFlorian Hahn     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
584bcbd26bfSFlorian Hahn     // Scanning starts from the last instruction before the insertion point.
585bcbd26bfSFlorian Hahn     BasicBlock::iterator IP = Builder.GetInsertPoint();
586bcbd26bfSFlorian Hahn     if (IP != BlockBegin) {
587bcbd26bfSFlorian Hahn       --IP;
588bcbd26bfSFlorian Hahn       for (; ScanLimit; --IP, --ScanLimit) {
589bcbd26bfSFlorian Hahn         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
590bcbd26bfSFlorian Hahn         // generated code.
591bcbd26bfSFlorian Hahn         if (isa<DbgInfoIntrinsic>(IP))
592bcbd26bfSFlorian Hahn           ScanLimit++;
593bcbd26bfSFlorian Hahn         if (IP->getOpcode() == Instruction::GetElementPtr &&
594129af4daSArthur Eubanks             IP->getOperand(0) == V && IP->getOperand(1) == Idx &&
595129af4daSArthur Eubanks             cast<GEPOperator>(&*IP)->getSourceElementType() ==
596129af4daSArthur Eubanks                 Type::getInt8Ty(Ty->getContext()))
597bcbd26bfSFlorian Hahn           return &*IP;
598bcbd26bfSFlorian Hahn         if (IP == BlockBegin) break;
599bcbd26bfSFlorian Hahn       }
600bcbd26bfSFlorian Hahn     }
601bcbd26bfSFlorian Hahn 
602bcbd26bfSFlorian Hahn     // Save the original insertion point so we can restore it when we're done.
603bcbd26bfSFlorian Hahn     SCEVInsertPointGuard Guard(Builder, this);
604bcbd26bfSFlorian Hahn 
605bcbd26bfSFlorian Hahn     // Move the insertion point out of as many loops as we can.
606bcbd26bfSFlorian Hahn     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
607bcbd26bfSFlorian Hahn       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
608bcbd26bfSFlorian Hahn       BasicBlock *Preheader = L->getLoopPreheader();
609bcbd26bfSFlorian Hahn       if (!Preheader) break;
610bcbd26bfSFlorian Hahn 
611bcbd26bfSFlorian Hahn       // Ok, move up a level.
612bcbd26bfSFlorian Hahn       Builder.SetInsertPoint(Preheader->getTerminator());
613bcbd26bfSFlorian Hahn     }
614bcbd26bfSFlorian Hahn 
615bcbd26bfSFlorian Hahn     // Emit a GEP.
616ecd3f853SFlorian Hahn     return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
617bcbd26bfSFlorian Hahn   }
618bcbd26bfSFlorian Hahn 
619bcbd26bfSFlorian Hahn   {
620bcbd26bfSFlorian Hahn     SCEVInsertPointGuard Guard(Builder, this);
621bcbd26bfSFlorian Hahn 
622bcbd26bfSFlorian Hahn     // Move the insertion point out of as many loops as we can.
623bcbd26bfSFlorian Hahn     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
624bcbd26bfSFlorian Hahn       if (!L->isLoopInvariant(V)) break;
625bcbd26bfSFlorian Hahn 
626bcbd26bfSFlorian Hahn       bool AnyIndexNotLoopInvariant = any_of(
627bcbd26bfSFlorian Hahn           GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
628bcbd26bfSFlorian Hahn 
629bcbd26bfSFlorian Hahn       if (AnyIndexNotLoopInvariant)
630bcbd26bfSFlorian Hahn         break;
631bcbd26bfSFlorian Hahn 
632bcbd26bfSFlorian Hahn       BasicBlock *Preheader = L->getLoopPreheader();
633bcbd26bfSFlorian Hahn       if (!Preheader) break;
634bcbd26bfSFlorian Hahn 
635bcbd26bfSFlorian Hahn       // Ok, move up a level.
636bcbd26bfSFlorian Hahn       Builder.SetInsertPoint(Preheader->getTerminator());
637bcbd26bfSFlorian Hahn     }
638bcbd26bfSFlorian Hahn 
639bcbd26bfSFlorian Hahn     // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
640bcbd26bfSFlorian Hahn     // because ScalarEvolution may have changed the address arithmetic to
641bcbd26bfSFlorian Hahn     // compute a value which is beyond the end of the allocated object.
642bcbd26bfSFlorian Hahn     Value *Casted = V;
643bcbd26bfSFlorian Hahn     if (V->getType() != PTy)
644bcbd26bfSFlorian Hahn       Casted = InsertNoopCastOfTo(Casted, PTy);
645aa97bc11SNikita Popov     Value *GEP = Builder.CreateGEP(PTy->getNonOpaquePointerElementType(),
646aa97bc11SNikita Popov                                    Casted, GepIndices, "scevgep");
647bcbd26bfSFlorian Hahn     Ops.push_back(SE.getUnknown(GEP));
648bcbd26bfSFlorian Hahn   }
649bcbd26bfSFlorian Hahn 
650bcbd26bfSFlorian Hahn   return expand(SE.getAddExpr(Ops));
651bcbd26bfSFlorian Hahn }
652bcbd26bfSFlorian Hahn 
expandAddToGEP(const SCEV * Op,PointerType * PTy,Type * Ty,Value * V)653bcbd26bfSFlorian Hahn Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
654bcbd26bfSFlorian Hahn                                     Value *V) {
655bcbd26bfSFlorian Hahn   const SCEV *const Ops[1] = {Op};
656bcbd26bfSFlorian Hahn   return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
657bcbd26bfSFlorian Hahn }
658bcbd26bfSFlorian Hahn 
659bcbd26bfSFlorian Hahn /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
660bcbd26bfSFlorian Hahn /// SCEV expansion. If they are nested, this is the most nested. If they are
661bcbd26bfSFlorian Hahn /// neighboring, pick the later.
PickMostRelevantLoop(const Loop * A,const Loop * B,DominatorTree & DT)662bcbd26bfSFlorian Hahn static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
663bcbd26bfSFlorian Hahn                                         DominatorTree &DT) {
664bcbd26bfSFlorian Hahn   if (!A) return B;
665bcbd26bfSFlorian Hahn   if (!B) return A;
666bcbd26bfSFlorian Hahn   if (A->contains(B)) return B;
667bcbd26bfSFlorian Hahn   if (B->contains(A)) return A;
668bcbd26bfSFlorian Hahn   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
669bcbd26bfSFlorian Hahn   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
670bcbd26bfSFlorian Hahn   return A; // Arbitrarily break the tie.
671bcbd26bfSFlorian Hahn }
672bcbd26bfSFlorian Hahn 
673bcbd26bfSFlorian Hahn /// getRelevantLoop - Get the most relevant loop associated with the given
674bcbd26bfSFlorian Hahn /// expression, according to PickMostRelevantLoop.
getRelevantLoop(const SCEV * S)675bcbd26bfSFlorian Hahn const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
676bcbd26bfSFlorian Hahn   // Test whether we've already computed the most relevant loop for this SCEV.
677bcbd26bfSFlorian Hahn   auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
678bcbd26bfSFlorian Hahn   if (!Pair.second)
679bcbd26bfSFlorian Hahn     return Pair.first->second;
680bcbd26bfSFlorian Hahn 
681bcbd26bfSFlorian Hahn   if (isa<SCEVConstant>(S))
682bcbd26bfSFlorian Hahn     // A constant has no relevant loops.
683bcbd26bfSFlorian Hahn     return nullptr;
684bcbd26bfSFlorian Hahn   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
685bcbd26bfSFlorian Hahn     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
686bcbd26bfSFlorian Hahn       return Pair.first->second = SE.LI.getLoopFor(I->getParent());
687bcbd26bfSFlorian Hahn     // A non-instruction has no relevant loops.
688bcbd26bfSFlorian Hahn     return nullptr;
689bcbd26bfSFlorian Hahn   }
690bcbd26bfSFlorian Hahn   if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
691bcbd26bfSFlorian Hahn     const Loop *L = nullptr;
692bcbd26bfSFlorian Hahn     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
693bcbd26bfSFlorian Hahn       L = AR->getLoop();
694bcbd26bfSFlorian Hahn     for (const SCEV *Op : N->operands())
695bcbd26bfSFlorian Hahn       L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
696bcbd26bfSFlorian Hahn     return RelevantLoops[N] = L;
697bcbd26bfSFlorian Hahn   }
69881fc53a3SRoman Lebedev   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
699bcbd26bfSFlorian Hahn     const Loop *Result = getRelevantLoop(C->getOperand());
700bcbd26bfSFlorian Hahn     return RelevantLoops[C] = Result;
701bcbd26bfSFlorian Hahn   }
702bcbd26bfSFlorian Hahn   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
703bcbd26bfSFlorian Hahn     const Loop *Result = PickMostRelevantLoop(
704bcbd26bfSFlorian Hahn         getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
705bcbd26bfSFlorian Hahn     return RelevantLoops[D] = Result;
706bcbd26bfSFlorian Hahn   }
707bcbd26bfSFlorian Hahn   llvm_unreachable("Unexpected SCEV type!");
708bcbd26bfSFlorian Hahn }
709bcbd26bfSFlorian Hahn 
710bcbd26bfSFlorian Hahn namespace {
711bcbd26bfSFlorian Hahn 
712bcbd26bfSFlorian Hahn /// LoopCompare - Compare loops by PickMostRelevantLoop.
713bcbd26bfSFlorian Hahn class LoopCompare {
714bcbd26bfSFlorian Hahn   DominatorTree &DT;
715bcbd26bfSFlorian Hahn public:
LoopCompare(DominatorTree & dt)716bcbd26bfSFlorian Hahn   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
717bcbd26bfSFlorian Hahn 
operator ()(std::pair<const Loop *,const SCEV * > LHS,std::pair<const Loop *,const SCEV * > RHS) const718bcbd26bfSFlorian Hahn   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
719bcbd26bfSFlorian Hahn                   std::pair<const Loop *, const SCEV *> RHS) const {
720bcbd26bfSFlorian Hahn     // Keep pointer operands sorted at the end.
721bcbd26bfSFlorian Hahn     if (LHS.second->getType()->isPointerTy() !=
722bcbd26bfSFlorian Hahn         RHS.second->getType()->isPointerTy())
723bcbd26bfSFlorian Hahn       return LHS.second->getType()->isPointerTy();
724bcbd26bfSFlorian Hahn 
725bcbd26bfSFlorian Hahn     // Compare loops with PickMostRelevantLoop.
726bcbd26bfSFlorian Hahn     if (LHS.first != RHS.first)
727bcbd26bfSFlorian Hahn       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
728bcbd26bfSFlorian Hahn 
729bcbd26bfSFlorian Hahn     // If one operand is a non-constant negative and the other is not,
730bcbd26bfSFlorian Hahn     // put the non-constant negative on the right so that a sub can
731bcbd26bfSFlorian Hahn     // be used instead of a negate and add.
732bcbd26bfSFlorian Hahn     if (LHS.second->isNonConstantNegative()) {
733bcbd26bfSFlorian Hahn       if (!RHS.second->isNonConstantNegative())
734bcbd26bfSFlorian Hahn         return false;
735bcbd26bfSFlorian Hahn     } else if (RHS.second->isNonConstantNegative())
736bcbd26bfSFlorian Hahn       return true;
737bcbd26bfSFlorian Hahn 
738bcbd26bfSFlorian Hahn     // Otherwise they are equivalent according to this comparison.
739bcbd26bfSFlorian Hahn     return false;
740bcbd26bfSFlorian Hahn   }
741bcbd26bfSFlorian Hahn };
742bcbd26bfSFlorian Hahn 
743bcbd26bfSFlorian Hahn }
744bcbd26bfSFlorian Hahn 
visitAddExpr(const SCEVAddExpr * S)745bcbd26bfSFlorian Hahn Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
746bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
747bcbd26bfSFlorian Hahn 
748bcbd26bfSFlorian Hahn   // Collect all the add operands in a loop, along with their associated loops.
749bcbd26bfSFlorian Hahn   // Iterate in reverse so that constants are emitted last, all else equal, and
750bcbd26bfSFlorian Hahn   // so that pointer operands are inserted first, which the code below relies on
751bcbd26bfSFlorian Hahn   // to form more involved GEPs.
752bcbd26bfSFlorian Hahn   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
75311a8423dSNikita Popov   for (const SCEV *Op : reverse(S->operands()))
75411a8423dSNikita Popov     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
755bcbd26bfSFlorian Hahn 
756bcbd26bfSFlorian Hahn   // Sort by loop. Use a stable sort so that constants follow non-constants and
757bcbd26bfSFlorian Hahn   // pointer operands precede non-pointer operands.
758bcbd26bfSFlorian Hahn   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
759bcbd26bfSFlorian Hahn 
760bcbd26bfSFlorian Hahn   // Emit instructions to add all the operands. Hoist as much as possible
761bcbd26bfSFlorian Hahn   // out of loops, and form meaningful getelementptrs where possible.
762bcbd26bfSFlorian Hahn   Value *Sum = nullptr;
763bcbd26bfSFlorian Hahn   for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
764bcbd26bfSFlorian Hahn     const Loop *CurLoop = I->first;
765bcbd26bfSFlorian Hahn     const SCEV *Op = I->second;
766bcbd26bfSFlorian Hahn     if (!Sum) {
767bcbd26bfSFlorian Hahn       // This is the first operand. Just expand it.
768bcbd26bfSFlorian Hahn       Sum = expand(Op);
769bcbd26bfSFlorian Hahn       ++I;
7703f162e8eSNikita Popov       continue;
7713f162e8eSNikita Popov     }
7723f162e8eSNikita Popov 
7733f162e8eSNikita Popov     assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
7743f162e8eSNikita Popov     if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
775bcbd26bfSFlorian Hahn       // The running sum expression is a pointer. Try to form a getelementptr
776bcbd26bfSFlorian Hahn       // at this level with that as the base.
777bcbd26bfSFlorian Hahn       SmallVector<const SCEV *, 4> NewOps;
778bcbd26bfSFlorian Hahn       for (; I != E && I->first == CurLoop; ++I) {
779bcbd26bfSFlorian Hahn         // If the operand is SCEVUnknown and not instructions, peek through
780bcbd26bfSFlorian Hahn         // it, to enable more of it to be folded into the GEP.
781bcbd26bfSFlorian Hahn         const SCEV *X = I->second;
782bcbd26bfSFlorian Hahn         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
783bcbd26bfSFlorian Hahn           if (!isa<Instruction>(U->getValue()))
784bcbd26bfSFlorian Hahn             X = SE.getSCEV(U->getValue());
785bcbd26bfSFlorian Hahn         NewOps.push_back(X);
786bcbd26bfSFlorian Hahn       }
787bcbd26bfSFlorian Hahn       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
788bcbd26bfSFlorian Hahn     } else if (Op->isNonConstantNegative()) {
789bcbd26bfSFlorian Hahn       // Instead of doing a negate and add, just do a subtract.
790f75564adSFlorian Hahn       Value *W = expandCodeForImpl(SE.getNegativeSCEV(Op), Ty, false);
791bcbd26bfSFlorian Hahn       Sum = InsertNoopCastOfTo(Sum, Ty);
792bcbd26bfSFlorian Hahn       Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
793bcbd26bfSFlorian Hahn                         /*IsSafeToHoist*/ true);
794bcbd26bfSFlorian Hahn       ++I;
795bcbd26bfSFlorian Hahn     } else {
796bcbd26bfSFlorian Hahn       // A simple add.
797f75564adSFlorian Hahn       Value *W = expandCodeForImpl(Op, Ty, false);
798bcbd26bfSFlorian Hahn       Sum = InsertNoopCastOfTo(Sum, Ty);
799bcbd26bfSFlorian Hahn       // Canonicalize a constant to the RHS.
800bcbd26bfSFlorian Hahn       if (isa<Constant>(Sum)) std::swap(Sum, W);
801bcbd26bfSFlorian Hahn       Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
802bcbd26bfSFlorian Hahn                         /*IsSafeToHoist*/ true);
803bcbd26bfSFlorian Hahn       ++I;
804bcbd26bfSFlorian Hahn     }
805bcbd26bfSFlorian Hahn   }
806bcbd26bfSFlorian Hahn 
807bcbd26bfSFlorian Hahn   return Sum;
808bcbd26bfSFlorian Hahn }
809bcbd26bfSFlorian Hahn 
visitMulExpr(const SCEVMulExpr * S)810bcbd26bfSFlorian Hahn Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
811bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
812bcbd26bfSFlorian Hahn 
813bcbd26bfSFlorian Hahn   // Collect all the mul operands in a loop, along with their associated loops.
814bcbd26bfSFlorian Hahn   // Iterate in reverse so that constants are emitted last, all else equal.
815bcbd26bfSFlorian Hahn   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
81611a8423dSNikita Popov   for (const SCEV *Op : reverse(S->operands()))
81711a8423dSNikita Popov     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
818bcbd26bfSFlorian Hahn 
819bcbd26bfSFlorian Hahn   // Sort by loop. Use a stable sort so that constants follow non-constants.
820bcbd26bfSFlorian Hahn   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
821bcbd26bfSFlorian Hahn 
822bcbd26bfSFlorian Hahn   // Emit instructions to mul all the operands. Hoist as much as possible
823bcbd26bfSFlorian Hahn   // out of loops.
824bcbd26bfSFlorian Hahn   Value *Prod = nullptr;
825bcbd26bfSFlorian Hahn   auto I = OpsAndLoops.begin();
826bcbd26bfSFlorian Hahn 
827bcbd26bfSFlorian Hahn   // Expand the calculation of X pow N in the following manner:
828bcbd26bfSFlorian Hahn   // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
829bcbd26bfSFlorian Hahn   // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
830bcbd26bfSFlorian Hahn   const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
831bcbd26bfSFlorian Hahn     auto E = I;
832bcbd26bfSFlorian Hahn     // Calculate how many times the same operand from the same loop is included
833bcbd26bfSFlorian Hahn     // into this power.
834bcbd26bfSFlorian Hahn     uint64_t Exponent = 0;
835bcbd26bfSFlorian Hahn     const uint64_t MaxExponent = UINT64_MAX >> 1;
836bcbd26bfSFlorian Hahn     // No one sane will ever try to calculate such huge exponents, but if we
837bcbd26bfSFlorian Hahn     // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
838bcbd26bfSFlorian Hahn     // below when the power of 2 exceeds our Exponent, and we want it to be
839bcbd26bfSFlorian Hahn     // 1u << 31 at most to not deal with unsigned overflow.
840bcbd26bfSFlorian Hahn     while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
841bcbd26bfSFlorian Hahn       ++Exponent;
842bcbd26bfSFlorian Hahn       ++E;
843bcbd26bfSFlorian Hahn     }
844bcbd26bfSFlorian Hahn     assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
845bcbd26bfSFlorian Hahn 
846bcbd26bfSFlorian Hahn     // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
847bcbd26bfSFlorian Hahn     // that are needed into the result.
848f75564adSFlorian Hahn     Value *P = expandCodeForImpl(I->second, Ty, false);
849bcbd26bfSFlorian Hahn     Value *Result = nullptr;
850bcbd26bfSFlorian Hahn     if (Exponent & 1)
851bcbd26bfSFlorian Hahn       Result = P;
852bcbd26bfSFlorian Hahn     for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
853bcbd26bfSFlorian Hahn       P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
854bcbd26bfSFlorian Hahn                       /*IsSafeToHoist*/ true);
855bcbd26bfSFlorian Hahn       if (Exponent & BinExp)
856bcbd26bfSFlorian Hahn         Result = Result ? InsertBinop(Instruction::Mul, Result, P,
857bcbd26bfSFlorian Hahn                                       SCEV::FlagAnyWrap,
858bcbd26bfSFlorian Hahn                                       /*IsSafeToHoist*/ true)
859bcbd26bfSFlorian Hahn                         : P;
860bcbd26bfSFlorian Hahn     }
861bcbd26bfSFlorian Hahn 
862bcbd26bfSFlorian Hahn     I = E;
863bcbd26bfSFlorian Hahn     assert(Result && "Nothing was expanded?");
864bcbd26bfSFlorian Hahn     return Result;
865bcbd26bfSFlorian Hahn   };
866bcbd26bfSFlorian Hahn 
867bcbd26bfSFlorian Hahn   while (I != OpsAndLoops.end()) {
868bcbd26bfSFlorian Hahn     if (!Prod) {
869bcbd26bfSFlorian Hahn       // This is the first operand. Just expand it.
870bcbd26bfSFlorian Hahn       Prod = ExpandOpBinPowN();
871bcbd26bfSFlorian Hahn     } else if (I->second->isAllOnesValue()) {
872bcbd26bfSFlorian Hahn       // Instead of doing a multiply by negative one, just do a negate.
873bcbd26bfSFlorian Hahn       Prod = InsertNoopCastOfTo(Prod, Ty);
874bcbd26bfSFlorian Hahn       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
875bcbd26bfSFlorian Hahn                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
876bcbd26bfSFlorian Hahn       ++I;
877bcbd26bfSFlorian Hahn     } else {
878bcbd26bfSFlorian Hahn       // A simple mul.
879bcbd26bfSFlorian Hahn       Value *W = ExpandOpBinPowN();
880bcbd26bfSFlorian Hahn       Prod = InsertNoopCastOfTo(Prod, Ty);
881bcbd26bfSFlorian Hahn       // Canonicalize a constant to the RHS.
882bcbd26bfSFlorian Hahn       if (isa<Constant>(Prod)) std::swap(Prod, W);
883bcbd26bfSFlorian Hahn       const APInt *RHS;
884bcbd26bfSFlorian Hahn       if (match(W, m_Power2(RHS))) {
885bcbd26bfSFlorian Hahn         // Canonicalize Prod*(1<<C) to Prod<<C.
886bcbd26bfSFlorian Hahn         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
887bcbd26bfSFlorian Hahn         auto NWFlags = S->getNoWrapFlags();
888bcbd26bfSFlorian Hahn         // clear nsw flag if shl will produce poison value.
889bcbd26bfSFlorian Hahn         if (RHS->logBase2() == RHS->getBitWidth() - 1)
890bcbd26bfSFlorian Hahn           NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
891bcbd26bfSFlorian Hahn         Prod = InsertBinop(Instruction::Shl, Prod,
892bcbd26bfSFlorian Hahn                            ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
893bcbd26bfSFlorian Hahn                            /*IsSafeToHoist*/ true);
894bcbd26bfSFlorian Hahn       } else {
895bcbd26bfSFlorian Hahn         Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
896bcbd26bfSFlorian Hahn                            /*IsSafeToHoist*/ true);
897bcbd26bfSFlorian Hahn       }
898bcbd26bfSFlorian Hahn     }
899bcbd26bfSFlorian Hahn   }
900bcbd26bfSFlorian Hahn 
901bcbd26bfSFlorian Hahn   return Prod;
902bcbd26bfSFlorian Hahn }
903bcbd26bfSFlorian Hahn 
visitUDivExpr(const SCEVUDivExpr * S)904bcbd26bfSFlorian Hahn Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
905bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
906bcbd26bfSFlorian Hahn 
907f75564adSFlorian Hahn   Value *LHS = expandCodeForImpl(S->getLHS(), Ty, false);
908bcbd26bfSFlorian Hahn   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
909bcbd26bfSFlorian Hahn     const APInt &RHS = SC->getAPInt();
910bcbd26bfSFlorian Hahn     if (RHS.isPowerOf2())
911bcbd26bfSFlorian Hahn       return InsertBinop(Instruction::LShr, LHS,
912bcbd26bfSFlorian Hahn                          ConstantInt::get(Ty, RHS.logBase2()),
913bcbd26bfSFlorian Hahn                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
914bcbd26bfSFlorian Hahn   }
915bcbd26bfSFlorian Hahn 
916f75564adSFlorian Hahn   Value *RHS = expandCodeForImpl(S->getRHS(), Ty, false);
917bcbd26bfSFlorian Hahn   return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
918bcbd26bfSFlorian Hahn                      /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
919bcbd26bfSFlorian Hahn }
920bcbd26bfSFlorian Hahn 
921bcbd26bfSFlorian Hahn /// Determine if this is a well-behaved chain of instructions leading back to
922bcbd26bfSFlorian Hahn /// the PHI. If so, it may be reused by expanded expressions.
isNormalAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)923bcbd26bfSFlorian Hahn bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
924bcbd26bfSFlorian Hahn                                          const Loop *L) {
925bcbd26bfSFlorian Hahn   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
926bcbd26bfSFlorian Hahn       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
927bcbd26bfSFlorian Hahn     return false;
928bcbd26bfSFlorian Hahn   // If any of the operands don't dominate the insert position, bail.
929bcbd26bfSFlorian Hahn   // Addrec operands are always loop-invariant, so this can only happen
930bcbd26bfSFlorian Hahn   // if there are instructions which haven't been hoisted.
931bcbd26bfSFlorian Hahn   if (L == IVIncInsertLoop) {
9321d4a2f37SKazu Hirata     for (Use &Op : llvm::drop_begin(IncV->operands()))
9331d4a2f37SKazu Hirata       if (Instruction *OInst = dyn_cast<Instruction>(Op))
934bcbd26bfSFlorian Hahn         if (!SE.DT.dominates(OInst, IVIncInsertPos))
935bcbd26bfSFlorian Hahn           return false;
936bcbd26bfSFlorian Hahn   }
937bcbd26bfSFlorian Hahn   // Advance to the next instruction.
938bcbd26bfSFlorian Hahn   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
939bcbd26bfSFlorian Hahn   if (!IncV)
940bcbd26bfSFlorian Hahn     return false;
941bcbd26bfSFlorian Hahn 
942bcbd26bfSFlorian Hahn   if (IncV->mayHaveSideEffects())
943bcbd26bfSFlorian Hahn     return false;
944bcbd26bfSFlorian Hahn 
945bcbd26bfSFlorian Hahn   if (IncV == PN)
946bcbd26bfSFlorian Hahn     return true;
947bcbd26bfSFlorian Hahn 
948bcbd26bfSFlorian Hahn   return isNormalAddRecExprPHI(PN, IncV, L);
949bcbd26bfSFlorian Hahn }
950bcbd26bfSFlorian Hahn 
951bcbd26bfSFlorian Hahn /// getIVIncOperand returns an induction variable increment's induction
952bcbd26bfSFlorian Hahn /// variable operand.
953bcbd26bfSFlorian Hahn ///
954bcbd26bfSFlorian Hahn /// If allowScale is set, any type of GEP is allowed as long as the nonIV
955bcbd26bfSFlorian Hahn /// operands dominate InsertPos.
956bcbd26bfSFlorian Hahn ///
957bcbd26bfSFlorian Hahn /// If allowScale is not set, ensure that a GEP increment conforms to one of the
958bcbd26bfSFlorian Hahn /// simple patterns generated by getAddRecExprPHILiterally and
959bcbd26bfSFlorian Hahn /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
getIVIncOperand(Instruction * IncV,Instruction * InsertPos,bool allowScale)960bcbd26bfSFlorian Hahn Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
961bcbd26bfSFlorian Hahn                                            Instruction *InsertPos,
962bcbd26bfSFlorian Hahn                                            bool allowScale) {
963bcbd26bfSFlorian Hahn   if (IncV == InsertPos)
964bcbd26bfSFlorian Hahn     return nullptr;
965bcbd26bfSFlorian Hahn 
966bcbd26bfSFlorian Hahn   switch (IncV->getOpcode()) {
967bcbd26bfSFlorian Hahn   default:
968bcbd26bfSFlorian Hahn     return nullptr;
969bcbd26bfSFlorian Hahn   // Check for a simple Add/Sub or GEP of a loop invariant step.
970bcbd26bfSFlorian Hahn   case Instruction::Add:
971bcbd26bfSFlorian Hahn   case Instruction::Sub: {
972bcbd26bfSFlorian Hahn     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
973bcbd26bfSFlorian Hahn     if (!OInst || SE.DT.dominates(OInst, InsertPos))
974bcbd26bfSFlorian Hahn       return dyn_cast<Instruction>(IncV->getOperand(0));
975bcbd26bfSFlorian Hahn     return nullptr;
976bcbd26bfSFlorian Hahn   }
977bcbd26bfSFlorian Hahn   case Instruction::BitCast:
978bcbd26bfSFlorian Hahn     return dyn_cast<Instruction>(IncV->getOperand(0));
979bcbd26bfSFlorian Hahn   case Instruction::GetElementPtr:
9801d4a2f37SKazu Hirata     for (Use &U : llvm::drop_begin(IncV->operands())) {
9811d4a2f37SKazu Hirata       if (isa<Constant>(U))
982bcbd26bfSFlorian Hahn         continue;
9831d4a2f37SKazu Hirata       if (Instruction *OInst = dyn_cast<Instruction>(U)) {
984bcbd26bfSFlorian Hahn         if (!SE.DT.dominates(OInst, InsertPos))
985bcbd26bfSFlorian Hahn           return nullptr;
986bcbd26bfSFlorian Hahn       }
987bcbd26bfSFlorian Hahn       if (allowScale) {
988bcbd26bfSFlorian Hahn         // allow any kind of GEP as long as it can be hoisted.
989bcbd26bfSFlorian Hahn         continue;
990bcbd26bfSFlorian Hahn       }
991bcbd26bfSFlorian Hahn       // This must be a pointer addition of constants (pretty), which is already
992bcbd26bfSFlorian Hahn       // handled, or some number of address-size elements (ugly). Ugly geps
993bcbd26bfSFlorian Hahn       // have 2 operands. i1* is used by the expander to represent an
994bcbd26bfSFlorian Hahn       // address-size element.
995bcbd26bfSFlorian Hahn       if (IncV->getNumOperands() != 2)
996bcbd26bfSFlorian Hahn         return nullptr;
997bcbd26bfSFlorian Hahn       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
998bcbd26bfSFlorian Hahn       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
999bcbd26bfSFlorian Hahn           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
1000bcbd26bfSFlorian Hahn         return nullptr;
1001bcbd26bfSFlorian Hahn       break;
1002bcbd26bfSFlorian Hahn     }
1003bcbd26bfSFlorian Hahn     return dyn_cast<Instruction>(IncV->getOperand(0));
1004bcbd26bfSFlorian Hahn   }
1005bcbd26bfSFlorian Hahn }
1006bcbd26bfSFlorian Hahn 
1007bcbd26bfSFlorian Hahn /// If the insert point of the current builder or any of the builders on the
1008bcbd26bfSFlorian Hahn /// stack of saved builders has 'I' as its insert point, update it to point to
1009bcbd26bfSFlorian Hahn /// the instruction after 'I'.  This is intended to be used when the instruction
1010bcbd26bfSFlorian Hahn /// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
1011bcbd26bfSFlorian Hahn /// different block, the inconsistent insert point (with a mismatched
1012bcbd26bfSFlorian Hahn /// Instruction and Block) can lead to an instruction being inserted in a block
1013bcbd26bfSFlorian Hahn /// other than its parent.
fixupInsertPoints(Instruction * I)1014bcbd26bfSFlorian Hahn void SCEVExpander::fixupInsertPoints(Instruction *I) {
1015bcbd26bfSFlorian Hahn   BasicBlock::iterator It(*I);
1016bcbd26bfSFlorian Hahn   BasicBlock::iterator NewInsertPt = std::next(It);
1017bcbd26bfSFlorian Hahn   if (Builder.GetInsertPoint() == It)
1018bcbd26bfSFlorian Hahn     Builder.SetInsertPoint(&*NewInsertPt);
1019bcbd26bfSFlorian Hahn   for (auto *InsertPtGuard : InsertPointGuards)
1020bcbd26bfSFlorian Hahn     if (InsertPtGuard->GetInsertPoint() == It)
1021bcbd26bfSFlorian Hahn       InsertPtGuard->SetInsertPoint(NewInsertPt);
1022bcbd26bfSFlorian Hahn }
1023bcbd26bfSFlorian Hahn 
1024bcbd26bfSFlorian Hahn /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
1025bcbd26bfSFlorian Hahn /// it available to other uses in this loop. Recursively hoist any operands,
1026bcbd26bfSFlorian Hahn /// until we reach a value that dominates InsertPos.
hoistIVInc(Instruction * IncV,Instruction * InsertPos)1027bcbd26bfSFlorian Hahn bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
1028bcbd26bfSFlorian Hahn   if (SE.DT.dominates(IncV, InsertPos))
1029bcbd26bfSFlorian Hahn       return true;
1030bcbd26bfSFlorian Hahn 
1031bcbd26bfSFlorian Hahn   // InsertPos must itself dominate IncV so that IncV's new position satisfies
1032bcbd26bfSFlorian Hahn   // its existing users.
1033bcbd26bfSFlorian Hahn   if (isa<PHINode>(InsertPos) ||
1034bcbd26bfSFlorian Hahn       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
1035bcbd26bfSFlorian Hahn     return false;
1036bcbd26bfSFlorian Hahn 
1037bcbd26bfSFlorian Hahn   if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
1038bcbd26bfSFlorian Hahn     return false;
1039bcbd26bfSFlorian Hahn 
1040bcbd26bfSFlorian Hahn   // Check that the chain of IV operands leading back to Phi can be hoisted.
1041bcbd26bfSFlorian Hahn   SmallVector<Instruction*, 4> IVIncs;
1042bcbd26bfSFlorian Hahn   for(;;) {
1043bcbd26bfSFlorian Hahn     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
1044bcbd26bfSFlorian Hahn     if (!Oper)
1045bcbd26bfSFlorian Hahn       return false;
1046bcbd26bfSFlorian Hahn     // IncV is safe to hoist.
1047bcbd26bfSFlorian Hahn     IVIncs.push_back(IncV);
1048bcbd26bfSFlorian Hahn     IncV = Oper;
1049bcbd26bfSFlorian Hahn     if (SE.DT.dominates(IncV, InsertPos))
1050bcbd26bfSFlorian Hahn       break;
1051bcbd26bfSFlorian Hahn   }
10527787a8f1SKazu Hirata   for (Instruction *I : llvm::reverse(IVIncs)) {
10537787a8f1SKazu Hirata     fixupInsertPoints(I);
10547787a8f1SKazu Hirata     I->moveBefore(InsertPos);
1055bcbd26bfSFlorian Hahn   }
1056bcbd26bfSFlorian Hahn   return true;
1057bcbd26bfSFlorian Hahn }
1058bcbd26bfSFlorian Hahn 
1059bcbd26bfSFlorian Hahn /// Determine if this cyclic phi is in a form that would have been generated by
1060bcbd26bfSFlorian Hahn /// LSR. We don't care if the phi was actually expanded in this pass, as long
1061bcbd26bfSFlorian Hahn /// as it is in a low-cost form, for example, no implied multiplication. This
1062bcbd26bfSFlorian Hahn /// should match any patterns generated by getAddRecExprPHILiterally and
1063bcbd26bfSFlorian Hahn /// expandAddtoGEP.
isExpandedAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)1064bcbd26bfSFlorian Hahn bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
1065bcbd26bfSFlorian Hahn                                            const Loop *L) {
1066bcbd26bfSFlorian Hahn   for(Instruction *IVOper = IncV;
1067bcbd26bfSFlorian Hahn       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
1068bcbd26bfSFlorian Hahn                                 /*allowScale=*/false));) {
1069bcbd26bfSFlorian Hahn     if (IVOper == PN)
1070bcbd26bfSFlorian Hahn       return true;
1071bcbd26bfSFlorian Hahn   }
1072bcbd26bfSFlorian Hahn   return false;
1073bcbd26bfSFlorian Hahn }
1074bcbd26bfSFlorian Hahn 
1075bcbd26bfSFlorian Hahn /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1076bcbd26bfSFlorian Hahn /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1077bcbd26bfSFlorian Hahn /// need to materialize IV increments elsewhere to handle difficult situations.
expandIVInc(PHINode * PN,Value * StepV,const Loop * L,Type * ExpandTy,Type * IntTy,bool useSubtract)1078bcbd26bfSFlorian Hahn Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1079bcbd26bfSFlorian Hahn                                  Type *ExpandTy, Type *IntTy,
1080bcbd26bfSFlorian Hahn                                  bool useSubtract) {
1081bcbd26bfSFlorian Hahn   Value *IncV;
1082bcbd26bfSFlorian Hahn   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1083bcbd26bfSFlorian Hahn   if (ExpandTy->isPointerTy()) {
1084bcbd26bfSFlorian Hahn     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1085bcbd26bfSFlorian Hahn     // If the step isn't constant, don't use an implicitly scaled GEP, because
1086bcbd26bfSFlorian Hahn     // that would require a multiply inside the loop.
1087bcbd26bfSFlorian Hahn     if (!isa<ConstantInt>(StepV))
1088bcbd26bfSFlorian Hahn       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1089bcbd26bfSFlorian Hahn                                   GEPPtrTy->getAddressSpace());
1090bcbd26bfSFlorian Hahn     IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1091ecd3f853SFlorian Hahn     if (IncV->getType() != PN->getType())
1092bcbd26bfSFlorian Hahn       IncV = Builder.CreateBitCast(IncV, PN->getType());
1093bcbd26bfSFlorian Hahn   } else {
1094bcbd26bfSFlorian Hahn     IncV = useSubtract ?
1095bcbd26bfSFlorian Hahn       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1096bcbd26bfSFlorian Hahn       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1097bcbd26bfSFlorian Hahn   }
1098bcbd26bfSFlorian Hahn   return IncV;
1099bcbd26bfSFlorian Hahn }
1100bcbd26bfSFlorian Hahn 
1101bcbd26bfSFlorian Hahn /// Check whether we can cheaply express the requested SCEV in terms of
1102bcbd26bfSFlorian Hahn /// the available PHI SCEV by truncation and/or inversion of the step.
canBeCheaplyTransformed(ScalarEvolution & SE,const SCEVAddRecExpr * Phi,const SCEVAddRecExpr * Requested,bool & InvertStep)1103bcbd26bfSFlorian Hahn static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1104bcbd26bfSFlorian Hahn                                     const SCEVAddRecExpr *Phi,
1105bcbd26bfSFlorian Hahn                                     const SCEVAddRecExpr *Requested,
1106bcbd26bfSFlorian Hahn                                     bool &InvertStep) {
11079c4baf51SEli Friedman   // We can't transform to match a pointer PHI.
11089c4baf51SEli Friedman   if (Phi->getType()->isPointerTy())
11099c4baf51SEli Friedman     return false;
11109c4baf51SEli Friedman 
1111bcbd26bfSFlorian Hahn   Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1112bcbd26bfSFlorian Hahn   Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1113bcbd26bfSFlorian Hahn 
1114bcbd26bfSFlorian Hahn   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1115bcbd26bfSFlorian Hahn     return false;
1116bcbd26bfSFlorian Hahn 
1117bcbd26bfSFlorian Hahn   // Try truncate it if necessary.
1118bcbd26bfSFlorian Hahn   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1119bcbd26bfSFlorian Hahn   if (!Phi)
1120bcbd26bfSFlorian Hahn     return false;
1121bcbd26bfSFlorian Hahn 
1122bcbd26bfSFlorian Hahn   // Check whether truncation will help.
1123bcbd26bfSFlorian Hahn   if (Phi == Requested) {
1124bcbd26bfSFlorian Hahn     InvertStep = false;
1125bcbd26bfSFlorian Hahn     return true;
1126bcbd26bfSFlorian Hahn   }
1127bcbd26bfSFlorian Hahn 
1128bcbd26bfSFlorian Hahn   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
11299c4baf51SEli Friedman   if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
1130bcbd26bfSFlorian Hahn     InvertStep = true;
1131bcbd26bfSFlorian Hahn     return true;
1132bcbd26bfSFlorian Hahn   }
1133bcbd26bfSFlorian Hahn 
1134bcbd26bfSFlorian Hahn   return false;
1135bcbd26bfSFlorian Hahn }
1136bcbd26bfSFlorian Hahn 
IsIncrementNSW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1137bcbd26bfSFlorian Hahn static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1138bcbd26bfSFlorian Hahn   if (!isa<IntegerType>(AR->getType()))
1139bcbd26bfSFlorian Hahn     return false;
1140bcbd26bfSFlorian Hahn 
1141bcbd26bfSFlorian Hahn   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1142bcbd26bfSFlorian Hahn   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1143bcbd26bfSFlorian Hahn   const SCEV *Step = AR->getStepRecurrence(SE);
1144bcbd26bfSFlorian Hahn   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1145bcbd26bfSFlorian Hahn                                             SE.getSignExtendExpr(AR, WideTy));
1146bcbd26bfSFlorian Hahn   const SCEV *ExtendAfterOp =
1147bcbd26bfSFlorian Hahn     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1148bcbd26bfSFlorian Hahn   return ExtendAfterOp == OpAfterExtend;
1149bcbd26bfSFlorian Hahn }
1150bcbd26bfSFlorian Hahn 
IsIncrementNUW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1151bcbd26bfSFlorian Hahn static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1152bcbd26bfSFlorian Hahn   if (!isa<IntegerType>(AR->getType()))
1153bcbd26bfSFlorian Hahn     return false;
1154bcbd26bfSFlorian Hahn 
1155bcbd26bfSFlorian Hahn   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1156bcbd26bfSFlorian Hahn   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1157bcbd26bfSFlorian Hahn   const SCEV *Step = AR->getStepRecurrence(SE);
1158bcbd26bfSFlorian Hahn   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1159bcbd26bfSFlorian Hahn                                             SE.getZeroExtendExpr(AR, WideTy));
1160bcbd26bfSFlorian Hahn   const SCEV *ExtendAfterOp =
1161bcbd26bfSFlorian Hahn     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1162bcbd26bfSFlorian Hahn   return ExtendAfterOp == OpAfterExtend;
1163bcbd26bfSFlorian Hahn }
1164bcbd26bfSFlorian Hahn 
1165bcbd26bfSFlorian Hahn /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1166bcbd26bfSFlorian Hahn /// the base addrec, which is the addrec without any non-loop-dominating
1167bcbd26bfSFlorian Hahn /// values, and return the PHI.
1168bcbd26bfSFlorian Hahn PHINode *
getAddRecExprPHILiterally(const SCEVAddRecExpr * Normalized,const Loop * L,Type * ExpandTy,Type * IntTy,Type * & TruncTy,bool & InvertStep)1169bcbd26bfSFlorian Hahn SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1170bcbd26bfSFlorian Hahn                                         const Loop *L,
1171bcbd26bfSFlorian Hahn                                         Type *ExpandTy,
1172bcbd26bfSFlorian Hahn                                         Type *IntTy,
1173bcbd26bfSFlorian Hahn                                         Type *&TruncTy,
1174bcbd26bfSFlorian Hahn                                         bool &InvertStep) {
1175bcbd26bfSFlorian Hahn   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1176bcbd26bfSFlorian Hahn 
1177bcbd26bfSFlorian Hahn   // Reuse a previously-inserted PHI, if present.
1178bcbd26bfSFlorian Hahn   BasicBlock *LatchBlock = L->getLoopLatch();
1179bcbd26bfSFlorian Hahn   if (LatchBlock) {
1180bcbd26bfSFlorian Hahn     PHINode *AddRecPhiMatch = nullptr;
1181bcbd26bfSFlorian Hahn     Instruction *IncV = nullptr;
1182bcbd26bfSFlorian Hahn     TruncTy = nullptr;
1183bcbd26bfSFlorian Hahn     InvertStep = false;
1184bcbd26bfSFlorian Hahn 
1185bcbd26bfSFlorian Hahn     // Only try partially matching scevs that need truncation and/or
1186bcbd26bfSFlorian Hahn     // step-inversion if we know this loop is outside the current loop.
1187bcbd26bfSFlorian Hahn     bool TryNonMatchingSCEV =
1188bcbd26bfSFlorian Hahn         IVIncInsertLoop &&
1189bcbd26bfSFlorian Hahn         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1190bcbd26bfSFlorian Hahn 
1191bcbd26bfSFlorian Hahn     for (PHINode &PN : L->getHeader()->phis()) {
1192bcbd26bfSFlorian Hahn       if (!SE.isSCEVable(PN.getType()))
1193bcbd26bfSFlorian Hahn         continue;
1194bcbd26bfSFlorian Hahn 
11958c5edf50SChen Zheng       // We should not look for a incomplete PHI. Getting SCEV for a incomplete
11968c5edf50SChen Zheng       // PHI has no meaning at all.
11978c5edf50SChen Zheng       if (!PN.isComplete()) {
11981540da3bSNeil Henning         SCEV_DEBUG_WITH_TYPE(
11998c5edf50SChen Zheng             DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
12008c5edf50SChen Zheng         continue;
12018c5edf50SChen Zheng       }
12028c5edf50SChen Zheng 
1203bcbd26bfSFlorian Hahn       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1204bcbd26bfSFlorian Hahn       if (!PhiSCEV)
1205bcbd26bfSFlorian Hahn         continue;
1206bcbd26bfSFlorian Hahn 
1207bcbd26bfSFlorian Hahn       bool IsMatchingSCEV = PhiSCEV == Normalized;
1208bcbd26bfSFlorian Hahn       // We only handle truncation and inversion of phi recurrences for the
1209bcbd26bfSFlorian Hahn       // expanded expression if the expanded expression's loop dominates the
1210bcbd26bfSFlorian Hahn       // loop we insert to. Check now, so we can bail out early.
1211bcbd26bfSFlorian Hahn       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1212bcbd26bfSFlorian Hahn           continue;
1213bcbd26bfSFlorian Hahn 
1214bcbd26bfSFlorian Hahn       // TODO: this possibly can be reworked to avoid this cast at all.
1215bcbd26bfSFlorian Hahn       Instruction *TempIncV =
1216bcbd26bfSFlorian Hahn           dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
1217bcbd26bfSFlorian Hahn       if (!TempIncV)
1218bcbd26bfSFlorian Hahn         continue;
1219bcbd26bfSFlorian Hahn 
1220bcbd26bfSFlorian Hahn       // Check whether we can reuse this PHI node.
1221bcbd26bfSFlorian Hahn       if (LSRMode) {
1222bcbd26bfSFlorian Hahn         if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1223bcbd26bfSFlorian Hahn           continue;
1224bcbd26bfSFlorian Hahn       } else {
1225bcbd26bfSFlorian Hahn         if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1226bcbd26bfSFlorian Hahn           continue;
1227bcbd26bfSFlorian Hahn       }
1228bcbd26bfSFlorian Hahn 
1229bcbd26bfSFlorian Hahn       // Stop if we have found an exact match SCEV.
1230bcbd26bfSFlorian Hahn       if (IsMatchingSCEV) {
1231bcbd26bfSFlorian Hahn         IncV = TempIncV;
1232bcbd26bfSFlorian Hahn         TruncTy = nullptr;
1233bcbd26bfSFlorian Hahn         InvertStep = false;
1234bcbd26bfSFlorian Hahn         AddRecPhiMatch = &PN;
1235bcbd26bfSFlorian Hahn         break;
1236bcbd26bfSFlorian Hahn       }
1237bcbd26bfSFlorian Hahn 
1238bcbd26bfSFlorian Hahn       // Try whether the phi can be translated into the requested form
1239bcbd26bfSFlorian Hahn       // (truncated and/or offset by a constant).
1240bcbd26bfSFlorian Hahn       if ((!TruncTy || InvertStep) &&
1241bcbd26bfSFlorian Hahn           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1242bcbd26bfSFlorian Hahn         // Record the phi node. But don't stop we might find an exact match
1243bcbd26bfSFlorian Hahn         // later.
1244bcbd26bfSFlorian Hahn         AddRecPhiMatch = &PN;
1245bcbd26bfSFlorian Hahn         IncV = TempIncV;
1246bcbd26bfSFlorian Hahn         TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1247bcbd26bfSFlorian Hahn       }
1248bcbd26bfSFlorian Hahn     }
1249bcbd26bfSFlorian Hahn 
1250bcbd26bfSFlorian Hahn     if (AddRecPhiMatch) {
1251bcbd26bfSFlorian Hahn       // Ok, the add recurrence looks usable.
1252bcbd26bfSFlorian Hahn       // Remember this PHI, even in post-inc mode.
1253bcbd26bfSFlorian Hahn       InsertedValues.insert(AddRecPhiMatch);
1254bcbd26bfSFlorian Hahn       // Remember the increment.
1255bcbd26bfSFlorian Hahn       rememberInstruction(IncV);
12568eded24bSFlorian Hahn       // Those values were not actually inserted but re-used.
12578eded24bSFlorian Hahn       ReusedValues.insert(AddRecPhiMatch);
12588eded24bSFlorian Hahn       ReusedValues.insert(IncV);
1259bcbd26bfSFlorian Hahn       return AddRecPhiMatch;
1260bcbd26bfSFlorian Hahn     }
1261bcbd26bfSFlorian Hahn   }
1262bcbd26bfSFlorian Hahn 
1263bcbd26bfSFlorian Hahn   // Save the original insertion point so we can restore it when we're done.
1264bcbd26bfSFlorian Hahn   SCEVInsertPointGuard Guard(Builder, this);
1265bcbd26bfSFlorian Hahn 
1266bcbd26bfSFlorian Hahn   // Another AddRec may need to be recursively expanded below. For example, if
1267bcbd26bfSFlorian Hahn   // this AddRec is quadratic, the StepV may itself be an AddRec in this
1268bcbd26bfSFlorian Hahn   // loop. Remove this loop from the PostIncLoops set before expanding such
1269bcbd26bfSFlorian Hahn   // AddRecs. Otherwise, we cannot find a valid position for the step
1270bcbd26bfSFlorian Hahn   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1271bcbd26bfSFlorian Hahn   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1272bcbd26bfSFlorian Hahn   // so it's not worth implementing SmallPtrSet::swap.
1273bcbd26bfSFlorian Hahn   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1274bcbd26bfSFlorian Hahn   PostIncLoops.clear();
1275bcbd26bfSFlorian Hahn 
1276bcbd26bfSFlorian Hahn   // Expand code for the start value into the loop preheader.
1277bcbd26bfSFlorian Hahn   assert(L->getLoopPreheader() &&
1278bcbd26bfSFlorian Hahn          "Can't expand add recurrences without a loop preheader!");
1279f75564adSFlorian Hahn   Value *StartV =
1280f75564adSFlorian Hahn       expandCodeForImpl(Normalized->getStart(), ExpandTy,
1281f75564adSFlorian Hahn                         L->getLoopPreheader()->getTerminator(), false);
1282bcbd26bfSFlorian Hahn 
1283bcbd26bfSFlorian Hahn   // StartV must have been be inserted into L's preheader to dominate the new
1284bcbd26bfSFlorian Hahn   // phi.
1285bcbd26bfSFlorian Hahn   assert(!isa<Instruction>(StartV) ||
1286bcbd26bfSFlorian Hahn          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1287bcbd26bfSFlorian Hahn                                  L->getHeader()));
1288bcbd26bfSFlorian Hahn 
1289bcbd26bfSFlorian Hahn   // Expand code for the step value. Do this before creating the PHI so that PHI
1290bcbd26bfSFlorian Hahn   // reuse code doesn't see an incomplete PHI.
1291bcbd26bfSFlorian Hahn   const SCEV *Step = Normalized->getStepRecurrence(SE);
1292bcbd26bfSFlorian Hahn   // If the stride is negative, insert a sub instead of an add for the increment
1293bcbd26bfSFlorian Hahn   // (unless it's a constant, because subtracts of constants are canonicalized
1294bcbd26bfSFlorian Hahn   // to adds).
1295bcbd26bfSFlorian Hahn   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1296bcbd26bfSFlorian Hahn   if (useSubtract)
1297bcbd26bfSFlorian Hahn     Step = SE.getNegativeSCEV(Step);
1298bcbd26bfSFlorian Hahn   // Expand the step somewhere that dominates the loop header.
1299f75564adSFlorian Hahn   Value *StepV = expandCodeForImpl(
1300f75564adSFlorian Hahn       Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
1301bcbd26bfSFlorian Hahn 
1302bcbd26bfSFlorian Hahn   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1303bcbd26bfSFlorian Hahn   // we actually do emit an addition.  It does not apply if we emit a
1304bcbd26bfSFlorian Hahn   // subtraction.
1305bcbd26bfSFlorian Hahn   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1306bcbd26bfSFlorian Hahn   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1307bcbd26bfSFlorian Hahn 
1308bcbd26bfSFlorian Hahn   // Create the PHI.
1309bcbd26bfSFlorian Hahn   BasicBlock *Header = L->getHeader();
1310bcbd26bfSFlorian Hahn   Builder.SetInsertPoint(Header, Header->begin());
1311bcbd26bfSFlorian Hahn   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1312bcbd26bfSFlorian Hahn   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1313bcbd26bfSFlorian Hahn                                   Twine(IVName) + ".iv");
1314bcbd26bfSFlorian Hahn 
1315bcbd26bfSFlorian Hahn   // Create the step instructions and populate the PHI.
1316bcbd26bfSFlorian Hahn   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1317bcbd26bfSFlorian Hahn     BasicBlock *Pred = *HPI;
1318bcbd26bfSFlorian Hahn 
1319bcbd26bfSFlorian Hahn     // Add a start value.
1320bcbd26bfSFlorian Hahn     if (!L->contains(Pred)) {
1321bcbd26bfSFlorian Hahn       PN->addIncoming(StartV, Pred);
1322bcbd26bfSFlorian Hahn       continue;
1323bcbd26bfSFlorian Hahn     }
1324bcbd26bfSFlorian Hahn 
1325bcbd26bfSFlorian Hahn     // Create a step value and add it to the PHI.
1326bcbd26bfSFlorian Hahn     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1327bcbd26bfSFlorian Hahn     // instructions at IVIncInsertPos.
1328bcbd26bfSFlorian Hahn     Instruction *InsertPos = L == IVIncInsertLoop ?
1329bcbd26bfSFlorian Hahn       IVIncInsertPos : Pred->getTerminator();
1330bcbd26bfSFlorian Hahn     Builder.SetInsertPoint(InsertPos);
1331bcbd26bfSFlorian Hahn     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1332bcbd26bfSFlorian Hahn 
1333bcbd26bfSFlorian Hahn     if (isa<OverflowingBinaryOperator>(IncV)) {
1334bcbd26bfSFlorian Hahn       if (IncrementIsNUW)
1335bcbd26bfSFlorian Hahn         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1336bcbd26bfSFlorian Hahn       if (IncrementIsNSW)
1337bcbd26bfSFlorian Hahn         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1338bcbd26bfSFlorian Hahn     }
1339bcbd26bfSFlorian Hahn     PN->addIncoming(IncV, Pred);
1340bcbd26bfSFlorian Hahn   }
1341bcbd26bfSFlorian Hahn 
1342bcbd26bfSFlorian Hahn   // After expanding subexpressions, restore the PostIncLoops set so the caller
1343bcbd26bfSFlorian Hahn   // can ensure that IVIncrement dominates the current uses.
1344bcbd26bfSFlorian Hahn   PostIncLoops = SavedPostIncLoops;
1345bcbd26bfSFlorian Hahn 
13460ba85952SChris Jackson   // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
13470ba85952SChris Jackson   // effective when we are able to use an IV inserted here, so record it.
1348bcbd26bfSFlorian Hahn   InsertedValues.insert(PN);
13490ba85952SChris Jackson   InsertedIVs.push_back(PN);
1350bcbd26bfSFlorian Hahn   return PN;
1351bcbd26bfSFlorian Hahn }
1352bcbd26bfSFlorian Hahn 
expandAddRecExprLiterally(const SCEVAddRecExpr * S)1353bcbd26bfSFlorian Hahn Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1354bcbd26bfSFlorian Hahn   Type *STy = S->getType();
1355bcbd26bfSFlorian Hahn   Type *IntTy = SE.getEffectiveSCEVType(STy);
1356bcbd26bfSFlorian Hahn   const Loop *L = S->getLoop();
1357bcbd26bfSFlorian Hahn 
1358bcbd26bfSFlorian Hahn   // Determine a normalized form of this expression, which is the expression
1359bcbd26bfSFlorian Hahn   // before any post-inc adjustment is made.
1360bcbd26bfSFlorian Hahn   const SCEVAddRecExpr *Normalized = S;
1361bcbd26bfSFlorian Hahn   if (PostIncLoops.count(L)) {
1362bcbd26bfSFlorian Hahn     PostIncLoopSet Loops;
1363bcbd26bfSFlorian Hahn     Loops.insert(L);
1364bcbd26bfSFlorian Hahn     Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
1365bcbd26bfSFlorian Hahn   }
1366bcbd26bfSFlorian Hahn 
1367bcbd26bfSFlorian Hahn   // Strip off any non-loop-dominating component from the addrec start.
1368bcbd26bfSFlorian Hahn   const SCEV *Start = Normalized->getStart();
1369bcbd26bfSFlorian Hahn   const SCEV *PostLoopOffset = nullptr;
1370bcbd26bfSFlorian Hahn   if (!SE.properlyDominates(Start, L->getHeader())) {
1371bcbd26bfSFlorian Hahn     PostLoopOffset = Start;
1372bcbd26bfSFlorian Hahn     Start = SE.getConstant(Normalized->getType(), 0);
1373bcbd26bfSFlorian Hahn     Normalized = cast<SCEVAddRecExpr>(
1374bcbd26bfSFlorian Hahn       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1375bcbd26bfSFlorian Hahn                        Normalized->getLoop(),
1376bcbd26bfSFlorian Hahn                        Normalized->getNoWrapFlags(SCEV::FlagNW)));
1377bcbd26bfSFlorian Hahn   }
1378bcbd26bfSFlorian Hahn 
1379bcbd26bfSFlorian Hahn   // Strip off any non-loop-dominating component from the addrec step.
1380bcbd26bfSFlorian Hahn   const SCEV *Step = Normalized->getStepRecurrence(SE);
1381bcbd26bfSFlorian Hahn   const SCEV *PostLoopScale = nullptr;
1382bcbd26bfSFlorian Hahn   if (!SE.dominates(Step, L->getHeader())) {
1383bcbd26bfSFlorian Hahn     PostLoopScale = Step;
1384bcbd26bfSFlorian Hahn     Step = SE.getConstant(Normalized->getType(), 1);
1385bcbd26bfSFlorian Hahn     if (!Start->isZero()) {
1386bcbd26bfSFlorian Hahn         // The normalization below assumes that Start is constant zero, so if
1387bcbd26bfSFlorian Hahn         // it isn't re-associate Start to PostLoopOffset.
1388bcbd26bfSFlorian Hahn         assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1389bcbd26bfSFlorian Hahn         PostLoopOffset = Start;
1390bcbd26bfSFlorian Hahn         Start = SE.getConstant(Normalized->getType(), 0);
1391bcbd26bfSFlorian Hahn     }
1392bcbd26bfSFlorian Hahn     Normalized =
1393bcbd26bfSFlorian Hahn       cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1394bcbd26bfSFlorian Hahn                              Start, Step, Normalized->getLoop(),
1395bcbd26bfSFlorian Hahn                              Normalized->getNoWrapFlags(SCEV::FlagNW)));
1396bcbd26bfSFlorian Hahn   }
1397bcbd26bfSFlorian Hahn 
1398bcbd26bfSFlorian Hahn   // Expand the core addrec. If we need post-loop scaling, force it to
1399bcbd26bfSFlorian Hahn   // expand to an integer type to avoid the need for additional casting.
1400bcbd26bfSFlorian Hahn   Type *ExpandTy = PostLoopScale ? IntTy : STy;
1401bcbd26bfSFlorian Hahn   // We can't use a pointer type for the addrec if the pointer type is
1402bcbd26bfSFlorian Hahn   // non-integral.
1403bcbd26bfSFlorian Hahn   Type *AddRecPHIExpandTy =
1404bcbd26bfSFlorian Hahn       DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
1405bcbd26bfSFlorian Hahn 
1406bcbd26bfSFlorian Hahn   // In some cases, we decide to reuse an existing phi node but need to truncate
1407bcbd26bfSFlorian Hahn   // it and/or invert the step.
1408bcbd26bfSFlorian Hahn   Type *TruncTy = nullptr;
1409bcbd26bfSFlorian Hahn   bool InvertStep = false;
1410bcbd26bfSFlorian Hahn   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1411bcbd26bfSFlorian Hahn                                           IntTy, TruncTy, InvertStep);
1412bcbd26bfSFlorian Hahn 
1413bcbd26bfSFlorian Hahn   // Accommodate post-inc mode, if necessary.
1414bcbd26bfSFlorian Hahn   Value *Result;
1415bcbd26bfSFlorian Hahn   if (!PostIncLoops.count(L))
1416bcbd26bfSFlorian Hahn     Result = PN;
1417bcbd26bfSFlorian Hahn   else {
1418bcbd26bfSFlorian Hahn     // In PostInc mode, use the post-incremented value.
1419bcbd26bfSFlorian Hahn     BasicBlock *LatchBlock = L->getLoopLatch();
1420bcbd26bfSFlorian Hahn     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1421bcbd26bfSFlorian Hahn     Result = PN->getIncomingValueForBlock(LatchBlock);
1422bcbd26bfSFlorian Hahn 
1423835104a1SNikita Popov     // We might be introducing a new use of the post-inc IV that is not poison
1424835104a1SNikita Popov     // safe, in which case we should drop poison generating flags. Only keep
1425835104a1SNikita Popov     // those flags for which SCEV has proven that they always hold.
1426835104a1SNikita Popov     if (isa<OverflowingBinaryOperator>(Result)) {
1427835104a1SNikita Popov       auto *I = cast<Instruction>(Result);
1428835104a1SNikita Popov       if (!S->hasNoUnsignedWrap())
1429835104a1SNikita Popov         I->setHasNoUnsignedWrap(false);
1430835104a1SNikita Popov       if (!S->hasNoSignedWrap())
1431835104a1SNikita Popov         I->setHasNoSignedWrap(false);
1432835104a1SNikita Popov     }
1433835104a1SNikita Popov 
1434bcbd26bfSFlorian Hahn     // For an expansion to use the postinc form, the client must call
1435bcbd26bfSFlorian Hahn     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1436bcbd26bfSFlorian Hahn     // or dominated by IVIncInsertPos.
1437bcbd26bfSFlorian Hahn     if (isa<Instruction>(Result) &&
1438bcbd26bfSFlorian Hahn         !SE.DT.dominates(cast<Instruction>(Result),
1439bcbd26bfSFlorian Hahn                          &*Builder.GetInsertPoint())) {
1440bcbd26bfSFlorian Hahn       // The induction variable's postinc expansion does not dominate this use.
1441bcbd26bfSFlorian Hahn       // IVUsers tries to prevent this case, so it is rare. However, it can
1442bcbd26bfSFlorian Hahn       // happen when an IVUser outside the loop is not dominated by the latch
1443bcbd26bfSFlorian Hahn       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1444bcbd26bfSFlorian Hahn       // all cases. Consider a phi outside whose operand is replaced during
1445bcbd26bfSFlorian Hahn       // expansion with the value of the postinc user. Without fundamentally
1446bcbd26bfSFlorian Hahn       // changing the way postinc users are tracked, the only remedy is
1447bcbd26bfSFlorian Hahn       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1448bcbd26bfSFlorian Hahn       // but hopefully expandCodeFor handles that.
1449bcbd26bfSFlorian Hahn       bool useSubtract =
1450bcbd26bfSFlorian Hahn         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1451bcbd26bfSFlorian Hahn       if (useSubtract)
1452bcbd26bfSFlorian Hahn         Step = SE.getNegativeSCEV(Step);
1453bcbd26bfSFlorian Hahn       Value *StepV;
1454bcbd26bfSFlorian Hahn       {
1455bcbd26bfSFlorian Hahn         // Expand the step somewhere that dominates the loop header.
1456bcbd26bfSFlorian Hahn         SCEVInsertPointGuard Guard(Builder, this);
1457f75564adSFlorian Hahn         StepV = expandCodeForImpl(
1458f75564adSFlorian Hahn             Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
1459bcbd26bfSFlorian Hahn       }
1460bcbd26bfSFlorian Hahn       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1461bcbd26bfSFlorian Hahn     }
1462bcbd26bfSFlorian Hahn   }
1463bcbd26bfSFlorian Hahn 
1464bcbd26bfSFlorian Hahn   // We have decided to reuse an induction variable of a dominating loop. Apply
1465bcbd26bfSFlorian Hahn   // truncation and/or inversion of the step.
1466bcbd26bfSFlorian Hahn   if (TruncTy) {
1467bcbd26bfSFlorian Hahn     Type *ResTy = Result->getType();
1468bcbd26bfSFlorian Hahn     // Normalize the result type.
1469bcbd26bfSFlorian Hahn     if (ResTy != SE.getEffectiveSCEVType(ResTy))
1470bcbd26bfSFlorian Hahn       Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1471bcbd26bfSFlorian Hahn     // Truncate the result.
1472ecd3f853SFlorian Hahn     if (TruncTy != Result->getType())
1473bcbd26bfSFlorian Hahn       Result = Builder.CreateTrunc(Result, TruncTy);
1474ecd3f853SFlorian Hahn 
1475bcbd26bfSFlorian Hahn     // Invert the result.
1476ecd3f853SFlorian Hahn     if (InvertStep)
1477f75564adSFlorian Hahn       Result = Builder.CreateSub(
1478f75564adSFlorian Hahn           expandCodeForImpl(Normalized->getStart(), TruncTy, false), Result);
1479bcbd26bfSFlorian Hahn   }
1480bcbd26bfSFlorian Hahn 
1481bcbd26bfSFlorian Hahn   // Re-apply any non-loop-dominating scale.
1482bcbd26bfSFlorian Hahn   if (PostLoopScale) {
1483bcbd26bfSFlorian Hahn     assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1484bcbd26bfSFlorian Hahn     Result = InsertNoopCastOfTo(Result, IntTy);
1485bcbd26bfSFlorian Hahn     Result = Builder.CreateMul(Result,
1486f75564adSFlorian Hahn                                expandCodeForImpl(PostLoopScale, IntTy, false));
1487bcbd26bfSFlorian Hahn   }
1488bcbd26bfSFlorian Hahn 
1489bcbd26bfSFlorian Hahn   // Re-apply any non-loop-dominating offset.
1490bcbd26bfSFlorian Hahn   if (PostLoopOffset) {
1491bcbd26bfSFlorian Hahn     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1492bcbd26bfSFlorian Hahn       if (Result->getType()->isIntegerTy()) {
1493f75564adSFlorian Hahn         Value *Base = expandCodeForImpl(PostLoopOffset, ExpandTy, false);
1494bcbd26bfSFlorian Hahn         Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
1495bcbd26bfSFlorian Hahn       } else {
1496bcbd26bfSFlorian Hahn         Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
1497bcbd26bfSFlorian Hahn       }
1498bcbd26bfSFlorian Hahn     } else {
1499bcbd26bfSFlorian Hahn       Result = InsertNoopCastOfTo(Result, IntTy);
1500f75564adSFlorian Hahn       Result = Builder.CreateAdd(
1501f75564adSFlorian Hahn           Result, expandCodeForImpl(PostLoopOffset, IntTy, false));
1502bcbd26bfSFlorian Hahn     }
1503bcbd26bfSFlorian Hahn   }
1504bcbd26bfSFlorian Hahn 
1505bcbd26bfSFlorian Hahn   return Result;
1506bcbd26bfSFlorian Hahn }
1507bcbd26bfSFlorian Hahn 
visitAddRecExpr(const SCEVAddRecExpr * S)1508bcbd26bfSFlorian Hahn Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1509bcbd26bfSFlorian Hahn   // In canonical mode we compute the addrec as an expression of a canonical IV
1510bcbd26bfSFlorian Hahn   // using evaluateAtIteration and expand the resulting SCEV expression. This
1511bcbd26bfSFlorian Hahn   // way we avoid introducing new IVs to carry on the comutation of the addrec
1512bcbd26bfSFlorian Hahn   // throughout the loop.
1513bcbd26bfSFlorian Hahn   //
1514bcbd26bfSFlorian Hahn   // For nested addrecs evaluateAtIteration might need a canonical IV of a
1515bcbd26bfSFlorian Hahn   // type wider than the addrec itself. Emitting a canonical IV of the
1516bcbd26bfSFlorian Hahn   // proper type might produce non-legal types, for example expanding an i64
1517bcbd26bfSFlorian Hahn   // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1518bcbd26bfSFlorian Hahn   // back to non-canonical mode for nested addrecs.
1519bcbd26bfSFlorian Hahn   if (!CanonicalMode || (S->getNumOperands() > 2))
1520bcbd26bfSFlorian Hahn     return expandAddRecExprLiterally(S);
1521bcbd26bfSFlorian Hahn 
1522bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1523bcbd26bfSFlorian Hahn   const Loop *L = S->getLoop();
1524bcbd26bfSFlorian Hahn 
1525bcbd26bfSFlorian Hahn   // First check for an existing canonical IV in a suitable type.
1526bcbd26bfSFlorian Hahn   PHINode *CanonicalIV = nullptr;
1527bcbd26bfSFlorian Hahn   if (PHINode *PN = L->getCanonicalInductionVariable())
1528bcbd26bfSFlorian Hahn     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1529bcbd26bfSFlorian Hahn       CanonicalIV = PN;
1530bcbd26bfSFlorian Hahn 
1531bcbd26bfSFlorian Hahn   // Rewrite an AddRec in terms of the canonical induction variable, if
1532bcbd26bfSFlorian Hahn   // its type is more narrow.
1533bcbd26bfSFlorian Hahn   if (CanonicalIV &&
15349c4baf51SEli Friedman       SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
15359c4baf51SEli Friedman       !S->getType()->isPointerTy()) {
1536bcbd26bfSFlorian Hahn     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1537bcbd26bfSFlorian Hahn     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1538bcbd26bfSFlorian Hahn       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1539bcbd26bfSFlorian Hahn     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1540bcbd26bfSFlorian Hahn                                        S->getNoWrapFlags(SCEV::FlagNW)));
1541bcbd26bfSFlorian Hahn     BasicBlock::iterator NewInsertPt =
1542c70f0b9dSFlorian Hahn         findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1543f75564adSFlorian Hahn     V = expandCodeForImpl(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1544f75564adSFlorian Hahn                           &*NewInsertPt, false);
1545bcbd26bfSFlorian Hahn     return V;
1546bcbd26bfSFlorian Hahn   }
1547bcbd26bfSFlorian Hahn 
1548bcbd26bfSFlorian Hahn   // {X,+,F} --> X + {0,+,F}
1549bcbd26bfSFlorian Hahn   if (!S->getStart()->isZero()) {
15509f787378SNikita Popov     if (PointerType *PTy = dyn_cast<PointerType>(S->getType())) {
15519f787378SNikita Popov       Value *StartV = expand(SE.getPointerBase(S));
15529f787378SNikita Popov       assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
15539f787378SNikita Popov       return expandAddToGEP(SE.removePointerBase(S), PTy, Ty, StartV);
15549f787378SNikita Popov     }
15559f787378SNikita Popov 
155616d20e25SKazu Hirata     SmallVector<const SCEV *, 4> NewOps(S->operands());
1557bcbd26bfSFlorian Hahn     NewOps[0] = SE.getConstant(Ty, 0);
1558bcbd26bfSFlorian Hahn     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1559bcbd26bfSFlorian Hahn                                         S->getNoWrapFlags(SCEV::FlagNW));
1560bcbd26bfSFlorian Hahn 
1561bcbd26bfSFlorian Hahn     // Just do a normal add. Pre-expand the operands to suppress folding.
1562bcbd26bfSFlorian Hahn     //
1563bcbd26bfSFlorian Hahn     // The LHS and RHS values are factored out of the expand call to make the
1564bcbd26bfSFlorian Hahn     // output independent of the argument evaluation order.
1565bcbd26bfSFlorian Hahn     const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1566bcbd26bfSFlorian Hahn     const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1567bcbd26bfSFlorian Hahn     return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1568bcbd26bfSFlorian Hahn   }
1569bcbd26bfSFlorian Hahn 
1570bcbd26bfSFlorian Hahn   // If we don't yet have a canonical IV, create one.
1571bcbd26bfSFlorian Hahn   if (!CanonicalIV) {
1572bcbd26bfSFlorian Hahn     // Create and insert the PHI node for the induction variable in the
1573bcbd26bfSFlorian Hahn     // specified loop.
1574bcbd26bfSFlorian Hahn     BasicBlock *Header = L->getHeader();
1575bcbd26bfSFlorian Hahn     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1576bcbd26bfSFlorian Hahn     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1577bcbd26bfSFlorian Hahn                                   &Header->front());
1578bcbd26bfSFlorian Hahn     rememberInstruction(CanonicalIV);
1579bcbd26bfSFlorian Hahn 
1580bcbd26bfSFlorian Hahn     SmallSet<BasicBlock *, 4> PredSeen;
1581bcbd26bfSFlorian Hahn     Constant *One = ConstantInt::get(Ty, 1);
1582bcbd26bfSFlorian Hahn     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1583bcbd26bfSFlorian Hahn       BasicBlock *HP = *HPI;
1584bcbd26bfSFlorian Hahn       if (!PredSeen.insert(HP).second) {
1585bcbd26bfSFlorian Hahn         // There must be an incoming value for each predecessor, even the
1586bcbd26bfSFlorian Hahn         // duplicates!
1587bcbd26bfSFlorian Hahn         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1588bcbd26bfSFlorian Hahn         continue;
1589bcbd26bfSFlorian Hahn       }
1590bcbd26bfSFlorian Hahn 
1591bcbd26bfSFlorian Hahn       if (L->contains(HP)) {
1592bcbd26bfSFlorian Hahn         // Insert a unit add instruction right before the terminator
1593bcbd26bfSFlorian Hahn         // corresponding to the back-edge.
1594bcbd26bfSFlorian Hahn         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1595bcbd26bfSFlorian Hahn                                                      "indvar.next",
1596bcbd26bfSFlorian Hahn                                                      HP->getTerminator());
1597bcbd26bfSFlorian Hahn         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1598bcbd26bfSFlorian Hahn         rememberInstruction(Add);
1599bcbd26bfSFlorian Hahn         CanonicalIV->addIncoming(Add, HP);
1600bcbd26bfSFlorian Hahn       } else {
1601bcbd26bfSFlorian Hahn         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1602bcbd26bfSFlorian Hahn       }
1603bcbd26bfSFlorian Hahn     }
1604bcbd26bfSFlorian Hahn   }
1605bcbd26bfSFlorian Hahn 
1606bcbd26bfSFlorian Hahn   // {0,+,1} --> Insert a canonical induction variable into the loop!
1607bcbd26bfSFlorian Hahn   if (S->isAffine() && S->getOperand(1)->isOne()) {
1608bcbd26bfSFlorian Hahn     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1609bcbd26bfSFlorian Hahn            "IVs with types different from the canonical IV should "
1610bcbd26bfSFlorian Hahn            "already have been handled!");
1611bcbd26bfSFlorian Hahn     return CanonicalIV;
1612bcbd26bfSFlorian Hahn   }
1613bcbd26bfSFlorian Hahn 
1614bcbd26bfSFlorian Hahn   // {0,+,F} --> {0,+,1} * F
1615bcbd26bfSFlorian Hahn 
1616bcbd26bfSFlorian Hahn   // If this is a simple linear addrec, emit it now as a special case.
1617bcbd26bfSFlorian Hahn   if (S->isAffine())    // {0,+,F} --> i*F
1618bcbd26bfSFlorian Hahn     return
1619bcbd26bfSFlorian Hahn       expand(SE.getTruncateOrNoop(
1620bcbd26bfSFlorian Hahn         SE.getMulExpr(SE.getUnknown(CanonicalIV),
1621bcbd26bfSFlorian Hahn                       SE.getNoopOrAnyExtend(S->getOperand(1),
1622bcbd26bfSFlorian Hahn                                             CanonicalIV->getType())),
1623bcbd26bfSFlorian Hahn         Ty));
1624bcbd26bfSFlorian Hahn 
1625bcbd26bfSFlorian Hahn   // If this is a chain of recurrences, turn it into a closed form, using the
1626bcbd26bfSFlorian Hahn   // folders, then expandCodeFor the closed form.  This allows the folders to
1627bcbd26bfSFlorian Hahn   // simplify the expression without having to build a bunch of special code
1628bcbd26bfSFlorian Hahn   // into this folder.
1629bcbd26bfSFlorian Hahn   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
1630bcbd26bfSFlorian Hahn 
1631bcbd26bfSFlorian Hahn   // Promote S up to the canonical IV type, if the cast is foldable.
1632bcbd26bfSFlorian Hahn   const SCEV *NewS = S;
1633bcbd26bfSFlorian Hahn   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1634bcbd26bfSFlorian Hahn   if (isa<SCEVAddRecExpr>(Ext))
1635bcbd26bfSFlorian Hahn     NewS = Ext;
1636bcbd26bfSFlorian Hahn 
1637bcbd26bfSFlorian Hahn   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1638bcbd26bfSFlorian Hahn 
1639bcbd26bfSFlorian Hahn   // Truncate the result down to the original type, if needed.
1640bcbd26bfSFlorian Hahn   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1641bcbd26bfSFlorian Hahn   return expand(T);
1642bcbd26bfSFlorian Hahn }
1643bcbd26bfSFlorian Hahn 
visitPtrToIntExpr(const SCEVPtrToIntExpr * S)164481fc53a3SRoman Lebedev Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
164581fc53a3SRoman Lebedev   Value *V =
164681fc53a3SRoman Lebedev       expandCodeForImpl(S->getOperand(), S->getOperand()->getType(), false);
1647ecc9d7e9SRoman Lebedev   return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1648ecc9d7e9SRoman Lebedev                            GetOptimalInsertionPointForCastOf(V));
164981fc53a3SRoman Lebedev }
165081fc53a3SRoman Lebedev 
visitTruncateExpr(const SCEVTruncateExpr * S)1651bcbd26bfSFlorian Hahn Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1652bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1653f75564adSFlorian Hahn   Value *V = expandCodeForImpl(
1654f75564adSFlorian Hahn       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1655f75564adSFlorian Hahn       false);
1656ecd3f853SFlorian Hahn   return Builder.CreateTrunc(V, Ty);
1657bcbd26bfSFlorian Hahn }
1658bcbd26bfSFlorian Hahn 
visitZeroExtendExpr(const SCEVZeroExtendExpr * S)1659bcbd26bfSFlorian Hahn Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1660bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1661f75564adSFlorian Hahn   Value *V = expandCodeForImpl(
1662f75564adSFlorian Hahn       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1663f75564adSFlorian Hahn       false);
1664ecd3f853SFlorian Hahn   return Builder.CreateZExt(V, Ty);
1665bcbd26bfSFlorian Hahn }
1666bcbd26bfSFlorian Hahn 
visitSignExtendExpr(const SCEVSignExtendExpr * S)1667bcbd26bfSFlorian Hahn Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1668bcbd26bfSFlorian Hahn   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1669f75564adSFlorian Hahn   Value *V = expandCodeForImpl(
1670f75564adSFlorian Hahn       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1671f75564adSFlorian Hahn       false);
1672ecd3f853SFlorian Hahn   return Builder.CreateSExt(V, Ty);
1673bcbd26bfSFlorian Hahn }
1674bcbd26bfSFlorian Hahn 
expandMinMaxExpr(const SCEVNAryExpr * S,Intrinsic::ID IntrinID,Twine Name,bool IsSequential)1675c1bb4a88SNikita Popov Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S,
1676e9a1c82dSNikita Popov                                       Intrinsic::ID IntrinID, Twine Name,
1677e9a1c82dSNikita Popov                                       bool IsSequential) {
1678bcbd26bfSFlorian Hahn   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1679bcbd26bfSFlorian Hahn   Type *Ty = LHS->getType();
1680e9a1c82dSNikita Popov   if (IsSequential)
1681e9a1c82dSNikita Popov     LHS = Builder.CreateFreeze(LHS);
1682bcbd26bfSFlorian Hahn   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1683f75564adSFlorian Hahn     Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
1684e9a1c82dSNikita Popov     if (IsSequential && i != 0)
1685e9a1c82dSNikita Popov       RHS = Builder.CreateFreeze(RHS);
1686b46c085dSRoman Lebedev     Value *Sel;
1687b46c085dSRoman Lebedev     if (Ty->isIntegerTy())
1688c1bb4a88SNikita Popov       Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1689c1bb4a88SNikita Popov                                     /*FMFSource=*/nullptr, Name);
1690b46c085dSRoman Lebedev     else {
1691c1bb4a88SNikita Popov       Value *ICmp =
1692c1bb4a88SNikita Popov           Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1693c1bb4a88SNikita Popov       Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1694b46c085dSRoman Lebedev     }
1695bcbd26bfSFlorian Hahn     LHS = Sel;
1696bcbd26bfSFlorian Hahn   }
1697bcbd26bfSFlorian Hahn   return LHS;
1698bcbd26bfSFlorian Hahn }
1699bcbd26bfSFlorian Hahn 
visitSMaxExpr(const SCEVSMaxExpr * S)170082fb4f4bSRoman Lebedev Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1701c1bb4a88SNikita Popov   return expandMinMaxExpr(S, Intrinsic::smax, "smax");
170282fb4f4bSRoman Lebedev }
170382fb4f4bSRoman Lebedev 
visitUMaxExpr(const SCEVUMaxExpr * S)170482fb4f4bSRoman Lebedev Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1705c1bb4a88SNikita Popov   return expandMinMaxExpr(S, Intrinsic::umax, "umax");
170682fb4f4bSRoman Lebedev }
170782fb4f4bSRoman Lebedev 
visitSMinExpr(const SCEVSMinExpr * S)170882fb4f4bSRoman Lebedev Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1709c1bb4a88SNikita Popov   return expandMinMaxExpr(S, Intrinsic::smin, "smin");
171082fb4f4bSRoman Lebedev }
171182fb4f4bSRoman Lebedev 
visitUMinExpr(const SCEVUMinExpr * S)171282fb4f4bSRoman Lebedev Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1713c1bb4a88SNikita Popov   return expandMinMaxExpr(S, Intrinsic::umin, "umin");
171482fb4f4bSRoman Lebedev }
171582fb4f4bSRoman Lebedev 
visitSequentialUMinExpr(const SCEVSequentialUMinExpr * S)171682fb4f4bSRoman Lebedev Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
1717e9a1c82dSNikita Popov   return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true);
171882fb4f4bSRoman Lebedev }
171982fb4f4bSRoman Lebedev 
expandCodeForImpl(const SCEV * SH,Type * Ty,Instruction * IP,bool Root)1720f75564adSFlorian Hahn Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty,
1721f75564adSFlorian Hahn                                        Instruction *IP, bool Root) {
1722bcbd26bfSFlorian Hahn   setInsertPoint(IP);
1723f75564adSFlorian Hahn   Value *V = expandCodeForImpl(SH, Ty, Root);
1724f75564adSFlorian Hahn   return V;
1725bcbd26bfSFlorian Hahn }
1726bcbd26bfSFlorian Hahn 
expandCodeForImpl(const SCEV * SH,Type * Ty,bool Root)1727f75564adSFlorian Hahn Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty, bool Root) {
1728bcbd26bfSFlorian Hahn   // Expand the code for this SCEV.
1729bcbd26bfSFlorian Hahn   Value *V = expand(SH);
1730f75564adSFlorian Hahn 
1731f75564adSFlorian Hahn   if (PreserveLCSSA) {
1732f75564adSFlorian Hahn     if (auto *Inst = dyn_cast<Instruction>(V)) {
1733f75564adSFlorian Hahn       // Create a temporary instruction to at the current insertion point, so we
1734f75564adSFlorian Hahn       // can hand it off to the helper to create LCSSA PHIs if required for the
1735f75564adSFlorian Hahn       // new use.
1736f75564adSFlorian Hahn       // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
1737f75564adSFlorian Hahn       // would accept a insertion point and return an LCSSA phi for that
1738f75564adSFlorian Hahn       // insertion point, so there is no need to insert & remove the temporary
1739f75564adSFlorian Hahn       // instruction.
1740f75564adSFlorian Hahn       Instruction *Tmp;
1741f75564adSFlorian Hahn       if (Inst->getType()->isIntegerTy())
17422d67a86bSFlorian Hahn         Tmp = cast<Instruction>(Builder.CreateIntToPtr(
17432d67a86bSFlorian Hahn             Inst, Inst->getType()->getPointerTo(), "tmp.lcssa.user"));
1744f75564adSFlorian Hahn       else {
1745f75564adSFlorian Hahn         assert(Inst->getType()->isPointerTy());
17462983053dSArthur Eubanks         Tmp = cast<Instruction>(Builder.CreatePtrToInt(
17472983053dSArthur Eubanks             Inst, Type::getInt32Ty(Inst->getContext()), "tmp.lcssa.user"));
1748f75564adSFlorian Hahn       }
1749f75564adSFlorian Hahn       V = fixupLCSSAFormFor(Tmp, 0);
1750f75564adSFlorian Hahn 
1751f75564adSFlorian Hahn       // Clean up temporary instruction.
1752f75564adSFlorian Hahn       InsertedValues.erase(Tmp);
1753f75564adSFlorian Hahn       InsertedPostIncValues.erase(Tmp);
1754f75564adSFlorian Hahn       Tmp->eraseFromParent();
1755f75564adSFlorian Hahn     }
1756f75564adSFlorian Hahn   }
1757f75564adSFlorian Hahn 
1758f75564adSFlorian Hahn   InsertedExpressions[std::make_pair(SH, &*Builder.GetInsertPoint())] = V;
1759bcbd26bfSFlorian Hahn   if (Ty) {
1760bcbd26bfSFlorian Hahn     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1761bcbd26bfSFlorian Hahn            "non-trivial casts should be done with the SCEVs directly!");
1762bcbd26bfSFlorian Hahn     V = InsertNoopCastOfTo(V, Ty);
1763bcbd26bfSFlorian Hahn   }
1764bcbd26bfSFlorian Hahn   return V;
1765bcbd26bfSFlorian Hahn }
1766bcbd26bfSFlorian Hahn 
FindValueInExprValueMap(const SCEV * S,const Instruction * InsertPt)1767d9715a72SNikita Popov Value *SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1768bcbd26bfSFlorian Hahn                                              const Instruction *InsertPt) {
1769bcbd26bfSFlorian Hahn   // If the expansion is not in CanonicalMode, and the SCEV contains any
1770bcbd26bfSFlorian Hahn   // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
177116a2d5f8SNikita Popov   if (!CanonicalMode && SE.containsAddRecurrence(S))
177216a2d5f8SNikita Popov     return nullptr;
177316a2d5f8SNikita Popov 
177416a2d5f8SNikita Popov   // If S is a constant, it may be worse to reuse an existing Value.
177516a2d5f8SNikita Popov   if (isa<SCEVConstant>(S))
177616a2d5f8SNikita Popov     return nullptr;
177716a2d5f8SNikita Popov 
1778477551fdSNikita Popov   // Choose a Value from the set which dominates the InsertPt.
1779477551fdSNikita Popov   // InsertPt should be inside the Value's parent loop so as not to break
1780bcbd26bfSFlorian Hahn   // the LCSSA form.
178116a2d5f8SNikita Popov   for (Value *V : SE.getSCEVValues(S)) {
17822d0fc3e4SNikita Popov     Instruction *EntInst = dyn_cast<Instruction>(V);
1783477551fdSNikita Popov     if (!EntInst)
1784477551fdSNikita Popov       continue;
1785477551fdSNikita Popov 
1786477551fdSNikita Popov     assert(EntInst->getFunction() == InsertPt->getFunction());
1787477551fdSNikita Popov     if (S->getType() == V->getType() &&
1788bcbd26bfSFlorian Hahn         SE.DT.dominates(EntInst, InsertPt) &&
1789bcbd26bfSFlorian Hahn         (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
17908906a0feSPhilip Reames          SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1791d9715a72SNikita Popov       return V;
1792bcbd26bfSFlorian Hahn   }
1793d9715a72SNikita Popov   return nullptr;
1794bcbd26bfSFlorian Hahn }
1795bcbd26bfSFlorian Hahn 
1796bcbd26bfSFlorian Hahn // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1797bcbd26bfSFlorian Hahn // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1798bcbd26bfSFlorian Hahn // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1799bcbd26bfSFlorian Hahn // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1800bcbd26bfSFlorian Hahn // the expansion will try to reuse Value from ExprValueMap, and only when it
1801bcbd26bfSFlorian Hahn // fails, expand the SCEV literally.
expand(const SCEV * S)1802bcbd26bfSFlorian Hahn Value *SCEVExpander::expand(const SCEV *S) {
1803bcbd26bfSFlorian Hahn   // Compute an insertion point for this SCEV object. Hoist the instructions
1804bcbd26bfSFlorian Hahn   // as far out in the loop nest as possible.
1805bcbd26bfSFlorian Hahn   Instruction *InsertPt = &*Builder.GetInsertPoint();
1806bcbd26bfSFlorian Hahn 
1807bcbd26bfSFlorian Hahn   // We can move insertion point only if there is no div or rem operations
1808bcbd26bfSFlorian Hahn   // otherwise we are risky to move it over the check for zero denominator.
1809bcbd26bfSFlorian Hahn   auto SafeToHoist = [](const SCEV *S) {
1810bcbd26bfSFlorian Hahn     return !SCEVExprContains(S, [](const SCEV *S) {
1811bcbd26bfSFlorian Hahn               if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1812bcbd26bfSFlorian Hahn                 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1813bcbd26bfSFlorian Hahn                   // Division by non-zero constants can be hoisted.
1814bcbd26bfSFlorian Hahn                   return SC->getValue()->isZero();
1815bcbd26bfSFlorian Hahn                 // All other divisions should not be moved as they may be
1816bcbd26bfSFlorian Hahn                 // divisions by zero and should be kept within the
1817bcbd26bfSFlorian Hahn                 // conditions of the surrounding loops that guard their
1818bcbd26bfSFlorian Hahn                 // execution (see PR35406).
1819bcbd26bfSFlorian Hahn                 return true;
1820bcbd26bfSFlorian Hahn               }
1821bcbd26bfSFlorian Hahn               return false;
1822bcbd26bfSFlorian Hahn             });
1823bcbd26bfSFlorian Hahn   };
1824bcbd26bfSFlorian Hahn   if (SafeToHoist(S)) {
1825bcbd26bfSFlorian Hahn     for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1826bcbd26bfSFlorian Hahn          L = L->getParentLoop()) {
1827bcbd26bfSFlorian Hahn       if (SE.isLoopInvariant(S, L)) {
1828bcbd26bfSFlorian Hahn         if (!L) break;
1829bcbd26bfSFlorian Hahn         if (BasicBlock *Preheader = L->getLoopPreheader())
1830bcbd26bfSFlorian Hahn           InsertPt = Preheader->getTerminator();
1831bcbd26bfSFlorian Hahn         else
1832bcbd26bfSFlorian Hahn           // LSR sets the insertion point for AddRec start/step values to the
1833bcbd26bfSFlorian Hahn           // block start to simplify value reuse, even though it's an invalid
1834bcbd26bfSFlorian Hahn           // position. SCEVExpander must correct for this in all cases.
1835bcbd26bfSFlorian Hahn           InsertPt = &*L->getHeader()->getFirstInsertionPt();
1836bcbd26bfSFlorian Hahn       } else {
1837bcbd26bfSFlorian Hahn         // If the SCEV is computable at this level, insert it into the header
1838bcbd26bfSFlorian Hahn         // after the PHIs (and after any other instructions that we've inserted
1839bcbd26bfSFlorian Hahn         // there) so that it is guaranteed to dominate any user inside the loop.
1840bcbd26bfSFlorian Hahn         if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1841bcbd26bfSFlorian Hahn           InsertPt = &*L->getHeader()->getFirstInsertionPt();
18428eded24bSFlorian Hahn 
1843bcbd26bfSFlorian Hahn         while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1844bcbd26bfSFlorian Hahn                (isInsertedInstruction(InsertPt) ||
18458eded24bSFlorian Hahn                 isa<DbgInfoIntrinsic>(InsertPt))) {
1846bcbd26bfSFlorian Hahn           InsertPt = &*std::next(InsertPt->getIterator());
18478eded24bSFlorian Hahn         }
1848bcbd26bfSFlorian Hahn         break;
1849bcbd26bfSFlorian Hahn       }
1850bcbd26bfSFlorian Hahn     }
1851bcbd26bfSFlorian Hahn   }
1852bcbd26bfSFlorian Hahn 
1853bcbd26bfSFlorian Hahn   // Check to see if we already expanded this here.
1854bcbd26bfSFlorian Hahn   auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1855bcbd26bfSFlorian Hahn   if (I != InsertedExpressions.end())
1856bcbd26bfSFlorian Hahn     return I->second;
1857bcbd26bfSFlorian Hahn 
1858bcbd26bfSFlorian Hahn   SCEVInsertPointGuard Guard(Builder, this);
1859bcbd26bfSFlorian Hahn   Builder.SetInsertPoint(InsertPt);
1860bcbd26bfSFlorian Hahn 
1861bcbd26bfSFlorian Hahn   // Expand the expression into instructions.
1862d9715a72SNikita Popov   Value *V = FindValueInExprValueMap(S, InsertPt);
1863bcbd26bfSFlorian Hahn   if (!V)
1864bcbd26bfSFlorian Hahn     V = visit(S);
18658906a0feSPhilip Reames   else {
18668906a0feSPhilip Reames     // If we're reusing an existing instruction, we are effectively CSEing two
18678906a0feSPhilip Reames     // copies of the instruction (with potentially different flags).  As such,
18688906a0feSPhilip Reames     // we need to drop any poison generating flags unless we can prove that
18698906a0feSPhilip Reames     // said flags must be valid for all new users.
18708906a0feSPhilip Reames     if (auto *I = dyn_cast<Instruction>(V))
18718906a0feSPhilip Reames       if (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I))
18728906a0feSPhilip Reames         I->dropPoisonGeneratingFlags();
18738906a0feSPhilip Reames   }
1874bcbd26bfSFlorian Hahn   // Remember the expanded value for this SCEV at this location.
1875bcbd26bfSFlorian Hahn   //
1876bcbd26bfSFlorian Hahn   // This is independent of PostIncLoops. The mapped value simply materializes
1877bcbd26bfSFlorian Hahn   // the expression at this insertion point. If the mapped value happened to be
1878bcbd26bfSFlorian Hahn   // a postinc expansion, it could be reused by a non-postinc user, but only if
1879bcbd26bfSFlorian Hahn   // its insertion point was already at the head of the loop.
1880bcbd26bfSFlorian Hahn   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1881bcbd26bfSFlorian Hahn   return V;
1882bcbd26bfSFlorian Hahn }
1883bcbd26bfSFlorian Hahn 
rememberInstruction(Value * I)1884bcbd26bfSFlorian Hahn void SCEVExpander::rememberInstruction(Value *I) {
1885f75564adSFlorian Hahn   auto DoInsert = [this](Value *V) {
1886bcbd26bfSFlorian Hahn     if (!PostIncLoops.empty())
1887f75564adSFlorian Hahn       InsertedPostIncValues.insert(V);
1888bcbd26bfSFlorian Hahn     else
1889f75564adSFlorian Hahn       InsertedValues.insert(V);
1890f75564adSFlorian Hahn   };
1891f75564adSFlorian Hahn   DoInsert(I);
1892f75564adSFlorian Hahn 
1893f75564adSFlorian Hahn   if (!PreserveLCSSA)
1894f75564adSFlorian Hahn     return;
1895f75564adSFlorian Hahn 
1896f75564adSFlorian Hahn   if (auto *Inst = dyn_cast<Instruction>(I)) {
1897f75564adSFlorian Hahn     // A new instruction has been added, which might introduce new uses outside
1898f75564adSFlorian Hahn     // a defining loop. Fix LCSSA from for each operand of the new instruction,
1899f75564adSFlorian Hahn     // if required.
1900f75564adSFlorian Hahn     for (unsigned OpIdx = 0, OpEnd = Inst->getNumOperands(); OpIdx != OpEnd;
1901a9b06a2cSFlorian Hahn          OpIdx++)
1902a9b06a2cSFlorian Hahn       fixupLCSSAFormFor(Inst, OpIdx);
1903f75564adSFlorian Hahn   }
1904bcbd26bfSFlorian Hahn }
1905bcbd26bfSFlorian Hahn 
1906bcbd26bfSFlorian Hahn /// replaceCongruentIVs - Check for congruent phis in this loop header and
1907bcbd26bfSFlorian Hahn /// replace them with their most canonical representative. Return the number of
1908bcbd26bfSFlorian Hahn /// phis eliminated.
1909bcbd26bfSFlorian Hahn ///
1910bcbd26bfSFlorian Hahn /// This does not depend on any SCEVExpander state but should be used in
1911bcbd26bfSFlorian Hahn /// the same context that SCEVExpander is used.
1912bcbd26bfSFlorian Hahn unsigned
replaceCongruentIVs(Loop * L,const DominatorTree * DT,SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetTransformInfo * TTI)1913bcbd26bfSFlorian Hahn SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1914bcbd26bfSFlorian Hahn                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1915bcbd26bfSFlorian Hahn                                   const TargetTransformInfo *TTI) {
1916bcbd26bfSFlorian Hahn   // Find integer phis in order of increasing width.
1917bcbd26bfSFlorian Hahn   SmallVector<PHINode*, 8> Phis;
1918bcbd26bfSFlorian Hahn   for (PHINode &PN : L->getHeader()->phis())
1919bcbd26bfSFlorian Hahn     Phis.push_back(&PN);
1920bcbd26bfSFlorian Hahn 
1921bcbd26bfSFlorian Hahn   if (TTI)
1922ae14fae0SDmitry Makogon     // Use stable_sort to preserve order of equivalent PHIs, so the order
1923ae14fae0SDmitry Makogon     // of the sorted Phis is the same from run to run on the same loop.
1924ae14fae0SDmitry Makogon     llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1925bcbd26bfSFlorian Hahn       // Put pointers at the back and make sure pointer < pointer = false.
1926bcbd26bfSFlorian Hahn       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1927bcbd26bfSFlorian Hahn         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
192824156364SCaroline Concatto       return RHS->getType()->getPrimitiveSizeInBits().getFixedSize() <
192924156364SCaroline Concatto              LHS->getType()->getPrimitiveSizeInBits().getFixedSize();
1930bcbd26bfSFlorian Hahn     });
1931bcbd26bfSFlorian Hahn 
1932bcbd26bfSFlorian Hahn   unsigned NumElim = 0;
1933bcbd26bfSFlorian Hahn   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1934bcbd26bfSFlorian Hahn   // Process phis from wide to narrow. Map wide phis to their truncation
1935bcbd26bfSFlorian Hahn   // so narrow phis can reuse them.
1936bcbd26bfSFlorian Hahn   for (PHINode *Phi : Phis) {
1937bcbd26bfSFlorian Hahn     auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1938b8c2781fSSimon Moll       if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1939bcbd26bfSFlorian Hahn         return V;
1940bcbd26bfSFlorian Hahn       if (!SE.isSCEVable(PN->getType()))
1941bcbd26bfSFlorian Hahn         return nullptr;
1942bcbd26bfSFlorian Hahn       auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1943bcbd26bfSFlorian Hahn       if (!Const)
1944bcbd26bfSFlorian Hahn         return nullptr;
1945bcbd26bfSFlorian Hahn       return Const->getValue();
1946bcbd26bfSFlorian Hahn     };
1947bcbd26bfSFlorian Hahn 
1948bcbd26bfSFlorian Hahn     // Fold constant phis. They may be congruent to other constant phis and
1949bcbd26bfSFlorian Hahn     // would confuse the logic below that expects proper IVs.
1950bcbd26bfSFlorian Hahn     if (Value *V = SimplifyPHINode(Phi)) {
1951bcbd26bfSFlorian Hahn       if (V->getType() != Phi->getType())
1952bcbd26bfSFlorian Hahn         continue;
1953bcbd26bfSFlorian Hahn       Phi->replaceAllUsesWith(V);
1954bcbd26bfSFlorian Hahn       DeadInsts.emplace_back(Phi);
1955bcbd26bfSFlorian Hahn       ++NumElim;
19561540da3bSNeil Henning       SCEV_DEBUG_WITH_TYPE(DebugType,
19571540da3bSNeil Henning                            dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
19581540da3bSNeil Henning                                   << '\n');
1959bcbd26bfSFlorian Hahn       continue;
1960bcbd26bfSFlorian Hahn     }
1961bcbd26bfSFlorian Hahn 
1962bcbd26bfSFlorian Hahn     if (!SE.isSCEVable(Phi->getType()))
1963bcbd26bfSFlorian Hahn       continue;
1964bcbd26bfSFlorian Hahn 
1965bcbd26bfSFlorian Hahn     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1966bcbd26bfSFlorian Hahn     if (!OrigPhiRef) {
1967bcbd26bfSFlorian Hahn       OrigPhiRef = Phi;
1968bcbd26bfSFlorian Hahn       if (Phi->getType()->isIntegerTy() && TTI &&
1969bcbd26bfSFlorian Hahn           TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1970bcbd26bfSFlorian Hahn         // This phi can be freely truncated to the narrowest phi type. Map the
1971bcbd26bfSFlorian Hahn         // truncated expression to it so it will be reused for narrow types.
1972bcbd26bfSFlorian Hahn         const SCEV *TruncExpr =
1973bcbd26bfSFlorian Hahn           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1974bcbd26bfSFlorian Hahn         ExprToIVMap[TruncExpr] = Phi;
1975bcbd26bfSFlorian Hahn       }
1976bcbd26bfSFlorian Hahn       continue;
1977bcbd26bfSFlorian Hahn     }
1978bcbd26bfSFlorian Hahn 
1979bcbd26bfSFlorian Hahn     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1980bcbd26bfSFlorian Hahn     // sense.
1981bcbd26bfSFlorian Hahn     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1982bcbd26bfSFlorian Hahn       continue;
1983bcbd26bfSFlorian Hahn 
1984bcbd26bfSFlorian Hahn     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1985bcbd26bfSFlorian Hahn       Instruction *OrigInc = dyn_cast<Instruction>(
1986bcbd26bfSFlorian Hahn           OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1987bcbd26bfSFlorian Hahn       Instruction *IsomorphicInc =
1988bcbd26bfSFlorian Hahn           dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1989bcbd26bfSFlorian Hahn 
1990bcbd26bfSFlorian Hahn       if (OrigInc && IsomorphicInc) {
1991bcbd26bfSFlorian Hahn         // If this phi has the same width but is more canonical, replace the
1992bcbd26bfSFlorian Hahn         // original with it. As part of the "more canonical" determination,
1993bcbd26bfSFlorian Hahn         // respect a prior decision to use an IV chain.
1994bcbd26bfSFlorian Hahn         if (OrigPhiRef->getType() == Phi->getType() &&
1995bcbd26bfSFlorian Hahn             !(ChainedPhis.count(Phi) ||
1996bcbd26bfSFlorian Hahn               isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1997bcbd26bfSFlorian Hahn             (ChainedPhis.count(Phi) ||
1998bcbd26bfSFlorian Hahn              isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1999bcbd26bfSFlorian Hahn           std::swap(OrigPhiRef, Phi);
2000bcbd26bfSFlorian Hahn           std::swap(OrigInc, IsomorphicInc);
2001bcbd26bfSFlorian Hahn         }
2002bcbd26bfSFlorian Hahn         // Replacing the congruent phi is sufficient because acyclic
2003bcbd26bfSFlorian Hahn         // redundancy elimination, CSE/GVN, should handle the
2004bcbd26bfSFlorian Hahn         // rest. However, once SCEV proves that a phi is congruent,
2005bcbd26bfSFlorian Hahn         // it's often the head of an IV user cycle that is isomorphic
2006bcbd26bfSFlorian Hahn         // with the original phi. It's worth eagerly cleaning up the
2007bcbd26bfSFlorian Hahn         // common case of a single IV increment so that DeleteDeadPHIs
2008bcbd26bfSFlorian Hahn         // can remove cycles that had postinc uses.
2009bcbd26bfSFlorian Hahn         const SCEV *TruncExpr =
2010bcbd26bfSFlorian Hahn             SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
2011bcbd26bfSFlorian Hahn         if (OrigInc != IsomorphicInc &&
2012bcbd26bfSFlorian Hahn             TruncExpr == SE.getSCEV(IsomorphicInc) &&
2013bcbd26bfSFlorian Hahn             SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
2014bcbd26bfSFlorian Hahn             hoistIVInc(OrigInc, IsomorphicInc)) {
20151540da3bSNeil Henning           SCEV_DEBUG_WITH_TYPE(
20161540da3bSNeil Henning               DebugType, dbgs() << "INDVARS: Eliminated congruent iv.inc: "
2017bcbd26bfSFlorian Hahn                                 << *IsomorphicInc << '\n');
2018bcbd26bfSFlorian Hahn           Value *NewInc = OrigInc;
2019bcbd26bfSFlorian Hahn           if (OrigInc->getType() != IsomorphicInc->getType()) {
2020bcbd26bfSFlorian Hahn             Instruction *IP = nullptr;
2021bcbd26bfSFlorian Hahn             if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
2022bcbd26bfSFlorian Hahn               IP = &*PN->getParent()->getFirstInsertionPt();
2023bcbd26bfSFlorian Hahn             else
2024bcbd26bfSFlorian Hahn               IP = OrigInc->getNextNode();
2025bcbd26bfSFlorian Hahn 
2026bcbd26bfSFlorian Hahn             IRBuilder<> Builder(IP);
2027bcbd26bfSFlorian Hahn             Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
2028bcbd26bfSFlorian Hahn             NewInc = Builder.CreateTruncOrBitCast(
2029bcbd26bfSFlorian Hahn                 OrigInc, IsomorphicInc->getType(), IVName);
2030bcbd26bfSFlorian Hahn           }
2031bcbd26bfSFlorian Hahn           IsomorphicInc->replaceAllUsesWith(NewInc);
2032bcbd26bfSFlorian Hahn           DeadInsts.emplace_back(IsomorphicInc);
2033bcbd26bfSFlorian Hahn         }
2034bcbd26bfSFlorian Hahn       }
2035bcbd26bfSFlorian Hahn     }
20361540da3bSNeil Henning     SCEV_DEBUG_WITH_TYPE(DebugType,
20371540da3bSNeil Henning                          dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
20381540da3bSNeil Henning                                 << '\n');
20391540da3bSNeil Henning     SCEV_DEBUG_WITH_TYPE(
20401540da3bSNeil Henning         DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
2041bcbd26bfSFlorian Hahn     ++NumElim;
2042bcbd26bfSFlorian Hahn     Value *NewIV = OrigPhiRef;
2043bcbd26bfSFlorian Hahn     if (OrigPhiRef->getType() != Phi->getType()) {
2044bcbd26bfSFlorian Hahn       IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
2045bcbd26bfSFlorian Hahn       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
2046bcbd26bfSFlorian Hahn       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
2047bcbd26bfSFlorian Hahn     }
2048bcbd26bfSFlorian Hahn     Phi->replaceAllUsesWith(NewIV);
2049bcbd26bfSFlorian Hahn     DeadInsts.emplace_back(Phi);
2050bcbd26bfSFlorian Hahn   }
2051bcbd26bfSFlorian Hahn   return NumElim;
2052bcbd26bfSFlorian Hahn }
2053bcbd26bfSFlorian Hahn 
getRelatedExistingExpansion(const SCEV * S,const Instruction * At,Loop * L)2054d9715a72SNikita Popov Value *SCEVExpander::getRelatedExistingExpansion(const SCEV *S,
2055d9715a72SNikita Popov                                                  const Instruction *At,
2056bcbd26bfSFlorian Hahn                                                  Loop *L) {
2057bcbd26bfSFlorian Hahn   using namespace llvm::PatternMatch;
2058bcbd26bfSFlorian Hahn 
2059bcbd26bfSFlorian Hahn   SmallVector<BasicBlock *, 4> ExitingBlocks;
2060bcbd26bfSFlorian Hahn   L->getExitingBlocks(ExitingBlocks);
2061bcbd26bfSFlorian Hahn 
2062bcbd26bfSFlorian Hahn   // Look for suitable value in simple conditions at the loop exits.
2063bcbd26bfSFlorian Hahn   for (BasicBlock *BB : ExitingBlocks) {
2064bcbd26bfSFlorian Hahn     ICmpInst::Predicate Pred;
2065bcbd26bfSFlorian Hahn     Instruction *LHS, *RHS;
2066bcbd26bfSFlorian Hahn 
2067bcbd26bfSFlorian Hahn     if (!match(BB->getTerminator(),
2068bcbd26bfSFlorian Hahn                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2069bcbd26bfSFlorian Hahn                     m_BasicBlock(), m_BasicBlock())))
2070bcbd26bfSFlorian Hahn       continue;
2071bcbd26bfSFlorian Hahn 
2072bcbd26bfSFlorian Hahn     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2073d9715a72SNikita Popov       return LHS;
2074bcbd26bfSFlorian Hahn 
2075bcbd26bfSFlorian Hahn     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2076d9715a72SNikita Popov       return RHS;
2077bcbd26bfSFlorian Hahn   }
2078bcbd26bfSFlorian Hahn 
2079bcbd26bfSFlorian Hahn   // Use expand's logic which is used for reusing a previous Value in
20808906a0feSPhilip Reames   // ExprValueMap.  Note that we don't currently model the cost of
20818906a0feSPhilip Reames   // needing to drop poison generating flags on the instruction if we
20828906a0feSPhilip Reames   // want to reuse it.  We effectively assume that has zero cost.
2083d9715a72SNikita Popov   return FindValueInExprValueMap(S, At);
2084bcbd26bfSFlorian Hahn }
2085bcbd26bfSFlorian Hahn 
costAndCollectOperands(const SCEVOperand & WorkItem,const TargetTransformInfo & TTI,TargetTransformInfo::TargetCostKind CostKind,SmallVectorImpl<SCEVOperand> & Worklist)208600fe10c6SSander de Smalen template<typename T> static InstructionCost costAndCollectOperands(
2087928c4b4bSSam Parker   const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
2088928c4b4bSSam Parker   TargetTransformInfo::TargetCostKind CostKind,
2089928c4b4bSSam Parker   SmallVectorImpl<SCEVOperand> &Worklist) {
2090928c4b4bSSam Parker 
2091928c4b4bSSam Parker   const T *S = cast<T>(WorkItem.S);
209200fe10c6SSander de Smalen   InstructionCost Cost = 0;
20930bdf8c91SSam Parker   // Object to help map SCEV operands to expanded IR instructions.
20940bdf8c91SSam Parker   struct OperationIndices {
20950bdf8c91SSam Parker     OperationIndices(unsigned Opc, size_t min, size_t max) :
20960bdf8c91SSam Parker       Opcode(Opc), MinIdx(min), MaxIdx(max) { }
20970bdf8c91SSam Parker     unsigned Opcode;
20980bdf8c91SSam Parker     size_t MinIdx;
20990bdf8c91SSam Parker     size_t MaxIdx;
21000bdf8c91SSam Parker   };
21010bdf8c91SSam Parker 
21020bdf8c91SSam Parker   // Collect the operations of all the instructions that will be needed to
21030bdf8c91SSam Parker   // expand the SCEVExpr. This is so that when we come to cost the operands,
21040bdf8c91SSam Parker   // we know what the generated user(s) will be.
21050bdf8c91SSam Parker   SmallVector<OperationIndices, 2> Operations;
2106928c4b4bSSam Parker 
210700fe10c6SSander de Smalen   auto CastCost = [&](unsigned Opcode) -> InstructionCost {
21080bdf8c91SSam Parker     Operations.emplace_back(Opcode, 0, 0);
2109928c4b4bSSam Parker     return TTI.getCastInstrCost(Opcode, S->getType(),
2110928c4b4bSSam Parker                                 S->getOperand(0)->getType(),
2111928c4b4bSSam Parker                                 TTI::CastContextHint::None, CostKind);
2112928c4b4bSSam Parker   };
2113928c4b4bSSam Parker 
21140bdf8c91SSam Parker   auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
211500fe10c6SSander de Smalen                        unsigned MinIdx = 0,
211600fe10c6SSander de Smalen                        unsigned MaxIdx = 1) -> InstructionCost {
21170bdf8c91SSam Parker     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2118928c4b4bSSam Parker     return NumRequired *
2119928c4b4bSSam Parker       TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
2120928c4b4bSSam Parker   };
2121928c4b4bSSam Parker 
212200fe10c6SSander de Smalen   auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
212300fe10c6SSander de Smalen                         unsigned MaxIdx) -> InstructionCost {
21240bdf8c91SSam Parker     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2125928c4b4bSSam Parker     Type *OpType = S->getOperand(0)->getType();
2126b3b993a7SFlorian Hahn     return NumRequired * TTI.getCmpSelInstrCost(
2127b3b993a7SFlorian Hahn                              Opcode, OpType, CmpInst::makeCmpResultType(OpType),
2128b3b993a7SFlorian Hahn                              CmpInst::BAD_ICMP_PREDICATE, CostKind);
2129928c4b4bSSam Parker   };
2130928c4b4bSSam Parker 
2131928c4b4bSSam Parker   switch (S->getSCEVType()) {
2132e0567582SRoman Lebedev   case scCouldNotCompute:
2133e0567582SRoman Lebedev     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2134928c4b4bSSam Parker   case scUnknown:
2135928c4b4bSSam Parker   case scConstant:
2136928c4b4bSSam Parker     return 0;
213781fc53a3SRoman Lebedev   case scPtrToInt:
213881fc53a3SRoman Lebedev     Cost = CastCost(Instruction::PtrToInt);
213981fc53a3SRoman Lebedev     break;
2140928c4b4bSSam Parker   case scTruncate:
2141928c4b4bSSam Parker     Cost = CastCost(Instruction::Trunc);
2142928c4b4bSSam Parker     break;
2143928c4b4bSSam Parker   case scZeroExtend:
2144928c4b4bSSam Parker     Cost = CastCost(Instruction::ZExt);
2145928c4b4bSSam Parker     break;
2146928c4b4bSSam Parker   case scSignExtend:
2147928c4b4bSSam Parker     Cost = CastCost(Instruction::SExt);
2148928c4b4bSSam Parker     break;
2149928c4b4bSSam Parker   case scUDivExpr: {
2150928c4b4bSSam Parker     unsigned Opcode = Instruction::UDiv;
2151928c4b4bSSam Parker     if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
2152928c4b4bSSam Parker       if (SC->getAPInt().isPowerOf2())
2153928c4b4bSSam Parker         Opcode = Instruction::LShr;
2154928c4b4bSSam Parker     Cost = ArithCost(Opcode, 1);
2155928c4b4bSSam Parker     break;
2156928c4b4bSSam Parker   }
2157928c4b4bSSam Parker   case scAddExpr:
2158928c4b4bSSam Parker     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2159928c4b4bSSam Parker     break;
2160928c4b4bSSam Parker   case scMulExpr:
2161928c4b4bSSam Parker     // TODO: this is a very pessimistic cost modelling for Mul,
2162928c4b4bSSam Parker     // because of Bin Pow algorithm actually used by the expander,
2163928c4b4bSSam Parker     // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
2164928c4b4bSSam Parker     Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
2165928c4b4bSSam Parker     break;
2166928c4b4bSSam Parker   case scSMaxExpr:
2167928c4b4bSSam Parker   case scUMaxExpr:
2168928c4b4bSSam Parker   case scSMinExpr:
216982fb4f4bSRoman Lebedev   case scUMinExpr:
217082fb4f4bSRoman Lebedev   case scSequentialUMinExpr: {
2171b46c085dSRoman Lebedev     // FIXME: should this ask the cost for Intrinsic's?
217282fb4f4bSRoman Lebedev     // The reduction tree.
21730bdf8c91SSam Parker     Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
21740bdf8c91SSam Parker     Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
217582fb4f4bSRoman Lebedev     switch (S->getSCEVType()) {
217682fb4f4bSRoman Lebedev     case scSequentialUMinExpr: {
217782fb4f4bSRoman Lebedev       // The safety net against poison.
217882fb4f4bSRoman Lebedev       // FIXME: this is broken.
217982fb4f4bSRoman Lebedev       Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
218082fb4f4bSRoman Lebedev       Cost += ArithCost(Instruction::Or,
218182fb4f4bSRoman Lebedev                         S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
218282fb4f4bSRoman Lebedev       Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
218382fb4f4bSRoman Lebedev       break;
218482fb4f4bSRoman Lebedev     }
218582fb4f4bSRoman Lebedev     default:
218682fb4f4bSRoman Lebedev       assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
218782fb4f4bSRoman Lebedev              "Unhandled SCEV expression type?");
218882fb4f4bSRoman Lebedev       break;
218982fb4f4bSRoman Lebedev     }
2190928c4b4bSSam Parker     break;
2191928c4b4bSSam Parker   }
2192928c4b4bSSam Parker   case scAddRecExpr: {
2193928c4b4bSSam Parker     // In this polynominal, we may have some zero operands, and we shouldn't
2194928c4b4bSSam Parker     // really charge for those. So how many non-zero coeffients are there?
2195928c4b4bSSam Parker     int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) {
2196928c4b4bSSam Parker                                     return !Op->isZero();
2197928c4b4bSSam Parker                                   });
2198928c4b4bSSam Parker 
2199928c4b4bSSam Parker     assert(NumTerms >= 1 && "Polynominal should have at least one term.");
2200928c4b4bSSam Parker     assert(!(*std::prev(S->operands().end()))->isZero() &&
2201928c4b4bSSam Parker            "Last operand should not be zero");
2202928c4b4bSSam Parker 
2203928c4b4bSSam Parker     // Ignoring constant term (operand 0), how many of the coeffients are u> 1?
2204928c4b4bSSam Parker     int NumNonZeroDegreeNonOneTerms =
2205928c4b4bSSam Parker       llvm::count_if(S->operands(), [](const SCEV *Op) {
2206928c4b4bSSam Parker                       auto *SConst = dyn_cast<SCEVConstant>(Op);
2207928c4b4bSSam Parker                       return !SConst || SConst->getAPInt().ugt(1);
2208928c4b4bSSam Parker                     });
2209928c4b4bSSam Parker 
2210928c4b4bSSam Parker     // Much like with normal add expr, the polynominal will require
2211928c4b4bSSam Parker     // one less addition than the number of it's terms.
221200fe10c6SSander de Smalen     InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1,
22130bdf8c91SSam Parker                                         /*MinIdx*/ 1, /*MaxIdx*/ 1);
2214928c4b4bSSam Parker     // Here, *each* one of those will require a multiplication.
221500fe10c6SSander de Smalen     InstructionCost MulCost =
221600fe10c6SSander de Smalen         ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
2217928c4b4bSSam Parker     Cost = AddCost + MulCost;
2218928c4b4bSSam Parker 
2219928c4b4bSSam Parker     // What is the degree of this polynominal?
2220928c4b4bSSam Parker     int PolyDegree = S->getNumOperands() - 1;
2221928c4b4bSSam Parker     assert(PolyDegree >= 1 && "Should be at least affine.");
2222928c4b4bSSam Parker 
2223928c4b4bSSam Parker     // The final term will be:
2224928c4b4bSSam Parker     //   Op_{PolyDegree} * x ^ {PolyDegree}
2225928c4b4bSSam Parker     // Where  x ^ {PolyDegree}  will again require PolyDegree-1 mul operations.
2226928c4b4bSSam Parker     // Note that  x ^ {PolyDegree} = x * x ^ {PolyDegree-1}  so charging for
2227928c4b4bSSam Parker     // x ^ {PolyDegree}  will give us  x ^ {2} .. x ^ {PolyDegree-1}  for free.
2228928c4b4bSSam Parker     // FIXME: this is conservatively correct, but might be overly pessimistic.
2229928c4b4bSSam Parker     Cost += MulCost * (PolyDegree - 1);
22300bdf8c91SSam Parker     break;
2231928c4b4bSSam Parker   }
2232928c4b4bSSam Parker   }
2233928c4b4bSSam Parker 
22340bdf8c91SSam Parker   for (auto &CostOp : Operations) {
22350bdf8c91SSam Parker     for (auto SCEVOp : enumerate(S->operands())) {
22360bdf8c91SSam Parker       // Clamp the index to account for multiple IR operations being chained.
22370bdf8c91SSam Parker       size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
22380bdf8c91SSam Parker       size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
22390bdf8c91SSam Parker       Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
22400bdf8c91SSam Parker     }
22410bdf8c91SSam Parker   }
2242928c4b4bSSam Parker   return Cost;
2243928c4b4bSSam Parker }
2244928c4b4bSSam Parker 
isHighCostExpansionHelper(const SCEVOperand & WorkItem,Loop * L,const Instruction & At,InstructionCost & Cost,unsigned Budget,const TargetTransformInfo & TTI,SmallPtrSetImpl<const SCEV * > & Processed,SmallVectorImpl<SCEVOperand> & Worklist)2245bcbd26bfSFlorian Hahn bool SCEVExpander::isHighCostExpansionHelper(
2246928c4b4bSSam Parker     const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
224700fe10c6SSander de Smalen     InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
2248928c4b4bSSam Parker     SmallPtrSetImpl<const SCEV *> &Processed,
2249928c4b4bSSam Parker     SmallVectorImpl<SCEVOperand> &Worklist) {
225000fe10c6SSander de Smalen   if (Cost > Budget)
2251bcbd26bfSFlorian Hahn     return true; // Already run out of budget, give up.
2252bcbd26bfSFlorian Hahn 
2253928c4b4bSSam Parker   const SCEV *S = WorkItem.S;
2254bcbd26bfSFlorian Hahn   // Was the cost of expansion of this expression already accounted for?
22550bdf8c91SSam Parker   if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
2256bcbd26bfSFlorian Hahn     return false; // We have already accounted for this expression.
2257bcbd26bfSFlorian Hahn 
2258bcbd26bfSFlorian Hahn   // If we can find an existing value for this scev available at the point "At"
2259bcbd26bfSFlorian Hahn   // then consider the expression cheap.
2260bcbd26bfSFlorian Hahn   if (getRelatedExistingExpansion(S, &At, L))
2261bcbd26bfSFlorian Hahn     return false; // Consider the expression to be free.
2262bcbd26bfSFlorian Hahn 
2263bcbd26bfSFlorian Hahn   TargetTransformInfo::TargetCostKind CostKind =
22640bdf8c91SSam Parker       L->getHeader()->getParent()->hasMinSize()
22650bdf8c91SSam Parker           ? TargetTransformInfo::TCK_CodeSize
22660bdf8c91SSam Parker           : TargetTransformInfo::TCK_RecipThroughput;
2267bcbd26bfSFlorian Hahn 
22683355284bSRoman Lebedev   switch (S->getSCEVType()) {
2269e0567582SRoman Lebedev   case scCouldNotCompute:
2270e0567582SRoman Lebedev     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
22713355284bSRoman Lebedev   case scUnknown:
22723355284bSRoman Lebedev     // Assume to be zero-cost.
22733355284bSRoman Lebedev     return false;
22743355284bSRoman Lebedev   case scConstant: {
22750bdf8c91SSam Parker     // Only evalulate the costs of constants when optimizing for size.
22760bdf8c91SSam Parker     if (CostKind != TargetTransformInfo::TCK_CodeSize)
22772aed0813SKazu Hirata       return false;
2278ed577892SSimon Pilgrim     const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
22790bdf8c91SSam Parker     Type *Ty = S->getType();
228000fe10c6SSander de Smalen     Cost += TTI.getIntImmCostInst(
22813355284bSRoman Lebedev         WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
228200fe10c6SSander de Smalen     return Cost > Budget;
22833355284bSRoman Lebedev   }
22843355284bSRoman Lebedev   case scTruncate:
228581fc53a3SRoman Lebedev   case scPtrToInt:
22863355284bSRoman Lebedev   case scZeroExtend:
22873355284bSRoman Lebedev   case scSignExtend: {
228800fe10c6SSander de Smalen     Cost +=
228981fc53a3SRoman Lebedev         costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
2290bcbd26bfSFlorian Hahn     return false; // Will answer upon next entry into this function.
22913355284bSRoman Lebedev   }
22923355284bSRoman Lebedev   case scUDivExpr: {
2293bcbd26bfSFlorian Hahn     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2294bcbd26bfSFlorian Hahn     // HowManyLessThans produced to compute a precise expression, rather than a
2295bcbd26bfSFlorian Hahn     // UDiv from the user's code. If we can't find a UDiv in the code with some
2296bcbd26bfSFlorian Hahn     // simple searching, we need to account for it's cost.
2297bcbd26bfSFlorian Hahn 
2298bcbd26bfSFlorian Hahn     // At the beginning of this function we already tried to find existing
2299bcbd26bfSFlorian Hahn     // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2300bcbd26bfSFlorian Hahn     // pattern involving division. This is just a simple search heuristic.
2301bcbd26bfSFlorian Hahn     if (getRelatedExistingExpansion(
2302bcbd26bfSFlorian Hahn             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2303bcbd26bfSFlorian Hahn       return false; // Consider it to be free.
2304bcbd26bfSFlorian Hahn 
230500fe10c6SSander de Smalen     Cost +=
2306928c4b4bSSam Parker         costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
2307bcbd26bfSFlorian Hahn     return false; // Will answer upon next entry into this function.
23083355284bSRoman Lebedev   }
23093355284bSRoman Lebedev   case scAddExpr:
23103355284bSRoman Lebedev   case scMulExpr:
23113355284bSRoman Lebedev   case scUMaxExpr:
23123355284bSRoman Lebedev   case scSMaxExpr:
23133355284bSRoman Lebedev   case scUMinExpr:
231482fb4f4bSRoman Lebedev   case scSMinExpr:
231582fb4f4bSRoman Lebedev   case scSequentialUMinExpr: {
2316ed577892SSimon Pilgrim     assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2317bcbd26bfSFlorian Hahn            "Nary expr should have more than 1 operand.");
2318bcbd26bfSFlorian Hahn     // The simple nary expr will require one less op (or pair of ops)
2319bcbd26bfSFlorian Hahn     // than the number of it's terms.
232000fe10c6SSander de Smalen     Cost +=
2321928c4b4bSSam Parker         costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
232200fe10c6SSander de Smalen     return Cost > Budget;
23233355284bSRoman Lebedev   }
23243355284bSRoman Lebedev   case scAddRecExpr: {
232576eec6c9SFangrui Song     assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2326928c4b4bSSam Parker            "Polynomial should be at least linear");
232700fe10c6SSander de Smalen     Cost += costAndCollectOperands<SCEVAddRecExpr>(
2328928c4b4bSSam Parker         WorkItem, TTI, CostKind, Worklist);
232900fe10c6SSander de Smalen     return Cost > Budget;
23303355284bSRoman Lebedev   }
23313355284bSRoman Lebedev   }
2332e0567582SRoman Lebedev   llvm_unreachable("Unknown SCEV kind!");
2333bcbd26bfSFlorian Hahn }
2334bcbd26bfSFlorian Hahn 
expandCodeForPredicate(const SCEVPredicate * Pred,Instruction * IP)2335bcbd26bfSFlorian Hahn Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2336bcbd26bfSFlorian Hahn                                             Instruction *IP) {
2337bcbd26bfSFlorian Hahn   assert(IP);
2338bcbd26bfSFlorian Hahn   switch (Pred->getKind()) {
2339bcbd26bfSFlorian Hahn   case SCEVPredicate::P_Union:
2340bcbd26bfSFlorian Hahn     return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2341c302f1e6SPhilip Reames   case SCEVPredicate::P_Compare:
2342c302f1e6SPhilip Reames     return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP);
2343bcbd26bfSFlorian Hahn   case SCEVPredicate::P_Wrap: {
2344bcbd26bfSFlorian Hahn     auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2345bcbd26bfSFlorian Hahn     return expandWrapPredicate(AddRecPred, IP);
2346bcbd26bfSFlorian Hahn   }
2347bcbd26bfSFlorian Hahn   }
2348bcbd26bfSFlorian Hahn   llvm_unreachable("Unknown SCEV predicate type");
2349bcbd26bfSFlorian Hahn }
2350bcbd26bfSFlorian Hahn 
expandComparePredicate(const SCEVComparePredicate * Pred,Instruction * IP)2351c302f1e6SPhilip Reames Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred,
2352bcbd26bfSFlorian Hahn                                             Instruction *IP) {
2353f75564adSFlorian Hahn   Value *Expr0 =
2354f75564adSFlorian Hahn       expandCodeForImpl(Pred->getLHS(), Pred->getLHS()->getType(), IP, false);
2355f75564adSFlorian Hahn   Value *Expr1 =
2356f75564adSFlorian Hahn       expandCodeForImpl(Pred->getRHS(), Pred->getRHS()->getType(), IP, false);
2357bcbd26bfSFlorian Hahn 
2358bcbd26bfSFlorian Hahn   Builder.SetInsertPoint(IP);
2359c302f1e6SPhilip Reames   auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2360c302f1e6SPhilip Reames   auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2361bcbd26bfSFlorian Hahn   return I;
2362bcbd26bfSFlorian Hahn }
2363bcbd26bfSFlorian Hahn 
generateOverflowCheck(const SCEVAddRecExpr * AR,Instruction * Loc,bool Signed)2364bcbd26bfSFlorian Hahn Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2365bcbd26bfSFlorian Hahn                                            Instruction *Loc, bool Signed) {
2366bcbd26bfSFlorian Hahn   assert(AR->isAffine() && "Cannot generate RT check for "
2367bcbd26bfSFlorian Hahn                            "non-affine expression");
2368bcbd26bfSFlorian Hahn 
2369d39f4ac4SPhilip Reames   // FIXME: It is highly suspicious that we're ignoring the predicates here.
2370d39f4ac4SPhilip Reames   SmallVector<const SCEVPredicate *, 4> Pred;
2371bcbd26bfSFlorian Hahn   const SCEV *ExitCount =
2372bcbd26bfSFlorian Hahn       SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2373bcbd26bfSFlorian Hahn 
237410ddb927SPhilip Reames   assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2375bcbd26bfSFlorian Hahn 
2376bcbd26bfSFlorian Hahn   const SCEV *Step = AR->getStepRecurrence(SE);
2377bcbd26bfSFlorian Hahn   const SCEV *Start = AR->getStart();
2378bcbd26bfSFlorian Hahn 
2379bcbd26bfSFlorian Hahn   Type *ARTy = AR->getType();
2380bcbd26bfSFlorian Hahn   unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2381bcbd26bfSFlorian Hahn   unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2382bcbd26bfSFlorian Hahn 
2383bcbd26bfSFlorian Hahn   // The expression {Start,+,Step} has nusw/nssw if
2384bcbd26bfSFlorian Hahn   //   Step < 0, Start - |Step| * Backedge <= Start
2385bcbd26bfSFlorian Hahn   //   Step >= 0, Start + |Step| * Backedge > Start
2386bcbd26bfSFlorian Hahn   // and |Step| * Backedge doesn't unsigned overflow.
2387bcbd26bfSFlorian Hahn 
2388bcbd26bfSFlorian Hahn   IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2389bcbd26bfSFlorian Hahn   Builder.SetInsertPoint(Loc);
2390f75564adSFlorian Hahn   Value *TripCountVal = expandCodeForImpl(ExitCount, CountTy, Loc, false);
2391bcbd26bfSFlorian Hahn 
2392bcbd26bfSFlorian Hahn   IntegerType *Ty =
2393bcbd26bfSFlorian Hahn       IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2394bcbd26bfSFlorian Hahn 
2395f75564adSFlorian Hahn   Value *StepValue = expandCodeForImpl(Step, Ty, Loc, false);
2396f75564adSFlorian Hahn   Value *NegStepValue =
2397f75564adSFlorian Hahn       expandCodeForImpl(SE.getNegativeSCEV(Step), Ty, Loc, false);
2398e735f2bfSPhilip Reames   Value *StartValue = expandCodeForImpl(Start, ARTy, Loc, false);
2399bcbd26bfSFlorian Hahn 
2400bcbd26bfSFlorian Hahn   ConstantInt *Zero =
2401735f4671SChris Lattner       ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2402bcbd26bfSFlorian Hahn 
2403bcbd26bfSFlorian Hahn   Builder.SetInsertPoint(Loc);
2404bcbd26bfSFlorian Hahn   // Compute |Step|
2405bcbd26bfSFlorian Hahn   Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2406bcbd26bfSFlorian Hahn   Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2407bcbd26bfSFlorian Hahn 
2408bcbd26bfSFlorian Hahn   // Compute |Step| * Backedge
2409bcbd26bfSFlorian Hahn   // Compute:
2410f395a4f8SFlorian Hahn   //   1. Start + |Step| * Backedge < Start
2411f395a4f8SFlorian Hahn   //   2. Start - |Step| * Backedge > Start
2412f395a4f8SFlorian Hahn   //
2413f395a4f8SFlorian Hahn   // And select either 1. or 2. depending on whether step is positive or
2414f395a4f8SFlorian Hahn   // negative. If Step is known to be positive or negative, only create
2415f395a4f8SFlorian Hahn   // either 1. or 2.
24169345ab3aSFlorian Hahn   auto ComputeEndCheck = [&]() -> Value * {
24179345ab3aSFlorian Hahn     // Checking <u 0 is always false.
24189345ab3aSFlorian Hahn     if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
24199345ab3aSFlorian Hahn       return ConstantInt::getFalse(Loc->getContext());
24209345ab3aSFlorian Hahn 
2421aecad582SFlorian Hahn     // Get the backedge taken count and truncate or extended to the AR type.
2422aecad582SFlorian Hahn     Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2423aecad582SFlorian Hahn 
2424ad1b8772SFlorian Hahn     Value *MulV, *OfMul;
2425ad1b8772SFlorian Hahn     if (Step->isOne()) {
2426ad1b8772SFlorian Hahn       // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
2427ad1b8772SFlorian Hahn       // needed, there is never an overflow, so to avoid artificially inflating
2428ad1b8772SFlorian Hahn       // the cost of the check, directly emit the optimized IR.
2429ad1b8772SFlorian Hahn       MulV = TruncTripCount;
2430ad1b8772SFlorian Hahn       OfMul = ConstantInt::getFalse(MulV->getContext());
2431ad1b8772SFlorian Hahn     } else {
2432ad1b8772SFlorian Hahn       auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2433ad1b8772SFlorian Hahn                                              Intrinsic::umul_with_overflow, Ty);
2434ad1b8772SFlorian Hahn       CallInst *Mul =
2435ad1b8772SFlorian Hahn           Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2436ad1b8772SFlorian Hahn       MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2437ad1b8772SFlorian Hahn       OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2438ad1b8772SFlorian Hahn     }
2439ad1b8772SFlorian Hahn 
2440bcbd26bfSFlorian Hahn     Value *Add = nullptr, *Sub = nullptr;
2441f395a4f8SFlorian Hahn     bool NeedPosCheck = !SE.isKnownNegative(Step);
2442f395a4f8SFlorian Hahn     bool NeedNegCheck = !SE.isKnownPositive(Step);
2443f395a4f8SFlorian Hahn 
2444e735f2bfSPhilip Reames     if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARTy)) {
2445c86e1ce7SNikita Popov       StartValue = InsertNoopCastOfTo(
2446c86e1ce7SNikita Popov           StartValue, Builder.getInt8PtrTy(ARPtrTy->getAddressSpace()));
2447c86e1ce7SNikita Popov       Value *NegMulV = Builder.CreateNeg(MulV);
2448f395a4f8SFlorian Hahn       if (NeedPosCheck)
2449c86e1ce7SNikita Popov         Add = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, MulV);
2450f395a4f8SFlorian Hahn       if (NeedNegCheck)
2451c86e1ce7SNikita Popov         Sub = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, NegMulV);
2452bcbd26bfSFlorian Hahn     } else {
2453f395a4f8SFlorian Hahn       if (NeedPosCheck)
2454bcbd26bfSFlorian Hahn         Add = Builder.CreateAdd(StartValue, MulV);
2455f395a4f8SFlorian Hahn       if (NeedNegCheck)
2456bcbd26bfSFlorian Hahn         Sub = Builder.CreateSub(StartValue, MulV);
2457bcbd26bfSFlorian Hahn     }
2458bcbd26bfSFlorian Hahn 
2459f395a4f8SFlorian Hahn     Value *EndCompareLT = nullptr;
2460f395a4f8SFlorian Hahn     Value *EndCompareGT = nullptr;
2461f395a4f8SFlorian Hahn     Value *EndCheck = nullptr;
2462f395a4f8SFlorian Hahn     if (NeedPosCheck)
2463f395a4f8SFlorian Hahn       EndCheck = EndCompareLT = Builder.CreateICmp(
2464bcbd26bfSFlorian Hahn           Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2465f395a4f8SFlorian Hahn     if (NeedNegCheck)
2466f395a4f8SFlorian Hahn       EndCheck = EndCompareGT = Builder.CreateICmp(
2467f395a4f8SFlorian Hahn           Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2468f395a4f8SFlorian Hahn     if (NeedPosCheck && NeedNegCheck) {
2469bcbd26bfSFlorian Hahn       // Select the answer based on the sign of Step.
2470f395a4f8SFlorian Hahn       EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2471f395a4f8SFlorian Hahn     }
24727f1bf68dSFlorian Hahn     return Builder.CreateOr(EndCheck, OfMul);
24739345ab3aSFlorian Hahn   };
24749345ab3aSFlorian Hahn   Value *EndCheck = ComputeEndCheck();
2475bcbd26bfSFlorian Hahn 
2476bcbd26bfSFlorian Hahn   // If the backedge taken count type is larger than the AR type,
2477bcbd26bfSFlorian Hahn   // check that we don't drop any bits by truncating it. If we are
2478bcbd26bfSFlorian Hahn   // dropping bits, then we have overflow (unless the step is zero).
2479bcbd26bfSFlorian Hahn   if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2480bcbd26bfSFlorian Hahn     auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2481bcbd26bfSFlorian Hahn     auto *BackedgeCheck =
2482bcbd26bfSFlorian Hahn         Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2483bcbd26bfSFlorian Hahn                            ConstantInt::get(Loc->getContext(), MaxVal));
2484bcbd26bfSFlorian Hahn     BackedgeCheck = Builder.CreateAnd(
2485bcbd26bfSFlorian Hahn         BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2486bcbd26bfSFlorian Hahn 
2487bcbd26bfSFlorian Hahn     EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2488bcbd26bfSFlorian Hahn   }
2489bcbd26bfSFlorian Hahn 
24907f1bf68dSFlorian Hahn   return EndCheck;
2491bcbd26bfSFlorian Hahn }
2492bcbd26bfSFlorian Hahn 
expandWrapPredicate(const SCEVWrapPredicate * Pred,Instruction * IP)2493bcbd26bfSFlorian Hahn Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2494bcbd26bfSFlorian Hahn                                          Instruction *IP) {
2495bcbd26bfSFlorian Hahn   const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2496bcbd26bfSFlorian Hahn   Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2497bcbd26bfSFlorian Hahn 
2498bcbd26bfSFlorian Hahn   // Add a check for NUSW
2499bcbd26bfSFlorian Hahn   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2500bcbd26bfSFlorian Hahn     NUSWCheck = generateOverflowCheck(A, IP, false);
2501bcbd26bfSFlorian Hahn 
2502bcbd26bfSFlorian Hahn   // Add a check for NSSW
2503bcbd26bfSFlorian Hahn   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2504bcbd26bfSFlorian Hahn     NSSWCheck = generateOverflowCheck(A, IP, true);
2505bcbd26bfSFlorian Hahn 
2506bcbd26bfSFlorian Hahn   if (NUSWCheck && NSSWCheck)
2507bcbd26bfSFlorian Hahn     return Builder.CreateOr(NUSWCheck, NSSWCheck);
2508bcbd26bfSFlorian Hahn 
2509bcbd26bfSFlorian Hahn   if (NUSWCheck)
2510bcbd26bfSFlorian Hahn     return NUSWCheck;
2511bcbd26bfSFlorian Hahn 
2512bcbd26bfSFlorian Hahn   if (NSSWCheck)
2513bcbd26bfSFlorian Hahn     return NSSWCheck;
2514bcbd26bfSFlorian Hahn 
2515bcbd26bfSFlorian Hahn   return ConstantInt::getFalse(IP->getContext());
2516bcbd26bfSFlorian Hahn }
2517bcbd26bfSFlorian Hahn 
expandUnionPredicate(const SCEVUnionPredicate * Union,Instruction * IP)2518bcbd26bfSFlorian Hahn Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2519bcbd26bfSFlorian Hahn                                           Instruction *IP) {
2520bcbd26bfSFlorian Hahn   // Loop over all checks in this set.
252186d113a8SFlorian Hahn   SmallVector<Value *> Checks;
2522bcbd26bfSFlorian Hahn   for (auto Pred : Union->getPredicates()) {
252386d113a8SFlorian Hahn     Checks.push_back(expandCodeForPredicate(Pred, IP));
2524bcbd26bfSFlorian Hahn     Builder.SetInsertPoint(IP);
2525bcbd26bfSFlorian Hahn   }
2526bcbd26bfSFlorian Hahn 
252786d113a8SFlorian Hahn   if (Checks.empty())
252886d113a8SFlorian Hahn     return ConstantInt::getFalse(IP->getContext());
252986d113a8SFlorian Hahn   return Builder.CreateOr(Checks);
2530bcbd26bfSFlorian Hahn }
2531bcbd26bfSFlorian Hahn 
fixupLCSSAFormFor(Instruction * User,unsigned OpIdx)2532f75564adSFlorian Hahn Value *SCEVExpander::fixupLCSSAFormFor(Instruction *User, unsigned OpIdx) {
2533f75564adSFlorian Hahn   assert(PreserveLCSSA);
2534f75564adSFlorian Hahn   SmallVector<Instruction *, 1> ToUpdate;
2535f75564adSFlorian Hahn 
2536f75564adSFlorian Hahn   auto *OpV = User->getOperand(OpIdx);
2537f75564adSFlorian Hahn   auto *OpI = dyn_cast<Instruction>(OpV);
2538f75564adSFlorian Hahn   if (!OpI)
2539f75564adSFlorian Hahn     return OpV;
2540f75564adSFlorian Hahn 
2541f75564adSFlorian Hahn   Loop *DefLoop = SE.LI.getLoopFor(OpI->getParent());
2542f75564adSFlorian Hahn   Loop *UseLoop = SE.LI.getLoopFor(User->getParent());
2543f75564adSFlorian Hahn   if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2544f75564adSFlorian Hahn     return OpV;
2545f75564adSFlorian Hahn 
2546f75564adSFlorian Hahn   ToUpdate.push_back(OpI);
254705b44f7eSFlorian Hahn   SmallVector<PHINode *, 16> PHIsToRemove;
254805b44f7eSFlorian Hahn   formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, Builder, &PHIsToRemove);
254905b44f7eSFlorian Hahn   for (PHINode *PN : PHIsToRemove) {
255005b44f7eSFlorian Hahn     if (!PN->use_empty())
255105b44f7eSFlorian Hahn       continue;
255205b44f7eSFlorian Hahn     InsertedValues.erase(PN);
255305b44f7eSFlorian Hahn     InsertedPostIncValues.erase(PN);
255405b44f7eSFlorian Hahn     PN->eraseFromParent();
255505b44f7eSFlorian Hahn   }
255605b44f7eSFlorian Hahn 
2557f75564adSFlorian Hahn   return User->getOperand(OpIdx);
2558f75564adSFlorian Hahn }
2559f75564adSFlorian Hahn 
2560bcbd26bfSFlorian Hahn namespace {
2561bcbd26bfSFlorian Hahn // Search for a SCEV subexpression that is not safe to expand.  Any expression
2562bcbd26bfSFlorian Hahn // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2563bcbd26bfSFlorian Hahn // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2564bcbd26bfSFlorian Hahn // instruction, but the important thing is that we prove the denominator is
2565bcbd26bfSFlorian Hahn // nonzero before expansion.
2566bcbd26bfSFlorian Hahn //
2567bcbd26bfSFlorian Hahn // IVUsers already checks that IV-derived expressions are safe. So this check is
2568bcbd26bfSFlorian Hahn // only needed when the expression includes some subexpression that is not IV
2569bcbd26bfSFlorian Hahn // derived.
2570bcbd26bfSFlorian Hahn //
25713bc09c7dSPhilip Reames // Currently, we only allow division by a value provably non-zero here.
2572bcbd26bfSFlorian Hahn //
2573bcbd26bfSFlorian Hahn // We cannot generally expand recurrences unless the step dominates the loop
2574bcbd26bfSFlorian Hahn // header. The expander handles the special case of affine recurrences by
2575bcbd26bfSFlorian Hahn // scaling the recurrence outside the loop, but this technique isn't generally
2576bcbd26bfSFlorian Hahn // applicable. Expanding a nested recurrence outside a loop requires computing
2577bcbd26bfSFlorian Hahn // binomial coefficients. This could be done, but the recurrence has to be in a
2578bcbd26bfSFlorian Hahn // perfectly reduced form, which can't be guaranteed.
2579bcbd26bfSFlorian Hahn struct SCEVFindUnsafe {
2580bcbd26bfSFlorian Hahn   ScalarEvolution &SE;
258169853f99SNikita Popov   bool CanonicalMode;
25822d650ee0SKazu Hirata   bool IsUnsafe = false;
2583bcbd26bfSFlorian Hahn 
SCEVFindUnsafe__anon307280901011::SCEVFindUnsafe258469853f99SNikita Popov   SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
25852d650ee0SKazu Hirata       : SE(SE), CanonicalMode(CanonicalMode) {}
2586bcbd26bfSFlorian Hahn 
follow__anon307280901011::SCEVFindUnsafe2587bcbd26bfSFlorian Hahn   bool follow(const SCEV *S) {
2588bcbd26bfSFlorian Hahn     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
25893bc09c7dSPhilip Reames       if (!SE.isKnownNonZero(D->getRHS())) {
2590bcbd26bfSFlorian Hahn         IsUnsafe = true;
2591bcbd26bfSFlorian Hahn         return false;
2592bcbd26bfSFlorian Hahn       }
2593bcbd26bfSFlorian Hahn     }
2594bcbd26bfSFlorian Hahn     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2595bcbd26bfSFlorian Hahn       const SCEV *Step = AR->getStepRecurrence(SE);
2596bcbd26bfSFlorian Hahn       if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2597bcbd26bfSFlorian Hahn         IsUnsafe = true;
2598bcbd26bfSFlorian Hahn         return false;
2599bcbd26bfSFlorian Hahn       }
260069853f99SNikita Popov 
260169853f99SNikita Popov       // For non-affine addrecs or in non-canonical mode we need a preheader
260269853f99SNikita Popov       // to insert into.
260369853f99SNikita Popov       if (!AR->getLoop()->getLoopPreheader() &&
260469853f99SNikita Popov           (!CanonicalMode || !AR->isAffine())) {
260569853f99SNikita Popov         IsUnsafe = true;
260669853f99SNikita Popov         return false;
260769853f99SNikita Popov       }
2608bcbd26bfSFlorian Hahn     }
2609bcbd26bfSFlorian Hahn     return true;
2610bcbd26bfSFlorian Hahn   }
isDone__anon307280901011::SCEVFindUnsafe2611bcbd26bfSFlorian Hahn   bool isDone() const { return IsUnsafe; }
2612bcbd26bfSFlorian Hahn };
26139e6e631bSNikita Popov } // namespace
2614bcbd26bfSFlorian Hahn 
isSafeToExpand(const SCEV * S) const2615*f75ccadcSNikita Popov bool SCEVExpander::isSafeToExpand(const SCEV *S) const {
261669853f99SNikita Popov   SCEVFindUnsafe Search(SE, CanonicalMode);
2617bcbd26bfSFlorian Hahn   visitAll(S, Search);
2618bcbd26bfSFlorian Hahn   return !Search.IsUnsafe;
2619bcbd26bfSFlorian Hahn }
2620bcbd26bfSFlorian Hahn 
isSafeToExpandAt(const SCEV * S,const Instruction * InsertionPoint) const26219e6e631bSNikita Popov bool SCEVExpander::isSafeToExpandAt(const SCEV *S,
26229e6e631bSNikita Popov                                     const Instruction *InsertionPoint) const {
26239e6e631bSNikita Popov   if (!isSafeToExpand(S))
2624bcbd26bfSFlorian Hahn     return false;
2625bcbd26bfSFlorian Hahn   // We have to prove that the expanded site of S dominates InsertionPoint.
2626bcbd26bfSFlorian Hahn   // This is easy when not in the same block, but hard when S is an instruction
2627bcbd26bfSFlorian Hahn   // to be expanded somewhere inside the same block as our insertion point.
2628bcbd26bfSFlorian Hahn   // What we really need here is something analogous to an OrderedBasicBlock,
2629bcbd26bfSFlorian Hahn   // but for the moment, we paper over the problem by handling two common and
2630bcbd26bfSFlorian Hahn   // cheap to check cases.
2631bcbd26bfSFlorian Hahn   if (SE.properlyDominates(S, InsertionPoint->getParent()))
2632bcbd26bfSFlorian Hahn     return true;
2633bcbd26bfSFlorian Hahn   if (SE.dominates(S, InsertionPoint->getParent())) {
2634bcbd26bfSFlorian Hahn     if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2635bcbd26bfSFlorian Hahn       return true;
2636bcbd26bfSFlorian Hahn     if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2637910e2d1eSKazu Hirata       if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2638bcbd26bfSFlorian Hahn         return true;
2639bcbd26bfSFlorian Hahn   }
2640bcbd26bfSFlorian Hahn   return false;
2641bcbd26bfSFlorian Hahn }
26428eded24bSFlorian Hahn 
cleanup()264353dacb7bSFlorian Hahn void SCEVExpanderCleaner::cleanup() {
26448eded24bSFlorian Hahn   // Result is used, nothing to remove.
26458eded24bSFlorian Hahn   if (ResultUsed)
26468eded24bSFlorian Hahn     return;
26478eded24bSFlorian Hahn 
26488eded24bSFlorian Hahn   auto InsertedInstructions = Expander.getAllInsertedInstructions();
26498eded24bSFlorian Hahn #ifndef NDEBUG
26508eded24bSFlorian Hahn   SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
26518eded24bSFlorian Hahn                                             InsertedInstructions.end());
26528eded24bSFlorian Hahn   (void)InsertedSet;
26538eded24bSFlorian Hahn #endif
26548eded24bSFlorian Hahn   // Remove sets with value handles.
26558eded24bSFlorian Hahn   Expander.clear();
26568eded24bSFlorian Hahn 
26578eded24bSFlorian Hahn   // Remove all inserted instructions.
26581ce01b7dSFlorian Hahn   for (Instruction *I : reverse(InsertedInstructions)) {
26598eded24bSFlorian Hahn #ifndef NDEBUG
26608eded24bSFlorian Hahn     assert(all_of(I->users(),
26618eded24bSFlorian Hahn                   [&InsertedSet](Value *U) {
26628eded24bSFlorian Hahn                     return InsertedSet.contains(cast<Instruction>(U));
26638eded24bSFlorian Hahn                   }) &&
26648eded24bSFlorian Hahn            "removed instruction should only be used by instructions inserted "
26658eded24bSFlorian Hahn            "during expansion");
26668eded24bSFlorian Hahn #endif
26678eded24bSFlorian Hahn     assert(!I->getType()->isVoidTy() &&
26688eded24bSFlorian Hahn            "inserted instruction should have non-void types");
26698eded24bSFlorian Hahn     I->replaceAllUsesWith(UndefValue::get(I->getType()));
26708eded24bSFlorian Hahn     I->eraseFromParent();
26718eded24bSFlorian Hahn   }
26728eded24bSFlorian Hahn }
2673