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