xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
15ffd83dbSDimitry Andric //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric //
95ffd83dbSDimitry Andric // This file contains the implementation of the scalar evolution expander,
105ffd83dbSDimitry Andric // which is used to generate the code corresponding to a given scalar evolution
115ffd83dbSDimitry Andric // expression.
125ffd83dbSDimitry Andric //
135ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
145ffd83dbSDimitry Andric 
155ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
165ffd83dbSDimitry Andric #include "llvm/ADT/STLExtras.h"
17bdd1243dSDimitry Andric #include "llvm/ADT/ScopeExit.h"
185ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
195ffd83dbSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
205ffd83dbSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
215ffd83dbSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
224824e7fdSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
235ffd83dbSDimitry Andric #include "llvm/IR/DataLayout.h"
245ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h"
255ffd83dbSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
265ffd83dbSDimitry Andric #include "llvm/IR/PatternMatch.h"
275ffd83dbSDimitry Andric #include "llvm/Support/CommandLine.h"
285ffd83dbSDimitry Andric #include "llvm/Support/raw_ostream.h"
29e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
305ffd83dbSDimitry Andric 
31fe6060f1SDimitry Andric #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
32fe6060f1SDimitry Andric #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
33fe6060f1SDimitry Andric #else
34fe6060f1SDimitry Andric #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
35fe6060f1SDimitry Andric #endif
36fe6060f1SDimitry Andric 
375ffd83dbSDimitry Andric using namespace llvm;
385ffd83dbSDimitry Andric 
395ffd83dbSDimitry Andric cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
405ffd83dbSDimitry Andric     "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
415ffd83dbSDimitry Andric     cl::desc("When performing SCEV expansion only if it is cheap to do, this "
425ffd83dbSDimitry Andric              "controls the budget that is considered cheap (default = 4)"));
435ffd83dbSDimitry Andric 
445ffd83dbSDimitry Andric using namespace PatternMatch;
455ffd83dbSDimitry Andric 
465ffd83dbSDimitry Andric /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
47e8d8bef9SDimitry Andric /// reusing an existing cast if a suitable one (= dominating IP) exists, or
485ffd83dbSDimitry Andric /// creating a new one.
495ffd83dbSDimitry Andric Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
505ffd83dbSDimitry Andric                                        Instruction::CastOps Op,
515ffd83dbSDimitry Andric                                        BasicBlock::iterator IP) {
525ffd83dbSDimitry Andric   // This function must be called with the builder having a valid insertion
535ffd83dbSDimitry Andric   // point. It doesn't need to be the actual IP where the uses of the returned
545ffd83dbSDimitry Andric   // cast will be added, but it must dominate such IP.
555ffd83dbSDimitry Andric   // We use this precondition to produce a cast that will dominate all its
565ffd83dbSDimitry Andric   // uses. In particular, this is crucial for the case where the builder's
575ffd83dbSDimitry Andric   // insertion point *is* the point where we were asked to put the cast.
585ffd83dbSDimitry Andric   // Since we don't know the builder's insertion point is actually
595ffd83dbSDimitry Andric   // where the uses will be added (only that it dominates it), we are
605ffd83dbSDimitry Andric   // not allowed to move it.
615ffd83dbSDimitry Andric   BasicBlock::iterator BIP = Builder.GetInsertPoint();
625ffd83dbSDimitry Andric 
63fe6060f1SDimitry Andric   Value *Ret = nullptr;
645ffd83dbSDimitry Andric 
655ffd83dbSDimitry Andric   // Check to see if there is already a cast!
66e8d8bef9SDimitry Andric   for (User *U : V->users()) {
67e8d8bef9SDimitry Andric     if (U->getType() != Ty)
68e8d8bef9SDimitry Andric       continue;
69e8d8bef9SDimitry Andric     CastInst *CI = dyn_cast<CastInst>(U);
70e8d8bef9SDimitry Andric     if (!CI || CI->getOpcode() != Op)
71e8d8bef9SDimitry Andric       continue;
72e8d8bef9SDimitry Andric 
73e8d8bef9SDimitry Andric     // Found a suitable cast that is at IP or comes before IP. Use it. Note that
74e8d8bef9SDimitry Andric     // the cast must also properly dominate the Builder's insertion point.
75e8d8bef9SDimitry Andric     if (IP->getParent() == CI->getParent() && &*BIP != CI &&
76e8d8bef9SDimitry Andric         (&*IP == CI || CI->comesBefore(&*IP))) {
775ffd83dbSDimitry Andric       Ret = CI;
785ffd83dbSDimitry Andric       break;
795ffd83dbSDimitry Andric     }
80e8d8bef9SDimitry Andric   }
815ffd83dbSDimitry Andric 
825ffd83dbSDimitry Andric   // Create a new cast.
83e8d8bef9SDimitry Andric   if (!Ret) {
84fe6060f1SDimitry Andric     SCEVInsertPointGuard Guard(Builder, this);
85fe6060f1SDimitry Andric     Builder.SetInsertPoint(&*IP);
86fe6060f1SDimitry Andric     Ret = Builder.CreateCast(Op, V, Ty, V->getName());
87e8d8bef9SDimitry Andric   }
885ffd83dbSDimitry Andric 
895ffd83dbSDimitry Andric   // We assert at the end of the function since IP might point to an
905ffd83dbSDimitry Andric   // instruction with different dominance properties than a cast
915ffd83dbSDimitry Andric   // (an invoke for example) and not dominate BIP (but the cast does).
92fe6060f1SDimitry Andric   assert(!isa<Instruction>(Ret) ||
93fe6060f1SDimitry Andric          SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
945ffd83dbSDimitry Andric 
955ffd83dbSDimitry Andric   return Ret;
965ffd83dbSDimitry Andric }
975ffd83dbSDimitry Andric 
98e8d8bef9SDimitry Andric BasicBlock::iterator
99fe6060f1SDimitry Andric SCEVExpander::findInsertPointAfter(Instruction *I,
100fe6060f1SDimitry Andric                                    Instruction *MustDominate) const {
1015ffd83dbSDimitry Andric   BasicBlock::iterator IP = ++I->getIterator();
1025ffd83dbSDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(I))
1035ffd83dbSDimitry Andric     IP = II->getNormalDest()->begin();
1045ffd83dbSDimitry Andric 
1055ffd83dbSDimitry Andric   while (isa<PHINode>(IP))
1065ffd83dbSDimitry Andric     ++IP;
1075ffd83dbSDimitry Andric 
1085ffd83dbSDimitry Andric   if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
1095ffd83dbSDimitry Andric     ++IP;
1105ffd83dbSDimitry Andric   } else if (isa<CatchSwitchInst>(IP)) {
111e8d8bef9SDimitry Andric     IP = MustDominate->getParent()->getFirstInsertionPt();
1125ffd83dbSDimitry Andric   } else {
1135ffd83dbSDimitry Andric     assert(!IP->isEHPad() && "unexpected eh pad!");
1145ffd83dbSDimitry Andric   }
1155ffd83dbSDimitry Andric 
116e8d8bef9SDimitry Andric   // Adjust insert point to be after instructions inserted by the expander, so
117e8d8bef9SDimitry Andric   // we can re-use already inserted instructions. Avoid skipping past the
118e8d8bef9SDimitry Andric   // original \p MustDominate, in case it is an inserted instruction.
119e8d8bef9SDimitry Andric   while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
120e8d8bef9SDimitry Andric     ++IP;
121e8d8bef9SDimitry Andric 
1225ffd83dbSDimitry Andric   return IP;
1235ffd83dbSDimitry Andric }
1245ffd83dbSDimitry Andric 
125fe6060f1SDimitry Andric BasicBlock::iterator
126fe6060f1SDimitry Andric SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
127fe6060f1SDimitry Andric   // Cast the argument at the beginning of the entry block, after
128fe6060f1SDimitry Andric   // any bitcasts of other arguments.
129fe6060f1SDimitry Andric   if (Argument *A = dyn_cast<Argument>(V)) {
130fe6060f1SDimitry Andric     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
131fe6060f1SDimitry Andric     while ((isa<BitCastInst>(IP) &&
132fe6060f1SDimitry Andric             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
133fe6060f1SDimitry Andric             cast<BitCastInst>(IP)->getOperand(0) != A) ||
134fe6060f1SDimitry Andric            isa<DbgInfoIntrinsic>(IP))
135fe6060f1SDimitry Andric       ++IP;
136fe6060f1SDimitry Andric     return IP;
137fe6060f1SDimitry Andric   }
138fe6060f1SDimitry Andric 
139fe6060f1SDimitry Andric   // Cast the instruction immediately after the instruction.
140fe6060f1SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
141fe6060f1SDimitry Andric     return findInsertPointAfter(I, &*Builder.GetInsertPoint());
142fe6060f1SDimitry Andric 
143fe6060f1SDimitry Andric   // Otherwise, this must be some kind of a constant,
144fe6060f1SDimitry Andric   // so let's plop this cast into the function's entry block.
145fe6060f1SDimitry Andric   assert(isa<Constant>(V) &&
146fe6060f1SDimitry Andric          "Expected the cast argument to be a global/constant");
147fe6060f1SDimitry Andric   return Builder.GetInsertBlock()
148fe6060f1SDimitry Andric       ->getParent()
149fe6060f1SDimitry Andric       ->getEntryBlock()
150fe6060f1SDimitry Andric       .getFirstInsertionPt();
151fe6060f1SDimitry Andric }
152fe6060f1SDimitry Andric 
1535ffd83dbSDimitry Andric /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
1545ffd83dbSDimitry Andric /// which must be possible with a noop cast, doing what we can to share
1555ffd83dbSDimitry Andric /// the casts.
1565ffd83dbSDimitry Andric Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
1575ffd83dbSDimitry Andric   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
1585ffd83dbSDimitry Andric   assert((Op == Instruction::BitCast ||
1595ffd83dbSDimitry Andric           Op == Instruction::PtrToInt ||
1605ffd83dbSDimitry Andric           Op == Instruction::IntToPtr) &&
1615ffd83dbSDimitry Andric          "InsertNoopCastOfTo cannot perform non-noop casts!");
1625ffd83dbSDimitry Andric   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
1635ffd83dbSDimitry Andric          "InsertNoopCastOfTo cannot change sizes!");
1645ffd83dbSDimitry Andric 
165e8d8bef9SDimitry Andric   // inttoptr only works for integral pointers. For non-integral pointers, we
16606c3fb27SDimitry Andric   // can create a GEP on null with the integral value as index. Note that
167e8d8bef9SDimitry Andric   // it is safe to use GEP of null instead of inttoptr here, because only
168e8d8bef9SDimitry Andric   // expressions already based on a GEP of null should be converted to pointers
169e8d8bef9SDimitry Andric   // during expansion.
170e8d8bef9SDimitry Andric   if (Op == Instruction::IntToPtr) {
171e8d8bef9SDimitry Andric     auto *PtrTy = cast<PointerType>(Ty);
172e8d8bef9SDimitry Andric     if (DL.isNonIntegralPointerType(PtrTy)) {
17304eeddc0SDimitry Andric       assert(DL.getTypeAllocSize(Builder.getInt8Ty()) == 1 &&
174e8d8bef9SDimitry Andric              "alloc size of i8 must by 1 byte for the GEP to be correct");
17506c3fb27SDimitry Andric       return Builder.CreateGEP(
176*5f757f3fSDimitry Andric           Builder.getInt8Ty(), Constant::getNullValue(PtrTy), V, "scevgep");
177e8d8bef9SDimitry Andric     }
178e8d8bef9SDimitry Andric   }
1795ffd83dbSDimitry Andric   // Short-circuit unnecessary bitcasts.
1805ffd83dbSDimitry Andric   if (Op == Instruction::BitCast) {
1815ffd83dbSDimitry Andric     if (V->getType() == Ty)
1825ffd83dbSDimitry Andric       return V;
1835ffd83dbSDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(V)) {
1845ffd83dbSDimitry Andric       if (CI->getOperand(0)->getType() == Ty)
1855ffd83dbSDimitry Andric         return CI->getOperand(0);
1865ffd83dbSDimitry Andric     }
1875ffd83dbSDimitry Andric   }
1885ffd83dbSDimitry Andric   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
1895ffd83dbSDimitry Andric   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
1905ffd83dbSDimitry Andric       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
1915ffd83dbSDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(V))
1925ffd83dbSDimitry Andric       if ((CI->getOpcode() == Instruction::PtrToInt ||
1935ffd83dbSDimitry Andric            CI->getOpcode() == Instruction::IntToPtr) &&
1945ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CI->getType()) ==
1955ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
1965ffd83dbSDimitry Andric         return CI->getOperand(0);
1975ffd83dbSDimitry Andric     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1985ffd83dbSDimitry Andric       if ((CE->getOpcode() == Instruction::PtrToInt ||
1995ffd83dbSDimitry Andric            CE->getOpcode() == Instruction::IntToPtr) &&
2005ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CE->getType()) ==
2015ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
2025ffd83dbSDimitry Andric         return CE->getOperand(0);
2035ffd83dbSDimitry Andric   }
2045ffd83dbSDimitry Andric 
2055ffd83dbSDimitry Andric   // Fold a cast of a constant.
2065ffd83dbSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V))
2075ffd83dbSDimitry Andric     return ConstantExpr::getCast(Op, C, Ty);
2085ffd83dbSDimitry Andric 
209fe6060f1SDimitry Andric   // Try to reuse existing cast, or insert one.
210fe6060f1SDimitry Andric   return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
2115ffd83dbSDimitry Andric }
2125ffd83dbSDimitry Andric 
2135ffd83dbSDimitry Andric /// InsertBinop - Insert the specified binary operator, doing a small amount
2145ffd83dbSDimitry Andric /// of work to avoid inserting an obviously redundant operation, and hoisting
2155ffd83dbSDimitry Andric /// to an outer loop when the opportunity is there and it is safe.
2165ffd83dbSDimitry Andric Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
2175ffd83dbSDimitry Andric                                  Value *LHS, Value *RHS,
2185ffd83dbSDimitry Andric                                  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
2195ffd83dbSDimitry Andric   // Fold a binop with constant operands.
2205ffd83dbSDimitry Andric   if (Constant *CLHS = dyn_cast<Constant>(LHS))
2215ffd83dbSDimitry Andric     if (Constant *CRHS = dyn_cast<Constant>(RHS))
222753f127fSDimitry Andric       if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
223753f127fSDimitry Andric         return Res;
2245ffd83dbSDimitry Andric 
2255ffd83dbSDimitry Andric   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
2265ffd83dbSDimitry Andric   unsigned ScanLimit = 6;
2275ffd83dbSDimitry Andric   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
2285ffd83dbSDimitry Andric   // Scanning starts from the last instruction before the insertion point.
2295ffd83dbSDimitry Andric   BasicBlock::iterator IP = Builder.GetInsertPoint();
2305ffd83dbSDimitry Andric   if (IP != BlockBegin) {
2315ffd83dbSDimitry Andric     --IP;
2325ffd83dbSDimitry Andric     for (; ScanLimit; --IP, --ScanLimit) {
2335ffd83dbSDimitry Andric       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
2345ffd83dbSDimitry Andric       // generated code.
2355ffd83dbSDimitry Andric       if (isa<DbgInfoIntrinsic>(IP))
2365ffd83dbSDimitry Andric         ScanLimit++;
2375ffd83dbSDimitry Andric 
2385ffd83dbSDimitry Andric       auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
2395ffd83dbSDimitry Andric         // Ensure that no-wrap flags match.
2405ffd83dbSDimitry Andric         if (isa<OverflowingBinaryOperator>(I)) {
2415ffd83dbSDimitry Andric           if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
2425ffd83dbSDimitry Andric             return true;
2435ffd83dbSDimitry Andric           if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
2445ffd83dbSDimitry Andric             return true;
2455ffd83dbSDimitry Andric         }
2465ffd83dbSDimitry Andric         // Conservatively, do not use any instruction which has any of exact
2475ffd83dbSDimitry Andric         // flags installed.
2485ffd83dbSDimitry Andric         if (isa<PossiblyExactOperator>(I) && I->isExact())
2495ffd83dbSDimitry Andric           return true;
2505ffd83dbSDimitry Andric         return false;
2515ffd83dbSDimitry Andric       };
2525ffd83dbSDimitry Andric       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
2535ffd83dbSDimitry Andric           IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
2545ffd83dbSDimitry Andric         return &*IP;
2555ffd83dbSDimitry Andric       if (IP == BlockBegin) break;
2565ffd83dbSDimitry Andric     }
2575ffd83dbSDimitry Andric   }
2585ffd83dbSDimitry Andric 
2595ffd83dbSDimitry Andric   // Save the original insertion point so we can restore it when we're done.
2605ffd83dbSDimitry Andric   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
2615ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
2625ffd83dbSDimitry Andric 
2635ffd83dbSDimitry Andric   if (IsSafeToHoist) {
2645ffd83dbSDimitry Andric     // Move the insertion point out of as many loops as we can.
2655ffd83dbSDimitry Andric     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
2665ffd83dbSDimitry Andric       if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
2675ffd83dbSDimitry Andric       BasicBlock *Preheader = L->getLoopPreheader();
2685ffd83dbSDimitry Andric       if (!Preheader) break;
2695ffd83dbSDimitry Andric 
2705ffd83dbSDimitry Andric       // Ok, move up a level.
2715ffd83dbSDimitry Andric       Builder.SetInsertPoint(Preheader->getTerminator());
2725ffd83dbSDimitry Andric     }
2735ffd83dbSDimitry Andric   }
2745ffd83dbSDimitry Andric 
2755ffd83dbSDimitry Andric   // If we haven't found this binop, insert it.
27681ad6265SDimitry Andric   // TODO: Use the Builder, which will make CreateBinOp below fold with
27781ad6265SDimitry Andric   // InstSimplifyFolder.
27881ad6265SDimitry Andric   Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS));
2795ffd83dbSDimitry Andric   BO->setDebugLoc(Loc);
2805ffd83dbSDimitry Andric   if (Flags & SCEV::FlagNUW)
2815ffd83dbSDimitry Andric     BO->setHasNoUnsignedWrap();
2825ffd83dbSDimitry Andric   if (Flags & SCEV::FlagNSW)
2835ffd83dbSDimitry Andric     BO->setHasNoSignedWrap();
2845ffd83dbSDimitry Andric 
2855ffd83dbSDimitry Andric   return BO;
2865ffd83dbSDimitry Andric }
2875ffd83dbSDimitry Andric 
2885ffd83dbSDimitry Andric /// expandAddToGEP - Expand an addition expression with a pointer type into
2895ffd83dbSDimitry Andric /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
2905ffd83dbSDimitry Andric /// BasicAliasAnalysis and other passes analyze the result. See the rules
2915ffd83dbSDimitry Andric /// for getelementptr vs. inttoptr in
2925ffd83dbSDimitry Andric /// http://llvm.org/docs/LangRef.html#pointeraliasing
2935ffd83dbSDimitry Andric /// for details.
2945ffd83dbSDimitry Andric ///
2955ffd83dbSDimitry Andric /// Design note: The correctness of using getelementptr here depends on
2965ffd83dbSDimitry Andric /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
2975ffd83dbSDimitry Andric /// they may introduce pointer arithmetic which may not be safely converted
2985ffd83dbSDimitry Andric /// into getelementptr.
2995ffd83dbSDimitry Andric ///
3005ffd83dbSDimitry Andric /// Design note: It might seem desirable for this function to be more
3015ffd83dbSDimitry Andric /// loop-aware. If some of the indices are loop-invariant while others
3025ffd83dbSDimitry Andric /// aren't, it might seem desirable to emit multiple GEPs, keeping the
3035ffd83dbSDimitry Andric /// loop-invariant portions of the overall computation outside the loop.
3045ffd83dbSDimitry Andric /// However, there are a few reasons this is not done here. Hoisting simple
3055ffd83dbSDimitry Andric /// arithmetic is a low-level optimization that often isn't very
3065ffd83dbSDimitry Andric /// important until late in the optimization process. In fact, passes
3075ffd83dbSDimitry Andric /// like InstructionCombining will combine GEPs, even if it means
3085ffd83dbSDimitry Andric /// pushing loop-invariant computation down into loops, so even if the
3095ffd83dbSDimitry Andric /// GEPs were split here, the work would quickly be undone. The
3105ffd83dbSDimitry Andric /// LoopStrengthReduction pass, which is usually run quite late (and
3115ffd83dbSDimitry Andric /// after the last InstructionCombining pass), takes care of hoisting
3125ffd83dbSDimitry Andric /// loop-invariant portions of expressions, after considering what
3135ffd83dbSDimitry Andric /// can be folded using target addressing modes.
3145ffd83dbSDimitry Andric ///
315*5f757f3fSDimitry Andric Value *SCEVExpander::expandAddToGEP(const SCEV *Offset, Value *V) {
3165ffd83dbSDimitry Andric   assert(!isa<Instruction>(V) ||
3175ffd83dbSDimitry Andric          SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
3185ffd83dbSDimitry Andric 
319*5f757f3fSDimitry Andric   Value *Idx = expand(Offset);
3205ffd83dbSDimitry Andric 
3215ffd83dbSDimitry Andric   // Fold a GEP with constant operands.
3225ffd83dbSDimitry Andric   if (Constant *CLHS = dyn_cast<Constant>(V))
3235ffd83dbSDimitry Andric     if (Constant *CRHS = dyn_cast<Constant>(Idx))
324bdd1243dSDimitry Andric       return Builder.CreateGEP(Builder.getInt8Ty(), CLHS, CRHS);
3255ffd83dbSDimitry Andric 
3265ffd83dbSDimitry Andric   // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
3275ffd83dbSDimitry Andric   unsigned ScanLimit = 6;
3285ffd83dbSDimitry Andric   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
3295ffd83dbSDimitry Andric   // Scanning starts from the last instruction before the insertion point.
3305ffd83dbSDimitry Andric   BasicBlock::iterator IP = Builder.GetInsertPoint();
3315ffd83dbSDimitry Andric   if (IP != BlockBegin) {
3325ffd83dbSDimitry Andric     --IP;
3335ffd83dbSDimitry Andric     for (; ScanLimit; --IP, --ScanLimit) {
3345ffd83dbSDimitry Andric       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
3355ffd83dbSDimitry Andric       // generated code.
3365ffd83dbSDimitry Andric       if (isa<DbgInfoIntrinsic>(IP))
3375ffd83dbSDimitry Andric         ScanLimit++;
3385ffd83dbSDimitry Andric       if (IP->getOpcode() == Instruction::GetElementPtr &&
33981ad6265SDimitry Andric           IP->getOperand(0) == V && IP->getOperand(1) == Idx &&
34081ad6265SDimitry Andric           cast<GEPOperator>(&*IP)->getSourceElementType() ==
341*5f757f3fSDimitry Andric               Builder.getInt8Ty())
3425ffd83dbSDimitry Andric         return &*IP;
3435ffd83dbSDimitry Andric       if (IP == BlockBegin) break;
3445ffd83dbSDimitry Andric     }
3455ffd83dbSDimitry Andric   }
3465ffd83dbSDimitry Andric 
3475ffd83dbSDimitry Andric   // Save the original insertion point so we can restore it when we're done.
3485ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
3495ffd83dbSDimitry Andric 
3505ffd83dbSDimitry Andric   // Move the insertion point out of as many loops as we can.
3515ffd83dbSDimitry Andric   while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
3525ffd83dbSDimitry Andric     if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
3535ffd83dbSDimitry Andric     BasicBlock *Preheader = L->getLoopPreheader();
3545ffd83dbSDimitry Andric     if (!Preheader) break;
3555ffd83dbSDimitry Andric 
3565ffd83dbSDimitry Andric     // Ok, move up a level.
3575ffd83dbSDimitry Andric     Builder.SetInsertPoint(Preheader->getTerminator());
3585ffd83dbSDimitry Andric   }
3595ffd83dbSDimitry Andric 
3605ffd83dbSDimitry Andric   // Emit a GEP.
36106c3fb27SDimitry Andric   return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "scevgep");
3625ffd83dbSDimitry Andric }
3635ffd83dbSDimitry Andric 
3645ffd83dbSDimitry Andric /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
3655ffd83dbSDimitry Andric /// SCEV expansion. If they are nested, this is the most nested. If they are
3665ffd83dbSDimitry Andric /// neighboring, pick the later.
3675ffd83dbSDimitry Andric static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
3685ffd83dbSDimitry Andric                                         DominatorTree &DT) {
3695ffd83dbSDimitry Andric   if (!A) return B;
3705ffd83dbSDimitry Andric   if (!B) return A;
3715ffd83dbSDimitry Andric   if (A->contains(B)) return B;
3725ffd83dbSDimitry Andric   if (B->contains(A)) return A;
3735ffd83dbSDimitry Andric   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
3745ffd83dbSDimitry Andric   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
3755ffd83dbSDimitry Andric   return A; // Arbitrarily break the tie.
3765ffd83dbSDimitry Andric }
3775ffd83dbSDimitry Andric 
3785ffd83dbSDimitry Andric /// getRelevantLoop - Get the most relevant loop associated with the given
3795ffd83dbSDimitry Andric /// expression, according to PickMostRelevantLoop.
3805ffd83dbSDimitry Andric const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
3815ffd83dbSDimitry Andric   // Test whether we've already computed the most relevant loop for this SCEV.
3825ffd83dbSDimitry Andric   auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
3835ffd83dbSDimitry Andric   if (!Pair.second)
3845ffd83dbSDimitry Andric     return Pair.first->second;
3855ffd83dbSDimitry Andric 
386bdd1243dSDimitry Andric   switch (S->getSCEVType()) {
387bdd1243dSDimitry Andric   case scConstant:
38806c3fb27SDimitry Andric   case scVScale:
389bdd1243dSDimitry Andric     return nullptr; // A constant has no relevant loops.
390bdd1243dSDimitry Andric   case scTruncate:
391bdd1243dSDimitry Andric   case scZeroExtend:
392bdd1243dSDimitry Andric   case scSignExtend:
393bdd1243dSDimitry Andric   case scPtrToInt:
394bdd1243dSDimitry Andric   case scAddExpr:
395bdd1243dSDimitry Andric   case scMulExpr:
396bdd1243dSDimitry Andric   case scUDivExpr:
397bdd1243dSDimitry Andric   case scAddRecExpr:
398bdd1243dSDimitry Andric   case scUMaxExpr:
399bdd1243dSDimitry Andric   case scSMaxExpr:
400bdd1243dSDimitry Andric   case scUMinExpr:
401bdd1243dSDimitry Andric   case scSMinExpr:
402bdd1243dSDimitry Andric   case scSequentialUMinExpr: {
403bdd1243dSDimitry Andric     const Loop *L = nullptr;
404bdd1243dSDimitry Andric     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
405bdd1243dSDimitry Andric       L = AR->getLoop();
406bdd1243dSDimitry Andric     for (const SCEV *Op : S->operands())
407bdd1243dSDimitry Andric       L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
408bdd1243dSDimitry Andric     return RelevantLoops[S] = L;
409bdd1243dSDimitry Andric   }
410bdd1243dSDimitry Andric   case scUnknown: {
411bdd1243dSDimitry Andric     const SCEVUnknown *U = cast<SCEVUnknown>(S);
4125ffd83dbSDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
4135ffd83dbSDimitry Andric       return Pair.first->second = SE.LI.getLoopFor(I->getParent());
4145ffd83dbSDimitry Andric     // A non-instruction has no relevant loops.
4155ffd83dbSDimitry Andric     return nullptr;
4165ffd83dbSDimitry Andric   }
417bdd1243dSDimitry Andric   case scCouldNotCompute:
418bdd1243dSDimitry Andric     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4195ffd83dbSDimitry Andric   }
4205ffd83dbSDimitry Andric   llvm_unreachable("Unexpected SCEV type!");
4215ffd83dbSDimitry Andric }
4225ffd83dbSDimitry Andric 
4235ffd83dbSDimitry Andric namespace {
4245ffd83dbSDimitry Andric 
4255ffd83dbSDimitry Andric /// LoopCompare - Compare loops by PickMostRelevantLoop.
4265ffd83dbSDimitry Andric class LoopCompare {
4275ffd83dbSDimitry Andric   DominatorTree &DT;
4285ffd83dbSDimitry Andric public:
4295ffd83dbSDimitry Andric   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
4305ffd83dbSDimitry Andric 
4315ffd83dbSDimitry Andric   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
4325ffd83dbSDimitry Andric                   std::pair<const Loop *, const SCEV *> RHS) const {
4335ffd83dbSDimitry Andric     // Keep pointer operands sorted at the end.
4345ffd83dbSDimitry Andric     if (LHS.second->getType()->isPointerTy() !=
4355ffd83dbSDimitry Andric         RHS.second->getType()->isPointerTy())
4365ffd83dbSDimitry Andric       return LHS.second->getType()->isPointerTy();
4375ffd83dbSDimitry Andric 
4385ffd83dbSDimitry Andric     // Compare loops with PickMostRelevantLoop.
4395ffd83dbSDimitry Andric     if (LHS.first != RHS.first)
4405ffd83dbSDimitry Andric       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
4415ffd83dbSDimitry Andric 
4425ffd83dbSDimitry Andric     // If one operand is a non-constant negative and the other is not,
4435ffd83dbSDimitry Andric     // put the non-constant negative on the right so that a sub can
4445ffd83dbSDimitry Andric     // be used instead of a negate and add.
4455ffd83dbSDimitry Andric     if (LHS.second->isNonConstantNegative()) {
4465ffd83dbSDimitry Andric       if (!RHS.second->isNonConstantNegative())
4475ffd83dbSDimitry Andric         return false;
4485ffd83dbSDimitry Andric     } else if (RHS.second->isNonConstantNegative())
4495ffd83dbSDimitry Andric       return true;
4505ffd83dbSDimitry Andric 
4515ffd83dbSDimitry Andric     // Otherwise they are equivalent according to this comparison.
4525ffd83dbSDimitry Andric     return false;
4535ffd83dbSDimitry Andric   }
4545ffd83dbSDimitry Andric };
4555ffd83dbSDimitry Andric 
4565ffd83dbSDimitry Andric }
4575ffd83dbSDimitry Andric 
4585ffd83dbSDimitry Andric Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
4595ffd83dbSDimitry Andric   // Collect all the add operands in a loop, along with their associated loops.
4605ffd83dbSDimitry Andric   // Iterate in reverse so that constants are emitted last, all else equal, and
4615ffd83dbSDimitry Andric   // so that pointer operands are inserted first, which the code below relies on
4625ffd83dbSDimitry Andric   // to form more involved GEPs.
4635ffd83dbSDimitry Andric   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
464349cc55cSDimitry Andric   for (const SCEV *Op : reverse(S->operands()))
465349cc55cSDimitry Andric     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
4665ffd83dbSDimitry Andric 
4675ffd83dbSDimitry Andric   // Sort by loop. Use a stable sort so that constants follow non-constants and
4685ffd83dbSDimitry Andric   // pointer operands precede non-pointer operands.
4695ffd83dbSDimitry Andric   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
4705ffd83dbSDimitry Andric 
4715ffd83dbSDimitry Andric   // Emit instructions to add all the operands. Hoist as much as possible
4725ffd83dbSDimitry Andric   // out of loops, and form meaningful getelementptrs where possible.
4735ffd83dbSDimitry Andric   Value *Sum = nullptr;
4745ffd83dbSDimitry Andric   for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
4755ffd83dbSDimitry Andric     const Loop *CurLoop = I->first;
4765ffd83dbSDimitry Andric     const SCEV *Op = I->second;
4775ffd83dbSDimitry Andric     if (!Sum) {
4785ffd83dbSDimitry Andric       // This is the first operand. Just expand it.
4795ffd83dbSDimitry Andric       Sum = expand(Op);
4805ffd83dbSDimitry Andric       ++I;
481349cc55cSDimitry Andric       continue;
482349cc55cSDimitry Andric     }
483349cc55cSDimitry Andric 
484349cc55cSDimitry Andric     assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
48506c3fb27SDimitry Andric     if (isa<PointerType>(Sum->getType())) {
4865ffd83dbSDimitry Andric       // The running sum expression is a pointer. Try to form a getelementptr
4875ffd83dbSDimitry Andric       // at this level with that as the base.
4885ffd83dbSDimitry Andric       SmallVector<const SCEV *, 4> NewOps;
4895ffd83dbSDimitry Andric       for (; I != E && I->first == CurLoop; ++I) {
4905ffd83dbSDimitry Andric         // If the operand is SCEVUnknown and not instructions, peek through
4915ffd83dbSDimitry Andric         // it, to enable more of it to be folded into the GEP.
4925ffd83dbSDimitry Andric         const SCEV *X = I->second;
4935ffd83dbSDimitry Andric         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
4945ffd83dbSDimitry Andric           if (!isa<Instruction>(U->getValue()))
4955ffd83dbSDimitry Andric             X = SE.getSCEV(U->getValue());
4965ffd83dbSDimitry Andric         NewOps.push_back(X);
4975ffd83dbSDimitry Andric       }
498*5f757f3fSDimitry Andric       Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum);
4995ffd83dbSDimitry Andric     } else if (Op->isNonConstantNegative()) {
5005ffd83dbSDimitry Andric       // Instead of doing a negate and add, just do a subtract.
501*5f757f3fSDimitry Andric       Value *W = expand(SE.getNegativeSCEV(Op));
5025ffd83dbSDimitry Andric       Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
5035ffd83dbSDimitry Andric                         /*IsSafeToHoist*/ true);
5045ffd83dbSDimitry Andric       ++I;
5055ffd83dbSDimitry Andric     } else {
5065ffd83dbSDimitry Andric       // A simple add.
507*5f757f3fSDimitry Andric       Value *W = expand(Op);
5085ffd83dbSDimitry Andric       // Canonicalize a constant to the RHS.
509*5f757f3fSDimitry Andric       if (isa<Constant>(Sum))
510*5f757f3fSDimitry Andric         std::swap(Sum, W);
5115ffd83dbSDimitry Andric       Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
5125ffd83dbSDimitry Andric                         /*IsSafeToHoist*/ true);
5135ffd83dbSDimitry Andric       ++I;
5145ffd83dbSDimitry Andric     }
5155ffd83dbSDimitry Andric   }
5165ffd83dbSDimitry Andric 
5175ffd83dbSDimitry Andric   return Sum;
5185ffd83dbSDimitry Andric }
5195ffd83dbSDimitry Andric 
5205ffd83dbSDimitry Andric Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
521*5f757f3fSDimitry Andric   Type *Ty = S->getType();
5225ffd83dbSDimitry Andric 
5235ffd83dbSDimitry Andric   // Collect all the mul operands in a loop, along with their associated loops.
5245ffd83dbSDimitry Andric   // Iterate in reverse so that constants are emitted last, all else equal.
5255ffd83dbSDimitry Andric   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
526349cc55cSDimitry Andric   for (const SCEV *Op : reverse(S->operands()))
527349cc55cSDimitry Andric     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
5285ffd83dbSDimitry Andric 
5295ffd83dbSDimitry Andric   // Sort by loop. Use a stable sort so that constants follow non-constants.
5305ffd83dbSDimitry Andric   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
5315ffd83dbSDimitry Andric 
5325ffd83dbSDimitry Andric   // Emit instructions to mul all the operands. Hoist as much as possible
5335ffd83dbSDimitry Andric   // out of loops.
5345ffd83dbSDimitry Andric   Value *Prod = nullptr;
5355ffd83dbSDimitry Andric   auto I = OpsAndLoops.begin();
5365ffd83dbSDimitry Andric 
5375ffd83dbSDimitry Andric   // Expand the calculation of X pow N in the following manner:
5385ffd83dbSDimitry Andric   // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
5395ffd83dbSDimitry Andric   // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
540*5f757f3fSDimitry Andric   const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() {
5415ffd83dbSDimitry Andric     auto E = I;
5425ffd83dbSDimitry Andric     // Calculate how many times the same operand from the same loop is included
5435ffd83dbSDimitry Andric     // into this power.
5445ffd83dbSDimitry Andric     uint64_t Exponent = 0;
5455ffd83dbSDimitry Andric     const uint64_t MaxExponent = UINT64_MAX >> 1;
5465ffd83dbSDimitry Andric     // No one sane will ever try to calculate such huge exponents, but if we
5475ffd83dbSDimitry Andric     // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
5485ffd83dbSDimitry Andric     // below when the power of 2 exceeds our Exponent, and we want it to be
5495ffd83dbSDimitry Andric     // 1u << 31 at most to not deal with unsigned overflow.
5505ffd83dbSDimitry Andric     while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
5515ffd83dbSDimitry Andric       ++Exponent;
5525ffd83dbSDimitry Andric       ++E;
5535ffd83dbSDimitry Andric     }
5545ffd83dbSDimitry Andric     assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
5555ffd83dbSDimitry Andric 
5565ffd83dbSDimitry Andric     // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
5575ffd83dbSDimitry Andric     // that are needed into the result.
558*5f757f3fSDimitry Andric     Value *P = expand(I->second);
5595ffd83dbSDimitry Andric     Value *Result = nullptr;
5605ffd83dbSDimitry Andric     if (Exponent & 1)
5615ffd83dbSDimitry Andric       Result = P;
5625ffd83dbSDimitry Andric     for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
5635ffd83dbSDimitry Andric       P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
5645ffd83dbSDimitry Andric                       /*IsSafeToHoist*/ true);
5655ffd83dbSDimitry Andric       if (Exponent & BinExp)
5665ffd83dbSDimitry Andric         Result = Result ? InsertBinop(Instruction::Mul, Result, P,
5675ffd83dbSDimitry Andric                                       SCEV::FlagAnyWrap,
5685ffd83dbSDimitry Andric                                       /*IsSafeToHoist*/ true)
5695ffd83dbSDimitry Andric                         : P;
5705ffd83dbSDimitry Andric     }
5715ffd83dbSDimitry Andric 
5725ffd83dbSDimitry Andric     I = E;
5735ffd83dbSDimitry Andric     assert(Result && "Nothing was expanded?");
5745ffd83dbSDimitry Andric     return Result;
5755ffd83dbSDimitry Andric   };
5765ffd83dbSDimitry Andric 
5775ffd83dbSDimitry Andric   while (I != OpsAndLoops.end()) {
5785ffd83dbSDimitry Andric     if (!Prod) {
5795ffd83dbSDimitry Andric       // This is the first operand. Just expand it.
5805ffd83dbSDimitry Andric       Prod = ExpandOpBinPowN();
5815ffd83dbSDimitry Andric     } else if (I->second->isAllOnesValue()) {
5825ffd83dbSDimitry Andric       // Instead of doing a multiply by negative one, just do a negate.
5835ffd83dbSDimitry Andric       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
5845ffd83dbSDimitry Andric                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
5855ffd83dbSDimitry Andric       ++I;
5865ffd83dbSDimitry Andric     } else {
5875ffd83dbSDimitry Andric       // A simple mul.
5885ffd83dbSDimitry Andric       Value *W = ExpandOpBinPowN();
5895ffd83dbSDimitry Andric       // Canonicalize a constant to the RHS.
5905ffd83dbSDimitry Andric       if (isa<Constant>(Prod)) std::swap(Prod, W);
5915ffd83dbSDimitry Andric       const APInt *RHS;
5925ffd83dbSDimitry Andric       if (match(W, m_Power2(RHS))) {
5935ffd83dbSDimitry Andric         // Canonicalize Prod*(1<<C) to Prod<<C.
5945ffd83dbSDimitry Andric         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
5955ffd83dbSDimitry Andric         auto NWFlags = S->getNoWrapFlags();
5965ffd83dbSDimitry Andric         // clear nsw flag if shl will produce poison value.
5975ffd83dbSDimitry Andric         if (RHS->logBase2() == RHS->getBitWidth() - 1)
5985ffd83dbSDimitry Andric           NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
5995ffd83dbSDimitry Andric         Prod = InsertBinop(Instruction::Shl, Prod,
6005ffd83dbSDimitry Andric                            ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
6015ffd83dbSDimitry Andric                            /*IsSafeToHoist*/ true);
6025ffd83dbSDimitry Andric       } else {
6035ffd83dbSDimitry Andric         Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
6045ffd83dbSDimitry Andric                            /*IsSafeToHoist*/ true);
6055ffd83dbSDimitry Andric       }
6065ffd83dbSDimitry Andric     }
6075ffd83dbSDimitry Andric   }
6085ffd83dbSDimitry Andric 
6095ffd83dbSDimitry Andric   return Prod;
6105ffd83dbSDimitry Andric }
6115ffd83dbSDimitry Andric 
6125ffd83dbSDimitry Andric Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
613*5f757f3fSDimitry Andric   Value *LHS = expand(S->getLHS());
6145ffd83dbSDimitry Andric   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
6155ffd83dbSDimitry Andric     const APInt &RHS = SC->getAPInt();
6165ffd83dbSDimitry Andric     if (RHS.isPowerOf2())
6175ffd83dbSDimitry Andric       return InsertBinop(Instruction::LShr, LHS,
618*5f757f3fSDimitry Andric                          ConstantInt::get(SC->getType(), RHS.logBase2()),
6195ffd83dbSDimitry Andric                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
6205ffd83dbSDimitry Andric   }
6215ffd83dbSDimitry Andric 
622*5f757f3fSDimitry Andric   Value *RHS = expand(S->getRHS());
6235ffd83dbSDimitry Andric   return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
6245ffd83dbSDimitry Andric                      /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
6255ffd83dbSDimitry Andric }
6265ffd83dbSDimitry Andric 
6275ffd83dbSDimitry Andric /// Determine if this is a well-behaved chain of instructions leading back to
6285ffd83dbSDimitry Andric /// the PHI. If so, it may be reused by expanded expressions.
6295ffd83dbSDimitry Andric bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
6305ffd83dbSDimitry Andric                                          const Loop *L) {
6315ffd83dbSDimitry Andric   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
6325ffd83dbSDimitry Andric       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
6335ffd83dbSDimitry Andric     return false;
6345ffd83dbSDimitry Andric   // If any of the operands don't dominate the insert position, bail.
6355ffd83dbSDimitry Andric   // Addrec operands are always loop-invariant, so this can only happen
6365ffd83dbSDimitry Andric   // if there are instructions which haven't been hoisted.
6375ffd83dbSDimitry Andric   if (L == IVIncInsertLoop) {
638fe6060f1SDimitry Andric     for (Use &Op : llvm::drop_begin(IncV->operands()))
639fe6060f1SDimitry Andric       if (Instruction *OInst = dyn_cast<Instruction>(Op))
6405ffd83dbSDimitry Andric         if (!SE.DT.dominates(OInst, IVIncInsertPos))
6415ffd83dbSDimitry Andric           return false;
6425ffd83dbSDimitry Andric   }
6435ffd83dbSDimitry Andric   // Advance to the next instruction.
6445ffd83dbSDimitry Andric   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
6455ffd83dbSDimitry Andric   if (!IncV)
6465ffd83dbSDimitry Andric     return false;
6475ffd83dbSDimitry Andric 
6485ffd83dbSDimitry Andric   if (IncV->mayHaveSideEffects())
6495ffd83dbSDimitry Andric     return false;
6505ffd83dbSDimitry Andric 
6515ffd83dbSDimitry Andric   if (IncV == PN)
6525ffd83dbSDimitry Andric     return true;
6535ffd83dbSDimitry Andric 
6545ffd83dbSDimitry Andric   return isNormalAddRecExprPHI(PN, IncV, L);
6555ffd83dbSDimitry Andric }
6565ffd83dbSDimitry Andric 
6575ffd83dbSDimitry Andric /// getIVIncOperand returns an induction variable increment's induction
6585ffd83dbSDimitry Andric /// variable operand.
6595ffd83dbSDimitry Andric ///
6605ffd83dbSDimitry Andric /// If allowScale is set, any type of GEP is allowed as long as the nonIV
6615ffd83dbSDimitry Andric /// operands dominate InsertPos.
6625ffd83dbSDimitry Andric ///
6635ffd83dbSDimitry Andric /// If allowScale is not set, ensure that a GEP increment conforms to one of the
6645ffd83dbSDimitry Andric /// simple patterns generated by getAddRecExprPHILiterally and
6655ffd83dbSDimitry Andric /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
6665ffd83dbSDimitry Andric Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
6675ffd83dbSDimitry Andric                                            Instruction *InsertPos,
6685ffd83dbSDimitry Andric                                            bool allowScale) {
6695ffd83dbSDimitry Andric   if (IncV == InsertPos)
6705ffd83dbSDimitry Andric     return nullptr;
6715ffd83dbSDimitry Andric 
6725ffd83dbSDimitry Andric   switch (IncV->getOpcode()) {
6735ffd83dbSDimitry Andric   default:
6745ffd83dbSDimitry Andric     return nullptr;
6755ffd83dbSDimitry Andric   // Check for a simple Add/Sub or GEP of a loop invariant step.
6765ffd83dbSDimitry Andric   case Instruction::Add:
6775ffd83dbSDimitry Andric   case Instruction::Sub: {
6785ffd83dbSDimitry Andric     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
6795ffd83dbSDimitry Andric     if (!OInst || SE.DT.dominates(OInst, InsertPos))
6805ffd83dbSDimitry Andric       return dyn_cast<Instruction>(IncV->getOperand(0));
6815ffd83dbSDimitry Andric     return nullptr;
6825ffd83dbSDimitry Andric   }
6835ffd83dbSDimitry Andric   case Instruction::BitCast:
6845ffd83dbSDimitry Andric     return dyn_cast<Instruction>(IncV->getOperand(0));
6855ffd83dbSDimitry Andric   case Instruction::GetElementPtr:
686fe6060f1SDimitry Andric     for (Use &U : llvm::drop_begin(IncV->operands())) {
687fe6060f1SDimitry Andric       if (isa<Constant>(U))
6885ffd83dbSDimitry Andric         continue;
689fe6060f1SDimitry Andric       if (Instruction *OInst = dyn_cast<Instruction>(U)) {
6905ffd83dbSDimitry Andric         if (!SE.DT.dominates(OInst, InsertPos))
6915ffd83dbSDimitry Andric           return nullptr;
6925ffd83dbSDimitry Andric       }
6935ffd83dbSDimitry Andric       if (allowScale) {
6945ffd83dbSDimitry Andric         // allow any kind of GEP as long as it can be hoisted.
6955ffd83dbSDimitry Andric         continue;
6965ffd83dbSDimitry Andric       }
69706c3fb27SDimitry Andric       // GEPs produced by SCEVExpander use i8 element type.
69806c3fb27SDimitry Andric       if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
6995ffd83dbSDimitry Andric         return nullptr;
7005ffd83dbSDimitry Andric       break;
7015ffd83dbSDimitry Andric     }
7025ffd83dbSDimitry Andric     return dyn_cast<Instruction>(IncV->getOperand(0));
7035ffd83dbSDimitry Andric   }
7045ffd83dbSDimitry Andric }
7055ffd83dbSDimitry Andric 
7065ffd83dbSDimitry Andric /// If the insert point of the current builder or any of the builders on the
7075ffd83dbSDimitry Andric /// stack of saved builders has 'I' as its insert point, update it to point to
7085ffd83dbSDimitry Andric /// the instruction after 'I'.  This is intended to be used when the instruction
7095ffd83dbSDimitry Andric /// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
7105ffd83dbSDimitry Andric /// different block, the inconsistent insert point (with a mismatched
7115ffd83dbSDimitry Andric /// Instruction and Block) can lead to an instruction being inserted in a block
7125ffd83dbSDimitry Andric /// other than its parent.
7135ffd83dbSDimitry Andric void SCEVExpander::fixupInsertPoints(Instruction *I) {
7145ffd83dbSDimitry Andric   BasicBlock::iterator It(*I);
7155ffd83dbSDimitry Andric   BasicBlock::iterator NewInsertPt = std::next(It);
7165ffd83dbSDimitry Andric   if (Builder.GetInsertPoint() == It)
7175ffd83dbSDimitry Andric     Builder.SetInsertPoint(&*NewInsertPt);
7185ffd83dbSDimitry Andric   for (auto *InsertPtGuard : InsertPointGuards)
7195ffd83dbSDimitry Andric     if (InsertPtGuard->GetInsertPoint() == It)
7205ffd83dbSDimitry Andric       InsertPtGuard->SetInsertPoint(NewInsertPt);
7215ffd83dbSDimitry Andric }
7225ffd83dbSDimitry Andric 
7235ffd83dbSDimitry Andric /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
7245ffd83dbSDimitry Andric /// it available to other uses in this loop. Recursively hoist any operands,
7255ffd83dbSDimitry Andric /// until we reach a value that dominates InsertPos.
726bdd1243dSDimitry Andric bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos,
727bdd1243dSDimitry Andric                               bool RecomputePoisonFlags) {
728bdd1243dSDimitry Andric   auto FixupPoisonFlags = [this](Instruction *I) {
729bdd1243dSDimitry Andric     // Drop flags that are potentially inferred from old context and infer flags
730bdd1243dSDimitry Andric     // in new context.
731bdd1243dSDimitry Andric     I->dropPoisonGeneratingFlags();
732bdd1243dSDimitry Andric     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
733bdd1243dSDimitry Andric       if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
734bdd1243dSDimitry Andric         auto *BO = cast<BinaryOperator>(I);
735bdd1243dSDimitry Andric         BO->setHasNoUnsignedWrap(
736bdd1243dSDimitry Andric             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
737bdd1243dSDimitry Andric         BO->setHasNoSignedWrap(
738bdd1243dSDimitry Andric             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
739bdd1243dSDimitry Andric       }
740bdd1243dSDimitry Andric   };
741bdd1243dSDimitry Andric 
742bdd1243dSDimitry Andric   if (SE.DT.dominates(IncV, InsertPos)) {
743bdd1243dSDimitry Andric     if (RecomputePoisonFlags)
744bdd1243dSDimitry Andric       FixupPoisonFlags(IncV);
7455ffd83dbSDimitry Andric     return true;
746bdd1243dSDimitry Andric   }
7475ffd83dbSDimitry Andric 
7485ffd83dbSDimitry Andric   // InsertPos must itself dominate IncV so that IncV's new position satisfies
7495ffd83dbSDimitry Andric   // its existing users.
7505ffd83dbSDimitry Andric   if (isa<PHINode>(InsertPos) ||
7515ffd83dbSDimitry Andric       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
7525ffd83dbSDimitry Andric     return false;
7535ffd83dbSDimitry Andric 
7545ffd83dbSDimitry Andric   if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
7555ffd83dbSDimitry Andric     return false;
7565ffd83dbSDimitry Andric 
7575ffd83dbSDimitry Andric   // Check that the chain of IV operands leading back to Phi can be hoisted.
7585ffd83dbSDimitry Andric   SmallVector<Instruction*, 4> IVIncs;
7595ffd83dbSDimitry Andric   for(;;) {
7605ffd83dbSDimitry Andric     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
7615ffd83dbSDimitry Andric     if (!Oper)
7625ffd83dbSDimitry Andric       return false;
7635ffd83dbSDimitry Andric     // IncV is safe to hoist.
7645ffd83dbSDimitry Andric     IVIncs.push_back(IncV);
7655ffd83dbSDimitry Andric     IncV = Oper;
7665ffd83dbSDimitry Andric     if (SE.DT.dominates(IncV, InsertPos))
7675ffd83dbSDimitry Andric       break;
7685ffd83dbSDimitry Andric   }
7690eae32dcSDimitry Andric   for (Instruction *I : llvm::reverse(IVIncs)) {
7700eae32dcSDimitry Andric     fixupInsertPoints(I);
7710eae32dcSDimitry Andric     I->moveBefore(InsertPos);
772bdd1243dSDimitry Andric     if (RecomputePoisonFlags)
773bdd1243dSDimitry Andric       FixupPoisonFlags(I);
7745ffd83dbSDimitry Andric   }
7755ffd83dbSDimitry Andric   return true;
7765ffd83dbSDimitry Andric }
7775ffd83dbSDimitry Andric 
7785ffd83dbSDimitry Andric /// Determine if this cyclic phi is in a form that would have been generated by
7795ffd83dbSDimitry Andric /// LSR. We don't care if the phi was actually expanded in this pass, as long
7805ffd83dbSDimitry Andric /// as it is in a low-cost form, for example, no implied multiplication. This
7815ffd83dbSDimitry Andric /// should match any patterns generated by getAddRecExprPHILiterally and
7825ffd83dbSDimitry Andric /// expandAddtoGEP.
7835ffd83dbSDimitry Andric bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
7845ffd83dbSDimitry Andric                                            const Loop *L) {
7855ffd83dbSDimitry Andric   for(Instruction *IVOper = IncV;
7865ffd83dbSDimitry Andric       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
7875ffd83dbSDimitry Andric                                 /*allowScale=*/false));) {
7885ffd83dbSDimitry Andric     if (IVOper == PN)
7895ffd83dbSDimitry Andric       return true;
7905ffd83dbSDimitry Andric   }
7915ffd83dbSDimitry Andric   return false;
7925ffd83dbSDimitry Andric }
7935ffd83dbSDimitry Andric 
7945ffd83dbSDimitry Andric /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
7955ffd83dbSDimitry Andric /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
7965ffd83dbSDimitry Andric /// need to materialize IV increments elsewhere to handle difficult situations.
7975ffd83dbSDimitry Andric Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
7985ffd83dbSDimitry Andric                                  bool useSubtract) {
7995ffd83dbSDimitry Andric   Value *IncV;
8005ffd83dbSDimitry Andric   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
801*5f757f3fSDimitry Andric   if (PN->getType()->isPointerTy()) {
802*5f757f3fSDimitry Andric     IncV = expandAddToGEP(SE.getSCEV(StepV), PN);
8035ffd83dbSDimitry Andric   } else {
8045ffd83dbSDimitry Andric     IncV = useSubtract ?
8055ffd83dbSDimitry Andric       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
8065ffd83dbSDimitry Andric       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
8075ffd83dbSDimitry Andric   }
8085ffd83dbSDimitry Andric   return IncV;
8095ffd83dbSDimitry Andric }
8105ffd83dbSDimitry Andric 
8115ffd83dbSDimitry Andric /// Check whether we can cheaply express the requested SCEV in terms of
8125ffd83dbSDimitry Andric /// the available PHI SCEV by truncation and/or inversion of the step.
8135ffd83dbSDimitry Andric static bool canBeCheaplyTransformed(ScalarEvolution &SE,
8145ffd83dbSDimitry Andric                                     const SCEVAddRecExpr *Phi,
8155ffd83dbSDimitry Andric                                     const SCEVAddRecExpr *Requested,
8165ffd83dbSDimitry Andric                                     bool &InvertStep) {
817fe6060f1SDimitry Andric   // We can't transform to match a pointer PHI.
818*5f757f3fSDimitry Andric   Type *PhiTy = Phi->getType();
819*5f757f3fSDimitry Andric   Type *RequestedTy = Requested->getType();
820*5f757f3fSDimitry Andric   if (PhiTy->isPointerTy() || RequestedTy->isPointerTy())
821fe6060f1SDimitry Andric     return false;
822fe6060f1SDimitry Andric 
8235ffd83dbSDimitry Andric   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
8245ffd83dbSDimitry Andric     return false;
8255ffd83dbSDimitry Andric 
8265ffd83dbSDimitry Andric   // Try truncate it if necessary.
8275ffd83dbSDimitry Andric   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
8285ffd83dbSDimitry Andric   if (!Phi)
8295ffd83dbSDimitry Andric     return false;
8305ffd83dbSDimitry Andric 
8315ffd83dbSDimitry Andric   // Check whether truncation will help.
8325ffd83dbSDimitry Andric   if (Phi == Requested) {
8335ffd83dbSDimitry Andric     InvertStep = false;
8345ffd83dbSDimitry Andric     return true;
8355ffd83dbSDimitry Andric   }
8365ffd83dbSDimitry Andric 
8375ffd83dbSDimitry Andric   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
838fe6060f1SDimitry Andric   if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
8395ffd83dbSDimitry Andric     InvertStep = true;
8405ffd83dbSDimitry Andric     return true;
8415ffd83dbSDimitry Andric   }
8425ffd83dbSDimitry Andric 
8435ffd83dbSDimitry Andric   return false;
8445ffd83dbSDimitry Andric }
8455ffd83dbSDimitry Andric 
8465ffd83dbSDimitry Andric static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
8475ffd83dbSDimitry Andric   if (!isa<IntegerType>(AR->getType()))
8485ffd83dbSDimitry Andric     return false;
8495ffd83dbSDimitry Andric 
8505ffd83dbSDimitry Andric   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
8515ffd83dbSDimitry Andric   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
8525ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
8535ffd83dbSDimitry Andric   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
8545ffd83dbSDimitry Andric                                             SE.getSignExtendExpr(AR, WideTy));
8555ffd83dbSDimitry Andric   const SCEV *ExtendAfterOp =
8565ffd83dbSDimitry Andric     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
8575ffd83dbSDimitry Andric   return ExtendAfterOp == OpAfterExtend;
8585ffd83dbSDimitry Andric }
8595ffd83dbSDimitry Andric 
8605ffd83dbSDimitry Andric static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
8615ffd83dbSDimitry Andric   if (!isa<IntegerType>(AR->getType()))
8625ffd83dbSDimitry Andric     return false;
8635ffd83dbSDimitry Andric 
8645ffd83dbSDimitry Andric   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
8655ffd83dbSDimitry Andric   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
8665ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
8675ffd83dbSDimitry Andric   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
8685ffd83dbSDimitry Andric                                             SE.getZeroExtendExpr(AR, WideTy));
8695ffd83dbSDimitry Andric   const SCEV *ExtendAfterOp =
8705ffd83dbSDimitry Andric     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
8715ffd83dbSDimitry Andric   return ExtendAfterOp == OpAfterExtend;
8725ffd83dbSDimitry Andric }
8735ffd83dbSDimitry Andric 
8745ffd83dbSDimitry Andric /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
8755ffd83dbSDimitry Andric /// the base addrec, which is the addrec without any non-loop-dominating
8765ffd83dbSDimitry Andric /// values, and return the PHI.
8775ffd83dbSDimitry Andric PHINode *
8785ffd83dbSDimitry Andric SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
879*5f757f3fSDimitry Andric                                         const Loop *L, Type *&TruncTy,
8805ffd83dbSDimitry Andric                                         bool &InvertStep) {
881*5f757f3fSDimitry Andric   assert((!IVIncInsertLoop || IVIncInsertPos) &&
882*5f757f3fSDimitry Andric          "Uninitialized insert position");
8835ffd83dbSDimitry Andric 
8845ffd83dbSDimitry Andric   // Reuse a previously-inserted PHI, if present.
8855ffd83dbSDimitry Andric   BasicBlock *LatchBlock = L->getLoopLatch();
8865ffd83dbSDimitry Andric   if (LatchBlock) {
8875ffd83dbSDimitry Andric     PHINode *AddRecPhiMatch = nullptr;
8885ffd83dbSDimitry Andric     Instruction *IncV = nullptr;
8895ffd83dbSDimitry Andric     TruncTy = nullptr;
8905ffd83dbSDimitry Andric     InvertStep = false;
8915ffd83dbSDimitry Andric 
8925ffd83dbSDimitry Andric     // Only try partially matching scevs that need truncation and/or
8935ffd83dbSDimitry Andric     // step-inversion if we know this loop is outside the current loop.
8945ffd83dbSDimitry Andric     bool TryNonMatchingSCEV =
8955ffd83dbSDimitry Andric         IVIncInsertLoop &&
8965ffd83dbSDimitry Andric         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
8975ffd83dbSDimitry Andric 
8985ffd83dbSDimitry Andric     for (PHINode &PN : L->getHeader()->phis()) {
8995ffd83dbSDimitry Andric       if (!SE.isSCEVable(PN.getType()))
9005ffd83dbSDimitry Andric         continue;
9015ffd83dbSDimitry Andric 
902e8d8bef9SDimitry Andric       // We should not look for a incomplete PHI. Getting SCEV for a incomplete
903e8d8bef9SDimitry Andric       // PHI has no meaning at all.
904e8d8bef9SDimitry Andric       if (!PN.isComplete()) {
905fe6060f1SDimitry Andric         SCEV_DEBUG_WITH_TYPE(
906e8d8bef9SDimitry Andric             DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
907e8d8bef9SDimitry Andric         continue;
908e8d8bef9SDimitry Andric       }
909e8d8bef9SDimitry Andric 
9105ffd83dbSDimitry Andric       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
9115ffd83dbSDimitry Andric       if (!PhiSCEV)
9125ffd83dbSDimitry Andric         continue;
9135ffd83dbSDimitry Andric 
9145ffd83dbSDimitry Andric       bool IsMatchingSCEV = PhiSCEV == Normalized;
9155ffd83dbSDimitry Andric       // We only handle truncation and inversion of phi recurrences for the
9165ffd83dbSDimitry Andric       // expanded expression if the expanded expression's loop dominates the
9175ffd83dbSDimitry Andric       // loop we insert to. Check now, so we can bail out early.
9185ffd83dbSDimitry Andric       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
9195ffd83dbSDimitry Andric           continue;
9205ffd83dbSDimitry Andric 
9215ffd83dbSDimitry Andric       // TODO: this possibly can be reworked to avoid this cast at all.
9225ffd83dbSDimitry Andric       Instruction *TempIncV =
9235ffd83dbSDimitry Andric           dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
9245ffd83dbSDimitry Andric       if (!TempIncV)
9255ffd83dbSDimitry Andric         continue;
9265ffd83dbSDimitry Andric 
9275ffd83dbSDimitry Andric       // Check whether we can reuse this PHI node.
9285ffd83dbSDimitry Andric       if (LSRMode) {
9295ffd83dbSDimitry Andric         if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
9305ffd83dbSDimitry Andric           continue;
9315ffd83dbSDimitry Andric       } else {
9325ffd83dbSDimitry Andric         if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
9335ffd83dbSDimitry Andric           continue;
9345ffd83dbSDimitry Andric       }
9355ffd83dbSDimitry Andric 
9365ffd83dbSDimitry Andric       // Stop if we have found an exact match SCEV.
9375ffd83dbSDimitry Andric       if (IsMatchingSCEV) {
9385ffd83dbSDimitry Andric         IncV = TempIncV;
9395ffd83dbSDimitry Andric         TruncTy = nullptr;
9405ffd83dbSDimitry Andric         InvertStep = false;
9415ffd83dbSDimitry Andric         AddRecPhiMatch = &PN;
9425ffd83dbSDimitry Andric         break;
9435ffd83dbSDimitry Andric       }
9445ffd83dbSDimitry Andric 
9455ffd83dbSDimitry Andric       // Try whether the phi can be translated into the requested form
9465ffd83dbSDimitry Andric       // (truncated and/or offset by a constant).
9475ffd83dbSDimitry Andric       if ((!TruncTy || InvertStep) &&
9485ffd83dbSDimitry Andric           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
9495ffd83dbSDimitry Andric         // Record the phi node. But don't stop we might find an exact match
9505ffd83dbSDimitry Andric         // later.
9515ffd83dbSDimitry Andric         AddRecPhiMatch = &PN;
9525ffd83dbSDimitry Andric         IncV = TempIncV;
953*5f757f3fSDimitry Andric         TruncTy = Normalized->getType();
9545ffd83dbSDimitry Andric       }
9555ffd83dbSDimitry Andric     }
9565ffd83dbSDimitry Andric 
9575ffd83dbSDimitry Andric     if (AddRecPhiMatch) {
9585ffd83dbSDimitry Andric       // Ok, the add recurrence looks usable.
9595ffd83dbSDimitry Andric       // Remember this PHI, even in post-inc mode.
9605ffd83dbSDimitry Andric       InsertedValues.insert(AddRecPhiMatch);
9615ffd83dbSDimitry Andric       // Remember the increment.
9625ffd83dbSDimitry Andric       rememberInstruction(IncV);
963e8d8bef9SDimitry Andric       // Those values were not actually inserted but re-used.
964e8d8bef9SDimitry Andric       ReusedValues.insert(AddRecPhiMatch);
965e8d8bef9SDimitry Andric       ReusedValues.insert(IncV);
9665ffd83dbSDimitry Andric       return AddRecPhiMatch;
9675ffd83dbSDimitry Andric     }
9685ffd83dbSDimitry Andric   }
9695ffd83dbSDimitry Andric 
9705ffd83dbSDimitry Andric   // Save the original insertion point so we can restore it when we're done.
9715ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
9725ffd83dbSDimitry Andric 
9735ffd83dbSDimitry Andric   // Another AddRec may need to be recursively expanded below. For example, if
9745ffd83dbSDimitry Andric   // this AddRec is quadratic, the StepV may itself be an AddRec in this
9755ffd83dbSDimitry Andric   // loop. Remove this loop from the PostIncLoops set before expanding such
9765ffd83dbSDimitry Andric   // AddRecs. Otherwise, we cannot find a valid position for the step
9775ffd83dbSDimitry Andric   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
9785ffd83dbSDimitry Andric   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
9795ffd83dbSDimitry Andric   // so it's not worth implementing SmallPtrSet::swap.
9805ffd83dbSDimitry Andric   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
9815ffd83dbSDimitry Andric   PostIncLoops.clear();
9825ffd83dbSDimitry Andric 
9835ffd83dbSDimitry Andric   // Expand code for the start value into the loop preheader.
9845ffd83dbSDimitry Andric   assert(L->getLoopPreheader() &&
9855ffd83dbSDimitry Andric          "Can't expand add recurrences without a loop preheader!");
986e8d8bef9SDimitry Andric   Value *StartV =
987*5f757f3fSDimitry Andric       expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator());
9885ffd83dbSDimitry Andric 
9895ffd83dbSDimitry Andric   // StartV must have been be inserted into L's preheader to dominate the new
9905ffd83dbSDimitry Andric   // phi.
9915ffd83dbSDimitry Andric   assert(!isa<Instruction>(StartV) ||
9925ffd83dbSDimitry Andric          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
9935ffd83dbSDimitry Andric                                  L->getHeader()));
9945ffd83dbSDimitry Andric 
9955ffd83dbSDimitry Andric   // Expand code for the step value. Do this before creating the PHI so that PHI
9965ffd83dbSDimitry Andric   // reuse code doesn't see an incomplete PHI.
9975ffd83dbSDimitry Andric   const SCEV *Step = Normalized->getStepRecurrence(SE);
998*5f757f3fSDimitry Andric   Type *ExpandTy = Normalized->getType();
9995ffd83dbSDimitry Andric   // If the stride is negative, insert a sub instead of an add for the increment
10005ffd83dbSDimitry Andric   // (unless it's a constant, because subtracts of constants are canonicalized
10015ffd83dbSDimitry Andric   // to adds).
10025ffd83dbSDimitry Andric   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
10035ffd83dbSDimitry Andric   if (useSubtract)
10045ffd83dbSDimitry Andric     Step = SE.getNegativeSCEV(Step);
10055ffd83dbSDimitry Andric   // Expand the step somewhere that dominates the loop header.
1006*5f757f3fSDimitry Andric   Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
10075ffd83dbSDimitry Andric 
10085ffd83dbSDimitry Andric   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
10095ffd83dbSDimitry Andric   // we actually do emit an addition.  It does not apply if we emit a
10105ffd83dbSDimitry Andric   // subtraction.
10115ffd83dbSDimitry Andric   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
10125ffd83dbSDimitry Andric   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
10135ffd83dbSDimitry Andric 
10145ffd83dbSDimitry Andric   // Create the PHI.
10155ffd83dbSDimitry Andric   BasicBlock *Header = L->getHeader();
10165ffd83dbSDimitry Andric   Builder.SetInsertPoint(Header, Header->begin());
10175ffd83dbSDimitry Andric   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
10185ffd83dbSDimitry Andric   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
10195ffd83dbSDimitry Andric                                   Twine(IVName) + ".iv");
10205ffd83dbSDimitry Andric 
10215ffd83dbSDimitry Andric   // Create the step instructions and populate the PHI.
10225ffd83dbSDimitry Andric   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
10235ffd83dbSDimitry Andric     BasicBlock *Pred = *HPI;
10245ffd83dbSDimitry Andric 
10255ffd83dbSDimitry Andric     // Add a start value.
10265ffd83dbSDimitry Andric     if (!L->contains(Pred)) {
10275ffd83dbSDimitry Andric       PN->addIncoming(StartV, Pred);
10285ffd83dbSDimitry Andric       continue;
10295ffd83dbSDimitry Andric     }
10305ffd83dbSDimitry Andric 
10315ffd83dbSDimitry Andric     // Create a step value and add it to the PHI.
10325ffd83dbSDimitry Andric     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
10335ffd83dbSDimitry Andric     // instructions at IVIncInsertPos.
10345ffd83dbSDimitry Andric     Instruction *InsertPos = L == IVIncInsertLoop ?
10355ffd83dbSDimitry Andric       IVIncInsertPos : Pred->getTerminator();
10365ffd83dbSDimitry Andric     Builder.SetInsertPoint(InsertPos);
1037*5f757f3fSDimitry Andric     Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
10385ffd83dbSDimitry Andric 
10395ffd83dbSDimitry Andric     if (isa<OverflowingBinaryOperator>(IncV)) {
10405ffd83dbSDimitry Andric       if (IncrementIsNUW)
10415ffd83dbSDimitry Andric         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
10425ffd83dbSDimitry Andric       if (IncrementIsNSW)
10435ffd83dbSDimitry Andric         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
10445ffd83dbSDimitry Andric     }
10455ffd83dbSDimitry Andric     PN->addIncoming(IncV, Pred);
10465ffd83dbSDimitry Andric   }
10475ffd83dbSDimitry Andric 
10485ffd83dbSDimitry Andric   // After expanding subexpressions, restore the PostIncLoops set so the caller
10495ffd83dbSDimitry Andric   // can ensure that IVIncrement dominates the current uses.
10505ffd83dbSDimitry Andric   PostIncLoops = SavedPostIncLoops;
10515ffd83dbSDimitry Andric 
1052fe6060f1SDimitry Andric   // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1053fe6060f1SDimitry Andric   // effective when we are able to use an IV inserted here, so record it.
10545ffd83dbSDimitry Andric   InsertedValues.insert(PN);
1055fe6060f1SDimitry Andric   InsertedIVs.push_back(PN);
10565ffd83dbSDimitry Andric   return PN;
10575ffd83dbSDimitry Andric }
10585ffd83dbSDimitry Andric 
10595ffd83dbSDimitry Andric Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
10605ffd83dbSDimitry Andric   const Loop *L = S->getLoop();
10615ffd83dbSDimitry Andric 
10625ffd83dbSDimitry Andric   // Determine a normalized form of this expression, which is the expression
10635ffd83dbSDimitry Andric   // before any post-inc adjustment is made.
10645ffd83dbSDimitry Andric   const SCEVAddRecExpr *Normalized = S;
10655ffd83dbSDimitry Andric   if (PostIncLoops.count(L)) {
10665ffd83dbSDimitry Andric     PostIncLoopSet Loops;
10675ffd83dbSDimitry Andric     Loops.insert(L);
106806c3fb27SDimitry Andric     Normalized = cast<SCEVAddRecExpr>(
106906c3fb27SDimitry Andric         normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false));
10705ffd83dbSDimitry Andric   }
10715ffd83dbSDimitry Andric 
1072*5f757f3fSDimitry Andric   [[maybe_unused]] const SCEV *Start = Normalized->getStart();
10735ffd83dbSDimitry Andric   const SCEV *Step = Normalized->getStepRecurrence(SE);
1074*5f757f3fSDimitry Andric   assert(SE.properlyDominates(Start, L->getHeader()) &&
1075*5f757f3fSDimitry Andric          "Start does not properly dominate loop header");
1076*5f757f3fSDimitry Andric   assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header");
10775ffd83dbSDimitry Andric 
10785ffd83dbSDimitry Andric   // In some cases, we decide to reuse an existing phi node but need to truncate
10795ffd83dbSDimitry Andric   // it and/or invert the step.
10805ffd83dbSDimitry Andric   Type *TruncTy = nullptr;
10815ffd83dbSDimitry Andric   bool InvertStep = false;
1082*5f757f3fSDimitry Andric   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
10835ffd83dbSDimitry Andric 
10845ffd83dbSDimitry Andric   // Accommodate post-inc mode, if necessary.
10855ffd83dbSDimitry Andric   Value *Result;
10865ffd83dbSDimitry Andric   if (!PostIncLoops.count(L))
10875ffd83dbSDimitry Andric     Result = PN;
10885ffd83dbSDimitry Andric   else {
10895ffd83dbSDimitry Andric     // In PostInc mode, use the post-incremented value.
10905ffd83dbSDimitry Andric     BasicBlock *LatchBlock = L->getLoopLatch();
10915ffd83dbSDimitry Andric     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
10925ffd83dbSDimitry Andric     Result = PN->getIncomingValueForBlock(LatchBlock);
10935ffd83dbSDimitry Andric 
1094e8d8bef9SDimitry Andric     // We might be introducing a new use of the post-inc IV that is not poison
1095e8d8bef9SDimitry Andric     // safe, in which case we should drop poison generating flags. Only keep
1096e8d8bef9SDimitry Andric     // those flags for which SCEV has proven that they always hold.
1097e8d8bef9SDimitry Andric     if (isa<OverflowingBinaryOperator>(Result)) {
1098e8d8bef9SDimitry Andric       auto *I = cast<Instruction>(Result);
1099e8d8bef9SDimitry Andric       if (!S->hasNoUnsignedWrap())
1100e8d8bef9SDimitry Andric         I->setHasNoUnsignedWrap(false);
1101e8d8bef9SDimitry Andric       if (!S->hasNoSignedWrap())
1102e8d8bef9SDimitry Andric         I->setHasNoSignedWrap(false);
1103e8d8bef9SDimitry Andric     }
1104e8d8bef9SDimitry Andric 
11055ffd83dbSDimitry Andric     // For an expansion to use the postinc form, the client must call
11065ffd83dbSDimitry Andric     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
11075ffd83dbSDimitry Andric     // or dominated by IVIncInsertPos.
11085ffd83dbSDimitry Andric     if (isa<Instruction>(Result) &&
11095ffd83dbSDimitry Andric         !SE.DT.dominates(cast<Instruction>(Result),
11105ffd83dbSDimitry Andric                          &*Builder.GetInsertPoint())) {
11115ffd83dbSDimitry Andric       // The induction variable's postinc expansion does not dominate this use.
11125ffd83dbSDimitry Andric       // IVUsers tries to prevent this case, so it is rare. However, it can
11135ffd83dbSDimitry Andric       // happen when an IVUser outside the loop is not dominated by the latch
11145ffd83dbSDimitry Andric       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
11155ffd83dbSDimitry Andric       // all cases. Consider a phi outside whose operand is replaced during
11165ffd83dbSDimitry Andric       // expansion with the value of the postinc user. Without fundamentally
11175ffd83dbSDimitry Andric       // changing the way postinc users are tracked, the only remedy is
11185ffd83dbSDimitry Andric       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
11195ffd83dbSDimitry Andric       // but hopefully expandCodeFor handles that.
11205ffd83dbSDimitry Andric       bool useSubtract =
1121*5f757f3fSDimitry Andric           !S->getType()->isPointerTy() && Step->isNonConstantNegative();
11225ffd83dbSDimitry Andric       if (useSubtract)
11235ffd83dbSDimitry Andric         Step = SE.getNegativeSCEV(Step);
11245ffd83dbSDimitry Andric       Value *StepV;
11255ffd83dbSDimitry Andric       {
11265ffd83dbSDimitry Andric         // Expand the step somewhere that dominates the loop header.
11275ffd83dbSDimitry Andric         SCEVInsertPointGuard Guard(Builder, this);
1128*5f757f3fSDimitry Andric         StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
11295ffd83dbSDimitry Andric       }
1130*5f757f3fSDimitry Andric       Result = expandIVInc(PN, StepV, L, useSubtract);
11315ffd83dbSDimitry Andric     }
11325ffd83dbSDimitry Andric   }
11335ffd83dbSDimitry Andric 
11345ffd83dbSDimitry Andric   // We have decided to reuse an induction variable of a dominating loop. Apply
11355ffd83dbSDimitry Andric   // truncation and/or inversion of the step.
11365ffd83dbSDimitry Andric   if (TruncTy) {
11375ffd83dbSDimitry Andric     // Truncate the result.
1138e8d8bef9SDimitry Andric     if (TruncTy != Result->getType())
11395ffd83dbSDimitry Andric       Result = Builder.CreateTrunc(Result, TruncTy);
1140e8d8bef9SDimitry Andric 
11415ffd83dbSDimitry Andric     // Invert the result.
1142e8d8bef9SDimitry Andric     if (InvertStep)
1143*5f757f3fSDimitry Andric       Result = Builder.CreateSub(expand(Normalized->getStart()), Result);
11445ffd83dbSDimitry Andric   }
11455ffd83dbSDimitry Andric 
11465ffd83dbSDimitry Andric   return Result;
11475ffd83dbSDimitry Andric }
11485ffd83dbSDimitry Andric 
11495ffd83dbSDimitry Andric Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
11505ffd83dbSDimitry Andric   // In canonical mode we compute the addrec as an expression of a canonical IV
11515ffd83dbSDimitry Andric   // using evaluateAtIteration and expand the resulting SCEV expression. This
1152bdd1243dSDimitry Andric   // way we avoid introducing new IVs to carry on the computation of the addrec
11535ffd83dbSDimitry Andric   // throughout the loop.
11545ffd83dbSDimitry Andric   //
11555ffd83dbSDimitry Andric   // For nested addrecs evaluateAtIteration might need a canonical IV of a
11565ffd83dbSDimitry Andric   // type wider than the addrec itself. Emitting a canonical IV of the
11575ffd83dbSDimitry Andric   // proper type might produce non-legal types, for example expanding an i64
11585ffd83dbSDimitry Andric   // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
11595ffd83dbSDimitry Andric   // back to non-canonical mode for nested addrecs.
11605ffd83dbSDimitry Andric   if (!CanonicalMode || (S->getNumOperands() > 2))
11615ffd83dbSDimitry Andric     return expandAddRecExprLiterally(S);
11625ffd83dbSDimitry Andric 
11635ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
11645ffd83dbSDimitry Andric   const Loop *L = S->getLoop();
11655ffd83dbSDimitry Andric 
11665ffd83dbSDimitry Andric   // First check for an existing canonical IV in a suitable type.
11675ffd83dbSDimitry Andric   PHINode *CanonicalIV = nullptr;
11685ffd83dbSDimitry Andric   if (PHINode *PN = L->getCanonicalInductionVariable())
11695ffd83dbSDimitry Andric     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
11705ffd83dbSDimitry Andric       CanonicalIV = PN;
11715ffd83dbSDimitry Andric 
11725ffd83dbSDimitry Andric   // Rewrite an AddRec in terms of the canonical induction variable, if
11735ffd83dbSDimitry Andric   // its type is more narrow.
11745ffd83dbSDimitry Andric   if (CanonicalIV &&
1175fe6060f1SDimitry Andric       SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1176fe6060f1SDimitry Andric       !S->getType()->isPointerTy()) {
11775ffd83dbSDimitry Andric     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
11785ffd83dbSDimitry Andric     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1179bdd1243dSDimitry Andric       NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType());
11805ffd83dbSDimitry Andric     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
11815ffd83dbSDimitry Andric                                        S->getNoWrapFlags(SCEV::FlagNW)));
11825ffd83dbSDimitry Andric     BasicBlock::iterator NewInsertPt =
1183e8d8bef9SDimitry Andric         findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1184*5f757f3fSDimitry Andric     V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
11855ffd83dbSDimitry Andric     return V;
11865ffd83dbSDimitry Andric   }
11875ffd83dbSDimitry Andric 
11885ffd83dbSDimitry Andric   // {X,+,F} --> X + {0,+,F}
11895ffd83dbSDimitry Andric   if (!S->getStart()->isZero()) {
119006c3fb27SDimitry Andric     if (isa<PointerType>(S->getType())) {
1191349cc55cSDimitry Andric       Value *StartV = expand(SE.getPointerBase(S));
1192*5f757f3fSDimitry Andric       return expandAddToGEP(SE.removePointerBase(S), StartV);
1193349cc55cSDimitry Andric     }
1194349cc55cSDimitry Andric 
1195e8d8bef9SDimitry Andric     SmallVector<const SCEV *, 4> NewOps(S->operands());
11965ffd83dbSDimitry Andric     NewOps[0] = SE.getConstant(Ty, 0);
11975ffd83dbSDimitry Andric     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
11985ffd83dbSDimitry Andric                                         S->getNoWrapFlags(SCEV::FlagNW));
11995ffd83dbSDimitry Andric 
12005ffd83dbSDimitry Andric     // Just do a normal add. Pre-expand the operands to suppress folding.
12015ffd83dbSDimitry Andric     //
12025ffd83dbSDimitry Andric     // The LHS and RHS values are factored out of the expand call to make the
12035ffd83dbSDimitry Andric     // output independent of the argument evaluation order.
12045ffd83dbSDimitry Andric     const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
12055ffd83dbSDimitry Andric     const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
12065ffd83dbSDimitry Andric     return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
12075ffd83dbSDimitry Andric   }
12085ffd83dbSDimitry Andric 
12095ffd83dbSDimitry Andric   // If we don't yet have a canonical IV, create one.
12105ffd83dbSDimitry Andric   if (!CanonicalIV) {
12115ffd83dbSDimitry Andric     // Create and insert the PHI node for the induction variable in the
12125ffd83dbSDimitry Andric     // specified loop.
12135ffd83dbSDimitry Andric     BasicBlock *Header = L->getHeader();
12145ffd83dbSDimitry Andric     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1215*5f757f3fSDimitry Andric     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar");
1216*5f757f3fSDimitry Andric     CanonicalIV->insertBefore(Header->begin());
12175ffd83dbSDimitry Andric     rememberInstruction(CanonicalIV);
12185ffd83dbSDimitry Andric 
12195ffd83dbSDimitry Andric     SmallSet<BasicBlock *, 4> PredSeen;
12205ffd83dbSDimitry Andric     Constant *One = ConstantInt::get(Ty, 1);
12215ffd83dbSDimitry Andric     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
12225ffd83dbSDimitry Andric       BasicBlock *HP = *HPI;
12235ffd83dbSDimitry Andric       if (!PredSeen.insert(HP).second) {
12245ffd83dbSDimitry Andric         // There must be an incoming value for each predecessor, even the
12255ffd83dbSDimitry Andric         // duplicates!
12265ffd83dbSDimitry Andric         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
12275ffd83dbSDimitry Andric         continue;
12285ffd83dbSDimitry Andric       }
12295ffd83dbSDimitry Andric 
12305ffd83dbSDimitry Andric       if (L->contains(HP)) {
12315ffd83dbSDimitry Andric         // Insert a unit add instruction right before the terminator
12325ffd83dbSDimitry Andric         // corresponding to the back-edge.
12335ffd83dbSDimitry Andric         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
12345ffd83dbSDimitry Andric                                                      "indvar.next",
12355ffd83dbSDimitry Andric                                                      HP->getTerminator());
12365ffd83dbSDimitry Andric         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
12375ffd83dbSDimitry Andric         rememberInstruction(Add);
12385ffd83dbSDimitry Andric         CanonicalIV->addIncoming(Add, HP);
12395ffd83dbSDimitry Andric       } else {
12405ffd83dbSDimitry Andric         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
12415ffd83dbSDimitry Andric       }
12425ffd83dbSDimitry Andric     }
12435ffd83dbSDimitry Andric   }
12445ffd83dbSDimitry Andric 
12455ffd83dbSDimitry Andric   // {0,+,1} --> Insert a canonical induction variable into the loop!
12465ffd83dbSDimitry Andric   if (S->isAffine() && S->getOperand(1)->isOne()) {
12475ffd83dbSDimitry Andric     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
12485ffd83dbSDimitry Andric            "IVs with types different from the canonical IV should "
12495ffd83dbSDimitry Andric            "already have been handled!");
12505ffd83dbSDimitry Andric     return CanonicalIV;
12515ffd83dbSDimitry Andric   }
12525ffd83dbSDimitry Andric 
12535ffd83dbSDimitry Andric   // {0,+,F} --> {0,+,1} * F
12545ffd83dbSDimitry Andric 
12555ffd83dbSDimitry Andric   // If this is a simple linear addrec, emit it now as a special case.
12565ffd83dbSDimitry Andric   if (S->isAffine())    // {0,+,F} --> i*F
12575ffd83dbSDimitry Andric     return
12585ffd83dbSDimitry Andric       expand(SE.getTruncateOrNoop(
12595ffd83dbSDimitry Andric         SE.getMulExpr(SE.getUnknown(CanonicalIV),
12605ffd83dbSDimitry Andric                       SE.getNoopOrAnyExtend(S->getOperand(1),
12615ffd83dbSDimitry Andric                                             CanonicalIV->getType())),
12625ffd83dbSDimitry Andric         Ty));
12635ffd83dbSDimitry Andric 
12645ffd83dbSDimitry Andric   // If this is a chain of recurrences, turn it into a closed form, using the
12655ffd83dbSDimitry Andric   // folders, then expandCodeFor the closed form.  This allows the folders to
12665ffd83dbSDimitry Andric   // simplify the expression without having to build a bunch of special code
12675ffd83dbSDimitry Andric   // into this folder.
12685ffd83dbSDimitry Andric   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
12695ffd83dbSDimitry Andric 
12705ffd83dbSDimitry Andric   // Promote S up to the canonical IV type, if the cast is foldable.
12715ffd83dbSDimitry Andric   const SCEV *NewS = S;
12725ffd83dbSDimitry Andric   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
12735ffd83dbSDimitry Andric   if (isa<SCEVAddRecExpr>(Ext))
12745ffd83dbSDimitry Andric     NewS = Ext;
12755ffd83dbSDimitry Andric 
12765ffd83dbSDimitry Andric   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
12775ffd83dbSDimitry Andric 
12785ffd83dbSDimitry Andric   // Truncate the result down to the original type, if needed.
12795ffd83dbSDimitry Andric   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
12805ffd83dbSDimitry Andric   return expand(T);
12815ffd83dbSDimitry Andric }
12825ffd83dbSDimitry Andric 
1283e8d8bef9SDimitry Andric Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
1284*5f757f3fSDimitry Andric   Value *V = expand(S->getOperand());
1285fe6060f1SDimitry Andric   return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1286fe6060f1SDimitry Andric                            GetOptimalInsertionPointForCastOf(V));
1287e8d8bef9SDimitry Andric }
1288e8d8bef9SDimitry Andric 
12895ffd83dbSDimitry Andric Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1290*5f757f3fSDimitry Andric   Value *V = expand(S->getOperand());
1291*5f757f3fSDimitry Andric   return Builder.CreateTrunc(V, S->getType());
12925ffd83dbSDimitry Andric }
12935ffd83dbSDimitry Andric 
12945ffd83dbSDimitry Andric Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1295*5f757f3fSDimitry Andric   Value *V = expand(S->getOperand());
1296*5f757f3fSDimitry Andric   return Builder.CreateZExt(V, S->getType(), "",
1297*5f757f3fSDimitry Andric                             SE.isKnownNonNegative(S->getOperand()));
12985ffd83dbSDimitry Andric }
12995ffd83dbSDimitry Andric 
13005ffd83dbSDimitry Andric Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1301*5f757f3fSDimitry Andric   Value *V = expand(S->getOperand());
1302*5f757f3fSDimitry Andric   return Builder.CreateSExt(V, S->getType());
13035ffd83dbSDimitry Andric }
13045ffd83dbSDimitry Andric 
130581ad6265SDimitry Andric Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S,
130681ad6265SDimitry Andric                                       Intrinsic::ID IntrinID, Twine Name,
130781ad6265SDimitry Andric                                       bool IsSequential) {
13085ffd83dbSDimitry Andric   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
13095ffd83dbSDimitry Andric   Type *Ty = LHS->getType();
131081ad6265SDimitry Andric   if (IsSequential)
131181ad6265SDimitry Andric     LHS = Builder.CreateFreeze(LHS);
13125ffd83dbSDimitry Andric   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1313*5f757f3fSDimitry Andric     Value *RHS = expand(S->getOperand(i));
131481ad6265SDimitry Andric     if (IsSequential && i != 0)
131581ad6265SDimitry Andric       RHS = Builder.CreateFreeze(RHS);
1316fe6060f1SDimitry Andric     Value *Sel;
1317fe6060f1SDimitry Andric     if (Ty->isIntegerTy())
131881ad6265SDimitry Andric       Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
131981ad6265SDimitry Andric                                     /*FMFSource=*/nullptr, Name);
1320fe6060f1SDimitry Andric     else {
132181ad6265SDimitry Andric       Value *ICmp =
132281ad6265SDimitry Andric           Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
132381ad6265SDimitry Andric       Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1324fe6060f1SDimitry Andric     }
13255ffd83dbSDimitry Andric     LHS = Sel;
13265ffd83dbSDimitry Andric   }
13275ffd83dbSDimitry Andric   return LHS;
13285ffd83dbSDimitry Andric }
13295ffd83dbSDimitry Andric 
133004eeddc0SDimitry Andric Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
133181ad6265SDimitry Andric   return expandMinMaxExpr(S, Intrinsic::smax, "smax");
133204eeddc0SDimitry Andric }
133304eeddc0SDimitry Andric 
133404eeddc0SDimitry Andric Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
133581ad6265SDimitry Andric   return expandMinMaxExpr(S, Intrinsic::umax, "umax");
133604eeddc0SDimitry Andric }
133704eeddc0SDimitry Andric 
133804eeddc0SDimitry Andric Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
133981ad6265SDimitry Andric   return expandMinMaxExpr(S, Intrinsic::smin, "smin");
134004eeddc0SDimitry Andric }
134104eeddc0SDimitry Andric 
134204eeddc0SDimitry Andric Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
134381ad6265SDimitry Andric   return expandMinMaxExpr(S, Intrinsic::umin, "umin");
134404eeddc0SDimitry Andric }
134504eeddc0SDimitry Andric 
134604eeddc0SDimitry Andric Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
134781ad6265SDimitry Andric   return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true);
134804eeddc0SDimitry Andric }
134904eeddc0SDimitry Andric 
135006c3fb27SDimitry Andric Value *SCEVExpander::visitVScale(const SCEVVScale *S) {
135106c3fb27SDimitry Andric   return Builder.CreateVScale(ConstantInt::get(S->getType(), 1));
135206c3fb27SDimitry Andric }
135306c3fb27SDimitry Andric 
1354*5f757f3fSDimitry Andric Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1355*5f757f3fSDimitry Andric                                    BasicBlock::iterator IP) {
13565ffd83dbSDimitry Andric   setInsertPoint(IP);
1357*5f757f3fSDimitry Andric   Value *V = expandCodeFor(SH, Ty);
1358e8d8bef9SDimitry Andric   return V;
13595ffd83dbSDimitry Andric }
13605ffd83dbSDimitry Andric 
1361*5f757f3fSDimitry Andric Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
13625ffd83dbSDimitry Andric   // Expand the code for this SCEV.
13635ffd83dbSDimitry Andric   Value *V = expand(SH);
1364e8d8bef9SDimitry Andric 
13655ffd83dbSDimitry Andric   if (Ty) {
13665ffd83dbSDimitry Andric     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
13675ffd83dbSDimitry Andric            "non-trivial casts should be done with the SCEVs directly!");
13685ffd83dbSDimitry Andric     V = InsertNoopCastOfTo(V, Ty);
13695ffd83dbSDimitry Andric   }
13705ffd83dbSDimitry Andric   return V;
13715ffd83dbSDimitry Andric }
13725ffd83dbSDimitry Andric 
1373*5f757f3fSDimitry Andric static bool
1374*5f757f3fSDimitry Andric canReuseInstruction(ScalarEvolution &SE, const SCEV *S, Instruction *I,
1375*5f757f3fSDimitry Andric                     SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
1376*5f757f3fSDimitry Andric   // If the instruction cannot be poison, it's always safe to reuse.
1377*5f757f3fSDimitry Andric   if (programUndefinedIfPoison(I))
1378*5f757f3fSDimitry Andric     return true;
1379*5f757f3fSDimitry Andric 
1380*5f757f3fSDimitry Andric   // Otherwise, it is possible that I is more poisonous that S. Collect the
1381*5f757f3fSDimitry Andric   // poison-contributors of S, and then check whether I has any additional
1382*5f757f3fSDimitry Andric   // poison-contributors. Poison that is contributed through poison-generating
1383*5f757f3fSDimitry Andric   // flags is handled by dropping those flags instead.
1384*5f757f3fSDimitry Andric   SmallPtrSet<const Value *, 8> PoisonVals;
1385*5f757f3fSDimitry Andric   SE.getPoisonGeneratingValues(PoisonVals, S);
1386*5f757f3fSDimitry Andric 
1387*5f757f3fSDimitry Andric   SmallVector<Value *> Worklist;
1388*5f757f3fSDimitry Andric   SmallPtrSet<Value *, 8> Visited;
1389*5f757f3fSDimitry Andric   Worklist.push_back(I);
1390*5f757f3fSDimitry Andric   while (!Worklist.empty()) {
1391*5f757f3fSDimitry Andric     Value *V = Worklist.pop_back_val();
1392*5f757f3fSDimitry Andric     if (!Visited.insert(V).second)
1393*5f757f3fSDimitry Andric       continue;
1394*5f757f3fSDimitry Andric 
1395*5f757f3fSDimitry Andric     // Avoid walking large instruction graphs.
1396*5f757f3fSDimitry Andric     if (Visited.size() > 16)
1397*5f757f3fSDimitry Andric       return false;
1398*5f757f3fSDimitry Andric 
1399*5f757f3fSDimitry Andric     // Either the value can't be poison, or the S would also be poison if it
1400*5f757f3fSDimitry Andric     // is.
1401*5f757f3fSDimitry Andric     if (PoisonVals.contains(V) || isGuaranteedNotToBePoison(V))
1402*5f757f3fSDimitry Andric       continue;
1403*5f757f3fSDimitry Andric 
1404*5f757f3fSDimitry Andric     auto *I = dyn_cast<Instruction>(V);
1405*5f757f3fSDimitry Andric     if (!I)
1406*5f757f3fSDimitry Andric       return false;
1407*5f757f3fSDimitry Andric 
1408*5f757f3fSDimitry Andric     // FIXME: Ignore vscale, even though it technically could be poison. Do this
1409*5f757f3fSDimitry Andric     // because SCEV currently assumes it can't be poison. Remove this special
1410*5f757f3fSDimitry Andric     // case once we proper model when vscale can be poison.
1411*5f757f3fSDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(I);
1412*5f757f3fSDimitry Andric         II && II->getIntrinsicID() == Intrinsic::vscale)
1413*5f757f3fSDimitry Andric       continue;
1414*5f757f3fSDimitry Andric 
1415*5f757f3fSDimitry Andric     if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
1416*5f757f3fSDimitry Andric       return false;
1417*5f757f3fSDimitry Andric 
1418*5f757f3fSDimitry Andric     // If the instruction can't create poison, we can recurse to its operands.
1419*5f757f3fSDimitry Andric     if (I->hasPoisonGeneratingFlagsOrMetadata())
1420*5f757f3fSDimitry Andric       DropPoisonGeneratingInsts.push_back(I);
1421*5f757f3fSDimitry Andric 
1422*5f757f3fSDimitry Andric     for (Value *Op : I->operands())
1423*5f757f3fSDimitry Andric       Worklist.push_back(Op);
1424*5f757f3fSDimitry Andric   }
1425*5f757f3fSDimitry Andric   return true;
1426*5f757f3fSDimitry Andric }
1427*5f757f3fSDimitry Andric 
1428*5f757f3fSDimitry Andric Value *SCEVExpander::FindValueInExprValueMap(
1429*5f757f3fSDimitry Andric     const SCEV *S, const Instruction *InsertPt,
1430*5f757f3fSDimitry Andric     SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
14315ffd83dbSDimitry Andric   // If the expansion is not in CanonicalMode, and the SCEV contains any
14325ffd83dbSDimitry Andric   // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
143381ad6265SDimitry Andric   if (!CanonicalMode && SE.containsAddRecurrence(S))
143481ad6265SDimitry Andric     return nullptr;
143581ad6265SDimitry Andric 
143681ad6265SDimitry Andric   // If S is a constant, it may be worse to reuse an existing Value.
143781ad6265SDimitry Andric   if (isa<SCEVConstant>(S))
143881ad6265SDimitry Andric     return nullptr;
143981ad6265SDimitry Andric 
144081ad6265SDimitry Andric   for (Value *V : SE.getSCEVValues(S)) {
144181ad6265SDimitry Andric     Instruction *EntInst = dyn_cast<Instruction>(V);
1442349cc55cSDimitry Andric     if (!EntInst)
1443349cc55cSDimitry Andric       continue;
1444349cc55cSDimitry Andric 
1445*5f757f3fSDimitry Andric     // Choose a Value from the set which dominates the InsertPt.
1446*5f757f3fSDimitry Andric     // InsertPt should be inside the Value's parent loop so as not to break
1447*5f757f3fSDimitry Andric     // the LCSSA form.
1448349cc55cSDimitry Andric     assert(EntInst->getFunction() == InsertPt->getFunction());
1449*5f757f3fSDimitry Andric     if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) ||
1450*5f757f3fSDimitry Andric         !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
14514824e7fdSDimitry Andric           SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1452*5f757f3fSDimitry Andric       continue;
1453*5f757f3fSDimitry Andric 
1454*5f757f3fSDimitry Andric     // Make sure reusing the instruction is poison-safe.
1455*5f757f3fSDimitry Andric     if (canReuseInstruction(SE, S, EntInst, DropPoisonGeneratingInsts))
145681ad6265SDimitry Andric       return V;
1457*5f757f3fSDimitry Andric     DropPoisonGeneratingInsts.clear();
14585ffd83dbSDimitry Andric   }
145981ad6265SDimitry Andric   return nullptr;
14605ffd83dbSDimitry Andric }
14615ffd83dbSDimitry Andric 
14625ffd83dbSDimitry Andric // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
14635ffd83dbSDimitry Andric // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
14645ffd83dbSDimitry Andric // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
14655ffd83dbSDimitry Andric // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
14665ffd83dbSDimitry Andric // the expansion will try to reuse Value from ExprValueMap, and only when it
14675ffd83dbSDimitry Andric // fails, expand the SCEV literally.
14685ffd83dbSDimitry Andric Value *SCEVExpander::expand(const SCEV *S) {
14695ffd83dbSDimitry Andric   // Compute an insertion point for this SCEV object. Hoist the instructions
14705ffd83dbSDimitry Andric   // as far out in the loop nest as possible.
1471*5f757f3fSDimitry Andric   BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
14725ffd83dbSDimitry Andric 
14735ffd83dbSDimitry Andric   // We can move insertion point only if there is no div or rem operations
14745ffd83dbSDimitry Andric   // otherwise we are risky to move it over the check for zero denominator.
14755ffd83dbSDimitry Andric   auto SafeToHoist = [](const SCEV *S) {
14765ffd83dbSDimitry Andric     return !SCEVExprContains(S, [](const SCEV *S) {
14775ffd83dbSDimitry Andric               if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
14785ffd83dbSDimitry Andric                 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
14795ffd83dbSDimitry Andric                   // Division by non-zero constants can be hoisted.
14805ffd83dbSDimitry Andric                   return SC->getValue()->isZero();
14815ffd83dbSDimitry Andric                 // All other divisions should not be moved as they may be
14825ffd83dbSDimitry Andric                 // divisions by zero and should be kept within the
14835ffd83dbSDimitry Andric                 // conditions of the surrounding loops that guard their
14845ffd83dbSDimitry Andric                 // execution (see PR35406).
14855ffd83dbSDimitry Andric                 return true;
14865ffd83dbSDimitry Andric               }
14875ffd83dbSDimitry Andric               return false;
14885ffd83dbSDimitry Andric             });
14895ffd83dbSDimitry Andric   };
14905ffd83dbSDimitry Andric   if (SafeToHoist(S)) {
14915ffd83dbSDimitry Andric     for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
14925ffd83dbSDimitry Andric          L = L->getParentLoop()) {
14935ffd83dbSDimitry Andric       if (SE.isLoopInvariant(S, L)) {
14945ffd83dbSDimitry Andric         if (!L) break;
1495*5f757f3fSDimitry Andric         if (BasicBlock *Preheader = L->getLoopPreheader()) {
1496*5f757f3fSDimitry Andric           InsertPt = Preheader->getTerminator()->getIterator();
1497*5f757f3fSDimitry Andric         } else {
14985ffd83dbSDimitry Andric           // LSR sets the insertion point for AddRec start/step values to the
14995ffd83dbSDimitry Andric           // block start to simplify value reuse, even though it's an invalid
15005ffd83dbSDimitry Andric           // position. SCEVExpander must correct for this in all cases.
1501*5f757f3fSDimitry Andric           InsertPt = L->getHeader()->getFirstInsertionPt();
1502*5f757f3fSDimitry Andric         }
15035ffd83dbSDimitry Andric       } else {
15045ffd83dbSDimitry Andric         // If the SCEV is computable at this level, insert it into the header
15055ffd83dbSDimitry Andric         // after the PHIs (and after any other instructions that we've inserted
15065ffd83dbSDimitry Andric         // there) so that it is guaranteed to dominate any user inside the loop.
15075ffd83dbSDimitry Andric         if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1508*5f757f3fSDimitry Andric           InsertPt = L->getHeader()->getFirstInsertionPt();
1509e8d8bef9SDimitry Andric 
1510*5f757f3fSDimitry Andric         while (InsertPt != Builder.GetInsertPoint() &&
1511*5f757f3fSDimitry Andric                (isInsertedInstruction(&*InsertPt) ||
1512*5f757f3fSDimitry Andric                 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1513*5f757f3fSDimitry Andric           InsertPt = std::next(InsertPt);
1514e8d8bef9SDimitry Andric         }
15155ffd83dbSDimitry Andric         break;
15165ffd83dbSDimitry Andric       }
15175ffd83dbSDimitry Andric     }
15185ffd83dbSDimitry Andric   }
15195ffd83dbSDimitry Andric 
15205ffd83dbSDimitry Andric   // Check to see if we already expanded this here.
1521*5f757f3fSDimitry Andric   auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
15225ffd83dbSDimitry Andric   if (I != InsertedExpressions.end())
15235ffd83dbSDimitry Andric     return I->second;
15245ffd83dbSDimitry Andric 
15255ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
1526*5f757f3fSDimitry Andric   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
15275ffd83dbSDimitry Andric 
15285ffd83dbSDimitry Andric   // Expand the expression into instructions.
1529*5f757f3fSDimitry Andric   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1530*5f757f3fSDimitry Andric   Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1531bdd1243dSDimitry Andric   if (!V) {
15325ffd83dbSDimitry Andric     V = visit(S);
1533bdd1243dSDimitry Andric     V = fixupLCSSAFormFor(V);
1534bdd1243dSDimitry Andric   } else {
1535*5f757f3fSDimitry Andric     for (Instruction *I : DropPoisonGeneratingInsts) {
1536*5f757f3fSDimitry Andric       I->dropPoisonGeneratingFlagsAndMetadata();
1537*5f757f3fSDimitry Andric       // See if we can re-infer from first principles any of the flags we just
1538*5f757f3fSDimitry Andric       // dropped.
1539*5f757f3fSDimitry Andric       if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
1540*5f757f3fSDimitry Andric         if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1541*5f757f3fSDimitry Andric           auto *BO = cast<BinaryOperator>(I);
1542*5f757f3fSDimitry Andric           BO->setHasNoUnsignedWrap(
1543*5f757f3fSDimitry Andric             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
1544*5f757f3fSDimitry Andric           BO->setHasNoSignedWrap(
1545*5f757f3fSDimitry Andric             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
1546*5f757f3fSDimitry Andric         }
1547*5f757f3fSDimitry Andric       if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) {
1548*5f757f3fSDimitry Andric         auto *Src = NNI->getOperand(0);
1549*5f757f3fSDimitry Andric         if (isImpliedByDomCondition(ICmpInst::ICMP_SGE, Src,
1550*5f757f3fSDimitry Andric                                     Constant::getNullValue(Src->getType()), I,
1551*5f757f3fSDimitry Andric                                     DL).value_or(false))
1552*5f757f3fSDimitry Andric           NNI->setNonNeg(true);
1553*5f757f3fSDimitry Andric       }
1554*5f757f3fSDimitry Andric     }
15554824e7fdSDimitry Andric   }
15565ffd83dbSDimitry Andric   // Remember the expanded value for this SCEV at this location.
15575ffd83dbSDimitry Andric   //
15585ffd83dbSDimitry Andric   // This is independent of PostIncLoops. The mapped value simply materializes
15595ffd83dbSDimitry Andric   // the expression at this insertion point. If the mapped value happened to be
15605ffd83dbSDimitry Andric   // a postinc expansion, it could be reused by a non-postinc user, but only if
15615ffd83dbSDimitry Andric   // its insertion point was already at the head of the loop.
1562*5f757f3fSDimitry Andric   InsertedExpressions[std::make_pair(S, &*InsertPt)] = V;
15635ffd83dbSDimitry Andric   return V;
15645ffd83dbSDimitry Andric }
15655ffd83dbSDimitry Andric 
15665ffd83dbSDimitry Andric void SCEVExpander::rememberInstruction(Value *I) {
1567e8d8bef9SDimitry Andric   auto DoInsert = [this](Value *V) {
15685ffd83dbSDimitry Andric     if (!PostIncLoops.empty())
1569e8d8bef9SDimitry Andric       InsertedPostIncValues.insert(V);
15705ffd83dbSDimitry Andric     else
1571e8d8bef9SDimitry Andric       InsertedValues.insert(V);
1572e8d8bef9SDimitry Andric   };
1573e8d8bef9SDimitry Andric   DoInsert(I);
15745ffd83dbSDimitry Andric }
15755ffd83dbSDimitry Andric 
15765ffd83dbSDimitry Andric /// replaceCongruentIVs - Check for congruent phis in this loop header and
15775ffd83dbSDimitry Andric /// replace them with their most canonical representative. Return the number of
15785ffd83dbSDimitry Andric /// phis eliminated.
15795ffd83dbSDimitry Andric ///
15805ffd83dbSDimitry Andric /// This does not depend on any SCEVExpander state but should be used in
15815ffd83dbSDimitry Andric /// the same context that SCEVExpander is used.
15825ffd83dbSDimitry Andric unsigned
15835ffd83dbSDimitry Andric SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
15845ffd83dbSDimitry Andric                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts,
15855ffd83dbSDimitry Andric                                   const TargetTransformInfo *TTI) {
15865ffd83dbSDimitry Andric   // Find integer phis in order of increasing width.
15875ffd83dbSDimitry Andric   SmallVector<PHINode*, 8> Phis;
15885ffd83dbSDimitry Andric   for (PHINode &PN : L->getHeader()->phis())
15895ffd83dbSDimitry Andric     Phis.push_back(&PN);
15905ffd83dbSDimitry Andric 
15915ffd83dbSDimitry Andric   if (TTI)
1592349cc55cSDimitry Andric     // Use stable_sort to preserve order of equivalent PHIs, so the order
1593349cc55cSDimitry Andric     // of the sorted Phis is the same from run to run on the same loop.
1594349cc55cSDimitry Andric     llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
15955ffd83dbSDimitry Andric       // Put pointers at the back and make sure pointer < pointer = false.
15965ffd83dbSDimitry Andric       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
15975ffd83dbSDimitry Andric         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1598bdd1243dSDimitry Andric       return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1599bdd1243dSDimitry Andric              LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
16005ffd83dbSDimitry Andric     });
16015ffd83dbSDimitry Andric 
16025ffd83dbSDimitry Andric   unsigned NumElim = 0;
16035ffd83dbSDimitry Andric   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
16045ffd83dbSDimitry Andric   // Process phis from wide to narrow. Map wide phis to their truncation
16055ffd83dbSDimitry Andric   // so narrow phis can reuse them.
16065ffd83dbSDimitry Andric   for (PHINode *Phi : Phis) {
16075ffd83dbSDimitry Andric     auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
160881ad6265SDimitry Andric       if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
16095ffd83dbSDimitry Andric         return V;
16105ffd83dbSDimitry Andric       if (!SE.isSCEVable(PN->getType()))
16115ffd83dbSDimitry Andric         return nullptr;
16125ffd83dbSDimitry Andric       auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
16135ffd83dbSDimitry Andric       if (!Const)
16145ffd83dbSDimitry Andric         return nullptr;
16155ffd83dbSDimitry Andric       return Const->getValue();
16165ffd83dbSDimitry Andric     };
16175ffd83dbSDimitry Andric 
16185ffd83dbSDimitry Andric     // Fold constant phis. They may be congruent to other constant phis and
16195ffd83dbSDimitry Andric     // would confuse the logic below that expects proper IVs.
16205ffd83dbSDimitry Andric     if (Value *V = SimplifyPHINode(Phi)) {
16215ffd83dbSDimitry Andric       if (V->getType() != Phi->getType())
16225ffd83dbSDimitry Andric         continue;
1623bdd1243dSDimitry Andric       SE.forgetValue(Phi);
16245ffd83dbSDimitry Andric       Phi->replaceAllUsesWith(V);
16255ffd83dbSDimitry Andric       DeadInsts.emplace_back(Phi);
16265ffd83dbSDimitry Andric       ++NumElim;
1627fe6060f1SDimitry Andric       SCEV_DEBUG_WITH_TYPE(DebugType,
1628fe6060f1SDimitry Andric                            dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1629fe6060f1SDimitry Andric                                   << '\n');
16305ffd83dbSDimitry Andric       continue;
16315ffd83dbSDimitry Andric     }
16325ffd83dbSDimitry Andric 
16335ffd83dbSDimitry Andric     if (!SE.isSCEVable(Phi->getType()))
16345ffd83dbSDimitry Andric       continue;
16355ffd83dbSDimitry Andric 
16365ffd83dbSDimitry Andric     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
16375ffd83dbSDimitry Andric     if (!OrigPhiRef) {
16385ffd83dbSDimitry Andric       OrigPhiRef = Phi;
16395ffd83dbSDimitry Andric       if (Phi->getType()->isIntegerTy() && TTI &&
16405ffd83dbSDimitry Andric           TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
164106c3fb27SDimitry Andric         // Make sure we only rewrite using simple induction variables;
164206c3fb27SDimitry Andric         // otherwise, we can make the trip count of a loop unanalyzable
164306c3fb27SDimitry Andric         // to SCEV.
164406c3fb27SDimitry Andric         const SCEV *PhiExpr = SE.getSCEV(Phi);
164506c3fb27SDimitry Andric         if (isa<SCEVAddRecExpr>(PhiExpr)) {
16465ffd83dbSDimitry Andric           // This phi can be freely truncated to the narrowest phi type. Map the
16475ffd83dbSDimitry Andric           // truncated expression to it so it will be reused for narrow types.
16485ffd83dbSDimitry Andric           const SCEV *TruncExpr =
164906c3fb27SDimitry Andric               SE.getTruncateExpr(PhiExpr, Phis.back()->getType());
16505ffd83dbSDimitry Andric           ExprToIVMap[TruncExpr] = Phi;
16515ffd83dbSDimitry Andric         }
165206c3fb27SDimitry Andric       }
16535ffd83dbSDimitry Andric       continue;
16545ffd83dbSDimitry Andric     }
16555ffd83dbSDimitry Andric 
16565ffd83dbSDimitry Andric     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
16575ffd83dbSDimitry Andric     // sense.
16585ffd83dbSDimitry Andric     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
16595ffd83dbSDimitry Andric       continue;
16605ffd83dbSDimitry Andric 
16615ffd83dbSDimitry Andric     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
16625ffd83dbSDimitry Andric       Instruction *OrigInc = dyn_cast<Instruction>(
16635ffd83dbSDimitry Andric           OrigPhiRef->getIncomingValueForBlock(LatchBlock));
16645ffd83dbSDimitry Andric       Instruction *IsomorphicInc =
16655ffd83dbSDimitry Andric           dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
16665ffd83dbSDimitry Andric 
16675ffd83dbSDimitry Andric       if (OrigInc && IsomorphicInc) {
16685ffd83dbSDimitry Andric         // If this phi has the same width but is more canonical, replace the
16695ffd83dbSDimitry Andric         // original with it. As part of the "more canonical" determination,
16705ffd83dbSDimitry Andric         // respect a prior decision to use an IV chain.
16715ffd83dbSDimitry Andric         if (OrigPhiRef->getType() == Phi->getType() &&
16725ffd83dbSDimitry Andric             !(ChainedPhis.count(Phi) ||
16735ffd83dbSDimitry Andric               isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
16745ffd83dbSDimitry Andric             (ChainedPhis.count(Phi) ||
16755ffd83dbSDimitry Andric              isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
16765ffd83dbSDimitry Andric           std::swap(OrigPhiRef, Phi);
16775ffd83dbSDimitry Andric           std::swap(OrigInc, IsomorphicInc);
16785ffd83dbSDimitry Andric         }
16795ffd83dbSDimitry Andric         // Replacing the congruent phi is sufficient because acyclic
16805ffd83dbSDimitry Andric         // redundancy elimination, CSE/GVN, should handle the
16815ffd83dbSDimitry Andric         // rest. However, once SCEV proves that a phi is congruent,
16825ffd83dbSDimitry Andric         // it's often the head of an IV user cycle that is isomorphic
16835ffd83dbSDimitry Andric         // with the original phi. It's worth eagerly cleaning up the
16845ffd83dbSDimitry Andric         // common case of a single IV increment so that DeleteDeadPHIs
16855ffd83dbSDimitry Andric         // can remove cycles that had postinc uses.
1686bdd1243dSDimitry Andric         // Because we may potentially introduce a new use of OrigIV that didn't
1687bdd1243dSDimitry Andric         // exist before at this point, its poison flags need readjustment.
16885ffd83dbSDimitry Andric         const SCEV *TruncExpr =
16895ffd83dbSDimitry Andric             SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
16905ffd83dbSDimitry Andric         if (OrigInc != IsomorphicInc &&
16915ffd83dbSDimitry Andric             TruncExpr == SE.getSCEV(IsomorphicInc) &&
16925ffd83dbSDimitry Andric             SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1693bdd1243dSDimitry Andric             hoistIVInc(OrigInc, IsomorphicInc, /*RecomputePoisonFlags*/ true)) {
1694fe6060f1SDimitry Andric           SCEV_DEBUG_WITH_TYPE(
1695fe6060f1SDimitry Andric               DebugType, dbgs() << "INDVARS: Eliminated congruent iv.inc: "
16965ffd83dbSDimitry Andric                                 << *IsomorphicInc << '\n');
16975ffd83dbSDimitry Andric           Value *NewInc = OrigInc;
16985ffd83dbSDimitry Andric           if (OrigInc->getType() != IsomorphicInc->getType()) {
1699*5f757f3fSDimitry Andric             BasicBlock::iterator IP;
17005ffd83dbSDimitry Andric             if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1701*5f757f3fSDimitry Andric               IP = PN->getParent()->getFirstInsertionPt();
17025ffd83dbSDimitry Andric             else
1703*5f757f3fSDimitry Andric               IP = OrigInc->getNextNonDebugInstruction()->getIterator();
17045ffd83dbSDimitry Andric 
1705*5f757f3fSDimitry Andric             IRBuilder<> Builder(IP->getParent(), IP);
17065ffd83dbSDimitry Andric             Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
17075ffd83dbSDimitry Andric             NewInc = Builder.CreateTruncOrBitCast(
17085ffd83dbSDimitry Andric                 OrigInc, IsomorphicInc->getType(), IVName);
17095ffd83dbSDimitry Andric           }
17105ffd83dbSDimitry Andric           IsomorphicInc->replaceAllUsesWith(NewInc);
17115ffd83dbSDimitry Andric           DeadInsts.emplace_back(IsomorphicInc);
17125ffd83dbSDimitry Andric         }
17135ffd83dbSDimitry Andric       }
17145ffd83dbSDimitry Andric     }
1715fe6060f1SDimitry Andric     SCEV_DEBUG_WITH_TYPE(DebugType,
1716fe6060f1SDimitry Andric                          dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
1717fe6060f1SDimitry Andric                                 << '\n');
1718fe6060f1SDimitry Andric     SCEV_DEBUG_WITH_TYPE(
1719fe6060f1SDimitry Andric         DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
17205ffd83dbSDimitry Andric     ++NumElim;
17215ffd83dbSDimitry Andric     Value *NewIV = OrigPhiRef;
17225ffd83dbSDimitry Andric     if (OrigPhiRef->getType() != Phi->getType()) {
1723*5f757f3fSDimitry Andric       IRBuilder<> Builder(L->getHeader(),
1724*5f757f3fSDimitry Andric                           L->getHeader()->getFirstInsertionPt());
17255ffd83dbSDimitry Andric       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
17265ffd83dbSDimitry Andric       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
17275ffd83dbSDimitry Andric     }
17285ffd83dbSDimitry Andric     Phi->replaceAllUsesWith(NewIV);
17295ffd83dbSDimitry Andric     DeadInsts.emplace_back(Phi);
17305ffd83dbSDimitry Andric   }
17315ffd83dbSDimitry Andric   return NumElim;
17325ffd83dbSDimitry Andric }
17335ffd83dbSDimitry Andric 
1734*5f757f3fSDimitry Andric bool SCEVExpander::hasRelatedExistingExpansion(const SCEV *S,
173581ad6265SDimitry Andric                                                const Instruction *At,
17365ffd83dbSDimitry Andric                                                Loop *L) {
17375ffd83dbSDimitry Andric   using namespace llvm::PatternMatch;
17385ffd83dbSDimitry Andric 
17395ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 4> ExitingBlocks;
17405ffd83dbSDimitry Andric   L->getExitingBlocks(ExitingBlocks);
17415ffd83dbSDimitry Andric 
17425ffd83dbSDimitry Andric   // Look for suitable value in simple conditions at the loop exits.
17435ffd83dbSDimitry Andric   for (BasicBlock *BB : ExitingBlocks) {
17445ffd83dbSDimitry Andric     ICmpInst::Predicate Pred;
17455ffd83dbSDimitry Andric     Instruction *LHS, *RHS;
17465ffd83dbSDimitry Andric 
17475ffd83dbSDimitry Andric     if (!match(BB->getTerminator(),
17485ffd83dbSDimitry Andric                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
17495ffd83dbSDimitry Andric                     m_BasicBlock(), m_BasicBlock())))
17505ffd83dbSDimitry Andric       continue;
17515ffd83dbSDimitry Andric 
17525ffd83dbSDimitry Andric     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1753*5f757f3fSDimitry Andric       return true;
17545ffd83dbSDimitry Andric 
17555ffd83dbSDimitry Andric     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1756*5f757f3fSDimitry Andric       return true;
17575ffd83dbSDimitry Andric   }
17585ffd83dbSDimitry Andric 
17595ffd83dbSDimitry Andric   // Use expand's logic which is used for reusing a previous Value in
17604824e7fdSDimitry Andric   // ExprValueMap.  Note that we don't currently model the cost of
17614824e7fdSDimitry Andric   // needing to drop poison generating flags on the instruction if we
17624824e7fdSDimitry Andric   // want to reuse it.  We effectively assume that has zero cost.
1763*5f757f3fSDimitry Andric   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1764*5f757f3fSDimitry Andric   return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr;
17655ffd83dbSDimitry Andric }
17665ffd83dbSDimitry Andric 
1767fe6060f1SDimitry Andric template<typename T> static InstructionCost costAndCollectOperands(
1768e8d8bef9SDimitry Andric   const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
1769e8d8bef9SDimitry Andric   TargetTransformInfo::TargetCostKind CostKind,
1770e8d8bef9SDimitry Andric   SmallVectorImpl<SCEVOperand> &Worklist) {
1771e8d8bef9SDimitry Andric 
1772e8d8bef9SDimitry Andric   const T *S = cast<T>(WorkItem.S);
1773fe6060f1SDimitry Andric   InstructionCost Cost = 0;
1774e8d8bef9SDimitry Andric   // Object to help map SCEV operands to expanded IR instructions.
1775e8d8bef9SDimitry Andric   struct OperationIndices {
1776e8d8bef9SDimitry Andric     OperationIndices(unsigned Opc, size_t min, size_t max) :
1777e8d8bef9SDimitry Andric       Opcode(Opc), MinIdx(min), MaxIdx(max) { }
1778e8d8bef9SDimitry Andric     unsigned Opcode;
1779e8d8bef9SDimitry Andric     size_t MinIdx;
1780e8d8bef9SDimitry Andric     size_t MaxIdx;
1781e8d8bef9SDimitry Andric   };
1782e8d8bef9SDimitry Andric 
1783e8d8bef9SDimitry Andric   // Collect the operations of all the instructions that will be needed to
1784e8d8bef9SDimitry Andric   // expand the SCEVExpr. This is so that when we come to cost the operands,
1785e8d8bef9SDimitry Andric   // we know what the generated user(s) will be.
1786e8d8bef9SDimitry Andric   SmallVector<OperationIndices, 2> Operations;
1787e8d8bef9SDimitry Andric 
1788fe6060f1SDimitry Andric   auto CastCost = [&](unsigned Opcode) -> InstructionCost {
1789e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, 0, 0);
1790e8d8bef9SDimitry Andric     return TTI.getCastInstrCost(Opcode, S->getType(),
1791e8d8bef9SDimitry Andric                                 S->getOperand(0)->getType(),
1792e8d8bef9SDimitry Andric                                 TTI::CastContextHint::None, CostKind);
1793e8d8bef9SDimitry Andric   };
1794e8d8bef9SDimitry Andric 
1795e8d8bef9SDimitry Andric   auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
1796fe6060f1SDimitry Andric                        unsigned MinIdx = 0,
1797fe6060f1SDimitry Andric                        unsigned MaxIdx = 1) -> InstructionCost {
1798e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1799e8d8bef9SDimitry Andric     return NumRequired *
1800e8d8bef9SDimitry Andric       TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
1801e8d8bef9SDimitry Andric   };
1802e8d8bef9SDimitry Andric 
1803fe6060f1SDimitry Andric   auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
1804fe6060f1SDimitry Andric                         unsigned MaxIdx) -> InstructionCost {
1805e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1806bdd1243dSDimitry Andric     Type *OpType = S->getType();
1807e8d8bef9SDimitry Andric     return NumRequired * TTI.getCmpSelInstrCost(
1808e8d8bef9SDimitry Andric                              Opcode, OpType, CmpInst::makeCmpResultType(OpType),
1809e8d8bef9SDimitry Andric                              CmpInst::BAD_ICMP_PREDICATE, CostKind);
1810e8d8bef9SDimitry Andric   };
1811e8d8bef9SDimitry Andric 
1812e8d8bef9SDimitry Andric   switch (S->getSCEVType()) {
1813e8d8bef9SDimitry Andric   case scCouldNotCompute:
1814e8d8bef9SDimitry Andric     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1815e8d8bef9SDimitry Andric   case scUnknown:
1816e8d8bef9SDimitry Andric   case scConstant:
181706c3fb27SDimitry Andric   case scVScale:
1818e8d8bef9SDimitry Andric     return 0;
1819e8d8bef9SDimitry Andric   case scPtrToInt:
1820e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::PtrToInt);
1821e8d8bef9SDimitry Andric     break;
1822e8d8bef9SDimitry Andric   case scTruncate:
1823e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::Trunc);
1824e8d8bef9SDimitry Andric     break;
1825e8d8bef9SDimitry Andric   case scZeroExtend:
1826e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::ZExt);
1827e8d8bef9SDimitry Andric     break;
1828e8d8bef9SDimitry Andric   case scSignExtend:
1829e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::SExt);
1830e8d8bef9SDimitry Andric     break;
1831e8d8bef9SDimitry Andric   case scUDivExpr: {
1832e8d8bef9SDimitry Andric     unsigned Opcode = Instruction::UDiv;
1833e8d8bef9SDimitry Andric     if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1834e8d8bef9SDimitry Andric       if (SC->getAPInt().isPowerOf2())
1835e8d8bef9SDimitry Andric         Opcode = Instruction::LShr;
1836e8d8bef9SDimitry Andric     Cost = ArithCost(Opcode, 1);
1837e8d8bef9SDimitry Andric     break;
1838e8d8bef9SDimitry Andric   }
1839e8d8bef9SDimitry Andric   case scAddExpr:
1840e8d8bef9SDimitry Andric     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1841e8d8bef9SDimitry Andric     break;
1842e8d8bef9SDimitry Andric   case scMulExpr:
1843e8d8bef9SDimitry Andric     // TODO: this is a very pessimistic cost modelling for Mul,
1844e8d8bef9SDimitry Andric     // because of Bin Pow algorithm actually used by the expander,
1845e8d8bef9SDimitry Andric     // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
1846e8d8bef9SDimitry Andric     Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1847e8d8bef9SDimitry Andric     break;
1848e8d8bef9SDimitry Andric   case scSMaxExpr:
1849e8d8bef9SDimitry Andric   case scUMaxExpr:
1850e8d8bef9SDimitry Andric   case scSMinExpr:
185104eeddc0SDimitry Andric   case scUMinExpr:
185204eeddc0SDimitry Andric   case scSequentialUMinExpr: {
1853fe6060f1SDimitry Andric     // FIXME: should this ask the cost for Intrinsic's?
185404eeddc0SDimitry Andric     // The reduction tree.
1855e8d8bef9SDimitry Andric     Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1856e8d8bef9SDimitry Andric     Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
185704eeddc0SDimitry Andric     switch (S->getSCEVType()) {
185804eeddc0SDimitry Andric     case scSequentialUMinExpr: {
185904eeddc0SDimitry Andric       // The safety net against poison.
186004eeddc0SDimitry Andric       // FIXME: this is broken.
186104eeddc0SDimitry Andric       Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
186204eeddc0SDimitry Andric       Cost += ArithCost(Instruction::Or,
186304eeddc0SDimitry Andric                         S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
186404eeddc0SDimitry Andric       Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
186504eeddc0SDimitry Andric       break;
186604eeddc0SDimitry Andric     }
186704eeddc0SDimitry Andric     default:
186804eeddc0SDimitry Andric       assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
186904eeddc0SDimitry Andric              "Unhandled SCEV expression type?");
187004eeddc0SDimitry Andric       break;
187104eeddc0SDimitry Andric     }
1872e8d8bef9SDimitry Andric     break;
1873e8d8bef9SDimitry Andric   }
1874e8d8bef9SDimitry Andric   case scAddRecExpr: {
1875e8d8bef9SDimitry Andric     // In this polynominal, we may have some zero operands, and we shouldn't
1876bdd1243dSDimitry Andric     // really charge for those. So how many non-zero coefficients are there?
1877e8d8bef9SDimitry Andric     int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) {
1878e8d8bef9SDimitry Andric                                     return !Op->isZero();
1879e8d8bef9SDimitry Andric                                   });
1880e8d8bef9SDimitry Andric 
1881e8d8bef9SDimitry Andric     assert(NumTerms >= 1 && "Polynominal should have at least one term.");
1882e8d8bef9SDimitry Andric     assert(!(*std::prev(S->operands().end()))->isZero() &&
1883e8d8bef9SDimitry Andric            "Last operand should not be zero");
1884e8d8bef9SDimitry Andric 
1885bdd1243dSDimitry Andric     // Ignoring constant term (operand 0), how many of the coefficients are u> 1?
1886e8d8bef9SDimitry Andric     int NumNonZeroDegreeNonOneTerms =
1887e8d8bef9SDimitry Andric       llvm::count_if(S->operands(), [](const SCEV *Op) {
1888e8d8bef9SDimitry Andric                       auto *SConst = dyn_cast<SCEVConstant>(Op);
1889e8d8bef9SDimitry Andric                       return !SConst || SConst->getAPInt().ugt(1);
1890e8d8bef9SDimitry Andric                     });
1891e8d8bef9SDimitry Andric 
1892e8d8bef9SDimitry Andric     // Much like with normal add expr, the polynominal will require
1893e8d8bef9SDimitry Andric     // one less addition than the number of it's terms.
1894fe6060f1SDimitry Andric     InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1,
1895e8d8bef9SDimitry Andric                                         /*MinIdx*/ 1, /*MaxIdx*/ 1);
1896e8d8bef9SDimitry Andric     // Here, *each* one of those will require a multiplication.
1897fe6060f1SDimitry Andric     InstructionCost MulCost =
1898fe6060f1SDimitry Andric         ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
1899e8d8bef9SDimitry Andric     Cost = AddCost + MulCost;
1900e8d8bef9SDimitry Andric 
1901e8d8bef9SDimitry Andric     // What is the degree of this polynominal?
1902e8d8bef9SDimitry Andric     int PolyDegree = S->getNumOperands() - 1;
1903e8d8bef9SDimitry Andric     assert(PolyDegree >= 1 && "Should be at least affine.");
1904e8d8bef9SDimitry Andric 
1905e8d8bef9SDimitry Andric     // The final term will be:
1906e8d8bef9SDimitry Andric     //   Op_{PolyDegree} * x ^ {PolyDegree}
1907e8d8bef9SDimitry Andric     // Where  x ^ {PolyDegree}  will again require PolyDegree-1 mul operations.
1908e8d8bef9SDimitry Andric     // Note that  x ^ {PolyDegree} = x * x ^ {PolyDegree-1}  so charging for
1909e8d8bef9SDimitry Andric     // x ^ {PolyDegree}  will give us  x ^ {2} .. x ^ {PolyDegree-1}  for free.
1910e8d8bef9SDimitry Andric     // FIXME: this is conservatively correct, but might be overly pessimistic.
1911e8d8bef9SDimitry Andric     Cost += MulCost * (PolyDegree - 1);
1912e8d8bef9SDimitry Andric     break;
1913e8d8bef9SDimitry Andric   }
1914e8d8bef9SDimitry Andric   }
1915e8d8bef9SDimitry Andric 
1916e8d8bef9SDimitry Andric   for (auto &CostOp : Operations) {
1917e8d8bef9SDimitry Andric     for (auto SCEVOp : enumerate(S->operands())) {
1918e8d8bef9SDimitry Andric       // Clamp the index to account for multiple IR operations being chained.
1919e8d8bef9SDimitry Andric       size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1920e8d8bef9SDimitry Andric       size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1921e8d8bef9SDimitry Andric       Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1922e8d8bef9SDimitry Andric     }
1923e8d8bef9SDimitry Andric   }
1924e8d8bef9SDimitry Andric   return Cost;
1925e8d8bef9SDimitry Andric }
1926e8d8bef9SDimitry Andric 
19275ffd83dbSDimitry Andric bool SCEVExpander::isHighCostExpansionHelper(
1928e8d8bef9SDimitry Andric     const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
1929fe6060f1SDimitry Andric     InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
1930e8d8bef9SDimitry Andric     SmallPtrSetImpl<const SCEV *> &Processed,
1931e8d8bef9SDimitry Andric     SmallVectorImpl<SCEVOperand> &Worklist) {
1932fe6060f1SDimitry Andric   if (Cost > Budget)
19335ffd83dbSDimitry Andric     return true; // Already run out of budget, give up.
19345ffd83dbSDimitry Andric 
1935e8d8bef9SDimitry Andric   const SCEV *S = WorkItem.S;
19365ffd83dbSDimitry Andric   // Was the cost of expansion of this expression already accounted for?
1937e8d8bef9SDimitry Andric   if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
19385ffd83dbSDimitry Andric     return false; // We have already accounted for this expression.
19395ffd83dbSDimitry Andric 
19405ffd83dbSDimitry Andric   // If we can find an existing value for this scev available at the point "At"
19415ffd83dbSDimitry Andric   // then consider the expression cheap.
1942*5f757f3fSDimitry Andric   if (hasRelatedExistingExpansion(S, &At, L))
19435ffd83dbSDimitry Andric     return false; // Consider the expression to be free.
19445ffd83dbSDimitry Andric 
19455ffd83dbSDimitry Andric   TargetTransformInfo::TargetCostKind CostKind =
1946e8d8bef9SDimitry Andric       L->getHeader()->getParent()->hasMinSize()
1947e8d8bef9SDimitry Andric           ? TargetTransformInfo::TCK_CodeSize
1948e8d8bef9SDimitry Andric           : TargetTransformInfo::TCK_RecipThroughput;
19495ffd83dbSDimitry Andric 
19505ffd83dbSDimitry Andric   switch (S->getSCEVType()) {
1951e8d8bef9SDimitry Andric   case scCouldNotCompute:
1952e8d8bef9SDimitry Andric     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1953e8d8bef9SDimitry Andric   case scUnknown:
195406c3fb27SDimitry Andric   case scVScale:
1955e8d8bef9SDimitry Andric     // Assume to be zero-cost.
1956e8d8bef9SDimitry Andric     return false;
1957e8d8bef9SDimitry Andric   case scConstant: {
1958e8d8bef9SDimitry Andric     // Only evalulate the costs of constants when optimizing for size.
1959e8d8bef9SDimitry Andric     if (CostKind != TargetTransformInfo::TCK_CodeSize)
196004eeddc0SDimitry Andric       return false;
1961e8d8bef9SDimitry Andric     const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
1962e8d8bef9SDimitry Andric     Type *Ty = S->getType();
1963fe6060f1SDimitry Andric     Cost += TTI.getIntImmCostInst(
1964e8d8bef9SDimitry Andric         WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
1965fe6060f1SDimitry Andric     return Cost > Budget;
1966e8d8bef9SDimitry Andric   }
19675ffd83dbSDimitry Andric   case scTruncate:
1968e8d8bef9SDimitry Andric   case scPtrToInt:
19695ffd83dbSDimitry Andric   case scZeroExtend:
1970e8d8bef9SDimitry Andric   case scSignExtend: {
1971fe6060f1SDimitry Andric     Cost +=
1972e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
19735ffd83dbSDimitry Andric     return false; // Will answer upon next entry into this function.
19745ffd83dbSDimitry Andric   }
1975e8d8bef9SDimitry Andric   case scUDivExpr: {
19765ffd83dbSDimitry Andric     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
19775ffd83dbSDimitry Andric     // HowManyLessThans produced to compute a precise expression, rather than a
19785ffd83dbSDimitry Andric     // UDiv from the user's code. If we can't find a UDiv in the code with some
19795ffd83dbSDimitry Andric     // simple searching, we need to account for it's cost.
19805ffd83dbSDimitry Andric 
19815ffd83dbSDimitry Andric     // At the beginning of this function we already tried to find existing
19825ffd83dbSDimitry Andric     // value for plain 'S'. Now try to lookup 'S + 1' since it is common
19835ffd83dbSDimitry Andric     // pattern involving division. This is just a simple search heuristic.
1984*5f757f3fSDimitry Andric     if (hasRelatedExistingExpansion(
19855ffd83dbSDimitry Andric             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
19865ffd83dbSDimitry Andric       return false; // Consider it to be free.
19875ffd83dbSDimitry Andric 
1988fe6060f1SDimitry Andric     Cost +=
1989e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
19905ffd83dbSDimitry Andric     return false; // Will answer upon next entry into this function.
19915ffd83dbSDimitry Andric   }
19925ffd83dbSDimitry Andric   case scAddExpr:
19935ffd83dbSDimitry Andric   case scMulExpr:
19945ffd83dbSDimitry Andric   case scUMaxExpr:
1995e8d8bef9SDimitry Andric   case scSMaxExpr:
19965ffd83dbSDimitry Andric   case scUMinExpr:
199704eeddc0SDimitry Andric   case scSMinExpr:
199804eeddc0SDimitry Andric   case scSequentialUMinExpr: {
1999e8d8bef9SDimitry Andric     assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
20005ffd83dbSDimitry Andric            "Nary expr should have more than 1 operand.");
20015ffd83dbSDimitry Andric     // The simple nary expr will require one less op (or pair of ops)
20025ffd83dbSDimitry Andric     // than the number of it's terms.
2003fe6060f1SDimitry Andric     Cost +=
2004e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
2005fe6060f1SDimitry Andric     return Cost > Budget;
20065ffd83dbSDimitry Andric   }
2007e8d8bef9SDimitry Andric   case scAddRecExpr: {
2008e8d8bef9SDimitry Andric     assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2009e8d8bef9SDimitry Andric            "Polynomial should be at least linear");
2010fe6060f1SDimitry Andric     Cost += costAndCollectOperands<SCEVAddRecExpr>(
2011e8d8bef9SDimitry Andric         WorkItem, TTI, CostKind, Worklist);
2012fe6060f1SDimitry Andric     return Cost > Budget;
2013e8d8bef9SDimitry Andric   }
2014e8d8bef9SDimitry Andric   }
2015e8d8bef9SDimitry Andric   llvm_unreachable("Unknown SCEV kind!");
20165ffd83dbSDimitry Andric }
20175ffd83dbSDimitry Andric 
20185ffd83dbSDimitry Andric Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
20195ffd83dbSDimitry Andric                                             Instruction *IP) {
20205ffd83dbSDimitry Andric   assert(IP);
20215ffd83dbSDimitry Andric   switch (Pred->getKind()) {
20225ffd83dbSDimitry Andric   case SCEVPredicate::P_Union:
20235ffd83dbSDimitry Andric     return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
202481ad6265SDimitry Andric   case SCEVPredicate::P_Compare:
202581ad6265SDimitry Andric     return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP);
20265ffd83dbSDimitry Andric   case SCEVPredicate::P_Wrap: {
20275ffd83dbSDimitry Andric     auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
20285ffd83dbSDimitry Andric     return expandWrapPredicate(AddRecPred, IP);
20295ffd83dbSDimitry Andric   }
20305ffd83dbSDimitry Andric   }
20315ffd83dbSDimitry Andric   llvm_unreachable("Unknown SCEV predicate type");
20325ffd83dbSDimitry Andric }
20335ffd83dbSDimitry Andric 
203481ad6265SDimitry Andric Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred,
20355ffd83dbSDimitry Andric                                             Instruction *IP) {
2036*5f757f3fSDimitry Andric   Value *Expr0 = expand(Pred->getLHS(), IP);
2037*5f757f3fSDimitry Andric   Value *Expr1 = expand(Pred->getRHS(), IP);
20385ffd83dbSDimitry Andric 
20395ffd83dbSDimitry Andric   Builder.SetInsertPoint(IP);
204081ad6265SDimitry Andric   auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
204181ad6265SDimitry Andric   auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
20425ffd83dbSDimitry Andric   return I;
20435ffd83dbSDimitry Andric }
20445ffd83dbSDimitry Andric 
20455ffd83dbSDimitry Andric Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
20465ffd83dbSDimitry Andric                                            Instruction *Loc, bool Signed) {
20475ffd83dbSDimitry Andric   assert(AR->isAffine() && "Cannot generate RT check for "
20485ffd83dbSDimitry Andric                            "non-affine expression");
20495ffd83dbSDimitry Andric 
205081ad6265SDimitry Andric   // FIXME: It is highly suspicious that we're ignoring the predicates here.
205181ad6265SDimitry Andric   SmallVector<const SCEVPredicate *, 4> Pred;
20525ffd83dbSDimitry Andric   const SCEV *ExitCount =
20535ffd83dbSDimitry Andric       SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
20545ffd83dbSDimitry Andric 
2055e8d8bef9SDimitry Andric   assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
20565ffd83dbSDimitry Andric 
20575ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
20585ffd83dbSDimitry Andric   const SCEV *Start = AR->getStart();
20595ffd83dbSDimitry Andric 
20605ffd83dbSDimitry Andric   Type *ARTy = AR->getType();
20615ffd83dbSDimitry Andric   unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
20625ffd83dbSDimitry Andric   unsigned DstBits = SE.getTypeSizeInBits(ARTy);
20635ffd83dbSDimitry Andric 
20645ffd83dbSDimitry Andric   // The expression {Start,+,Step} has nusw/nssw if
20655ffd83dbSDimitry Andric   //   Step < 0, Start - |Step| * Backedge <= Start
20665ffd83dbSDimitry Andric   //   Step >= 0, Start + |Step| * Backedge > Start
20675ffd83dbSDimitry Andric   // and |Step| * Backedge doesn't unsigned overflow.
20685ffd83dbSDimitry Andric 
20695ffd83dbSDimitry Andric   Builder.SetInsertPoint(Loc);
2070*5f757f3fSDimitry Andric   Value *TripCountVal = expand(ExitCount, Loc);
20715ffd83dbSDimitry Andric 
20725ffd83dbSDimitry Andric   IntegerType *Ty =
20735ffd83dbSDimitry Andric       IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
20745ffd83dbSDimitry Andric 
2075*5f757f3fSDimitry Andric   Value *StepValue = expand(Step, Loc);
2076*5f757f3fSDimitry Andric   Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc);
2077*5f757f3fSDimitry Andric   Value *StartValue = expand(Start, Loc);
20785ffd83dbSDimitry Andric 
20795ffd83dbSDimitry Andric   ConstantInt *Zero =
2080349cc55cSDimitry Andric       ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
20815ffd83dbSDimitry Andric 
20825ffd83dbSDimitry Andric   Builder.SetInsertPoint(Loc);
20835ffd83dbSDimitry Andric   // Compute |Step|
20845ffd83dbSDimitry Andric   Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
20855ffd83dbSDimitry Andric   Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
20865ffd83dbSDimitry Andric 
208704eeddc0SDimitry Andric   // Compute |Step| * Backedge
208804eeddc0SDimitry Andric   // Compute:
208904eeddc0SDimitry Andric   //   1. Start + |Step| * Backedge < Start
209004eeddc0SDimitry Andric   //   2. Start - |Step| * Backedge > Start
209104eeddc0SDimitry Andric   //
209204eeddc0SDimitry Andric   // And select either 1. or 2. depending on whether step is positive or
209304eeddc0SDimitry Andric   // negative. If Step is known to be positive or negative, only create
209404eeddc0SDimitry Andric   // either 1. or 2.
209504eeddc0SDimitry Andric   auto ComputeEndCheck = [&]() -> Value * {
209604eeddc0SDimitry Andric     // Checking <u 0 is always false.
209704eeddc0SDimitry Andric     if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
209804eeddc0SDimitry Andric       return ConstantInt::getFalse(Loc->getContext());
209904eeddc0SDimitry Andric 
21005ffd83dbSDimitry Andric     // Get the backedge taken count and truncate or extended to the AR type.
21015ffd83dbSDimitry Andric     Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
21025ffd83dbSDimitry Andric 
2103349cc55cSDimitry Andric     Value *MulV, *OfMul;
2104349cc55cSDimitry Andric     if (Step->isOne()) {
2105349cc55cSDimitry Andric       // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
2106349cc55cSDimitry Andric       // needed, there is never an overflow, so to avoid artificially inflating
2107349cc55cSDimitry Andric       // the cost of the check, directly emit the optimized IR.
2108349cc55cSDimitry Andric       MulV = TruncTripCount;
2109349cc55cSDimitry Andric       OfMul = ConstantInt::getFalse(MulV->getContext());
2110349cc55cSDimitry Andric     } else {
2111349cc55cSDimitry Andric       auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2112349cc55cSDimitry Andric                                              Intrinsic::umul_with_overflow, Ty);
211304eeddc0SDimitry Andric       CallInst *Mul =
211404eeddc0SDimitry Andric           Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2115349cc55cSDimitry Andric       MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2116349cc55cSDimitry Andric       OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2117349cc55cSDimitry Andric     }
21185ffd83dbSDimitry Andric 
21195ffd83dbSDimitry Andric     Value *Add = nullptr, *Sub = nullptr;
212004eeddc0SDimitry Andric     bool NeedPosCheck = !SE.isKnownNegative(Step);
212104eeddc0SDimitry Andric     bool NeedNegCheck = !SE.isKnownPositive(Step);
212204eeddc0SDimitry Andric 
2123*5f757f3fSDimitry Andric     if (isa<PointerType>(ARTy)) {
2124349cc55cSDimitry Andric       Value *NegMulV = Builder.CreateNeg(MulV);
212504eeddc0SDimitry Andric       if (NeedPosCheck)
2126349cc55cSDimitry Andric         Add = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, MulV);
212704eeddc0SDimitry Andric       if (NeedNegCheck)
2128349cc55cSDimitry Andric         Sub = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, NegMulV);
21295ffd83dbSDimitry Andric     } else {
213004eeddc0SDimitry Andric       if (NeedPosCheck)
21315ffd83dbSDimitry Andric         Add = Builder.CreateAdd(StartValue, MulV);
213204eeddc0SDimitry Andric       if (NeedNegCheck)
21335ffd83dbSDimitry Andric         Sub = Builder.CreateSub(StartValue, MulV);
21345ffd83dbSDimitry Andric     }
21355ffd83dbSDimitry Andric 
213604eeddc0SDimitry Andric     Value *EndCompareLT = nullptr;
213704eeddc0SDimitry Andric     Value *EndCompareGT = nullptr;
213804eeddc0SDimitry Andric     Value *EndCheck = nullptr;
213904eeddc0SDimitry Andric     if (NeedPosCheck)
214004eeddc0SDimitry Andric       EndCheck = EndCompareLT = Builder.CreateICmp(
21415ffd83dbSDimitry Andric           Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
214204eeddc0SDimitry Andric     if (NeedNegCheck)
214304eeddc0SDimitry Andric       EndCheck = EndCompareGT = Builder.CreateICmp(
214404eeddc0SDimitry Andric           Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
214504eeddc0SDimitry Andric     if (NeedPosCheck && NeedNegCheck) {
21465ffd83dbSDimitry Andric       // Select the answer based on the sign of Step.
214704eeddc0SDimitry Andric       EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
214804eeddc0SDimitry Andric     }
214904eeddc0SDimitry Andric     return Builder.CreateOr(EndCheck, OfMul);
215004eeddc0SDimitry Andric   };
215104eeddc0SDimitry Andric   Value *EndCheck = ComputeEndCheck();
21525ffd83dbSDimitry Andric 
21535ffd83dbSDimitry Andric   // If the backedge taken count type is larger than the AR type,
21545ffd83dbSDimitry Andric   // check that we don't drop any bits by truncating it. If we are
21555ffd83dbSDimitry Andric   // dropping bits, then we have overflow (unless the step is zero).
2156*5f757f3fSDimitry Andric   if (SrcBits > DstBits) {
21575ffd83dbSDimitry Andric     auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
21585ffd83dbSDimitry Andric     auto *BackedgeCheck =
21595ffd83dbSDimitry Andric         Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
21605ffd83dbSDimitry Andric                            ConstantInt::get(Loc->getContext(), MaxVal));
21615ffd83dbSDimitry Andric     BackedgeCheck = Builder.CreateAnd(
21625ffd83dbSDimitry Andric         BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
21635ffd83dbSDimitry Andric 
21645ffd83dbSDimitry Andric     EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
21655ffd83dbSDimitry Andric   }
21665ffd83dbSDimitry Andric 
216704eeddc0SDimitry Andric   return EndCheck;
21685ffd83dbSDimitry Andric }
21695ffd83dbSDimitry Andric 
21705ffd83dbSDimitry Andric Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
21715ffd83dbSDimitry Andric                                          Instruction *IP) {
21725ffd83dbSDimitry Andric   const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
21735ffd83dbSDimitry Andric   Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
21745ffd83dbSDimitry Andric 
21755ffd83dbSDimitry Andric   // Add a check for NUSW
21765ffd83dbSDimitry Andric   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
21775ffd83dbSDimitry Andric     NUSWCheck = generateOverflowCheck(A, IP, false);
21785ffd83dbSDimitry Andric 
21795ffd83dbSDimitry Andric   // Add a check for NSSW
21805ffd83dbSDimitry Andric   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
21815ffd83dbSDimitry Andric     NSSWCheck = generateOverflowCheck(A, IP, true);
21825ffd83dbSDimitry Andric 
21835ffd83dbSDimitry Andric   if (NUSWCheck && NSSWCheck)
21845ffd83dbSDimitry Andric     return Builder.CreateOr(NUSWCheck, NSSWCheck);
21855ffd83dbSDimitry Andric 
21865ffd83dbSDimitry Andric   if (NUSWCheck)
21875ffd83dbSDimitry Andric     return NUSWCheck;
21885ffd83dbSDimitry Andric 
21895ffd83dbSDimitry Andric   if (NSSWCheck)
21905ffd83dbSDimitry Andric     return NSSWCheck;
21915ffd83dbSDimitry Andric 
21925ffd83dbSDimitry Andric   return ConstantInt::getFalse(IP->getContext());
21935ffd83dbSDimitry Andric }
21945ffd83dbSDimitry Andric 
21955ffd83dbSDimitry Andric Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
21965ffd83dbSDimitry Andric                                           Instruction *IP) {
21975ffd83dbSDimitry Andric   // Loop over all checks in this set.
219804eeddc0SDimitry Andric   SmallVector<Value *> Checks;
2199bdd1243dSDimitry Andric   for (const auto *Pred : Union->getPredicates()) {
220004eeddc0SDimitry Andric     Checks.push_back(expandCodeForPredicate(Pred, IP));
22015ffd83dbSDimitry Andric     Builder.SetInsertPoint(IP);
22025ffd83dbSDimitry Andric   }
22035ffd83dbSDimitry Andric 
220404eeddc0SDimitry Andric   if (Checks.empty())
220504eeddc0SDimitry Andric     return ConstantInt::getFalse(IP->getContext());
220604eeddc0SDimitry Andric   return Builder.CreateOr(Checks);
22075ffd83dbSDimitry Andric }
22085ffd83dbSDimitry Andric 
2209bdd1243dSDimitry Andric Value *SCEVExpander::fixupLCSSAFormFor(Value *V) {
2210bdd1243dSDimitry Andric   auto *DefI = dyn_cast<Instruction>(V);
2211bdd1243dSDimitry Andric   if (!PreserveLCSSA || !DefI)
2212bdd1243dSDimitry Andric     return V;
2213e8d8bef9SDimitry Andric 
2214bdd1243dSDimitry Andric   Instruction *InsertPt = &*Builder.GetInsertPoint();
2215bdd1243dSDimitry Andric   Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent());
2216bdd1243dSDimitry Andric   Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent());
2217e8d8bef9SDimitry Andric   if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2218bdd1243dSDimitry Andric     return V;
2219e8d8bef9SDimitry Andric 
2220bdd1243dSDimitry Andric   // Create a temporary instruction to at the current insertion point, so we
2221bdd1243dSDimitry Andric   // can hand it off to the helper to create LCSSA PHIs if required for the
2222bdd1243dSDimitry Andric   // new use.
2223bdd1243dSDimitry Andric   // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
2224bdd1243dSDimitry Andric   // would accept a insertion point and return an LCSSA phi for that
2225bdd1243dSDimitry Andric   // insertion point, so there is no need to insert & remove the temporary
2226bdd1243dSDimitry Andric   // instruction.
2227bdd1243dSDimitry Andric   Type *ToTy;
2228bdd1243dSDimitry Andric   if (DefI->getType()->isIntegerTy())
2229*5f757f3fSDimitry Andric     ToTy = PointerType::get(DefI->getContext(), 0);
2230bdd1243dSDimitry Andric   else
2231bdd1243dSDimitry Andric     ToTy = Type::getInt32Ty(DefI->getContext());
2232bdd1243dSDimitry Andric   Instruction *User =
2233bdd1243dSDimitry Andric       CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt);
2234bdd1243dSDimitry Andric   auto RemoveUserOnExit =
2235bdd1243dSDimitry Andric       make_scope_exit([User]() { User->eraseFromParent(); });
2236bdd1243dSDimitry Andric 
2237bdd1243dSDimitry Andric   SmallVector<Instruction *, 1> ToUpdate;
2238bdd1243dSDimitry Andric   ToUpdate.push_back(DefI);
2239e8d8bef9SDimitry Andric   SmallVector<PHINode *, 16> PHIsToRemove;
224006c3fb27SDimitry Andric   SmallVector<PHINode *, 16> InsertedPHIs;
224106c3fb27SDimitry Andric   formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove,
224206c3fb27SDimitry Andric                            &InsertedPHIs);
224306c3fb27SDimitry Andric   for (PHINode *PN : InsertedPHIs)
224406c3fb27SDimitry Andric     rememberInstruction(PN);
2245e8d8bef9SDimitry Andric   for (PHINode *PN : PHIsToRemove) {
2246e8d8bef9SDimitry Andric     if (!PN->use_empty())
2247e8d8bef9SDimitry Andric       continue;
2248e8d8bef9SDimitry Andric     InsertedValues.erase(PN);
2249e8d8bef9SDimitry Andric     InsertedPostIncValues.erase(PN);
2250e8d8bef9SDimitry Andric     PN->eraseFromParent();
2251e8d8bef9SDimitry Andric   }
2252e8d8bef9SDimitry Andric 
2253bdd1243dSDimitry Andric   return User->getOperand(0);
2254e8d8bef9SDimitry Andric }
2255e8d8bef9SDimitry Andric 
22565ffd83dbSDimitry Andric namespace {
22575ffd83dbSDimitry Andric // Search for a SCEV subexpression that is not safe to expand.  Any expression
22585ffd83dbSDimitry Andric // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
22595ffd83dbSDimitry Andric // UDiv expressions. We don't know if the UDiv is derived from an IR divide
22605ffd83dbSDimitry Andric // instruction, but the important thing is that we prove the denominator is
22615ffd83dbSDimitry Andric // nonzero before expansion.
22625ffd83dbSDimitry Andric //
22635ffd83dbSDimitry Andric // IVUsers already checks that IV-derived expressions are safe. So this check is
22645ffd83dbSDimitry Andric // only needed when the expression includes some subexpression that is not IV
22655ffd83dbSDimitry Andric // derived.
22665ffd83dbSDimitry Andric //
2267fcaf7f86SDimitry Andric // Currently, we only allow division by a value provably non-zero here.
22685ffd83dbSDimitry Andric //
22695ffd83dbSDimitry Andric // We cannot generally expand recurrences unless the step dominates the loop
22705ffd83dbSDimitry Andric // header. The expander handles the special case of affine recurrences by
22715ffd83dbSDimitry Andric // scaling the recurrence outside the loop, but this technique isn't generally
22725ffd83dbSDimitry Andric // applicable. Expanding a nested recurrence outside a loop requires computing
22735ffd83dbSDimitry Andric // binomial coefficients. This could be done, but the recurrence has to be in a
22745ffd83dbSDimitry Andric // perfectly reduced form, which can't be guaranteed.
22755ffd83dbSDimitry Andric struct SCEVFindUnsafe {
22765ffd83dbSDimitry Andric   ScalarEvolution &SE;
2277349cc55cSDimitry Andric   bool CanonicalMode;
227881ad6265SDimitry Andric   bool IsUnsafe = false;
22795ffd83dbSDimitry Andric 
2280349cc55cSDimitry Andric   SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
228181ad6265SDimitry Andric       : SE(SE), CanonicalMode(CanonicalMode) {}
22825ffd83dbSDimitry Andric 
22835ffd83dbSDimitry Andric   bool follow(const SCEV *S) {
22845ffd83dbSDimitry Andric     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2285fcaf7f86SDimitry Andric       if (!SE.isKnownNonZero(D->getRHS())) {
22865ffd83dbSDimitry Andric         IsUnsafe = true;
22875ffd83dbSDimitry Andric         return false;
22885ffd83dbSDimitry Andric       }
22895ffd83dbSDimitry Andric     }
22905ffd83dbSDimitry Andric     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2291349cc55cSDimitry Andric       // For non-affine addrecs or in non-canonical mode we need a preheader
2292349cc55cSDimitry Andric       // to insert into.
2293349cc55cSDimitry Andric       if (!AR->getLoop()->getLoopPreheader() &&
2294349cc55cSDimitry Andric           (!CanonicalMode || !AR->isAffine())) {
2295349cc55cSDimitry Andric         IsUnsafe = true;
2296349cc55cSDimitry Andric         return false;
2297349cc55cSDimitry Andric       }
22985ffd83dbSDimitry Andric     }
22995ffd83dbSDimitry Andric     return true;
23005ffd83dbSDimitry Andric   }
23015ffd83dbSDimitry Andric   bool isDone() const { return IsUnsafe; }
23025ffd83dbSDimitry Andric };
2303fcaf7f86SDimitry Andric } // namespace
23045ffd83dbSDimitry Andric 
2305fcaf7f86SDimitry Andric bool SCEVExpander::isSafeToExpand(const SCEV *S) const {
2306349cc55cSDimitry Andric   SCEVFindUnsafe Search(SE, CanonicalMode);
23075ffd83dbSDimitry Andric   visitAll(S, Search);
23085ffd83dbSDimitry Andric   return !Search.IsUnsafe;
23095ffd83dbSDimitry Andric }
23105ffd83dbSDimitry Andric 
2311fcaf7f86SDimitry Andric bool SCEVExpander::isSafeToExpandAt(const SCEV *S,
2312fcaf7f86SDimitry Andric                                     const Instruction *InsertionPoint) const {
2313fcaf7f86SDimitry Andric   if (!isSafeToExpand(S))
23145ffd83dbSDimitry Andric     return false;
23155ffd83dbSDimitry Andric   // We have to prove that the expanded site of S dominates InsertionPoint.
23165ffd83dbSDimitry Andric   // This is easy when not in the same block, but hard when S is an instruction
23175ffd83dbSDimitry Andric   // to be expanded somewhere inside the same block as our insertion point.
23185ffd83dbSDimitry Andric   // What we really need here is something analogous to an OrderedBasicBlock,
23195ffd83dbSDimitry Andric   // but for the moment, we paper over the problem by handling two common and
23205ffd83dbSDimitry Andric   // cheap to check cases.
23215ffd83dbSDimitry Andric   if (SE.properlyDominates(S, InsertionPoint->getParent()))
23225ffd83dbSDimitry Andric     return true;
23235ffd83dbSDimitry Andric   if (SE.dominates(S, InsertionPoint->getParent())) {
23245ffd83dbSDimitry Andric     if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
23255ffd83dbSDimitry Andric       return true;
23265ffd83dbSDimitry Andric     if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2327fe6060f1SDimitry Andric       if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
23285ffd83dbSDimitry Andric         return true;
23295ffd83dbSDimitry Andric   }
23305ffd83dbSDimitry Andric   return false;
23315ffd83dbSDimitry Andric }
2332e8d8bef9SDimitry Andric 
2333fe6060f1SDimitry Andric void SCEVExpanderCleaner::cleanup() {
2334e8d8bef9SDimitry Andric   // Result is used, nothing to remove.
2335e8d8bef9SDimitry Andric   if (ResultUsed)
2336e8d8bef9SDimitry Andric     return;
2337e8d8bef9SDimitry Andric 
2338e8d8bef9SDimitry Andric   auto InsertedInstructions = Expander.getAllInsertedInstructions();
2339e8d8bef9SDimitry Andric #ifndef NDEBUG
2340e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
2341e8d8bef9SDimitry Andric                                             InsertedInstructions.end());
2342e8d8bef9SDimitry Andric   (void)InsertedSet;
2343e8d8bef9SDimitry Andric #endif
2344e8d8bef9SDimitry Andric   // Remove sets with value handles.
2345e8d8bef9SDimitry Andric   Expander.clear();
2346e8d8bef9SDimitry Andric 
2347e8d8bef9SDimitry Andric   // Remove all inserted instructions.
234804eeddc0SDimitry Andric   for (Instruction *I : reverse(InsertedInstructions)) {
2349e8d8bef9SDimitry Andric #ifndef NDEBUG
2350e8d8bef9SDimitry Andric     assert(all_of(I->users(),
2351e8d8bef9SDimitry Andric                   [&InsertedSet](Value *U) {
2352e8d8bef9SDimitry Andric                     return InsertedSet.contains(cast<Instruction>(U));
2353e8d8bef9SDimitry Andric                   }) &&
2354e8d8bef9SDimitry Andric            "removed instruction should only be used by instructions inserted "
2355e8d8bef9SDimitry Andric            "during expansion");
2356e8d8bef9SDimitry Andric #endif
2357e8d8bef9SDimitry Andric     assert(!I->getType()->isVoidTy() &&
2358e8d8bef9SDimitry Andric            "inserted instruction should have non-void types");
2359bdd1243dSDimitry Andric     I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2360e8d8bef9SDimitry Andric     I->eraseFromParent();
2361e8d8bef9SDimitry Andric   }
2362e8d8bef9SDimitry Andric }
2363