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