ScalarEvolutionExpander.cpp revision c37e3d5d7cd9576711204dfd0240edefba2df4c7
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/Analysis/LoopInfo.h"
18#include "llvm/LLVMContext.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/ADT/STLExtras.h"
21using namespace llvm;
22
23/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24/// which must be possible with a noop cast, doing what we can to share
25/// the casts.
26Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
27  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
28  assert((Op == Instruction::BitCast ||
29          Op == Instruction::PtrToInt ||
30          Op == Instruction::IntToPtr) &&
31         "InsertNoopCastOfTo cannot perform non-noop casts!");
32  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
33         "InsertNoopCastOfTo cannot change sizes!");
34
35  // Short-circuit unnecessary bitcasts.
36  if (Op == Instruction::BitCast && V->getType() == Ty)
37    return V;
38
39  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
40  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
41      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
42    if (CastInst *CI = dyn_cast<CastInst>(V))
43      if ((CI->getOpcode() == Instruction::PtrToInt ||
44           CI->getOpcode() == Instruction::IntToPtr) &&
45          SE.getTypeSizeInBits(CI->getType()) ==
46          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
47        return CI->getOperand(0);
48    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
49      if ((CE->getOpcode() == Instruction::PtrToInt ||
50           CE->getOpcode() == Instruction::IntToPtr) &&
51          SE.getTypeSizeInBits(CE->getType()) ==
52          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
53        return CE->getOperand(0);
54  }
55
56  if (Constant *C = dyn_cast<Constant>(V))
57    return ConstantExpr::getCast(Op, C, Ty);
58
59  if (Argument *A = dyn_cast<Argument>(V)) {
60    // Check to see if there is already a cast!
61    for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
62         UI != E; ++UI)
63      if ((*UI)->getType() == Ty)
64        if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
65          if (CI->getOpcode() == Op) {
66            // If the cast isn't the first instruction of the function, move it.
67            if (BasicBlock::iterator(CI) !=
68                A->getParent()->getEntryBlock().begin()) {
69              // Recreate the cast at the beginning of the entry block.
70              // The old cast is left in place in case it is being used
71              // as an insert point.
72              Instruction *NewCI =
73                CastInst::Create(Op, V, Ty, "",
74                                 A->getParent()->getEntryBlock().begin());
75              NewCI->takeName(CI);
76              CI->replaceAllUsesWith(NewCI);
77              return NewCI;
78            }
79            return CI;
80          }
81
82    Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
83                                      A->getParent()->getEntryBlock().begin());
84    rememberInstruction(I);
85    return I;
86  }
87
88  Instruction *I = cast<Instruction>(V);
89
90  // Check to see if there is already a cast.  If there is, use it.
91  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
92       UI != E; ++UI) {
93    if ((*UI)->getType() == Ty)
94      if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
95        if (CI->getOpcode() == Op) {
96          BasicBlock::iterator It = I; ++It;
97          if (isa<InvokeInst>(I))
98            It = cast<InvokeInst>(I)->getNormalDest()->begin();
99          while (isa<PHINode>(It)) ++It;
100          if (It != BasicBlock::iterator(CI)) {
101            // Recreate the cast after the user.
102            // The old cast is left in place in case it is being used
103            // as an insert point.
104            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
105            NewCI->takeName(CI);
106            CI->replaceAllUsesWith(NewCI);
107            rememberInstruction(NewCI);
108            return NewCI;
109          }
110          rememberInstruction(CI);
111          return CI;
112        }
113  }
114  BasicBlock::iterator IP = I; ++IP;
115  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
116    IP = II->getNormalDest()->begin();
117  while (isa<PHINode>(IP)) ++IP;
118  Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
119  rememberInstruction(CI);
120  return CI;
121}
122
123/// InsertBinop - Insert the specified binary operator, doing a small amount
124/// of work to avoid inserting an obviously redundant operation.
125Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
126                                 Value *LHS, Value *RHS) {
127  // Fold a binop with constant operands.
128  if (Constant *CLHS = dyn_cast<Constant>(LHS))
129    if (Constant *CRHS = dyn_cast<Constant>(RHS))
130      return ConstantExpr::get(Opcode, CLHS, CRHS);
131
132  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
133  unsigned ScanLimit = 6;
134  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
135  // Scanning starts from the last instruction before the insertion point.
136  BasicBlock::iterator IP = Builder.GetInsertPoint();
137  if (IP != BlockBegin) {
138    --IP;
139    for (; ScanLimit; --IP, --ScanLimit) {
140      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
141          IP->getOperand(1) == RHS)
142        return IP;
143      if (IP == BlockBegin) break;
144    }
145  }
146
147  // If we haven't found this binop, insert it.
148  Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
149  rememberInstruction(BO);
150  return BO;
151}
152
153/// FactorOutConstant - Test if S is divisible by Factor, using signed
154/// division. If so, update S with Factor divided out and return true.
155/// S need not be evenly divisble if a reasonable remainder can be
156/// computed.
157/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
158/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
159/// check to see if the divide was folded.
160static bool FactorOutConstant(const SCEV *&S,
161                              const SCEV *&Remainder,
162                              const SCEV *Factor,
163                              ScalarEvolution &SE,
164                              const TargetData *TD) {
165  // Everything is divisible by one.
166  if (Factor->isOne())
167    return true;
168
169  // x/x == 1.
170  if (S == Factor) {
171    S = SE.getIntegerSCEV(1, S->getType());
172    return true;
173  }
174
175  // For a Constant, check for a multiple of the given factor.
176  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
177    // 0/x == 0.
178    if (C->isZero())
179      return true;
180    // Check for divisibility.
181    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
182      ConstantInt *CI =
183        ConstantInt::get(SE.getContext(),
184                         C->getValue()->getValue().sdiv(
185                                                   FC->getValue()->getValue()));
186      // If the quotient is zero and the remainder is non-zero, reject
187      // the value at this scale. It will be considered for subsequent
188      // smaller scales.
189      if (!CI->isZero()) {
190        const SCEV *Div = SE.getConstant(CI);
191        S = Div;
192        Remainder =
193          SE.getAddExpr(Remainder,
194                        SE.getConstant(C->getValue()->getValue().srem(
195                                                  FC->getValue()->getValue())));
196        return true;
197      }
198    }
199  }
200
201  // In a Mul, check if there is a constant operand which is a multiple
202  // of the given factor.
203  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
204    if (TD) {
205      // With TargetData, the size is known. Check if there is a constant
206      // operand which is a multiple of the given factor. If so, we can
207      // factor it.
208      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
209      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
210        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
211          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
212          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
213                                                 MOperands.end());
214          NewMulOps[0] =
215            SE.getConstant(C->getValue()->getValue().sdiv(
216                                                   FC->getValue()->getValue()));
217          S = SE.getMulExpr(NewMulOps);
218          return true;
219        }
220    } else {
221      // Without TargetData, check if Factor can be factored out of any of the
222      // Mul's operands. If so, we can just remove it.
223      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
224        const SCEV *SOp = M->getOperand(i);
225        const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
226        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
227            Remainder->isZero()) {
228          const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
229          SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
230                                                 MOperands.end());
231          NewMulOps[i] = SOp;
232          S = SE.getMulExpr(NewMulOps);
233          return true;
234        }
235      }
236    }
237  }
238
239  // In an AddRec, check if both start and step are divisible.
240  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
241    const SCEV *Step = A->getStepRecurrence(SE);
242    const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
243    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
244      return false;
245    if (!StepRem->isZero())
246      return false;
247    const SCEV *Start = A->getStart();
248    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
249      return false;
250    S = SE.getAddRecExpr(Start, Step, A->getLoop());
251    return true;
252  }
253
254  return false;
255}
256
257/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
258/// is the number of SCEVAddRecExprs present, which are kept at the end of
259/// the list.
260///
261static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
262                                const Type *Ty,
263                                ScalarEvolution &SE) {
264  unsigned NumAddRecs = 0;
265  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
266    ++NumAddRecs;
267  // Group Ops into non-addrecs and addrecs.
268  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
269  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
270  // Let ScalarEvolution sort and simplify the non-addrecs list.
271  const SCEV *Sum = NoAddRecs.empty() ?
272                    SE.getIntegerSCEV(0, Ty) :
273                    SE.getAddExpr(NoAddRecs);
274  // If it returned an add, use the operands. Otherwise it simplified
275  // the sum into a single value, so just use that.
276  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
277    Ops = Add->getOperands();
278  else {
279    Ops.clear();
280    if (!Sum->isZero())
281      Ops.push_back(Sum);
282  }
283  // Then append the addrecs.
284  Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
285}
286
287/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
288/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
289/// This helps expose more opportunities for folding parts of the expressions
290/// into GEP indices.
291///
292static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
293                         const Type *Ty,
294                         ScalarEvolution &SE) {
295  // Find the addrecs.
296  SmallVector<const SCEV *, 8> AddRecs;
297  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
298    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
299      const SCEV *Start = A->getStart();
300      if (Start->isZero()) break;
301      const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
302      AddRecs.push_back(SE.getAddRecExpr(Zero,
303                                         A->getStepRecurrence(SE),
304                                         A->getLoop()));
305      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
306        Ops[i] = Zero;
307        Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
308        e += Add->getNumOperands();
309      } else {
310        Ops[i] = Start;
311      }
312    }
313  if (!AddRecs.empty()) {
314    // Add the addrecs onto the end of the list.
315    Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
316    // Resort the operand list, moving any constants to the front.
317    SimplifyAddOperands(Ops, Ty, SE);
318  }
319}
320
321/// expandAddToGEP - Expand an addition expression with a pointer type into
322/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
323/// BasicAliasAnalysis and other passes analyze the result. See the rules
324/// for getelementptr vs. inttoptr in
325/// http://llvm.org/docs/LangRef.html#pointeraliasing
326/// for details.
327///
328/// Design note: The correctness of using getelementptr here depends on
329/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
330/// they may introduce pointer arithmetic which may not be safely converted
331/// into getelementptr.
332///
333/// Design note: It might seem desirable for this function to be more
334/// loop-aware. If some of the indices are loop-invariant while others
335/// aren't, it might seem desirable to emit multiple GEPs, keeping the
336/// loop-invariant portions of the overall computation outside the loop.
337/// However, there are a few reasons this is not done here. Hoisting simple
338/// arithmetic is a low-level optimization that often isn't very
339/// important until late in the optimization process. In fact, passes
340/// like InstructionCombining will combine GEPs, even if it means
341/// pushing loop-invariant computation down into loops, so even if the
342/// GEPs were split here, the work would quickly be undone. The
343/// LoopStrengthReduction pass, which is usually run quite late (and
344/// after the last InstructionCombining pass), takes care of hoisting
345/// loop-invariant portions of expressions, after considering what
346/// can be folded using target addressing modes.
347///
348Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
349                                    const SCEV *const *op_end,
350                                    const PointerType *PTy,
351                                    const Type *Ty,
352                                    Value *V) {
353  const Type *ElTy = PTy->getElementType();
354  SmallVector<Value *, 4> GepIndices;
355  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
356  bool AnyNonZeroIndices = false;
357
358  // Split AddRecs up into parts as either of the parts may be usable
359  // without the other.
360  SplitAddRecs(Ops, Ty, SE);
361
362  // Descend down the pointer's type and attempt to convert the other
363  // operands into GEP indices, at each level. The first index in a GEP
364  // indexes into the array implied by the pointer operand; the rest of
365  // the indices index into the element or field type selected by the
366  // preceding index.
367  for (;;) {
368    const SCEV *ElSize = SE.getAllocSizeExpr(ElTy);
369    // If the scale size is not 0, attempt to factor out a scale for
370    // array indexing.
371    SmallVector<const SCEV *, 8> ScaledOps;
372    if (ElTy->isSized() && !ElSize->isZero()) {
373      SmallVector<const SCEV *, 8> NewOps;
374      for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
375        const SCEV *Op = Ops[i];
376        const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
377        if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
378          // Op now has ElSize factored out.
379          ScaledOps.push_back(Op);
380          if (!Remainder->isZero())
381            NewOps.push_back(Remainder);
382          AnyNonZeroIndices = true;
383        } else {
384          // The operand was not divisible, so add it to the list of operands
385          // we'll scan next iteration.
386          NewOps.push_back(Ops[i]);
387        }
388      }
389      // If we made any changes, update Ops.
390      if (!ScaledOps.empty()) {
391        Ops = NewOps;
392        SimplifyAddOperands(Ops, Ty, SE);
393      }
394    }
395
396    // Record the scaled array index for this level of the type. If
397    // we didn't find any operands that could be factored, tentatively
398    // assume that element zero was selected (since the zero offset
399    // would obviously be folded away).
400    Value *Scaled = ScaledOps.empty() ?
401                    Constant::getNullValue(Ty) :
402                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
403    GepIndices.push_back(Scaled);
404
405    // Collect struct field index operands.
406    while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
407      bool FoundFieldNo = false;
408      // An empty struct has no fields.
409      if (STy->getNumElements() == 0) break;
410      if (SE.TD) {
411        // With TargetData, field offsets are known. See if a constant offset
412        // falls within any of the struct fields.
413        if (Ops.empty()) break;
414        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
415          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
416            const StructLayout &SL = *SE.TD->getStructLayout(STy);
417            uint64_t FullOffset = C->getValue()->getZExtValue();
418            if (FullOffset < SL.getSizeInBytes()) {
419              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
420              GepIndices.push_back(
421                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
422              ElTy = STy->getTypeAtIndex(ElIdx);
423              Ops[0] =
424                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
425              AnyNonZeroIndices = true;
426              FoundFieldNo = true;
427            }
428          }
429      } else {
430        // Without TargetData, just check for a SCEVFieldOffsetExpr of the
431        // appropriate struct type.
432        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
433          if (const SCEVFieldOffsetExpr *FO =
434                dyn_cast<SCEVFieldOffsetExpr>(Ops[i]))
435            if (FO->getStructType() == STy) {
436              unsigned FieldNo = FO->getFieldNo();
437              GepIndices.push_back(
438                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
439                                   FieldNo));
440              ElTy = STy->getTypeAtIndex(FieldNo);
441              Ops[i] = SE.getConstant(Ty, 0);
442              AnyNonZeroIndices = true;
443              FoundFieldNo = true;
444              break;
445            }
446      }
447      // If no struct field offsets were found, tentatively assume that
448      // field zero was selected (since the zero offset would obviously
449      // be folded away).
450      if (!FoundFieldNo) {
451        ElTy = STy->getTypeAtIndex(0u);
452        GepIndices.push_back(
453          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
454      }
455    }
456
457    if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
458      ElTy = ATy->getElementType();
459    else
460      break;
461  }
462
463  // If none of the operands were convertable to proper GEP indices, cast
464  // the base to i8* and do an ugly getelementptr with that. It's still
465  // better than ptrtoint+arithmetic+inttoptr at least.
466  if (!AnyNonZeroIndices) {
467    // Cast the base to i8*.
468    V = InsertNoopCastOfTo(V,
469       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
470
471    // Expand the operands for a plain byte offset.
472    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
473
474    // Fold a GEP with constant operands.
475    if (Constant *CLHS = dyn_cast<Constant>(V))
476      if (Constant *CRHS = dyn_cast<Constant>(Idx))
477        return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
478
479    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
480    unsigned ScanLimit = 6;
481    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
482    // Scanning starts from the last instruction before the insertion point.
483    BasicBlock::iterator IP = Builder.GetInsertPoint();
484    if (IP != BlockBegin) {
485      --IP;
486      for (; ScanLimit; --IP, --ScanLimit) {
487        if (IP->getOpcode() == Instruction::GetElementPtr &&
488            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
489          return IP;
490        if (IP == BlockBegin) break;
491      }
492    }
493
494    // Emit a GEP.
495    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
496    rememberInstruction(GEP);
497    return GEP;
498  }
499
500  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
501  // because ScalarEvolution may have changed the address arithmetic to
502  // compute a value which is beyond the end of the allocated object.
503  Value *Casted = V;
504  if (V->getType() != PTy)
505    Casted = InsertNoopCastOfTo(Casted, PTy);
506  Value *GEP = Builder.CreateGEP(Casted,
507                                 GepIndices.begin(),
508                                 GepIndices.end(),
509                                 "scevgep");
510  Ops.push_back(SE.getUnknown(GEP));
511  rememberInstruction(GEP);
512  return expand(SE.getAddExpr(Ops));
513}
514
515/// isNonConstantNegative - Return true if the specified scev is negated, but
516/// not a constant.
517static bool isNonConstantNegative(const SCEV *F) {
518  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
519  if (!Mul) return false;
520
521  // If there is a constant factor, it will be first.
522  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
523  if (!SC) return false;
524
525  // Return true if the value is negative, this matches things like (-42 * V).
526  return SC->getValue()->getValue().isNegative();
527}
528
529Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
530  int NumOperands = S->getNumOperands();
531  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
532
533  // Find the index of an operand to start with. Choose the operand with
534  // pointer type, if there is one, or the last operand otherwise.
535  int PIdx = 0;
536  for (; PIdx != NumOperands - 1; ++PIdx)
537    if (isa<PointerType>(S->getOperand(PIdx)->getType())) break;
538
539  // Expand code for the operand that we chose.
540  Value *V = expand(S->getOperand(PIdx));
541
542  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
543  // comments on expandAddToGEP for details.
544  if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
545    // Take the operand at PIdx out of the list.
546    const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
547    SmallVector<const SCEV *, 8> NewOps;
548    NewOps.insert(NewOps.end(), Ops.begin(), Ops.begin() + PIdx);
549    NewOps.insert(NewOps.end(), Ops.begin() + PIdx + 1, Ops.end());
550    // Make a GEP.
551    return expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, V);
552  }
553
554  // Otherwise, we'll expand the rest of the SCEVAddExpr as plain integer
555  // arithmetic.
556  V = InsertNoopCastOfTo(V, Ty);
557
558  // Emit a bunch of add instructions
559  for (int i = NumOperands-1; i >= 0; --i) {
560    if (i == PIdx) continue;
561    const SCEV *Op = S->getOperand(i);
562    if (isNonConstantNegative(Op)) {
563      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
564      V = InsertBinop(Instruction::Sub, V, W);
565    } else {
566      Value *W = expandCodeFor(Op, Ty);
567      V = InsertBinop(Instruction::Add, V, W);
568    }
569  }
570  return V;
571}
572
573Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
574  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
575  int FirstOp = 0;  // Set if we should emit a subtract.
576  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
577    if (SC->getValue()->isAllOnesValue())
578      FirstOp = 1;
579
580  int i = S->getNumOperands()-2;
581  Value *V = expandCodeFor(S->getOperand(i+1), Ty);
582
583  // Emit a bunch of multiply instructions
584  for (; i >= FirstOp; --i) {
585    Value *W = expandCodeFor(S->getOperand(i), Ty);
586    V = InsertBinop(Instruction::Mul, V, W);
587  }
588
589  // -1 * ...  --->  0 - ...
590  if (FirstOp == 1)
591    V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
592  return V;
593}
594
595Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
596  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
597
598  Value *LHS = expandCodeFor(S->getLHS(), Ty);
599  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
600    const APInt &RHS = SC->getValue()->getValue();
601    if (RHS.isPowerOf2())
602      return InsertBinop(Instruction::LShr, LHS,
603                         ConstantInt::get(Ty, RHS.logBase2()));
604  }
605
606  Value *RHS = expandCodeFor(S->getRHS(), Ty);
607  return InsertBinop(Instruction::UDiv, LHS, RHS);
608}
609
610/// Move parts of Base into Rest to leave Base with the minimal
611/// expression that provides a pointer operand suitable for a
612/// GEP expansion.
613static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
614                              ScalarEvolution &SE) {
615  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
616    Base = A->getStart();
617    Rest = SE.getAddExpr(Rest,
618                         SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
619                                          A->getStepRecurrence(SE),
620                                          A->getLoop()));
621  }
622  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
623    Base = A->getOperand(A->getNumOperands()-1);
624    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
625    NewAddOps.back() = Rest;
626    Rest = SE.getAddExpr(NewAddOps);
627    ExposePointerBase(Base, Rest, SE);
628  }
629}
630
631/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
632/// the base addrec, which is the addrec without any non-loop-dominating
633/// values, and return the PHI.
634PHINode *
635SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
636                                        const Loop *L,
637                                        const Type *ExpandTy,
638                                        const Type *IntTy) {
639  // Reuse a previously-inserted PHI, if present.
640  for (BasicBlock::iterator I = L->getHeader()->begin();
641       PHINode *PN = dyn_cast<PHINode>(I); ++I)
642    if (isInsertedInstruction(PN) && SE.getSCEV(PN) == Normalized)
643      return PN;
644
645  // Save the original insertion point so we can restore it when we're done.
646  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
647  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
648
649  // Expand code for the start value.
650  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
651                                L->getHeader()->begin());
652
653  // Expand code for the step value. Insert instructions right before the
654  // terminator corresponding to the back-edge. Do this before creating the PHI
655  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
656  // negative, insert a sub instead of an add for the increment (unless it's a
657  // constant, because subtracts of constants are canonicalized to adds).
658  const SCEV *Step = Normalized->getStepRecurrence(SE);
659  bool isPointer = isa<PointerType>(ExpandTy);
660  bool isNegative = !isPointer && isNonConstantNegative(Step);
661  if (isNegative)
662    Step = SE.getNegativeSCEV(Step);
663  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
664
665  // Create the PHI.
666  Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
667  PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
668  rememberInstruction(PN);
669
670  // Create the step instructions and populate the PHI.
671  BasicBlock *Header = L->getHeader();
672  for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
673       HPI != HPE; ++HPI) {
674    BasicBlock *Pred = *HPI;
675
676    // Add a start value.
677    if (!L->contains(Pred)) {
678      PN->addIncoming(StartV, Pred);
679      continue;
680    }
681
682    // Create a step value and add it to the PHI. If IVIncInsertLoop is
683    // non-null and equal to the addrec's loop, insert the instructions
684    // at IVIncInsertPos.
685    Instruction *InsertPos = L == IVIncInsertLoop ?
686      IVIncInsertPos : Pred->getTerminator();
687    Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
688    Value *IncV;
689    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
690    if (isPointer) {
691      const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
692      // If the step isn't constant, don't use an implicitly scaled GEP, because
693      // that would require a multiply inside the loop.
694      if (!isa<ConstantInt>(StepV))
695        GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
696                                    GEPPtrTy->getAddressSpace());
697      const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
698      IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
699      if (IncV->getType() != PN->getType()) {
700        IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
701        rememberInstruction(IncV);
702      }
703    } else {
704      IncV = isNegative ?
705        Builder.CreateSub(PN, StepV, "lsr.iv.next") :
706        Builder.CreateAdd(PN, StepV, "lsr.iv.next");
707      rememberInstruction(IncV);
708    }
709    PN->addIncoming(IncV, Pred);
710  }
711
712  // Restore the original insert point.
713  if (SaveInsertBB)
714    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
715
716  // Remember this PHI, even in post-inc mode.
717  InsertedValues.insert(PN);
718
719  return PN;
720}
721
722Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
723  const Type *STy = S->getType();
724  const Type *IntTy = SE.getEffectiveSCEVType(STy);
725  const Loop *L = S->getLoop();
726
727  // Determine a normalized form of this expression, which is the expression
728  // before any post-inc adjustment is made.
729  const SCEVAddRecExpr *Normalized = S;
730  if (L == PostIncLoop) {
731    const SCEV *Step = S->getStepRecurrence(SE);
732    Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
733  }
734
735  // Strip off any non-loop-dominating component from the addrec start.
736  const SCEV *Start = Normalized->getStart();
737  const SCEV *PostLoopOffset = 0;
738  if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
739    PostLoopOffset = Start;
740    Start = SE.getIntegerSCEV(0, Normalized->getType());
741    Normalized =
742      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
743                                            Normalized->getStepRecurrence(SE),
744                                            Normalized->getLoop()));
745  }
746
747  // Strip off any non-loop-dominating component from the addrec step.
748  const SCEV *Step = Normalized->getStepRecurrence(SE);
749  const SCEV *PostLoopScale = 0;
750  if (!Step->hasComputableLoopEvolution(L) &&
751      !Step->dominates(L->getHeader(), SE.DT)) {
752    PostLoopScale = Step;
753    Step = SE.getIntegerSCEV(1, Normalized->getType());
754    Normalized =
755      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
756                                            Normalized->getLoop()));
757  }
758
759  // Expand the core addrec. If we need post-loop scaling, force it to
760  // expand to an integer type to avoid the need for additional casting.
761  const Type *ExpandTy = PostLoopScale ? IntTy : STy;
762  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
763
764  // Accomodate post-inc mode, if necessary.
765  Value *Result;
766  if (L != PostIncLoop)
767    Result = PN;
768  else {
769    // In PostInc mode, use the post-incremented value.
770    BasicBlock *LatchBlock = L->getLoopLatch();
771    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
772    Result = PN->getIncomingValueForBlock(LatchBlock);
773  }
774
775  // Re-apply any non-loop-dominating scale.
776  if (PostLoopScale) {
777    Result = Builder.CreateMul(Result,
778                               expandCodeFor(PostLoopScale, IntTy));
779    rememberInstruction(Result);
780  }
781
782  // Re-apply any non-loop-dominating offset.
783  if (PostLoopOffset) {
784    if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
785      const SCEV *const OffsetArray[1] = { PostLoopOffset };
786      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
787    } else {
788      Result = Builder.CreateAdd(Result,
789                                 expandCodeFor(PostLoopOffset, IntTy));
790      rememberInstruction(Result);
791    }
792  }
793
794  return Result;
795}
796
797Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
798  if (!CanonicalMode) return expandAddRecExprLiterally(S);
799
800  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
801  const Loop *L = S->getLoop();
802
803  // First check for an existing canonical IV in a suitable type.
804  PHINode *CanonicalIV = 0;
805  if (PHINode *PN = L->getCanonicalInductionVariable())
806    if (SE.isSCEVable(PN->getType()) &&
807        isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
808        SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
809      CanonicalIV = PN;
810
811  // Rewrite an AddRec in terms of the canonical induction variable, if
812  // its type is more narrow.
813  if (CanonicalIV &&
814      SE.getTypeSizeInBits(CanonicalIV->getType()) >
815      SE.getTypeSizeInBits(Ty)) {
816    const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
817    SmallVector<const SCEV *, 4> NewOps(Ops.size());
818    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
819      NewOps[i] = SE.getAnyExtendExpr(Ops[i], CanonicalIV->getType());
820    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
821    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
822    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
823    BasicBlock::iterator NewInsertPt =
824      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
825    while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
826    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
827                      NewInsertPt);
828    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
829    return V;
830  }
831
832  // {X,+,F} --> X + {0,+,F}
833  if (!S->getStart()->isZero()) {
834    const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
835    SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
836    NewOps[0] = SE.getIntegerSCEV(0, Ty);
837    const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
838
839    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
840    // comments on expandAddToGEP for details.
841    const SCEV *Base = S->getStart();
842    const SCEV *RestArray[1] = { Rest };
843    // Dig into the expression to find the pointer base for a GEP.
844    ExposePointerBase(Base, RestArray[0], SE);
845    // If we found a pointer, expand the AddRec with a GEP.
846    if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
847      // Make sure the Base isn't something exotic, such as a multiplied
848      // or divided pointer value. In those cases, the result type isn't
849      // actually a pointer type.
850      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
851        Value *StartV = expand(Base);
852        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
853        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
854      }
855    }
856
857    // Just do a normal add. Pre-expand the operands to suppress folding.
858    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
859                                SE.getUnknown(expand(Rest))));
860  }
861
862  // {0,+,1} --> Insert a canonical induction variable into the loop!
863  if (S->isAffine() &&
864      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
865    // If there's a canonical IV, just use it.
866    if (CanonicalIV) {
867      assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
868             "IVs with types different from the canonical IV should "
869             "already have been handled!");
870      return CanonicalIV;
871    }
872
873    // Create and insert the PHI node for the induction variable in the
874    // specified loop.
875    BasicBlock *Header = L->getHeader();
876    PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
877    rememberInstruction(PN);
878
879    Constant *One = ConstantInt::get(Ty, 1);
880    for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
881         HPI != HPE; ++HPI)
882      if (L->contains(*HPI)) {
883        // Insert a unit add instruction right before the terminator
884        // corresponding to the back-edge.
885        Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
886                                                     (*HPI)->getTerminator());
887        rememberInstruction(Add);
888        PN->addIncoming(Add, *HPI);
889      } else {
890        PN->addIncoming(Constant::getNullValue(Ty), *HPI);
891      }
892  }
893
894  // {0,+,F} --> {0,+,1} * F
895  // Get the canonical induction variable I for this loop.
896  Value *I = CanonicalIV ?
897             CanonicalIV :
898             getOrInsertCanonicalInductionVariable(L, Ty);
899
900  // If this is a simple linear addrec, emit it now as a special case.
901  if (S->isAffine())    // {0,+,F} --> i*F
902    return
903      expand(SE.getTruncateOrNoop(
904        SE.getMulExpr(SE.getUnknown(I),
905                      SE.getNoopOrAnyExtend(S->getOperand(1),
906                                            I->getType())),
907        Ty));
908
909  // If this is a chain of recurrences, turn it into a closed form, using the
910  // folders, then expandCodeFor the closed form.  This allows the folders to
911  // simplify the expression without having to build a bunch of special code
912  // into this folder.
913  const SCEV *IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
914
915  // Promote S up to the canonical IV type, if the cast is foldable.
916  const SCEV *NewS = S;
917  const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
918  if (isa<SCEVAddRecExpr>(Ext))
919    NewS = Ext;
920
921  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
922  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
923
924  // Truncate the result down to the original type, if needed.
925  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
926  return expand(T);
927}
928
929Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
930  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
931  Value *V = expandCodeFor(S->getOperand(),
932                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
933  Value *I = Builder.CreateTrunc(V, Ty, "tmp");
934  rememberInstruction(I);
935  return I;
936}
937
938Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
939  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
940  Value *V = expandCodeFor(S->getOperand(),
941                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
942  Value *I = Builder.CreateZExt(V, Ty, "tmp");
943  rememberInstruction(I);
944  return I;
945}
946
947Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
948  const Type *Ty = SE.getEffectiveSCEVType(S->getType());
949  Value *V = expandCodeFor(S->getOperand(),
950                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
951  Value *I = Builder.CreateSExt(V, Ty, "tmp");
952  rememberInstruction(I);
953  return I;
954}
955
956Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
957  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
958  const Type *Ty = LHS->getType();
959  for (int i = S->getNumOperands()-2; i >= 0; --i) {
960    // In the case of mixed integer and pointer types, do the
961    // rest of the comparisons as integer.
962    if (S->getOperand(i)->getType() != Ty) {
963      Ty = SE.getEffectiveSCEVType(Ty);
964      LHS = InsertNoopCastOfTo(LHS, Ty);
965    }
966    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
967    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
968    rememberInstruction(ICmp);
969    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
970    rememberInstruction(Sel);
971    LHS = Sel;
972  }
973  // In the case of mixed integer and pointer types, cast the
974  // final result back to the pointer type.
975  if (LHS->getType() != S->getType())
976    LHS = InsertNoopCastOfTo(LHS, S->getType());
977  return LHS;
978}
979
980Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
981  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
982  const Type *Ty = LHS->getType();
983  for (int i = S->getNumOperands()-2; i >= 0; --i) {
984    // In the case of mixed integer and pointer types, do the
985    // rest of the comparisons as integer.
986    if (S->getOperand(i)->getType() != Ty) {
987      Ty = SE.getEffectiveSCEVType(Ty);
988      LHS = InsertNoopCastOfTo(LHS, Ty);
989    }
990    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
991    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
992    rememberInstruction(ICmp);
993    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
994    rememberInstruction(Sel);
995    LHS = Sel;
996  }
997  // In the case of mixed integer and pointer types, cast the
998  // final result back to the pointer type.
999  if (LHS->getType() != S->getType())
1000    LHS = InsertNoopCastOfTo(LHS, S->getType());
1001  return LHS;
1002}
1003
1004Value *SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr *S) {
1005  return ConstantExpr::getOffsetOf(S->getStructType(), S->getFieldNo());
1006}
1007
1008Value *SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr *S) {
1009  return ConstantExpr::getSizeOf(S->getAllocType());
1010}
1011
1012Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
1013  // Expand the code for this SCEV.
1014  Value *V = expand(SH);
1015  if (Ty) {
1016    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1017           "non-trivial casts should be done with the SCEVs directly!");
1018    V = InsertNoopCastOfTo(V, Ty);
1019  }
1020  return V;
1021}
1022
1023Value *SCEVExpander::expand(const SCEV *S) {
1024  // Compute an insertion point for this SCEV object. Hoist the instructions
1025  // as far out in the loop nest as possible.
1026  Instruction *InsertPt = Builder.GetInsertPoint();
1027  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1028       L = L->getParentLoop())
1029    if (S->isLoopInvariant(L)) {
1030      if (!L) break;
1031      if (BasicBlock *Preheader = L->getLoopPreheader())
1032        InsertPt = Preheader->getTerminator();
1033    } else {
1034      // If the SCEV is computable at this level, insert it into the header
1035      // after the PHIs (and after any other instructions that we've inserted
1036      // there) so that it is guaranteed to dominate any user inside the loop.
1037      if (L && S->hasComputableLoopEvolution(L))
1038        InsertPt = L->getHeader()->getFirstNonPHI();
1039      while (isInsertedInstruction(InsertPt))
1040        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1041      break;
1042    }
1043
1044  // Check to see if we already expanded this here.
1045  std::map<std::pair<const SCEV *, Instruction *>,
1046           AssertingVH<Value> >::iterator I =
1047    InsertedExpressions.find(std::make_pair(S, InsertPt));
1048  if (I != InsertedExpressions.end())
1049    return I->second;
1050
1051  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1052  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1053  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1054
1055  // Expand the expression into instructions.
1056  Value *V = visit(S);
1057
1058  // Remember the expanded value for this SCEV at this location.
1059  if (!PostIncLoop)
1060    InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1061
1062  Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
1063  return V;
1064}
1065
1066/// getOrInsertCanonicalInductionVariable - This method returns the
1067/// canonical induction variable of the specified type for the specified
1068/// loop (inserting one if there is none).  A canonical induction variable
1069/// starts at zero and steps by one on each iteration.
1070Value *
1071SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1072                                                    const Type *Ty) {
1073  assert(Ty->isInteger() && "Can only insert integer induction variables!");
1074  const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
1075                                   SE.getIntegerSCEV(1, Ty), L);
1076  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1077  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1078  Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1079  if (SaveInsertBB)
1080    Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
1081  return V;
1082}
1083