xref: /llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp (revision 1905cdbf4ef15565504036c52725cb0622ee64ef)
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution expander,
10 // which is used to generate the code corresponding to a given scalar evolution
11 // expression.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/LoopUtils.h"
30 
31 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
32 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
33 #else
34 #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
35 #endif
36 
37 using namespace llvm;
38 
39 cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
40     "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
41     cl::desc("When performing SCEV expansion only if it is cheap to do, this "
42              "controls the budget that is considered cheap (default = 4)"));
43 
44 using namespace PatternMatch;
45 
46 PoisonFlags::PoisonFlags(const Instruction *I) {
47   NUW = false;
48   NSW = false;
49   Exact = false;
50   Disjoint = false;
51   NNeg = false;
52   GEPNW = GEPNoWrapFlags::none();
53   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
54     NUW = OBO->hasNoUnsignedWrap();
55     NSW = OBO->hasNoSignedWrap();
56   }
57   if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
58     Exact = PEO->isExact();
59   if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
60     Disjoint = PDI->isDisjoint();
61   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
62     NNeg = PNI->hasNonNeg();
63   if (auto *TI = dyn_cast<TruncInst>(I)) {
64     NUW = TI->hasNoUnsignedWrap();
65     NSW = TI->hasNoSignedWrap();
66   }
67   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
68     GEPNW = GEP->getNoWrapFlags();
69 }
70 
71 void PoisonFlags::apply(Instruction *I) {
72   if (isa<OverflowingBinaryOperator>(I)) {
73     I->setHasNoUnsignedWrap(NUW);
74     I->setHasNoSignedWrap(NSW);
75   }
76   if (isa<PossiblyExactOperator>(I))
77     I->setIsExact(Exact);
78   if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
79     PDI->setIsDisjoint(Disjoint);
80   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
81     PNI->setNonNeg(NNeg);
82   if (isa<TruncInst>(I)) {
83     I->setHasNoUnsignedWrap(NUW);
84     I->setHasNoSignedWrap(NSW);
85   }
86   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
87     GEP->setNoWrapFlags(GEPNW);
88 }
89 
90 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
91 /// reusing an existing cast if a suitable one (= dominating IP) exists, or
92 /// creating a new one.
93 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
94                                        Instruction::CastOps Op,
95                                        BasicBlock::iterator IP) {
96   // This function must be called with the builder having a valid insertion
97   // point. It doesn't need to be the actual IP where the uses of the returned
98   // cast will be added, but it must dominate such IP.
99   // We use this precondition to produce a cast that will dominate all its
100   // uses. In particular, this is crucial for the case where the builder's
101   // insertion point *is* the point where we were asked to put the cast.
102   // Since we don't know the builder's insertion point is actually
103   // where the uses will be added (only that it dominates it), we are
104   // not allowed to move it.
105   BasicBlock::iterator BIP = Builder.GetInsertPoint();
106 
107   Value *Ret = nullptr;
108 
109   // Check to see if there is already a cast!
110   for (User *U : V->users()) {
111     if (U->getType() != Ty)
112       continue;
113     CastInst *CI = dyn_cast<CastInst>(U);
114     if (!CI || CI->getOpcode() != Op)
115       continue;
116 
117     // Found a suitable cast that is at IP or comes before IP. Use it. Note that
118     // the cast must also properly dominate the Builder's insertion point.
119     if (IP->getParent() == CI->getParent() && &*BIP != CI &&
120         (&*IP == CI || CI->comesBefore(&*IP))) {
121       Ret = CI;
122       break;
123     }
124   }
125 
126   // Create a new cast.
127   if (!Ret) {
128     SCEVInsertPointGuard Guard(Builder, this);
129     Builder.SetInsertPoint(&*IP);
130     Ret = Builder.CreateCast(Op, V, Ty, V->getName());
131   }
132 
133   // We assert at the end of the function since IP might point to an
134   // instruction with different dominance properties than a cast
135   // (an invoke for example) and not dominate BIP (but the cast does).
136   assert(!isa<Instruction>(Ret) ||
137          SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
138 
139   return Ret;
140 }
141 
142 BasicBlock::iterator
143 SCEVExpander::findInsertPointAfter(Instruction *I,
144                                    Instruction *MustDominate) const {
145   BasicBlock::iterator IP = ++I->getIterator();
146   if (auto *II = dyn_cast<InvokeInst>(I))
147     IP = II->getNormalDest()->begin();
148 
149   while (isa<PHINode>(IP))
150     ++IP;
151 
152   if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
153     ++IP;
154   } else if (isa<CatchSwitchInst>(IP)) {
155     IP = MustDominate->getParent()->getFirstInsertionPt();
156   } else {
157     assert(!IP->isEHPad() && "unexpected eh pad!");
158   }
159 
160   // Adjust insert point to be after instructions inserted by the expander, so
161   // we can re-use already inserted instructions. Avoid skipping past the
162   // original \p MustDominate, in case it is an inserted instruction.
163   while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
164     ++IP;
165 
166   return IP;
167 }
168 
169 BasicBlock::iterator
170 SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
171   // Cast the argument at the beginning of the entry block, after
172   // any bitcasts of other arguments.
173   if (Argument *A = dyn_cast<Argument>(V)) {
174     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
175     while ((isa<BitCastInst>(IP) &&
176             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
177             cast<BitCastInst>(IP)->getOperand(0) != A) ||
178            isa<DbgInfoIntrinsic>(IP))
179       ++IP;
180     return IP;
181   }
182 
183   // Cast the instruction immediately after the instruction.
184   if (Instruction *I = dyn_cast<Instruction>(V))
185     return findInsertPointAfter(I, &*Builder.GetInsertPoint());
186 
187   // Otherwise, this must be some kind of a constant,
188   // so let's plop this cast into the function's entry block.
189   assert(isa<Constant>(V) &&
190          "Expected the cast argument to be a global/constant");
191   return Builder.GetInsertBlock()
192       ->getParent()
193       ->getEntryBlock()
194       .getFirstInsertionPt();
195 }
196 
197 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
198 /// which must be possible with a noop cast, doing what we can to share
199 /// the casts.
200 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
201   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
202   assert((Op == Instruction::BitCast ||
203           Op == Instruction::PtrToInt ||
204           Op == Instruction::IntToPtr) &&
205          "InsertNoopCastOfTo cannot perform non-noop casts!");
206   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
207          "InsertNoopCastOfTo cannot change sizes!");
208 
209   // inttoptr only works for integral pointers. For non-integral pointers, we
210   // can create a GEP on null with the integral value as index. Note that
211   // it is safe to use GEP of null instead of inttoptr here, because only
212   // expressions already based on a GEP of null should be converted to pointers
213   // during expansion.
214   if (Op == Instruction::IntToPtr) {
215     auto *PtrTy = cast<PointerType>(Ty);
216     if (DL.isNonIntegralPointerType(PtrTy))
217       return Builder.CreatePtrAdd(Constant::getNullValue(PtrTy), V, "scevgep");
218   }
219   // Short-circuit unnecessary bitcasts.
220   if (Op == Instruction::BitCast) {
221     if (V->getType() == Ty)
222       return V;
223     if (CastInst *CI = dyn_cast<CastInst>(V)) {
224       if (CI->getOperand(0)->getType() == Ty)
225         return CI->getOperand(0);
226     }
227   }
228   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
229   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
230       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
231     if (CastInst *CI = dyn_cast<CastInst>(V))
232       if ((CI->getOpcode() == Instruction::PtrToInt ||
233            CI->getOpcode() == Instruction::IntToPtr) &&
234           SE.getTypeSizeInBits(CI->getType()) ==
235           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
236         return CI->getOperand(0);
237     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
238       if ((CE->getOpcode() == Instruction::PtrToInt ||
239            CE->getOpcode() == Instruction::IntToPtr) &&
240           SE.getTypeSizeInBits(CE->getType()) ==
241           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
242         return CE->getOperand(0);
243   }
244 
245   // Fold a cast of a constant.
246   if (Constant *C = dyn_cast<Constant>(V))
247     return ConstantExpr::getCast(Op, C, Ty);
248 
249   // Try to reuse existing cast, or insert one.
250   return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
251 }
252 
253 /// InsertBinop - Insert the specified binary operator, doing a small amount
254 /// of work to avoid inserting an obviously redundant operation, and hoisting
255 /// to an outer loop when the opportunity is there and it is safe.
256 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
257                                  Value *LHS, Value *RHS,
258                                  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
259   // Fold a binop with constant operands.
260   if (Constant *CLHS = dyn_cast<Constant>(LHS))
261     if (Constant *CRHS = dyn_cast<Constant>(RHS))
262       if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
263         return Res;
264 
265   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
266   unsigned ScanLimit = 6;
267   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
268   // Scanning starts from the last instruction before the insertion point.
269   BasicBlock::iterator IP = Builder.GetInsertPoint();
270   if (IP != BlockBegin) {
271     --IP;
272     for (; ScanLimit; --IP, --ScanLimit) {
273       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
274       // generated code.
275       if (isa<DbgInfoIntrinsic>(IP))
276         ScanLimit++;
277 
278       auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
279         // Ensure that no-wrap flags match.
280         if (isa<OverflowingBinaryOperator>(I)) {
281           if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
282             return true;
283           if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
284             return true;
285         }
286         // Conservatively, do not use any instruction which has any of exact
287         // flags installed.
288         if (isa<PossiblyExactOperator>(I) && I->isExact())
289           return true;
290         return false;
291       };
292       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
293           IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
294         return &*IP;
295       if (IP == BlockBegin) break;
296     }
297   }
298 
299   // Save the original insertion point so we can restore it when we're done.
300   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
301   SCEVInsertPointGuard Guard(Builder, this);
302 
303   if (IsSafeToHoist) {
304     // Move the insertion point out of as many loops as we can.
305     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
306       if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
307       BasicBlock *Preheader = L->getLoopPreheader();
308       if (!Preheader) break;
309 
310       // Ok, move up a level.
311       Builder.SetInsertPoint(Preheader->getTerminator());
312     }
313   }
314 
315   // If we haven't found this binop, insert it.
316   // TODO: Use the Builder, which will make CreateBinOp below fold with
317   // InstSimplifyFolder.
318   Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS));
319   BO->setDebugLoc(Loc);
320   if (Flags & SCEV::FlagNUW)
321     BO->setHasNoUnsignedWrap();
322   if (Flags & SCEV::FlagNSW)
323     BO->setHasNoSignedWrap();
324 
325   return BO;
326 }
327 
328 /// expandAddToGEP - Expand an addition expression with a pointer type into
329 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
330 /// BasicAliasAnalysis and other passes analyze the result. See the rules
331 /// for getelementptr vs. inttoptr in
332 /// http://llvm.org/docs/LangRef.html#pointeraliasing
333 /// for details.
334 ///
335 /// Design note: The correctness of using getelementptr here depends on
336 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
337 /// they may introduce pointer arithmetic which may not be safely converted
338 /// into getelementptr.
339 ///
340 /// Design note: It might seem desirable for this function to be more
341 /// loop-aware. If some of the indices are loop-invariant while others
342 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
343 /// loop-invariant portions of the overall computation outside the loop.
344 /// However, there are a few reasons this is not done here. Hoisting simple
345 /// arithmetic is a low-level optimization that often isn't very
346 /// important until late in the optimization process. In fact, passes
347 /// like InstructionCombining will combine GEPs, even if it means
348 /// pushing loop-invariant computation down into loops, so even if the
349 /// GEPs were split here, the work would quickly be undone. The
350 /// LoopStrengthReduction pass, which is usually run quite late (and
351 /// after the last InstructionCombining pass), takes care of hoisting
352 /// loop-invariant portions of expressions, after considering what
353 /// can be folded using target addressing modes.
354 ///
355 Value *SCEVExpander::expandAddToGEP(const SCEV *Offset, Value *V,
356                                     SCEV::NoWrapFlags Flags) {
357   assert(!isa<Instruction>(V) ||
358          SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
359 
360   Value *Idx = expand(Offset);
361   GEPNoWrapFlags NW = (Flags & SCEV::FlagNUW) ? GEPNoWrapFlags::noUnsignedWrap()
362                                               : GEPNoWrapFlags::none();
363 
364   // Fold a GEP with constant operands.
365   if (Constant *CLHS = dyn_cast<Constant>(V))
366     if (Constant *CRHS = dyn_cast<Constant>(Idx))
367       return Builder.CreatePtrAdd(CLHS, CRHS, "", NW);
368 
369   // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
370   unsigned ScanLimit = 6;
371   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
372   // Scanning starts from the last instruction before the insertion point.
373   BasicBlock::iterator IP = Builder.GetInsertPoint();
374   if (IP != BlockBegin) {
375     --IP;
376     for (; ScanLimit; --IP, --ScanLimit) {
377       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
378       // generated code.
379       if (isa<DbgInfoIntrinsic>(IP))
380         ScanLimit++;
381       if (auto *GEP = dyn_cast<GetElementPtrInst>(IP)) {
382         if (GEP->getPointerOperand() == V &&
383             GEP->getSourceElementType() == Builder.getInt8Ty() &&
384             GEP->getOperand(1) == Idx) {
385           rememberFlags(GEP);
386           GEP->setNoWrapFlags(GEP->getNoWrapFlags() & NW);
387           return &*IP;
388         }
389       }
390       if (IP == BlockBegin) break;
391     }
392   }
393 
394   // Save the original insertion point so we can restore it when we're done.
395   SCEVInsertPointGuard Guard(Builder, this);
396 
397   // Move the insertion point out of as many loops as we can.
398   while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
399     if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
400     BasicBlock *Preheader = L->getLoopPreheader();
401     if (!Preheader) break;
402 
403     // Ok, move up a level.
404     Builder.SetInsertPoint(Preheader->getTerminator());
405   }
406 
407   // Emit a GEP.
408   return Builder.CreatePtrAdd(V, Idx, "scevgep", NW);
409 }
410 
411 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
412 /// SCEV expansion. If they are nested, this is the most nested. If they are
413 /// neighboring, pick the later.
414 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
415                                         DominatorTree &DT) {
416   if (!A) return B;
417   if (!B) return A;
418   if (A->contains(B)) return B;
419   if (B->contains(A)) return A;
420   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
421   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
422   return A; // Arbitrarily break the tie.
423 }
424 
425 /// getRelevantLoop - Get the most relevant loop associated with the given
426 /// expression, according to PickMostRelevantLoop.
427 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
428   // Test whether we've already computed the most relevant loop for this SCEV.
429   auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
430   if (!Pair.second)
431     return Pair.first->second;
432 
433   switch (S->getSCEVType()) {
434   case scConstant:
435   case scVScale:
436     return nullptr; // A constant has no relevant loops.
437   case scTruncate:
438   case scZeroExtend:
439   case scSignExtend:
440   case scPtrToInt:
441   case scAddExpr:
442   case scMulExpr:
443   case scUDivExpr:
444   case scAddRecExpr:
445   case scUMaxExpr:
446   case scSMaxExpr:
447   case scUMinExpr:
448   case scSMinExpr:
449   case scSequentialUMinExpr: {
450     const Loop *L = nullptr;
451     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
452       L = AR->getLoop();
453     for (const SCEV *Op : S->operands())
454       L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
455     return RelevantLoops[S] = L;
456   }
457   case scUnknown: {
458     const SCEVUnknown *U = cast<SCEVUnknown>(S);
459     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
460       return Pair.first->second = SE.LI.getLoopFor(I->getParent());
461     // A non-instruction has no relevant loops.
462     return nullptr;
463   }
464   case scCouldNotCompute:
465     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
466   }
467   llvm_unreachable("Unexpected SCEV type!");
468 }
469 
470 namespace {
471 
472 /// LoopCompare - Compare loops by PickMostRelevantLoop.
473 class LoopCompare {
474   DominatorTree &DT;
475 public:
476   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
477 
478   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
479                   std::pair<const Loop *, const SCEV *> RHS) const {
480     // Keep pointer operands sorted at the end.
481     if (LHS.second->getType()->isPointerTy() !=
482         RHS.second->getType()->isPointerTy())
483       return LHS.second->getType()->isPointerTy();
484 
485     // Compare loops with PickMostRelevantLoop.
486     if (LHS.first != RHS.first)
487       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
488 
489     // If one operand is a non-constant negative and the other is not,
490     // put the non-constant negative on the right so that a sub can
491     // be used instead of a negate and add.
492     if (LHS.second->isNonConstantNegative()) {
493       if (!RHS.second->isNonConstantNegative())
494         return false;
495     } else if (RHS.second->isNonConstantNegative())
496       return true;
497 
498     // Otherwise they are equivalent according to this comparison.
499     return false;
500   }
501 };
502 
503 }
504 
505 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
506   // Recognize the canonical representation of an unsimplifed urem.
507   const SCEV *URemLHS = nullptr;
508   const SCEV *URemRHS = nullptr;
509   if (SE.matchURem(S, URemLHS, URemRHS)) {
510     Value *LHS = expand(URemLHS);
511     Value *RHS = expand(URemRHS);
512     return InsertBinop(Instruction::URem, LHS, RHS, SCEV::FlagAnyWrap,
513                       /*IsSafeToHoist*/ false);
514   }
515 
516   // Collect all the add operands in a loop, along with their associated loops.
517   // Iterate in reverse so that constants are emitted last, all else equal, and
518   // so that pointer operands are inserted first, which the code below relies on
519   // to form more involved GEPs.
520   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
521   for (const SCEV *Op : reverse(S->operands()))
522     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
523 
524   // Sort by loop. Use a stable sort so that constants follow non-constants and
525   // pointer operands precede non-pointer operands.
526   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
527 
528   // Emit instructions to add all the operands. Hoist as much as possible
529   // out of loops, and form meaningful getelementptrs where possible.
530   Value *Sum = nullptr;
531   for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
532     const Loop *CurLoop = I->first;
533     const SCEV *Op = I->second;
534     if (!Sum) {
535       // This is the first operand. Just expand it.
536       Sum = expand(Op);
537       ++I;
538       continue;
539     }
540 
541     assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
542     if (isa<PointerType>(Sum->getType())) {
543       // The running sum expression is a pointer. Try to form a getelementptr
544       // at this level with that as the base.
545       SmallVector<const SCEV *, 4> NewOps;
546       for (; I != E && I->first == CurLoop; ++I) {
547         // If the operand is SCEVUnknown and not instructions, peek through
548         // it, to enable more of it to be folded into the GEP.
549         const SCEV *X = I->second;
550         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
551           if (!isa<Instruction>(U->getValue()))
552             X = SE.getSCEV(U->getValue());
553         NewOps.push_back(X);
554       }
555       Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S->getNoWrapFlags());
556     } else if (Op->isNonConstantNegative()) {
557       // Instead of doing a negate and add, just do a subtract.
558       Value *W = expand(SE.getNegativeSCEV(Op));
559       Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
560                         /*IsSafeToHoist*/ true);
561       ++I;
562     } else {
563       // A simple add.
564       Value *W = expand(Op);
565       // Canonicalize a constant to the RHS.
566       if (isa<Constant>(Sum))
567         std::swap(Sum, W);
568       Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
569                         /*IsSafeToHoist*/ true);
570       ++I;
571     }
572   }
573 
574   return Sum;
575 }
576 
577 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
578   Type *Ty = S->getType();
579 
580   // Collect all the mul operands in a loop, along with their associated loops.
581   // Iterate in reverse so that constants are emitted last, all else equal.
582   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
583   for (const SCEV *Op : reverse(S->operands()))
584     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
585 
586   // Sort by loop. Use a stable sort so that constants follow non-constants.
587   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
588 
589   // Emit instructions to mul all the operands. Hoist as much as possible
590   // out of loops.
591   Value *Prod = nullptr;
592   auto I = OpsAndLoops.begin();
593 
594   // Expand the calculation of X pow N in the following manner:
595   // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
596   // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
597   const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() {
598     auto E = I;
599     // Calculate how many times the same operand from the same loop is included
600     // into this power.
601     uint64_t Exponent = 0;
602     const uint64_t MaxExponent = UINT64_MAX >> 1;
603     // No one sane will ever try to calculate such huge exponents, but if we
604     // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
605     // below when the power of 2 exceeds our Exponent, and we want it to be
606     // 1u << 31 at most to not deal with unsigned overflow.
607     while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
608       ++Exponent;
609       ++E;
610     }
611     assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
612 
613     // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
614     // that are needed into the result.
615     Value *P = expand(I->second);
616     Value *Result = nullptr;
617     if (Exponent & 1)
618       Result = P;
619     for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
620       P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
621                       /*IsSafeToHoist*/ true);
622       if (Exponent & BinExp)
623         Result = Result ? InsertBinop(Instruction::Mul, Result, P,
624                                       SCEV::FlagAnyWrap,
625                                       /*IsSafeToHoist*/ true)
626                         : P;
627     }
628 
629     I = E;
630     assert(Result && "Nothing was expanded?");
631     return Result;
632   };
633 
634   while (I != OpsAndLoops.end()) {
635     if (!Prod) {
636       // This is the first operand. Just expand it.
637       Prod = ExpandOpBinPowN();
638     } else if (I->second->isAllOnesValue()) {
639       // Instead of doing a multiply by negative one, just do a negate.
640       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
641                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
642       ++I;
643     } else {
644       // A simple mul.
645       Value *W = ExpandOpBinPowN();
646       // Canonicalize a constant to the RHS.
647       if (isa<Constant>(Prod)) std::swap(Prod, W);
648       const APInt *RHS;
649       if (match(W, m_Power2(RHS))) {
650         // Canonicalize Prod*(1<<C) to Prod<<C.
651         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
652         auto NWFlags = S->getNoWrapFlags();
653         // clear nsw flag if shl will produce poison value.
654         if (RHS->logBase2() == RHS->getBitWidth() - 1)
655           NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
656         Prod = InsertBinop(Instruction::Shl, Prod,
657                            ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
658                            /*IsSafeToHoist*/ true);
659       } else {
660         Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
661                            /*IsSafeToHoist*/ true);
662       }
663     }
664   }
665 
666   return Prod;
667 }
668 
669 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
670   Value *LHS = expand(S->getLHS());
671   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
672     const APInt &RHS = SC->getAPInt();
673     if (RHS.isPowerOf2())
674       return InsertBinop(Instruction::LShr, LHS,
675                          ConstantInt::get(SC->getType(), RHS.logBase2()),
676                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
677   }
678 
679   Value *RHS = expand(S->getRHS());
680   return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
681                      /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
682 }
683 
684 /// Determine if this is a well-behaved chain of instructions leading back to
685 /// the PHI. If so, it may be reused by expanded expressions.
686 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
687                                          const Loop *L) {
688   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
689       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
690     return false;
691   // If any of the operands don't dominate the insert position, bail.
692   // Addrec operands are always loop-invariant, so this can only happen
693   // if there are instructions which haven't been hoisted.
694   if (L == IVIncInsertLoop) {
695     for (Use &Op : llvm::drop_begin(IncV->operands()))
696       if (Instruction *OInst = dyn_cast<Instruction>(Op))
697         if (!SE.DT.dominates(OInst, IVIncInsertPos))
698           return false;
699   }
700   // Advance to the next instruction.
701   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
702   if (!IncV)
703     return false;
704 
705   if (IncV->mayHaveSideEffects())
706     return false;
707 
708   if (IncV == PN)
709     return true;
710 
711   return isNormalAddRecExprPHI(PN, IncV, L);
712 }
713 
714 /// getIVIncOperand returns an induction variable increment's induction
715 /// variable operand.
716 ///
717 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
718 /// operands dominate InsertPos.
719 ///
720 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
721 /// simple patterns generated by getAddRecExprPHILiterally and
722 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
723 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
724                                            Instruction *InsertPos,
725                                            bool allowScale) {
726   if (IncV == InsertPos)
727     return nullptr;
728 
729   switch (IncV->getOpcode()) {
730   default:
731     return nullptr;
732   // Check for a simple Add/Sub or GEP of a loop invariant step.
733   case Instruction::Add:
734   case Instruction::Sub: {
735     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
736     if (!OInst || SE.DT.dominates(OInst, InsertPos))
737       return dyn_cast<Instruction>(IncV->getOperand(0));
738     return nullptr;
739   }
740   case Instruction::BitCast:
741     return dyn_cast<Instruction>(IncV->getOperand(0));
742   case Instruction::GetElementPtr:
743     for (Use &U : llvm::drop_begin(IncV->operands())) {
744       if (isa<Constant>(U))
745         continue;
746       if (Instruction *OInst = dyn_cast<Instruction>(U)) {
747         if (!SE.DT.dominates(OInst, InsertPos))
748           return nullptr;
749       }
750       if (allowScale) {
751         // allow any kind of GEP as long as it can be hoisted.
752         continue;
753       }
754       // GEPs produced by SCEVExpander use i8 element type.
755       if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
756         return nullptr;
757       break;
758     }
759     return dyn_cast<Instruction>(IncV->getOperand(0));
760   }
761 }
762 
763 /// If the insert point of the current builder or any of the builders on the
764 /// stack of saved builders has 'I' as its insert point, update it to point to
765 /// the instruction after 'I'.  This is intended to be used when the instruction
766 /// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
767 /// different block, the inconsistent insert point (with a mismatched
768 /// Instruction and Block) can lead to an instruction being inserted in a block
769 /// other than its parent.
770 void SCEVExpander::fixupInsertPoints(Instruction *I) {
771   BasicBlock::iterator It(*I);
772   BasicBlock::iterator NewInsertPt = std::next(It);
773   if (Builder.GetInsertPoint() == It)
774     Builder.SetInsertPoint(&*NewInsertPt);
775   for (auto *InsertPtGuard : InsertPointGuards)
776     if (InsertPtGuard->GetInsertPoint() == It)
777       InsertPtGuard->SetInsertPoint(NewInsertPt);
778 }
779 
780 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
781 /// it available to other uses in this loop. Recursively hoist any operands,
782 /// until we reach a value that dominates InsertPos.
783 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos,
784                               bool RecomputePoisonFlags) {
785   auto FixupPoisonFlags = [this](Instruction *I) {
786     // Drop flags that are potentially inferred from old context and infer flags
787     // in new context.
788     rememberFlags(I);
789     I->dropPoisonGeneratingFlags();
790     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
791       if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
792         auto *BO = cast<BinaryOperator>(I);
793         BO->setHasNoUnsignedWrap(
794             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
795         BO->setHasNoSignedWrap(
796             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
797       }
798   };
799 
800   if (SE.DT.dominates(IncV, InsertPos)) {
801     if (RecomputePoisonFlags)
802       FixupPoisonFlags(IncV);
803     return true;
804   }
805 
806   // InsertPos must itself dominate IncV so that IncV's new position satisfies
807   // its existing users.
808   if (isa<PHINode>(InsertPos) ||
809       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
810     return false;
811 
812   if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
813     return false;
814 
815   // Check that the chain of IV operands leading back to Phi can be hoisted.
816   SmallVector<Instruction*, 4> IVIncs;
817   for(;;) {
818     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
819     if (!Oper)
820       return false;
821     // IncV is safe to hoist.
822     IVIncs.push_back(IncV);
823     IncV = Oper;
824     if (SE.DT.dominates(IncV, InsertPos))
825       break;
826   }
827   for (Instruction *I : llvm::reverse(IVIncs)) {
828     fixupInsertPoints(I);
829     I->moveBefore(InsertPos);
830     if (RecomputePoisonFlags)
831       FixupPoisonFlags(I);
832   }
833   return true;
834 }
835 
836 bool SCEVExpander::canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi,
837                                                   PHINode *WidePhi,
838                                                   Instruction *OrigInc,
839                                                   Instruction *WideInc) {
840   return match(OrigInc, m_c_BinOp(m_Specific(OrigPhi), m_Value())) &&
841          match(WideInc, m_c_BinOp(m_Specific(WidePhi), m_Value())) &&
842          OrigInc->getOpcode() == WideInc->getOpcode();
843 }
844 
845 /// Determine if this cyclic phi is in a form that would have been generated by
846 /// LSR. We don't care if the phi was actually expanded in this pass, as long
847 /// as it is in a low-cost form, for example, no implied multiplication. This
848 /// should match any patterns generated by getAddRecExprPHILiterally and
849 /// expandAddtoGEP.
850 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
851                                            const Loop *L) {
852   for(Instruction *IVOper = IncV;
853       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
854                                 /*allowScale=*/false));) {
855     if (IVOper == PN)
856       return true;
857   }
858   return false;
859 }
860 
861 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
862 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
863 /// need to materialize IV increments elsewhere to handle difficult situations.
864 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
865                                  bool useSubtract) {
866   Value *IncV;
867   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
868   if (PN->getType()->isPointerTy()) {
869     // TODO: Change name to IVName.iv.next.
870     IncV = Builder.CreatePtrAdd(PN, StepV, "scevgep");
871   } else {
872     IncV = useSubtract ?
873       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
874       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
875   }
876   return IncV;
877 }
878 
879 /// Check whether we can cheaply express the requested SCEV in terms of
880 /// the available PHI SCEV by truncation and/or inversion of the step.
881 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
882                                     const SCEVAddRecExpr *Phi,
883                                     const SCEVAddRecExpr *Requested,
884                                     bool &InvertStep) {
885   // We can't transform to match a pointer PHI.
886   Type *PhiTy = Phi->getType();
887   Type *RequestedTy = Requested->getType();
888   if (PhiTy->isPointerTy() || RequestedTy->isPointerTy())
889     return false;
890 
891   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
892     return false;
893 
894   // Try truncate it if necessary.
895   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
896   if (!Phi)
897     return false;
898 
899   // Check whether truncation will help.
900   if (Phi == Requested) {
901     InvertStep = false;
902     return true;
903   }
904 
905   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
906   if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
907     InvertStep = true;
908     return true;
909   }
910 
911   return false;
912 }
913 
914 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
915   if (!isa<IntegerType>(AR->getType()))
916     return false;
917 
918   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
919   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
920   const SCEV *Step = AR->getStepRecurrence(SE);
921   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
922                                             SE.getSignExtendExpr(AR, WideTy));
923   const SCEV *ExtendAfterOp =
924     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
925   return ExtendAfterOp == OpAfterExtend;
926 }
927 
928 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
929   if (!isa<IntegerType>(AR->getType()))
930     return false;
931 
932   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
933   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
934   const SCEV *Step = AR->getStepRecurrence(SE);
935   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
936                                             SE.getZeroExtendExpr(AR, WideTy));
937   const SCEV *ExtendAfterOp =
938     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
939   return ExtendAfterOp == OpAfterExtend;
940 }
941 
942 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
943 /// the base addrec, which is the addrec without any non-loop-dominating
944 /// values, and return the PHI.
945 PHINode *
946 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
947                                         const Loop *L, Type *&TruncTy,
948                                         bool &InvertStep) {
949   assert((!IVIncInsertLoop || IVIncInsertPos) &&
950          "Uninitialized insert position");
951 
952   // Reuse a previously-inserted PHI, if present.
953   BasicBlock *LatchBlock = L->getLoopLatch();
954   if (LatchBlock) {
955     PHINode *AddRecPhiMatch = nullptr;
956     Instruction *IncV = nullptr;
957     TruncTy = nullptr;
958     InvertStep = false;
959 
960     // Only try partially matching scevs that need truncation and/or
961     // step-inversion if we know this loop is outside the current loop.
962     bool TryNonMatchingSCEV =
963         IVIncInsertLoop &&
964         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
965 
966     for (PHINode &PN : L->getHeader()->phis()) {
967       if (!SE.isSCEVable(PN.getType()))
968         continue;
969 
970       // We should not look for a incomplete PHI. Getting SCEV for a incomplete
971       // PHI has no meaning at all.
972       if (!PN.isComplete()) {
973         SCEV_DEBUG_WITH_TYPE(
974             DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
975         continue;
976       }
977 
978       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
979       if (!PhiSCEV)
980         continue;
981 
982       bool IsMatchingSCEV = PhiSCEV == Normalized;
983       // We only handle truncation and inversion of phi recurrences for the
984       // expanded expression if the expanded expression's loop dominates the
985       // loop we insert to. Check now, so we can bail out early.
986       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
987           continue;
988 
989       // TODO: this possibly can be reworked to avoid this cast at all.
990       Instruction *TempIncV =
991           dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
992       if (!TempIncV)
993         continue;
994 
995       // Check whether we can reuse this PHI node.
996       if (LSRMode) {
997         if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
998           continue;
999       } else {
1000         if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1001           continue;
1002       }
1003 
1004       // Stop if we have found an exact match SCEV.
1005       if (IsMatchingSCEV) {
1006         IncV = TempIncV;
1007         TruncTy = nullptr;
1008         InvertStep = false;
1009         AddRecPhiMatch = &PN;
1010         break;
1011       }
1012 
1013       // Try whether the phi can be translated into the requested form
1014       // (truncated and/or offset by a constant).
1015       if ((!TruncTy || InvertStep) &&
1016           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1017         // Record the phi node. But don't stop we might find an exact match
1018         // later.
1019         AddRecPhiMatch = &PN;
1020         IncV = TempIncV;
1021         TruncTy = Normalized->getType();
1022       }
1023     }
1024 
1025     if (AddRecPhiMatch) {
1026       // Ok, the add recurrence looks usable.
1027       // Remember this PHI, even in post-inc mode.
1028       InsertedValues.insert(AddRecPhiMatch);
1029       // Remember the increment.
1030       rememberInstruction(IncV);
1031       // Those values were not actually inserted but re-used.
1032       ReusedValues.insert(AddRecPhiMatch);
1033       ReusedValues.insert(IncV);
1034       return AddRecPhiMatch;
1035     }
1036   }
1037 
1038   // Save the original insertion point so we can restore it when we're done.
1039   SCEVInsertPointGuard Guard(Builder, this);
1040 
1041   // Another AddRec may need to be recursively expanded below. For example, if
1042   // this AddRec is quadratic, the StepV may itself be an AddRec in this
1043   // loop. Remove this loop from the PostIncLoops set before expanding such
1044   // AddRecs. Otherwise, we cannot find a valid position for the step
1045   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1046   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1047   // so it's not worth implementing SmallPtrSet::swap.
1048   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1049   PostIncLoops.clear();
1050 
1051   // Expand code for the start value into the loop preheader.
1052   assert(L->getLoopPreheader() &&
1053          "Can't expand add recurrences without a loop preheader!");
1054   Value *StartV =
1055       expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator());
1056 
1057   // StartV must have been be inserted into L's preheader to dominate the new
1058   // phi.
1059   assert(!isa<Instruction>(StartV) ||
1060          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1061                                  L->getHeader()));
1062 
1063   // Expand code for the step value. Do this before creating the PHI so that PHI
1064   // reuse code doesn't see an incomplete PHI.
1065   const SCEV *Step = Normalized->getStepRecurrence(SE);
1066   Type *ExpandTy = Normalized->getType();
1067   // If the stride is negative, insert a sub instead of an add for the increment
1068   // (unless it's a constant, because subtracts of constants are canonicalized
1069   // to adds).
1070   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1071   if (useSubtract)
1072     Step = SE.getNegativeSCEV(Step);
1073   // Expand the step somewhere that dominates the loop header.
1074   Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1075 
1076   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1077   // we actually do emit an addition.  It does not apply if we emit a
1078   // subtraction.
1079   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1080   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1081 
1082   // Create the PHI.
1083   BasicBlock *Header = L->getHeader();
1084   Builder.SetInsertPoint(Header, Header->begin());
1085   PHINode *PN =
1086       Builder.CreatePHI(ExpandTy, pred_size(Header), Twine(IVName) + ".iv");
1087 
1088   // Create the step instructions and populate the PHI.
1089   for (BasicBlock *Pred : predecessors(Header)) {
1090     // Add a start value.
1091     if (!L->contains(Pred)) {
1092       PN->addIncoming(StartV, Pred);
1093       continue;
1094     }
1095 
1096     // Create a step value and add it to the PHI.
1097     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1098     // instructions at IVIncInsertPos.
1099     Instruction *InsertPos = L == IVIncInsertLoop ?
1100       IVIncInsertPos : Pred->getTerminator();
1101     Builder.SetInsertPoint(InsertPos);
1102     Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1103 
1104     if (isa<OverflowingBinaryOperator>(IncV)) {
1105       if (IncrementIsNUW)
1106         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1107       if (IncrementIsNSW)
1108         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1109     }
1110     PN->addIncoming(IncV, Pred);
1111   }
1112 
1113   // After expanding subexpressions, restore the PostIncLoops set so the caller
1114   // can ensure that IVIncrement dominates the current uses.
1115   PostIncLoops = SavedPostIncLoops;
1116 
1117   // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1118   // effective when we are able to use an IV inserted here, so record it.
1119   InsertedValues.insert(PN);
1120   InsertedIVs.push_back(PN);
1121   return PN;
1122 }
1123 
1124 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1125   const Loop *L = S->getLoop();
1126 
1127   // Determine a normalized form of this expression, which is the expression
1128   // before any post-inc adjustment is made.
1129   const SCEVAddRecExpr *Normalized = S;
1130   if (PostIncLoops.count(L)) {
1131     PostIncLoopSet Loops;
1132     Loops.insert(L);
1133     Normalized = cast<SCEVAddRecExpr>(
1134         normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false));
1135   }
1136 
1137   [[maybe_unused]] const SCEV *Start = Normalized->getStart();
1138   const SCEV *Step = Normalized->getStepRecurrence(SE);
1139   assert(SE.properlyDominates(Start, L->getHeader()) &&
1140          "Start does not properly dominate loop header");
1141   assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header");
1142 
1143   // In some cases, we decide to reuse an existing phi node but need to truncate
1144   // it and/or invert the step.
1145   Type *TruncTy = nullptr;
1146   bool InvertStep = false;
1147   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1148 
1149   // Accommodate post-inc mode, if necessary.
1150   Value *Result;
1151   if (!PostIncLoops.count(L))
1152     Result = PN;
1153   else {
1154     // In PostInc mode, use the post-incremented value.
1155     BasicBlock *LatchBlock = L->getLoopLatch();
1156     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1157     Result = PN->getIncomingValueForBlock(LatchBlock);
1158 
1159     // We might be introducing a new use of the post-inc IV that is not poison
1160     // safe, in which case we should drop poison generating flags. Only keep
1161     // those flags for which SCEV has proven that they always hold.
1162     if (isa<OverflowingBinaryOperator>(Result)) {
1163       auto *I = cast<Instruction>(Result);
1164       if (!S->hasNoUnsignedWrap())
1165         I->setHasNoUnsignedWrap(false);
1166       if (!S->hasNoSignedWrap())
1167         I->setHasNoSignedWrap(false);
1168     }
1169 
1170     // For an expansion to use the postinc form, the client must call
1171     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1172     // or dominated by IVIncInsertPos.
1173     if (isa<Instruction>(Result) &&
1174         !SE.DT.dominates(cast<Instruction>(Result),
1175                          &*Builder.GetInsertPoint())) {
1176       // The induction variable's postinc expansion does not dominate this use.
1177       // IVUsers tries to prevent this case, so it is rare. However, it can
1178       // happen when an IVUser outside the loop is not dominated by the latch
1179       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1180       // all cases. Consider a phi outside whose operand is replaced during
1181       // expansion with the value of the postinc user. Without fundamentally
1182       // changing the way postinc users are tracked, the only remedy is
1183       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1184       // but hopefully expandCodeFor handles that.
1185       bool useSubtract =
1186           !S->getType()->isPointerTy() && Step->isNonConstantNegative();
1187       if (useSubtract)
1188         Step = SE.getNegativeSCEV(Step);
1189       Value *StepV;
1190       {
1191         // Expand the step somewhere that dominates the loop header.
1192         SCEVInsertPointGuard Guard(Builder, this);
1193         StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1194       }
1195       Result = expandIVInc(PN, StepV, L, useSubtract);
1196     }
1197   }
1198 
1199   // We have decided to reuse an induction variable of a dominating loop. Apply
1200   // truncation and/or inversion of the step.
1201   if (TruncTy) {
1202     // Truncate the result.
1203     if (TruncTy != Result->getType())
1204       Result = Builder.CreateTrunc(Result, TruncTy);
1205 
1206     // Invert the result.
1207     if (InvertStep)
1208       Result = Builder.CreateSub(expand(Normalized->getStart()), Result);
1209   }
1210 
1211   return Result;
1212 }
1213 
1214 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1215   // In canonical mode we compute the addrec as an expression of a canonical IV
1216   // using evaluateAtIteration and expand the resulting SCEV expression. This
1217   // way we avoid introducing new IVs to carry on the computation of the addrec
1218   // throughout the loop.
1219   //
1220   // For nested addrecs evaluateAtIteration might need a canonical IV of a
1221   // type wider than the addrec itself. Emitting a canonical IV of the
1222   // proper type might produce non-legal types, for example expanding an i64
1223   // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1224   // back to non-canonical mode for nested addrecs.
1225   if (!CanonicalMode || (S->getNumOperands() > 2))
1226     return expandAddRecExprLiterally(S);
1227 
1228   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1229   const Loop *L = S->getLoop();
1230 
1231   // First check for an existing canonical IV in a suitable type.
1232   PHINode *CanonicalIV = nullptr;
1233   if (PHINode *PN = L->getCanonicalInductionVariable())
1234     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1235       CanonicalIV = PN;
1236 
1237   // Rewrite an AddRec in terms of the canonical induction variable, if
1238   // its type is more narrow.
1239   if (CanonicalIV &&
1240       SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1241       !S->getType()->isPointerTy()) {
1242     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1243     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1244       NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType());
1245     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1246                                        S->getNoWrapFlags(SCEV::FlagNW)));
1247     BasicBlock::iterator NewInsertPt =
1248         findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1249     V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1250     return V;
1251   }
1252 
1253   // {X,+,F} --> X + {0,+,F}
1254   if (!S->getStart()->isZero()) {
1255     if (isa<PointerType>(S->getType())) {
1256       Value *StartV = expand(SE.getPointerBase(S));
1257       return expandAddToGEP(SE.removePointerBase(S), StartV,
1258                             S->getNoWrapFlags(SCEV::FlagNUW));
1259     }
1260 
1261     SmallVector<const SCEV *, 4> NewOps(S->operands());
1262     NewOps[0] = SE.getConstant(Ty, 0);
1263     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1264                                         S->getNoWrapFlags(SCEV::FlagNW));
1265 
1266     // Just do a normal add. Pre-expand the operands to suppress folding.
1267     //
1268     // The LHS and RHS values are factored out of the expand call to make the
1269     // output independent of the argument evaluation order.
1270     const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1271     const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1272     return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1273   }
1274 
1275   // If we don't yet have a canonical IV, create one.
1276   if (!CanonicalIV) {
1277     // Create and insert the PHI node for the induction variable in the
1278     // specified loop.
1279     BasicBlock *Header = L->getHeader();
1280     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1281     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar");
1282     CanonicalIV->insertBefore(Header->begin());
1283     rememberInstruction(CanonicalIV);
1284 
1285     SmallSet<BasicBlock *, 4> PredSeen;
1286     Constant *One = ConstantInt::get(Ty, 1);
1287     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1288       BasicBlock *HP = *HPI;
1289       if (!PredSeen.insert(HP).second) {
1290         // There must be an incoming value for each predecessor, even the
1291         // duplicates!
1292         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1293         continue;
1294       }
1295 
1296       if (L->contains(HP)) {
1297         // Insert a unit add instruction right before the terminator
1298         // corresponding to the back-edge.
1299         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1300                                                      "indvar.next",
1301                                                      HP->getTerminator()->getIterator());
1302         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1303         rememberInstruction(Add);
1304         CanonicalIV->addIncoming(Add, HP);
1305       } else {
1306         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1307       }
1308     }
1309   }
1310 
1311   // {0,+,1} --> Insert a canonical induction variable into the loop!
1312   if (S->isAffine() && S->getOperand(1)->isOne()) {
1313     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1314            "IVs with types different from the canonical IV should "
1315            "already have been handled!");
1316     return CanonicalIV;
1317   }
1318 
1319   // {0,+,F} --> {0,+,1} * F
1320 
1321   // If this is a simple linear addrec, emit it now as a special case.
1322   if (S->isAffine())    // {0,+,F} --> i*F
1323     return
1324       expand(SE.getTruncateOrNoop(
1325         SE.getMulExpr(SE.getUnknown(CanonicalIV),
1326                       SE.getNoopOrAnyExtend(S->getOperand(1),
1327                                             CanonicalIV->getType())),
1328         Ty));
1329 
1330   // If this is a chain of recurrences, turn it into a closed form, using the
1331   // folders, then expandCodeFor the closed form.  This allows the folders to
1332   // simplify the expression without having to build a bunch of special code
1333   // into this folder.
1334   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
1335 
1336   // Promote S up to the canonical IV type, if the cast is foldable.
1337   const SCEV *NewS = S;
1338   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1339   if (isa<SCEVAddRecExpr>(Ext))
1340     NewS = Ext;
1341 
1342   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1343 
1344   // Truncate the result down to the original type, if needed.
1345   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1346   return expand(T);
1347 }
1348 
1349 Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
1350   Value *V = expand(S->getOperand());
1351   return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1352                            GetOptimalInsertionPointForCastOf(V));
1353 }
1354 
1355 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1356   Value *V = expand(S->getOperand());
1357   return Builder.CreateTrunc(V, S->getType());
1358 }
1359 
1360 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1361   Value *V = expand(S->getOperand());
1362   return Builder.CreateZExt(V, S->getType(), "",
1363                             SE.isKnownNonNegative(S->getOperand()));
1364 }
1365 
1366 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1367   Value *V = expand(S->getOperand());
1368   return Builder.CreateSExt(V, S->getType());
1369 }
1370 
1371 Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S,
1372                                       Intrinsic::ID IntrinID, Twine Name,
1373                                       bool IsSequential) {
1374   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1375   Type *Ty = LHS->getType();
1376   if (IsSequential)
1377     LHS = Builder.CreateFreeze(LHS);
1378   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1379     Value *RHS = expand(S->getOperand(i));
1380     if (IsSequential && i != 0)
1381       RHS = Builder.CreateFreeze(RHS);
1382     Value *Sel;
1383     if (Ty->isIntegerTy())
1384       Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1385                                     /*FMFSource=*/nullptr, Name);
1386     else {
1387       Value *ICmp =
1388           Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1389       Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1390     }
1391     LHS = Sel;
1392   }
1393   return LHS;
1394 }
1395 
1396 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1397   return expandMinMaxExpr(S, Intrinsic::smax, "smax");
1398 }
1399 
1400 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1401   return expandMinMaxExpr(S, Intrinsic::umax, "umax");
1402 }
1403 
1404 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1405   return expandMinMaxExpr(S, Intrinsic::smin, "smin");
1406 }
1407 
1408 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1409   return expandMinMaxExpr(S, Intrinsic::umin, "umin");
1410 }
1411 
1412 Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
1413   return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true);
1414 }
1415 
1416 Value *SCEVExpander::visitVScale(const SCEVVScale *S) {
1417   return Builder.CreateVScale(ConstantInt::get(S->getType(), 1));
1418 }
1419 
1420 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1421                                    BasicBlock::iterator IP) {
1422   setInsertPoint(IP);
1423   Value *V = expandCodeFor(SH, Ty);
1424   return V;
1425 }
1426 
1427 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1428   // Expand the code for this SCEV.
1429   Value *V = expand(SH);
1430 
1431   if (Ty) {
1432     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1433            "non-trivial casts should be done with the SCEVs directly!");
1434     V = InsertNoopCastOfTo(V, Ty);
1435   }
1436   return V;
1437 }
1438 
1439 Value *SCEVExpander::FindValueInExprValueMap(
1440     const SCEV *S, const Instruction *InsertPt,
1441     SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
1442   // If the expansion is not in CanonicalMode, and the SCEV contains any
1443   // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1444   if (!CanonicalMode && SE.containsAddRecurrence(S))
1445     return nullptr;
1446 
1447   // If S is a constant, it may be worse to reuse an existing Value.
1448   if (isa<SCEVConstant>(S))
1449     return nullptr;
1450 
1451   for (Value *V : SE.getSCEVValues(S)) {
1452     Instruction *EntInst = dyn_cast<Instruction>(V);
1453     if (!EntInst)
1454       continue;
1455 
1456     // Choose a Value from the set which dominates the InsertPt.
1457     // InsertPt should be inside the Value's parent loop so as not to break
1458     // the LCSSA form.
1459     assert(EntInst->getFunction() == InsertPt->getFunction());
1460     if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) ||
1461         !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1462           SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1463       continue;
1464 
1465     // Make sure reusing the instruction is poison-safe.
1466     if (SE.canReuseInstruction(S, EntInst, DropPoisonGeneratingInsts))
1467       return V;
1468     DropPoisonGeneratingInsts.clear();
1469   }
1470   return nullptr;
1471 }
1472 
1473 // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1474 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1475 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1476 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1477 // the expansion will try to reuse Value from ExprValueMap, and only when it
1478 // fails, expand the SCEV literally.
1479 Value *SCEVExpander::expand(const SCEV *S) {
1480   // Compute an insertion point for this SCEV object. Hoist the instructions
1481   // as far out in the loop nest as possible.
1482   BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
1483 
1484   // We can move insertion point only if there is no div or rem operations
1485   // otherwise we are risky to move it over the check for zero denominator.
1486   auto SafeToHoist = [](const SCEV *S) {
1487     return !SCEVExprContains(S, [](const SCEV *S) {
1488               if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1489                 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1490                   // Division by non-zero constants can be hoisted.
1491                   return SC->getValue()->isZero();
1492                 // All other divisions should not be moved as they may be
1493                 // divisions by zero and should be kept within the
1494                 // conditions of the surrounding loops that guard their
1495                 // execution (see PR35406).
1496                 return true;
1497               }
1498               return false;
1499             });
1500   };
1501   if (SafeToHoist(S)) {
1502     for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1503          L = L->getParentLoop()) {
1504       if (SE.isLoopInvariant(S, L)) {
1505         if (!L) break;
1506         if (BasicBlock *Preheader = L->getLoopPreheader()) {
1507           InsertPt = Preheader->getTerminator()->getIterator();
1508         } else {
1509           // LSR sets the insertion point for AddRec start/step values to the
1510           // block start to simplify value reuse, even though it's an invalid
1511           // position. SCEVExpander must correct for this in all cases.
1512           InsertPt = L->getHeader()->getFirstInsertionPt();
1513         }
1514       } else {
1515         // If the SCEV is computable at this level, insert it into the header
1516         // after the PHIs (and after any other instructions that we've inserted
1517         // there) so that it is guaranteed to dominate any user inside the loop.
1518         if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1519           InsertPt = L->getHeader()->getFirstInsertionPt();
1520 
1521         while (InsertPt != Builder.GetInsertPoint() &&
1522                (isInsertedInstruction(&*InsertPt) ||
1523                 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1524           InsertPt = std::next(InsertPt);
1525         }
1526         break;
1527       }
1528     }
1529   }
1530 
1531   // Check to see if we already expanded this here.
1532   auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1533   if (I != InsertedExpressions.end())
1534     return I->second;
1535 
1536   SCEVInsertPointGuard Guard(Builder, this);
1537   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1538 
1539   // Expand the expression into instructions.
1540   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1541   Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1542   if (!V) {
1543     V = visit(S);
1544     V = fixupLCSSAFormFor(V);
1545   } else {
1546     for (Instruction *I : DropPoisonGeneratingInsts) {
1547       rememberFlags(I);
1548       I->dropPoisonGeneratingAnnotations();
1549       // See if we can re-infer from first principles any of the flags we just
1550       // dropped.
1551       if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
1552         if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1553           auto *BO = cast<BinaryOperator>(I);
1554           BO->setHasNoUnsignedWrap(
1555             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
1556           BO->setHasNoSignedWrap(
1557             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
1558         }
1559       if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) {
1560         auto *Src = NNI->getOperand(0);
1561         if (isImpliedByDomCondition(ICmpInst::ICMP_SGE, Src,
1562                                     Constant::getNullValue(Src->getType()), I,
1563                                     DL).value_or(false))
1564           NNI->setNonNeg(true);
1565       }
1566     }
1567   }
1568   // Remember the expanded value for this SCEV at this location.
1569   //
1570   // This is independent of PostIncLoops. The mapped value simply materializes
1571   // the expression at this insertion point. If the mapped value happened to be
1572   // a postinc expansion, it could be reused by a non-postinc user, but only if
1573   // its insertion point was already at the head of the loop.
1574   InsertedExpressions[std::make_pair(S, &*InsertPt)] = V;
1575   return V;
1576 }
1577 
1578 void SCEVExpander::rememberInstruction(Value *I) {
1579   auto DoInsert = [this](Value *V) {
1580     if (!PostIncLoops.empty())
1581       InsertedPostIncValues.insert(V);
1582     else
1583       InsertedValues.insert(V);
1584   };
1585   DoInsert(I);
1586 }
1587 
1588 void SCEVExpander::rememberFlags(Instruction *I) {
1589   // If we already have flags for the instruction, keep the existing ones.
1590   OrigFlags.try_emplace(I, PoisonFlags(I));
1591 }
1592 
1593 void SCEVExpander::replaceCongruentIVInc(
1594     PHINode *&Phi, PHINode *&OrigPhi, Loop *L, const DominatorTree *DT,
1595     SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
1596   BasicBlock *LatchBlock = L->getLoopLatch();
1597   if (!LatchBlock)
1598     return;
1599 
1600   Instruction *OrigInc =
1601       dyn_cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1602   Instruction *IsomorphicInc =
1603       dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1604   if (!OrigInc || !IsomorphicInc)
1605     return;
1606 
1607   // If this phi has the same width but is more canonical, replace the
1608   // original with it. As part of the "more canonical" determination,
1609   // respect a prior decision to use an IV chain.
1610   if (OrigPhi->getType() == Phi->getType() &&
1611       !(ChainedPhis.count(Phi) ||
1612         isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1613       (ChainedPhis.count(Phi) ||
1614        isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1615     std::swap(OrigPhi, Phi);
1616     std::swap(OrigInc, IsomorphicInc);
1617   }
1618 
1619   // Replacing the congruent phi is sufficient because acyclic
1620   // redundancy elimination, CSE/GVN, should handle the
1621   // rest. However, once SCEV proves that a phi is congruent,
1622   // it's often the head of an IV user cycle that is isomorphic
1623   // with the original phi. It's worth eagerly cleaning up the
1624   // common case of a single IV increment so that DeleteDeadPHIs
1625   // can remove cycles that had postinc uses.
1626   // Because we may potentially introduce a new use of OrigIV that didn't
1627   // exist before at this point, its poison flags need readjustment.
1628   const SCEV *TruncExpr =
1629       SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1630   if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1631       !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1632     return;
1633 
1634   bool BothHaveNUW = false;
1635   bool BothHaveNSW = false;
1636   auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1637   auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1638   if (OBOIncV && OBOIsomorphic) {
1639     BothHaveNUW =
1640         OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1641     BothHaveNSW =
1642         OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1643   }
1644 
1645   if (!hoistIVInc(OrigInc, IsomorphicInc,
1646                   /*RecomputePoisonFlags*/ true))
1647     return;
1648 
1649   // We are replacing with a wider increment. If both OrigInc and IsomorphicInc
1650   // are NUW/NSW, then we can preserve them on the wider increment; the narrower
1651   // IsomorphicInc would wrap before the wider OrigInc, so the replacement won't
1652   // make IsomorphicInc's uses more poisonous.
1653   assert(OrigInc->getType()->getScalarSizeInBits() >=
1654              IsomorphicInc->getType()->getScalarSizeInBits() &&
1655          "Should only replace an increment with a wider one.");
1656   if (BothHaveNUW || BothHaveNSW) {
1657     OrigInc->setHasNoUnsignedWrap(OBOIncV->hasNoUnsignedWrap() || BothHaveNUW);
1658     OrigInc->setHasNoSignedWrap(OBOIncV->hasNoSignedWrap() || BothHaveNSW);
1659   }
1660 
1661   SCEV_DEBUG_WITH_TYPE(DebugType,
1662                        dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1663                               << *IsomorphicInc << '\n');
1664   Value *NewInc = OrigInc;
1665   if (OrigInc->getType() != IsomorphicInc->getType()) {
1666     BasicBlock::iterator IP;
1667     if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1668       IP = PN->getParent()->getFirstInsertionPt();
1669     else
1670       IP = OrigInc->getNextNonDebugInstruction()->getIterator();
1671 
1672     IRBuilder<> Builder(IP->getParent(), IP);
1673     Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1674     NewInc =
1675         Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1676   }
1677   IsomorphicInc->replaceAllUsesWith(NewInc);
1678   DeadInsts.emplace_back(IsomorphicInc);
1679 }
1680 
1681 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1682 /// replace them with their most canonical representative. Return the number of
1683 /// phis eliminated.
1684 ///
1685 /// This does not depend on any SCEVExpander state but should be used in
1686 /// the same context that SCEVExpander is used.
1687 unsigned
1688 SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1689                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1690                                   const TargetTransformInfo *TTI) {
1691   // Find integer phis in order of increasing width.
1692   SmallVector<PHINode*, 8> Phis;
1693   for (PHINode &PN : L->getHeader()->phis())
1694     Phis.push_back(&PN);
1695 
1696   if (TTI)
1697     // Use stable_sort to preserve order of equivalent PHIs, so the order
1698     // of the sorted Phis is the same from run to run on the same loop.
1699     llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1700       // Put pointers at the back and make sure pointer < pointer = false.
1701       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1702         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1703       return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1704              LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1705     });
1706 
1707   unsigned NumElim = 0;
1708   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1709   // Process phis from wide to narrow. Map wide phis to their truncation
1710   // so narrow phis can reuse them.
1711   for (PHINode *Phi : Phis) {
1712     auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1713       if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1714         return V;
1715       if (!SE.isSCEVable(PN->getType()))
1716         return nullptr;
1717       auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1718       if (!Const)
1719         return nullptr;
1720       return Const->getValue();
1721     };
1722 
1723     // Fold constant phis. They may be congruent to other constant phis and
1724     // would confuse the logic below that expects proper IVs.
1725     if (Value *V = SimplifyPHINode(Phi)) {
1726       if (V->getType() != Phi->getType())
1727         continue;
1728       SE.forgetValue(Phi);
1729       Phi->replaceAllUsesWith(V);
1730       DeadInsts.emplace_back(Phi);
1731       ++NumElim;
1732       SCEV_DEBUG_WITH_TYPE(DebugType,
1733                            dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1734                                   << '\n');
1735       continue;
1736     }
1737 
1738     if (!SE.isSCEVable(Phi->getType()))
1739       continue;
1740 
1741     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1742     if (!OrigPhiRef) {
1743       OrigPhiRef = Phi;
1744       if (Phi->getType()->isIntegerTy() && TTI &&
1745           TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1746         // Make sure we only rewrite using simple induction variables;
1747         // otherwise, we can make the trip count of a loop unanalyzable
1748         // to SCEV.
1749         const SCEV *PhiExpr = SE.getSCEV(Phi);
1750         if (isa<SCEVAddRecExpr>(PhiExpr)) {
1751           // This phi can be freely truncated to the narrowest phi type. Map the
1752           // truncated expression to it so it will be reused for narrow types.
1753           const SCEV *TruncExpr =
1754               SE.getTruncateExpr(PhiExpr, Phis.back()->getType());
1755           ExprToIVMap[TruncExpr] = Phi;
1756         }
1757       }
1758       continue;
1759     }
1760 
1761     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1762     // sense.
1763     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1764       continue;
1765 
1766     replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1767     SCEV_DEBUG_WITH_TYPE(DebugType,
1768                          dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
1769                                 << '\n');
1770     SCEV_DEBUG_WITH_TYPE(
1771         DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
1772     ++NumElim;
1773     Value *NewIV = OrigPhiRef;
1774     if (OrigPhiRef->getType() != Phi->getType()) {
1775       IRBuilder<> Builder(L->getHeader(),
1776                           L->getHeader()->getFirstInsertionPt());
1777       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1778       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1779     }
1780     Phi->replaceAllUsesWith(NewIV);
1781     DeadInsts.emplace_back(Phi);
1782   }
1783   return NumElim;
1784 }
1785 
1786 bool SCEVExpander::hasRelatedExistingExpansion(const SCEV *S,
1787                                                const Instruction *At,
1788                                                Loop *L) {
1789   using namespace llvm::PatternMatch;
1790 
1791   SmallVector<BasicBlock *, 4> ExitingBlocks;
1792   L->getExitingBlocks(ExitingBlocks);
1793 
1794   // Look for suitable value in simple conditions at the loop exits.
1795   for (BasicBlock *BB : ExitingBlocks) {
1796     ICmpInst::Predicate Pred;
1797     Instruction *LHS, *RHS;
1798 
1799     if (!match(BB->getTerminator(),
1800                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1801                     m_BasicBlock(), m_BasicBlock())))
1802       continue;
1803 
1804     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1805       return true;
1806 
1807     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1808       return true;
1809   }
1810 
1811   // Use expand's logic which is used for reusing a previous Value in
1812   // ExprValueMap.  Note that we don't currently model the cost of
1813   // needing to drop poison generating flags on the instruction if we
1814   // want to reuse it.  We effectively assume that has zero cost.
1815   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1816   return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr;
1817 }
1818 
1819 template<typename T> static InstructionCost costAndCollectOperands(
1820   const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
1821   TargetTransformInfo::TargetCostKind CostKind,
1822   SmallVectorImpl<SCEVOperand> &Worklist) {
1823 
1824   const T *S = cast<T>(WorkItem.S);
1825   InstructionCost Cost = 0;
1826   // Object to help map SCEV operands to expanded IR instructions.
1827   struct OperationIndices {
1828     OperationIndices(unsigned Opc, size_t min, size_t max) :
1829       Opcode(Opc), MinIdx(min), MaxIdx(max) { }
1830     unsigned Opcode;
1831     size_t MinIdx;
1832     size_t MaxIdx;
1833   };
1834 
1835   // Collect the operations of all the instructions that will be needed to
1836   // expand the SCEVExpr. This is so that when we come to cost the operands,
1837   // we know what the generated user(s) will be.
1838   SmallVector<OperationIndices, 2> Operations;
1839 
1840   auto CastCost = [&](unsigned Opcode) -> InstructionCost {
1841     Operations.emplace_back(Opcode, 0, 0);
1842     return TTI.getCastInstrCost(Opcode, S->getType(),
1843                                 S->getOperand(0)->getType(),
1844                                 TTI::CastContextHint::None, CostKind);
1845   };
1846 
1847   auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
1848                        unsigned MinIdx = 0,
1849                        unsigned MaxIdx = 1) -> InstructionCost {
1850     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1851     return NumRequired *
1852       TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
1853   };
1854 
1855   auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
1856                         unsigned MaxIdx) -> InstructionCost {
1857     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1858     Type *OpType = S->getType();
1859     return NumRequired * TTI.getCmpSelInstrCost(
1860                              Opcode, OpType, CmpInst::makeCmpResultType(OpType),
1861                              CmpInst::BAD_ICMP_PREDICATE, CostKind);
1862   };
1863 
1864   switch (S->getSCEVType()) {
1865   case scCouldNotCompute:
1866     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1867   case scUnknown:
1868   case scConstant:
1869   case scVScale:
1870     return 0;
1871   case scPtrToInt:
1872     Cost = CastCost(Instruction::PtrToInt);
1873     break;
1874   case scTruncate:
1875     Cost = CastCost(Instruction::Trunc);
1876     break;
1877   case scZeroExtend:
1878     Cost = CastCost(Instruction::ZExt);
1879     break;
1880   case scSignExtend:
1881     Cost = CastCost(Instruction::SExt);
1882     break;
1883   case scUDivExpr: {
1884     unsigned Opcode = Instruction::UDiv;
1885     if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1886       if (SC->getAPInt().isPowerOf2())
1887         Opcode = Instruction::LShr;
1888     Cost = ArithCost(Opcode, 1);
1889     break;
1890   }
1891   case scAddExpr:
1892     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1893     break;
1894   case scMulExpr:
1895     // TODO: this is a very pessimistic cost modelling for Mul,
1896     // because of Bin Pow algorithm actually used by the expander,
1897     // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
1898     Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1899     break;
1900   case scSMaxExpr:
1901   case scUMaxExpr:
1902   case scSMinExpr:
1903   case scUMinExpr:
1904   case scSequentialUMinExpr: {
1905     // FIXME: should this ask the cost for Intrinsic's?
1906     // The reduction tree.
1907     Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1908     Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1909     switch (S->getSCEVType()) {
1910     case scSequentialUMinExpr: {
1911       // The safety net against poison.
1912       // FIXME: this is broken.
1913       Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1914       Cost += ArithCost(Instruction::Or,
1915                         S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1916       Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1917       break;
1918     }
1919     default:
1920       assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1921              "Unhandled SCEV expression type?");
1922       break;
1923     }
1924     break;
1925   }
1926   case scAddRecExpr: {
1927     // Addrec expands to a phi and add per recurrence.
1928     unsigned NumRecurrences = S->getNumOperands() - 1;
1929     Cost += TTI.getCFInstrCost(Instruction::PHI, CostKind) * NumRecurrences;
1930     Cost +=
1931         TTI.getArithmeticInstrCost(Instruction::Add, S->getType(), CostKind) *
1932         NumRecurrences;
1933     // AR start is used in phi.
1934     Worklist.emplace_back(Instruction::PHI, 0, S->getOperand(0));
1935     // Other operands are used in add.
1936     for (const SCEV *Op : S->operands().drop_front())
1937       Worklist.emplace_back(Instruction::Add, 1, Op);
1938     break;
1939   }
1940   }
1941 
1942   for (auto &CostOp : Operations) {
1943     for (auto SCEVOp : enumerate(S->operands())) {
1944       // Clamp the index to account for multiple IR operations being chained.
1945       size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1946       size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1947       Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1948     }
1949   }
1950   return Cost;
1951 }
1952 
1953 bool SCEVExpander::isHighCostExpansionHelper(
1954     const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
1955     InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
1956     SmallPtrSetImpl<const SCEV *> &Processed,
1957     SmallVectorImpl<SCEVOperand> &Worklist) {
1958   if (Cost > Budget)
1959     return true; // Already run out of budget, give up.
1960 
1961   const SCEV *S = WorkItem.S;
1962   // Was the cost of expansion of this expression already accounted for?
1963   if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
1964     return false; // We have already accounted for this expression.
1965 
1966   // If we can find an existing value for this scev available at the point "At"
1967   // then consider the expression cheap.
1968   if (hasRelatedExistingExpansion(S, &At, L))
1969     return false; // Consider the expression to be free.
1970 
1971   TargetTransformInfo::TargetCostKind CostKind =
1972       L->getHeader()->getParent()->hasMinSize()
1973           ? TargetTransformInfo::TCK_CodeSize
1974           : TargetTransformInfo::TCK_RecipThroughput;
1975 
1976   switch (S->getSCEVType()) {
1977   case scCouldNotCompute:
1978     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1979   case scUnknown:
1980   case scVScale:
1981     // Assume to be zero-cost.
1982     return false;
1983   case scConstant: {
1984     // Only evalulate the costs of constants when optimizing for size.
1985     if (CostKind != TargetTransformInfo::TCK_CodeSize)
1986       return false;
1987     const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
1988     Type *Ty = S->getType();
1989     Cost += TTI.getIntImmCostInst(
1990         WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
1991     return Cost > Budget;
1992   }
1993   case scTruncate:
1994   case scPtrToInt:
1995   case scZeroExtend:
1996   case scSignExtend: {
1997     Cost +=
1998         costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
1999     return false; // Will answer upon next entry into this function.
2000   }
2001   case scUDivExpr: {
2002     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2003     // HowManyLessThans produced to compute a precise expression, rather than a
2004     // UDiv from the user's code. If we can't find a UDiv in the code with some
2005     // simple searching, we need to account for it's cost.
2006 
2007     // At the beginning of this function we already tried to find existing
2008     // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2009     // pattern involving division. This is just a simple search heuristic.
2010     if (hasRelatedExistingExpansion(
2011             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2012       return false; // Consider it to be free.
2013 
2014     Cost +=
2015         costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
2016     return false; // Will answer upon next entry into this function.
2017   }
2018   case scAddExpr:
2019   case scMulExpr:
2020   case scUMaxExpr:
2021   case scSMaxExpr:
2022   case scUMinExpr:
2023   case scSMinExpr:
2024   case scSequentialUMinExpr: {
2025     assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2026            "Nary expr should have more than 1 operand.");
2027     // The simple nary expr will require one less op (or pair of ops)
2028     // than the number of it's terms.
2029     Cost +=
2030         costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
2031     return Cost > Budget;
2032   }
2033   case scAddRecExpr: {
2034     assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2035            "Polynomial should be at least linear");
2036     Cost += costAndCollectOperands<SCEVAddRecExpr>(
2037         WorkItem, TTI, CostKind, Worklist);
2038     return Cost > Budget;
2039   }
2040   }
2041   llvm_unreachable("Unknown SCEV kind!");
2042 }
2043 
2044 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2045                                             Instruction *IP) {
2046   assert(IP);
2047   switch (Pred->getKind()) {
2048   case SCEVPredicate::P_Union:
2049     return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2050   case SCEVPredicate::P_Compare:
2051     return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP);
2052   case SCEVPredicate::P_Wrap: {
2053     auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2054     return expandWrapPredicate(AddRecPred, IP);
2055   }
2056   }
2057   llvm_unreachable("Unknown SCEV predicate type");
2058 }
2059 
2060 Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred,
2061                                             Instruction *IP) {
2062   Value *Expr0 = expand(Pred->getLHS(), IP);
2063   Value *Expr1 = expand(Pred->getRHS(), IP);
2064 
2065   Builder.SetInsertPoint(IP);
2066   auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2067   auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2068   return I;
2069 }
2070 
2071 Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2072                                            Instruction *Loc, bool Signed) {
2073   assert(AR->isAffine() && "Cannot generate RT check for "
2074                            "non-affine expression");
2075 
2076   // FIXME: It is highly suspicious that we're ignoring the predicates here.
2077   SmallVector<const SCEVPredicate *, 4> Pred;
2078   const SCEV *ExitCount =
2079       SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->getLoop(), Pred);
2080 
2081   assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2082 
2083   const SCEV *Step = AR->getStepRecurrence(SE);
2084   const SCEV *Start = AR->getStart();
2085 
2086   Type *ARTy = AR->getType();
2087   unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2088   unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2089 
2090   // The expression {Start,+,Step} has nusw/nssw if
2091   //   Step < 0, Start - |Step| * Backedge <= Start
2092   //   Step >= 0, Start + |Step| * Backedge > Start
2093   // and |Step| * Backedge doesn't unsigned overflow.
2094 
2095   Builder.SetInsertPoint(Loc);
2096   Value *TripCountVal = expand(ExitCount, Loc);
2097 
2098   IntegerType *Ty =
2099       IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2100 
2101   Value *StepValue = expand(Step, Loc);
2102   Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc);
2103   Value *StartValue = expand(Start, Loc);
2104 
2105   ConstantInt *Zero =
2106       ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2107 
2108   Builder.SetInsertPoint(Loc);
2109   // Compute |Step|
2110   Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2111   Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2112 
2113   // Compute |Step| * Backedge
2114   // Compute:
2115   //   1. Start + |Step| * Backedge < Start
2116   //   2. Start - |Step| * Backedge > Start
2117   //
2118   // And select either 1. or 2. depending on whether step is positive or
2119   // negative. If Step is known to be positive or negative, only create
2120   // either 1. or 2.
2121   auto ComputeEndCheck = [&]() -> Value * {
2122     // Checking <u 0 is always false.
2123     if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
2124       return ConstantInt::getFalse(Loc->getContext());
2125 
2126     // Get the backedge taken count and truncate or extended to the AR type.
2127     Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2128 
2129     Value *MulV, *OfMul;
2130     if (Step->isOne()) {
2131       // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
2132       // needed, there is never an overflow, so to avoid artificially inflating
2133       // the cost of the check, directly emit the optimized IR.
2134       MulV = TruncTripCount;
2135       OfMul = ConstantInt::getFalse(MulV->getContext());
2136     } else {
2137       auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2138                                              Intrinsic::umul_with_overflow, Ty);
2139       CallInst *Mul =
2140           Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2141       MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2142       OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2143     }
2144 
2145     Value *Add = nullptr, *Sub = nullptr;
2146     bool NeedPosCheck = !SE.isKnownNegative(Step);
2147     bool NeedNegCheck = !SE.isKnownPositive(Step);
2148 
2149     if (isa<PointerType>(ARTy)) {
2150       Value *NegMulV = Builder.CreateNeg(MulV);
2151       if (NeedPosCheck)
2152         Add = Builder.CreatePtrAdd(StartValue, MulV);
2153       if (NeedNegCheck)
2154         Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2155     } else {
2156       if (NeedPosCheck)
2157         Add = Builder.CreateAdd(StartValue, MulV);
2158       if (NeedNegCheck)
2159         Sub = Builder.CreateSub(StartValue, MulV);
2160     }
2161 
2162     Value *EndCompareLT = nullptr;
2163     Value *EndCompareGT = nullptr;
2164     Value *EndCheck = nullptr;
2165     if (NeedPosCheck)
2166       EndCheck = EndCompareLT = Builder.CreateICmp(
2167           Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2168     if (NeedNegCheck)
2169       EndCheck = EndCompareGT = Builder.CreateICmp(
2170           Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2171     if (NeedPosCheck && NeedNegCheck) {
2172       // Select the answer based on the sign of Step.
2173       EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2174     }
2175     return Builder.CreateOr(EndCheck, OfMul);
2176   };
2177   Value *EndCheck = ComputeEndCheck();
2178 
2179   // If the backedge taken count type is larger than the AR type,
2180   // check that we don't drop any bits by truncating it. If we are
2181   // dropping bits, then we have overflow (unless the step is zero).
2182   if (SrcBits > DstBits) {
2183     auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2184     auto *BackedgeCheck =
2185         Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2186                            ConstantInt::get(Loc->getContext(), MaxVal));
2187     BackedgeCheck = Builder.CreateAnd(
2188         BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2189 
2190     EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2191   }
2192 
2193   return EndCheck;
2194 }
2195 
2196 Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2197                                          Instruction *IP) {
2198   const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2199   Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2200 
2201   // Add a check for NUSW
2202   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2203     NUSWCheck = generateOverflowCheck(A, IP, false);
2204 
2205   // Add a check for NSSW
2206   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2207     NSSWCheck = generateOverflowCheck(A, IP, true);
2208 
2209   if (NUSWCheck && NSSWCheck)
2210     return Builder.CreateOr(NUSWCheck, NSSWCheck);
2211 
2212   if (NUSWCheck)
2213     return NUSWCheck;
2214 
2215   if (NSSWCheck)
2216     return NSSWCheck;
2217 
2218   return ConstantInt::getFalse(IP->getContext());
2219 }
2220 
2221 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2222                                           Instruction *IP) {
2223   // Loop over all checks in this set.
2224   SmallVector<Value *> Checks;
2225   for (const auto *Pred : Union->getPredicates()) {
2226     Checks.push_back(expandCodeForPredicate(Pred, IP));
2227     Builder.SetInsertPoint(IP);
2228   }
2229 
2230   if (Checks.empty())
2231     return ConstantInt::getFalse(IP->getContext());
2232   return Builder.CreateOr(Checks);
2233 }
2234 
2235 Value *SCEVExpander::fixupLCSSAFormFor(Value *V) {
2236   auto *DefI = dyn_cast<Instruction>(V);
2237   if (!PreserveLCSSA || !DefI)
2238     return V;
2239 
2240   BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
2241   Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent());
2242   Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent());
2243   if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2244     return V;
2245 
2246   // Create a temporary instruction to at the current insertion point, so we
2247   // can hand it off to the helper to create LCSSA PHIs if required for the
2248   // new use.
2249   // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
2250   // would accept a insertion point and return an LCSSA phi for that
2251   // insertion point, so there is no need to insert & remove the temporary
2252   // instruction.
2253   Type *ToTy;
2254   if (DefI->getType()->isIntegerTy())
2255     ToTy = PointerType::get(DefI->getContext(), 0);
2256   else
2257     ToTy = Type::getInt32Ty(DefI->getContext());
2258   Instruction *User =
2259       CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt);
2260   auto RemoveUserOnExit =
2261       make_scope_exit([User]() { User->eraseFromParent(); });
2262 
2263   SmallVector<Instruction *, 1> ToUpdate;
2264   ToUpdate.push_back(DefI);
2265   SmallVector<PHINode *, 16> PHIsToRemove;
2266   SmallVector<PHINode *, 16> InsertedPHIs;
2267   formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove,
2268                            &InsertedPHIs);
2269   for (PHINode *PN : InsertedPHIs)
2270     rememberInstruction(PN);
2271   for (PHINode *PN : PHIsToRemove) {
2272     if (!PN->use_empty())
2273       continue;
2274     InsertedValues.erase(PN);
2275     InsertedPostIncValues.erase(PN);
2276     PN->eraseFromParent();
2277   }
2278 
2279   return User->getOperand(0);
2280 }
2281 
2282 namespace {
2283 // Search for a SCEV subexpression that is not safe to expand.  Any expression
2284 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2285 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2286 // instruction, but the important thing is that we prove the denominator is
2287 // nonzero before expansion.
2288 //
2289 // IVUsers already checks that IV-derived expressions are safe. So this check is
2290 // only needed when the expression includes some subexpression that is not IV
2291 // derived.
2292 //
2293 // Currently, we only allow division by a value provably non-zero here.
2294 //
2295 // We cannot generally expand recurrences unless the step dominates the loop
2296 // header. The expander handles the special case of affine recurrences by
2297 // scaling the recurrence outside the loop, but this technique isn't generally
2298 // applicable. Expanding a nested recurrence outside a loop requires computing
2299 // binomial coefficients. This could be done, but the recurrence has to be in a
2300 // perfectly reduced form, which can't be guaranteed.
2301 struct SCEVFindUnsafe {
2302   ScalarEvolution &SE;
2303   bool CanonicalMode;
2304   bool IsUnsafe = false;
2305 
2306   SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
2307       : SE(SE), CanonicalMode(CanonicalMode) {}
2308 
2309   bool follow(const SCEV *S) {
2310     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2311       if (!SE.isKnownNonZero(D->getRHS())) {
2312         IsUnsafe = true;
2313         return false;
2314       }
2315     }
2316     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2317       // For non-affine addrecs or in non-canonical mode we need a preheader
2318       // to insert into.
2319       if (!AR->getLoop()->getLoopPreheader() &&
2320           (!CanonicalMode || !AR->isAffine())) {
2321         IsUnsafe = true;
2322         return false;
2323       }
2324     }
2325     return true;
2326   }
2327   bool isDone() const { return IsUnsafe; }
2328 };
2329 } // namespace
2330 
2331 bool SCEVExpander::isSafeToExpand(const SCEV *S) const {
2332   SCEVFindUnsafe Search(SE, CanonicalMode);
2333   visitAll(S, Search);
2334   return !Search.IsUnsafe;
2335 }
2336 
2337 bool SCEVExpander::isSafeToExpandAt(const SCEV *S,
2338                                     const Instruction *InsertionPoint) const {
2339   if (!isSafeToExpand(S))
2340     return false;
2341   // We have to prove that the expanded site of S dominates InsertionPoint.
2342   // This is easy when not in the same block, but hard when S is an instruction
2343   // to be expanded somewhere inside the same block as our insertion point.
2344   // What we really need here is something analogous to an OrderedBasicBlock,
2345   // but for the moment, we paper over the problem by handling two common and
2346   // cheap to check cases.
2347   if (SE.properlyDominates(S, InsertionPoint->getParent()))
2348     return true;
2349   if (SE.dominates(S, InsertionPoint->getParent())) {
2350     if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2351       return true;
2352     if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2353       if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2354         return true;
2355   }
2356   return false;
2357 }
2358 
2359 void SCEVExpanderCleaner::cleanup() {
2360   // Result is used, nothing to remove.
2361   if (ResultUsed)
2362     return;
2363 
2364   // Restore original poison flags.
2365   for (auto [I, Flags] : Expander.OrigFlags)
2366     Flags.apply(I);
2367 
2368   auto InsertedInstructions = Expander.getAllInsertedInstructions();
2369 #ifndef NDEBUG
2370   SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
2371                                             InsertedInstructions.end());
2372   (void)InsertedSet;
2373 #endif
2374   // Remove sets with value handles.
2375   Expander.clear();
2376 
2377   // Remove all inserted instructions.
2378   for (Instruction *I : reverse(InsertedInstructions)) {
2379 #ifndef NDEBUG
2380     assert(all_of(I->users(),
2381                   [&InsertedSet](Value *U) {
2382                     return InsertedSet.contains(cast<Instruction>(U));
2383                   }) &&
2384            "removed instruction should only be used by instructions inserted "
2385            "during expansion");
2386 #endif
2387     assert(!I->getType()->isVoidTy() &&
2388            "inserted instruction should have non-void types");
2389     I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2390     I->eraseFromParent();
2391   }
2392 }
2393