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