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