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