Minor formatting, whitespace, and 80-column fixes.
[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/Analysis/LoopInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/ADT/STLExtras.h"
20 using namespace llvm;
21
22 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
23 /// which must be possible with a noop cast, doing what we can to share
24 /// the casts.
25 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
26   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
27   assert((Op == Instruction::BitCast ||
28           Op == Instruction::PtrToInt ||
29           Op == Instruction::IntToPtr) &&
30          "InsertNoopCastOfTo cannot perform non-noop casts!");
31   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
32          "InsertNoopCastOfTo cannot change sizes!");
33
34   // Short-circuit unnecessary bitcasts.
35   if (Op == Instruction::BitCast && V->getType() == Ty)
36     return V;
37
38   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
39   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
40       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
41     if (CastInst *CI = dyn_cast<CastInst>(V))
42       if ((CI->getOpcode() == Instruction::PtrToInt ||
43            CI->getOpcode() == Instruction::IntToPtr) &&
44           SE.getTypeSizeInBits(CI->getType()) ==
45           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
46         return CI->getOperand(0);
47     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
48       if ((CE->getOpcode() == Instruction::PtrToInt ||
49            CE->getOpcode() == Instruction::IntToPtr) &&
50           SE.getTypeSizeInBits(CE->getType()) ==
51           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
52         return CE->getOperand(0);
53   }
54
55   // FIXME: keep track of the cast instruction.
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     InsertedValues.insert(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 at the beginning of the entry block.
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             return NewCI;
108           }
109           return CI;
110         }
111   }
112   BasicBlock::iterator IP = I; ++IP;
113   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
114     IP = II->getNormalDest()->begin();
115   while (isa<PHINode>(IP)) ++IP;
116   Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
117   InsertedValues.insert(CI);
118   return CI;
119 }
120
121 /// InsertBinop - Insert the specified binary operator, doing a small amount
122 /// of work to avoid inserting an obviously redundant operation.
123 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
124                                  Value *LHS, Value *RHS) {
125   // Fold a binop with constant operands.
126   if (Constant *CLHS = dyn_cast<Constant>(LHS))
127     if (Constant *CRHS = dyn_cast<Constant>(RHS))
128       return ConstantExpr::get(Opcode, CLHS, CRHS);
129
130   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
131   unsigned ScanLimit = 6;
132   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
133   // Scanning starts from the last instruction before the insertion point.
134   BasicBlock::iterator IP = Builder.GetInsertPoint();
135   if (IP != BlockBegin) {
136     --IP;
137     for (; ScanLimit; --IP, --ScanLimit) {
138       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
139           IP->getOperand(1) == RHS)
140         return IP;
141       if (IP == BlockBegin) break;
142     }
143   }
144
145   // If we haven't found this binop, insert it.
146   Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
147   InsertedValues.insert(BO);
148   return BO;
149 }
150
151 /// FactorOutConstant - Test if S is divisible by Factor, using signed
152 /// division. If so, update S with Factor divided out and return true.
153 /// S need not be evenly divisble if a reasonable remainder can be
154 /// computed.
155 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
156 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
157 /// check to see if the divide was folded.
158 static bool FactorOutConstant(const SCEV* &S,
159                               const SCEV* &Remainder,
160                               const APInt &Factor,
161                               ScalarEvolution &SE) {
162   // Everything is divisible by one.
163   if (Factor == 1)
164     return true;
165
166   // For a Constant, check for a multiple of the given factor.
167   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
168     ConstantInt *CI =
169       ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
170     // If the quotient is zero and the remainder is non-zero, reject
171     // the value at this scale. It will be considered for subsequent
172     // smaller scales.
173     if (C->isZero() || !CI->isZero()) {
174       const SCEV* Div = SE.getConstant(CI);
175       S = Div;
176       Remainder =
177         SE.getAddExpr(Remainder,
178                       SE.getConstant(C->getValue()->getValue().srem(Factor)));
179       return true;
180     }
181   }
182
183   // In a Mul, check if there is a constant operand which is a multiple
184   // of the given factor.
185   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
186     if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
187       if (!C->getValue()->getValue().srem(Factor)) {
188         const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
189         SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
190                                                MOperands.end());
191         NewMulOps[0] =
192           SE.getConstant(C->getValue()->getValue().sdiv(Factor));
193         S = SE.getMulExpr(NewMulOps);
194         return true;
195       }
196
197   // In an AddRec, check if both start and step are divisible.
198   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
199     const SCEV* Step = A->getStepRecurrence(SE);
200     const SCEV* StepRem = SE.getIntegerSCEV(0, Step->getType());
201     if (!FactorOutConstant(Step, StepRem, Factor, SE))
202       return false;
203     if (!StepRem->isZero())
204       return false;
205     const SCEV* Start = A->getStart();
206     if (!FactorOutConstant(Start, Remainder, Factor, SE))
207       return false;
208     S = SE.getAddRecExpr(Start, Step, A->getLoop());
209     return true;
210   }
211
212   return false;
213 }
214
215 /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
216 /// instead of using ptrtoint+arithmetic+inttoptr. This helps
217 /// BasicAliasAnalysis analyze the result. However, it suffers from the
218 /// underlying bug described in PR2831. Addition in LLVM currently always
219 /// has two's complement wrapping guaranteed. However, the semantics for
220 /// getelementptr overflow are ambiguous. In the common case though, this
221 /// expansion gets used when a GEP in the original code has been converted
222 /// into integer arithmetic, in which case the resulting code will be no
223 /// more undefined than it was originally.
224 ///
225 /// Design note: It might seem desirable for this function to be more
226 /// loop-aware. If some of the indices are loop-invariant while others
227 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
228 /// loop-invariant portions of the overall computation outside the loop.
229 /// However, there are a few reasons this is not done here. Hoisting simple
230 /// arithmetic is a low-level optimization that often isn't very
231 /// important until late in the optimization process. In fact, passes
232 /// like InstructionCombining will combine GEPs, even if it means
233 /// pushing loop-invariant computation down into loops, so even if the
234 /// GEPs were split here, the work would quickly be undone. The
235 /// LoopStrengthReduction pass, which is usually run quite late (and
236 /// after the last InstructionCombining pass), takes care of hoisting
237 /// loop-invariant portions of expressions, after considering what
238 /// can be folded using target addressing modes.
239 ///
240 Value *SCEVExpander::expandAddToGEP(const SCEV* const *op_begin,
241                                     const SCEV* const *op_end,
242                                     const PointerType *PTy,
243                                     const Type *Ty,
244                                     Value *V) {
245   const Type *ElTy = PTy->getElementType();
246   SmallVector<Value *, 4> GepIndices;
247   SmallVector<const SCEV*, 8> Ops(op_begin, op_end);
248   bool AnyNonZeroIndices = false;
249
250   // Decend down the pointer's type and attempt to convert the other
251   // operands into GEP indices, at each level. The first index in a GEP
252   // indexes into the array implied by the pointer operand; the rest of
253   // the indices index into the element or field type selected by the
254   // preceding index.
255   for (;;) {
256     APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
257                          ElTy->isSized() ?  SE.TD->getTypeAllocSize(ElTy) : 0);
258     SmallVector<const SCEV*, 8> NewOps;
259     SmallVector<const SCEV*, 8> ScaledOps;
260     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
261       // Split AddRecs up into parts as either of the parts may be usable
262       // without the other.
263       if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
264         if (!A->getStart()->isZero()) {
265           const SCEV* Start = A->getStart();
266           Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
267                                          A->getStepRecurrence(SE),
268                                          A->getLoop()));
269           Ops[i] = Start;
270           ++e;
271         }
272       // If the scale size is not 0, attempt to factor out a scale.
273       if (ElSize != 0) {
274         const SCEV* Op = Ops[i];
275         const SCEV* Remainder = SE.getIntegerSCEV(0, Op->getType());
276         if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
277           ScaledOps.push_back(Op); // Op now has ElSize factored out.
278           NewOps.push_back(Remainder);
279           continue;
280         }
281       }
282       // If the operand was not divisible, add it to the list of operands
283       // we'll scan next iteration.
284       NewOps.push_back(Ops[i]);
285     }
286     Ops = NewOps;
287     AnyNonZeroIndices |= !ScaledOps.empty();
288     Value *Scaled = ScaledOps.empty() ?
289                     Constant::getNullValue(Ty) :
290                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
291     GepIndices.push_back(Scaled);
292
293     // Collect struct field index operands.
294     if (!Ops.empty())
295       while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
296         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
297           if (SE.getTypeSizeInBits(C->getType()) <= 64) {
298             const StructLayout &SL = *SE.TD->getStructLayout(STy);
299             uint64_t FullOffset = C->getValue()->getZExtValue();
300             if (FullOffset < SL.getSizeInBytes()) {
301               unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
302               GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
303               ElTy = STy->getTypeAtIndex(ElIdx);
304               Ops[0] =
305                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
306               AnyNonZeroIndices = true;
307               continue;
308             }
309           }
310         break;
311       }
312
313     if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
314       ElTy = ATy->getElementType();
315       continue;
316     }
317     break;
318   }
319
320   // If none of the operands were convertable to proper GEP indices, cast
321   // the base to i8* and do an ugly getelementptr with that. It's still
322   // better than ptrtoint+arithmetic+inttoptr at least.
323   if (!AnyNonZeroIndices) {
324     V = InsertNoopCastOfTo(V,
325                            Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
326     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
327
328     // Fold a GEP with constant operands.
329     if (Constant *CLHS = dyn_cast<Constant>(V))
330       if (Constant *CRHS = dyn_cast<Constant>(Idx))
331         return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
332
333     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
334     unsigned ScanLimit = 6;
335     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
336     // Scanning starts from the last instruction before the insertion point.
337     BasicBlock::iterator IP = Builder.GetInsertPoint();
338     if (IP != BlockBegin) {
339       --IP;
340       for (; ScanLimit; --IP, --ScanLimit) {
341         if (IP->getOpcode() == Instruction::GetElementPtr &&
342             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
343           return IP;
344         if (IP == BlockBegin) break;
345       }
346     }
347
348     Value *GEP = Builder.CreateGEP(V, Idx, "scevgep");
349     InsertedValues.insert(GEP);
350     return GEP;
351   }
352
353   // Insert a pretty getelementptr.
354   Value *GEP = Builder.CreateGEP(V,
355                                  GepIndices.begin(),
356                                  GepIndices.end(),
357                                  "scevgep");
358   Ops.push_back(SE.getUnknown(GEP));
359   InsertedValues.insert(GEP);
360   return expand(SE.getAddExpr(Ops));
361 }
362
363 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
364   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
365   Value *V = expand(S->getOperand(S->getNumOperands()-1));
366
367   // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
368   // comments on expandAddToGEP for details.
369   if (SE.TD)
370     if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
371       const SmallVectorImpl<const SCEV*> &Ops = S->getOperands();
372       return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
373     }
374
375   V = InsertNoopCastOfTo(V, Ty);
376
377   // Emit a bunch of add instructions
378   for (int i = S->getNumOperands()-2; i >= 0; --i) {
379     Value *W = expandCodeFor(S->getOperand(i), Ty);
380     V = InsertBinop(Instruction::Add, V, W);
381   }
382   return V;
383 }
384
385 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
386   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
387   int FirstOp = 0;  // Set if we should emit a subtract.
388   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
389     if (SC->getValue()->isAllOnesValue())
390       FirstOp = 1;
391
392   int i = S->getNumOperands()-2;
393   Value *V = expandCodeFor(S->getOperand(i+1), Ty);
394
395   // Emit a bunch of multiply instructions
396   for (; i >= FirstOp; --i) {
397     Value *W = expandCodeFor(S->getOperand(i), Ty);
398     V = InsertBinop(Instruction::Mul, V, W);
399   }
400
401   // -1 * ...  --->  0 - ...
402   if (FirstOp == 1)
403     V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
404   return V;
405 }
406
407 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
408   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
409
410   Value *LHS = expandCodeFor(S->getLHS(), Ty);
411   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
412     const APInt &RHS = SC->getValue()->getValue();
413     if (RHS.isPowerOf2())
414       return InsertBinop(Instruction::LShr, LHS,
415                          ConstantInt::get(Ty, RHS.logBase2()));
416   }
417
418   Value *RHS = expandCodeFor(S->getRHS(), Ty);
419   return InsertBinop(Instruction::UDiv, LHS, RHS);
420 }
421
422 /// Move parts of Base into Rest to leave Base with the minimal
423 /// expression that provides a pointer operand suitable for a
424 /// GEP expansion.
425 static void ExposePointerBase(const SCEV* &Base, const SCEV* &Rest,
426                               ScalarEvolution &SE) {
427   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
428     Base = A->getStart();
429     Rest = SE.getAddExpr(Rest,
430                          SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
431                                           A->getStepRecurrence(SE),
432                                           A->getLoop()));
433   }
434   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
435     Base = A->getOperand(A->getNumOperands()-1);
436     SmallVector<const SCEV*, 8> NewAddOps(A->op_begin(), A->op_end());
437     NewAddOps.back() = Rest;
438     Rest = SE.getAddExpr(NewAddOps);
439     ExposePointerBase(Base, Rest, SE);
440   }
441 }
442
443 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
444   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
445   const Loop *L = S->getLoop();
446
447   // First check for an existing canonical IV in a suitable type.
448   PHINode *CanonicalIV = 0;
449   if (PHINode *PN = L->getCanonicalInductionVariable())
450     if (SE.isSCEVable(PN->getType()) &&
451         isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
452         SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
453       CanonicalIV = PN;
454
455   // Rewrite an AddRec in terms of the canonical induction variable, if
456   // its type is more narrow.
457   if (CanonicalIV &&
458       SE.getTypeSizeInBits(CanonicalIV->getType()) >
459       SE.getTypeSizeInBits(Ty)) {
460     const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
461                                             CanonicalIV->getType());
462     const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
463                                            CanonicalIV->getType());
464     Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
465     BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
466     BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
467     BasicBlock::iterator NewInsertPt =
468       next(BasicBlock::iterator(cast<Instruction>(V)));
469     while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
470     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
471                       NewInsertPt);
472     Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
473     return V;
474   }
475
476   // {X,+,F} --> X + {0,+,F}
477   if (!S->getStart()->isZero()) {
478     const SmallVectorImpl<const SCEV*> &SOperands = S->getOperands();
479     SmallVector<const SCEV*, 4> NewOps(SOperands.begin(), SOperands.end());
480     NewOps[0] = SE.getIntegerSCEV(0, Ty);
481     const SCEV* Rest = SE.getAddRecExpr(NewOps, L);
482
483     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
484     // comments on expandAddToGEP for details.
485     if (SE.TD) {
486       const SCEV* Base = S->getStart();
487       const SCEV* RestArray[1] = { Rest };
488       // Dig into the expression to find the pointer base for a GEP.
489       ExposePointerBase(Base, RestArray[0], SE);
490       // If we found a pointer, expand the AddRec with a GEP.
491       if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
492         // Make sure the Base isn't something exotic, such as a multiplied
493         // or divided pointer value. In those cases, the result type isn't
494         // actually a pointer type.
495         if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
496           Value *StartV = expand(Base);
497           assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
498           return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
499         }
500       }
501     }
502
503     // Just do a normal add. Pre-expand the operands to suppress folding.
504     return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
505                                 SE.getUnknown(expand(Rest))));
506   }
507
508   // {0,+,1} --> Insert a canonical induction variable into the loop!
509   if (S->isAffine() &&
510       S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
511     // If there's a canonical IV, just use it.
512     if (CanonicalIV) {
513       assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
514              "IVs with types different from the canonical IV should "
515              "already have been handled!");
516       return CanonicalIV;
517     }
518
519     // Create and insert the PHI node for the induction variable in the
520     // specified loop.
521     BasicBlock *Header = L->getHeader();
522     BasicBlock *Preheader = L->getLoopPreheader();
523     PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
524     InsertedValues.insert(PN);
525     PN->addIncoming(Constant::getNullValue(Ty), Preheader);
526
527     pred_iterator HPI = pred_begin(Header);
528     assert(HPI != pred_end(Header) && "Loop with zero preds???");
529     if (!L->contains(*HPI)) ++HPI;
530     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
531            "No backedge in loop?");
532
533     // Insert a unit add instruction right before the terminator corresponding
534     // to the back-edge.
535     Constant *One = ConstantInt::get(Ty, 1);
536     Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
537                                                  (*HPI)->getTerminator());
538     InsertedValues.insert(Add);
539
540     pred_iterator PI = pred_begin(Header);
541     if (*PI == Preheader)
542       ++PI;
543     PN->addIncoming(Add, *PI);
544     return PN;
545   }
546
547   // {0,+,F} --> {0,+,1} * F
548   // Get the canonical induction variable I for this loop.
549   Value *I = CanonicalIV ?
550              CanonicalIV :
551              getOrInsertCanonicalInductionVariable(L, Ty);
552
553   // If this is a simple linear addrec, emit it now as a special case.
554   if (S->isAffine())    // {0,+,F} --> i*F
555     return
556       expand(SE.getTruncateOrNoop(
557         SE.getMulExpr(SE.getUnknown(I),
558                       SE.getNoopOrAnyExtend(S->getOperand(1),
559                                             I->getType())),
560         Ty));
561
562   // If this is a chain of recurrences, turn it into a closed form, using the
563   // folders, then expandCodeFor the closed form.  This allows the folders to
564   // simplify the expression without having to build a bunch of special code
565   // into this folder.
566   const SCEV* IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
567
568   // Promote S up to the canonical IV type, if the cast is foldable.
569   const SCEV* NewS = S;
570   const SCEV* Ext = SE.getNoopOrAnyExtend(S, I->getType());
571   if (isa<SCEVAddRecExpr>(Ext))
572     NewS = Ext;
573
574   const SCEV* V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
575   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
576
577   // Truncate the result down to the original type, if needed.
578   const SCEV* T = SE.getTruncateOrNoop(V, Ty);
579   return expand(T);
580 }
581
582 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
583   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
584   Value *V = expandCodeFor(S->getOperand(),
585                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
586   Value *I = Builder.CreateTrunc(V, Ty, "tmp");
587   InsertedValues.insert(I);
588   return I;
589 }
590
591 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
592   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
593   Value *V = expandCodeFor(S->getOperand(),
594                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
595   Value *I = Builder.CreateZExt(V, Ty, "tmp");
596   InsertedValues.insert(I);
597   return I;
598 }
599
600 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
601   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
602   Value *V = expandCodeFor(S->getOperand(),
603                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
604   Value *I = Builder.CreateSExt(V, Ty, "tmp");
605   InsertedValues.insert(I);
606   return I;
607 }
608
609 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
610   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
611   Value *LHS = expandCodeFor(S->getOperand(0), Ty);
612   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
613     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
614     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
615     InsertedValues.insert(ICmp);
616     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
617     InsertedValues.insert(Sel);
618     LHS = Sel;
619   }
620   return LHS;
621 }
622
623 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
624   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
625   Value *LHS = expandCodeFor(S->getOperand(0), Ty);
626   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
627     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
628     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
629     InsertedValues.insert(ICmp);
630     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
631     InsertedValues.insert(Sel);
632     LHS = Sel;
633   }
634   return LHS;
635 }
636
637 Value *SCEVExpander::expandCodeFor(const SCEV* SH, const Type *Ty) {
638   // Expand the code for this SCEV.
639   Value *V = expand(SH);
640   if (Ty) {
641     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
642            "non-trivial casts should be done with the SCEVs directly!");
643     V = InsertNoopCastOfTo(V, Ty);
644   }
645   return V;
646 }
647
648 Value *SCEVExpander::expand(const SCEV *S) {
649   // Compute an insertion point for this SCEV object. Hoist the instructions
650   // as far out in the loop nest as possible.
651   Instruction *InsertPt = Builder.GetInsertPoint();
652   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
653        L = L->getParentLoop())
654     if (S->isLoopInvariant(L)) {
655       if (!L) break;
656       if (BasicBlock *Preheader = L->getLoopPreheader())
657         InsertPt = Preheader->getTerminator();
658     } else {
659       // If the SCEV is computable at this level, insert it into the header
660       // after the PHIs (and after any other instructions that we've inserted
661       // there) so that it is guaranteed to dominate any user inside the loop.
662       if (L && S->hasComputableLoopEvolution(L))
663         InsertPt = L->getHeader()->getFirstNonPHI();
664       while (isInsertedInstruction(InsertPt))
665         InsertPt = next(BasicBlock::iterator(InsertPt));
666       break;
667     }
668
669   // Check to see if we already expanded this here.
670   std::map<std::pair<const SCEV *, Instruction *>,
671            AssertingVH<Value> >::iterator I =
672     InsertedExpressions.find(std::make_pair(S, InsertPt));
673   if (I != InsertedExpressions.end())
674     return I->second;
675
676   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
677   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
678   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
679
680   // Expand the expression into instructions.
681   Value *V = visit(S);
682
683   // Remember the expanded value for this SCEV at this location.
684   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
685
686   Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
687   return V;
688 }
689
690 /// getOrInsertCanonicalInductionVariable - This method returns the
691 /// canonical induction variable of the specified type for the specified
692 /// loop (inserting one if there is none).  A canonical induction variable
693 /// starts at zero and steps by one on each iteration.
694 Value *
695 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
696                                                     const Type *Ty) {
697   assert(Ty->isInteger() && "Can only insert integer induction variables!");
698   const SCEV* H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
699                                    SE.getIntegerSCEV(1, Ty), L);
700   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
701   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
702   Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
703   if (SaveInsertBB)
704     Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
705   return V;
706 }