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