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