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