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