Don't skip debug instructions when looking for the insertion point of
[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/Support/Debug.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/ADT/STLExtras.h"
24
25 using namespace llvm;
26
27 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
28 /// reusing an existing cast if a suitable one exists, moving an existing
29 /// cast if a suitable one exists but isn't in the right place, or
30 /// creating a new one.
31 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
32                                        Instruction::CastOps Op,
33                                        BasicBlock::iterator IP) {
34   // All new or reused instructions must strictly dominate the Builder's
35   // InsertPt to ensure that the expression's expansion dominates its uses.
36   // Assert that the requested insertion point works at least for new
37   // instructions.
38   assert(SE.DT->dominates(IP, Builder.GetInsertPoint()));
39
40   // Check to see if there is already a cast!
41   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
42        UI != E; ++UI) {
43     User *U = *UI;
44     if (U->getType() == Ty)
45       if (CastInst *CI = dyn_cast<CastInst>(U))
46         if (CI->getOpcode() == Op) {
47           // If the cast isn't where we want it, fix it.
48           if (BasicBlock::iterator(CI) != IP
49               || IP == Builder.GetInsertPoint()) {
50             // Create a new cast, and leave the old cast in place in case
51             // it is being used as an insert point. Clear its operand
52             // so that it doesn't hold anything live.
53             Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
54             NewCI->takeName(CI);
55             CI->replaceAllUsesWith(NewCI);
56             CI->setOperand(0, UndefValue::get(V->getType()));
57             rememberInstruction(NewCI);
58             return NewCI;
59           }
60           rememberInstruction(CI);
61           return CI;
62         }
63   }
64
65   // Create a new cast.
66   Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
67   rememberInstruction(I);
68   return I;
69 }
70
71 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
72 /// which must be possible with a noop cast, doing what we can to share
73 /// the casts.
74 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
75   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
76   assert((Op == Instruction::BitCast ||
77           Op == Instruction::PtrToInt ||
78           Op == Instruction::IntToPtr) &&
79          "InsertNoopCastOfTo cannot perform non-noop casts!");
80   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
81          "InsertNoopCastOfTo cannot change sizes!");
82
83   // Short-circuit unnecessary bitcasts.
84   if (Op == Instruction::BitCast) {
85     if (V->getType() == Ty)
86       return V;
87     if (CastInst *CI = dyn_cast<CastInst>(V)) {
88       if (CI->getOperand(0)->getType() == Ty)
89         return CI->getOperand(0);
90     }
91   }
92   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
93   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
94       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
95     if (CastInst *CI = dyn_cast<CastInst>(V))
96       if ((CI->getOpcode() == Instruction::PtrToInt ||
97            CI->getOpcode() == Instruction::IntToPtr) &&
98           SE.getTypeSizeInBits(CI->getType()) ==
99           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
100         return CI->getOperand(0);
101     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
102       if ((CE->getOpcode() == Instruction::PtrToInt ||
103            CE->getOpcode() == Instruction::IntToPtr) &&
104           SE.getTypeSizeInBits(CE->getType()) ==
105           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
106         return CE->getOperand(0);
107   }
108
109   // Fold a cast of a constant.
110   if (Constant *C = dyn_cast<Constant>(V))
111     return ConstantExpr::getCast(Op, C, Ty);
112
113   // Cast the argument at the beginning of the entry block, after
114   // any bitcasts of other arguments.
115   if (Argument *A = dyn_cast<Argument>(V)) {
116     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
117     while ((isa<BitCastInst>(IP) &&
118             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
119             cast<BitCastInst>(IP)->getOperand(0) != A) ||
120            isa<DbgInfoIntrinsic>(IP) ||
121            isa<LandingPadInst>(IP))
122       ++IP;
123     return ReuseOrCreateCast(A, Ty, Op, IP);
124   }
125
126   // Cast the instruction immediately after the instruction.
127   Instruction *I = cast<Instruction>(V);
128   BasicBlock::iterator IP = I; ++IP;
129   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
130     IP = II->getNormalDest()->begin();
131   while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
132     ++IP;
133   return ReuseOrCreateCast(I, Ty, Op, IP);
134 }
135
136 /// InsertBinop - Insert the specified binary operator, doing a small amount
137 /// of work to avoid inserting an obviously redundant operation.
138 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
139                                  Value *LHS, Value *RHS) {
140   // Fold a binop with constant operands.
141   if (Constant *CLHS = dyn_cast<Constant>(LHS))
142     if (Constant *CRHS = dyn_cast<Constant>(RHS))
143       return ConstantExpr::get(Opcode, CLHS, CRHS);
144
145   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
146   unsigned ScanLimit = 6;
147   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
148   // Scanning starts from the last instruction before the insertion point.
149   BasicBlock::iterator IP = Builder.GetInsertPoint();
150   if (IP != BlockBegin) {
151     --IP;
152     for (; ScanLimit; --IP, --ScanLimit) {
153       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
154       // generated code.
155       if (isa<DbgInfoIntrinsic>(IP))
156         ScanLimit++;
157       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
158           IP->getOperand(1) == RHS)
159         return IP;
160       if (IP == BlockBegin) break;
161     }
162   }
163
164   // Save the original insertion point so we can restore it when we're done.
165   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
166   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
167
168   // Move the insertion point out of as many loops as we can.
169   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
170     if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
171     BasicBlock *Preheader = L->getLoopPreheader();
172     if (!Preheader) break;
173
174     // Ok, move up a level.
175     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
176   }
177
178   // If we haven't found this binop, insert it.
179   Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
180   BO->setDebugLoc(SaveInsertPt->getDebugLoc());
181   rememberInstruction(BO);
182
183   // Restore the original insert point.
184   if (SaveInsertBB)
185     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
186
187   return BO;
188 }
189
190 /// FactorOutConstant - Test if S is divisible by Factor, using signed
191 /// division. If so, update S with Factor divided out and return true.
192 /// S need not be evenly divisible if a reasonable remainder can be
193 /// computed.
194 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
195 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
196 /// check to see if the divide was folded.
197 static bool FactorOutConstant(const SCEV *&S,
198                               const SCEV *&Remainder,
199                               const SCEV *Factor,
200                               ScalarEvolution &SE,
201                               const TargetData *TD) {
202   // Everything is divisible by one.
203   if (Factor->isOne())
204     return true;
205
206   // x/x == 1.
207   if (S == Factor) {
208     S = SE.getConstant(S->getType(), 1);
209     return true;
210   }
211
212   // For a Constant, check for a multiple of the given factor.
213   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
214     // 0/x == 0.
215     if (C->isZero())
216       return true;
217     // Check for divisibility.
218     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
219       ConstantInt *CI =
220         ConstantInt::get(SE.getContext(),
221                          C->getValue()->getValue().sdiv(
222                                                    FC->getValue()->getValue()));
223       // If the quotient is zero and the remainder is non-zero, reject
224       // the value at this scale. It will be considered for subsequent
225       // smaller scales.
226       if (!CI->isZero()) {
227         const SCEV *Div = SE.getConstant(CI);
228         S = Div;
229         Remainder =
230           SE.getAddExpr(Remainder,
231                         SE.getConstant(C->getValue()->getValue().srem(
232                                                   FC->getValue()->getValue())));
233         return true;
234       }
235     }
236   }
237
238   // In a Mul, check if there is a constant operand which is a multiple
239   // of the given factor.
240   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
241     if (TD) {
242       // With TargetData, the size is known. Check if there is a constant
243       // operand which is a multiple of the given factor. If so, we can
244       // factor it.
245       const SCEVConstant *FC = cast<SCEVConstant>(Factor);
246       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
247         if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
248           SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
249           NewMulOps[0] =
250             SE.getConstant(C->getValue()->getValue().sdiv(
251                                                    FC->getValue()->getValue()));
252           S = SE.getMulExpr(NewMulOps);
253           return true;
254         }
255     } else {
256       // Without TargetData, check if Factor can be factored out of any of the
257       // Mul's operands. If so, we can just remove it.
258       for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
259         const SCEV *SOp = M->getOperand(i);
260         const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
261         if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
262             Remainder->isZero()) {
263           SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
264           NewMulOps[i] = SOp;
265           S = SE.getMulExpr(NewMulOps);
266           return true;
267         }
268       }
269     }
270   }
271
272   // In an AddRec, check if both start and step are divisible.
273   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
274     const SCEV *Step = A->getStepRecurrence(SE);
275     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
276     if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
277       return false;
278     if (!StepRem->isZero())
279       return false;
280     const SCEV *Start = A->getStart();
281     if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
282       return false;
283     // FIXME: can use A->getNoWrapFlags(FlagNW)
284     S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
285     return true;
286   }
287
288   return false;
289 }
290
291 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
292 /// is the number of SCEVAddRecExprs present, which are kept at the end of
293 /// the list.
294 ///
295 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
296                                 Type *Ty,
297                                 ScalarEvolution &SE) {
298   unsigned NumAddRecs = 0;
299   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
300     ++NumAddRecs;
301   // Group Ops into non-addrecs and addrecs.
302   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
303   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
304   // Let ScalarEvolution sort and simplify the non-addrecs list.
305   const SCEV *Sum = NoAddRecs.empty() ?
306                     SE.getConstant(Ty, 0) :
307                     SE.getAddExpr(NoAddRecs);
308   // If it returned an add, use the operands. Otherwise it simplified
309   // the sum into a single value, so just use that.
310   Ops.clear();
311   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
312     Ops.append(Add->op_begin(), Add->op_end());
313   else if (!Sum->isZero())
314     Ops.push_back(Sum);
315   // Then append the addrecs.
316   Ops.append(AddRecs.begin(), AddRecs.end());
317 }
318
319 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
320 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
321 /// This helps expose more opportunities for folding parts of the expressions
322 /// into GEP indices.
323 ///
324 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
325                          Type *Ty,
326                          ScalarEvolution &SE) {
327   // Find the addrecs.
328   SmallVector<const SCEV *, 8> AddRecs;
329   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
330     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
331       const SCEV *Start = A->getStart();
332       if (Start->isZero()) break;
333       const SCEV *Zero = SE.getConstant(Ty, 0);
334       AddRecs.push_back(SE.getAddRecExpr(Zero,
335                                          A->getStepRecurrence(SE),
336                                          A->getLoop(),
337                                          // FIXME: A->getNoWrapFlags(FlagNW)
338                                          SCEV::FlagAnyWrap));
339       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
340         Ops[i] = Zero;
341         Ops.append(Add->op_begin(), Add->op_end());
342         e += Add->getNumOperands();
343       } else {
344         Ops[i] = Start;
345       }
346     }
347   if (!AddRecs.empty()) {
348     // Add the addrecs onto the end of the list.
349     Ops.append(AddRecs.begin(), AddRecs.end());
350     // Resort the operand list, moving any constants to the front.
351     SimplifyAddOperands(Ops, Ty, SE);
352   }
353 }
354
355 /// expandAddToGEP - Expand an addition expression with a pointer type into
356 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
357 /// BasicAliasAnalysis and other passes analyze the result. See the rules
358 /// for getelementptr vs. inttoptr in
359 /// http://llvm.org/docs/LangRef.html#pointeraliasing
360 /// for details.
361 ///
362 /// Design note: The correctness of using getelementptr here depends on
363 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
364 /// they may introduce pointer arithmetic which may not be safely converted
365 /// into getelementptr.
366 ///
367 /// Design note: It might seem desirable for this function to be more
368 /// loop-aware. If some of the indices are loop-invariant while others
369 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
370 /// loop-invariant portions of the overall computation outside the loop.
371 /// However, there are a few reasons this is not done here. Hoisting simple
372 /// arithmetic is a low-level optimization that often isn't very
373 /// important until late in the optimization process. In fact, passes
374 /// like InstructionCombining will combine GEPs, even if it means
375 /// pushing loop-invariant computation down into loops, so even if the
376 /// GEPs were split here, the work would quickly be undone. The
377 /// LoopStrengthReduction pass, which is usually run quite late (and
378 /// after the last InstructionCombining pass), takes care of hoisting
379 /// loop-invariant portions of expressions, after considering what
380 /// can be folded using target addressing modes.
381 ///
382 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
383                                     const SCEV *const *op_end,
384                                     PointerType *PTy,
385                                     Type *Ty,
386                                     Value *V) {
387   Type *ElTy = PTy->getElementType();
388   SmallVector<Value *, 4> GepIndices;
389   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
390   bool AnyNonZeroIndices = false;
391
392   // Split AddRecs up into parts as either of the parts may be usable
393   // without the other.
394   SplitAddRecs(Ops, Ty, SE);
395
396   // Descend down the pointer's type and attempt to convert the other
397   // operands into GEP indices, at each level. The first index in a GEP
398   // indexes into the array implied by the pointer operand; the rest of
399   // the indices index into the element or field type selected by the
400   // preceding index.
401   for (;;) {
402     // If the scale size is not 0, attempt to factor out a scale for
403     // array indexing.
404     SmallVector<const SCEV *, 8> ScaledOps;
405     if (ElTy->isSized()) {
406       const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
407       if (!ElSize->isZero()) {
408         SmallVector<const SCEV *, 8> NewOps;
409         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
410           const SCEV *Op = Ops[i];
411           const SCEV *Remainder = SE.getConstant(Ty, 0);
412           if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
413             // Op now has ElSize factored out.
414             ScaledOps.push_back(Op);
415             if (!Remainder->isZero())
416               NewOps.push_back(Remainder);
417             AnyNonZeroIndices = true;
418           } else {
419             // The operand was not divisible, so add it to the list of operands
420             // we'll scan next iteration.
421             NewOps.push_back(Ops[i]);
422           }
423         }
424         // If we made any changes, update Ops.
425         if (!ScaledOps.empty()) {
426           Ops = NewOps;
427           SimplifyAddOperands(Ops, Ty, SE);
428         }
429       }
430     }
431
432     // Record the scaled array index for this level of the type. If
433     // we didn't find any operands that could be factored, tentatively
434     // assume that element zero was selected (since the zero offset
435     // would obviously be folded away).
436     Value *Scaled = ScaledOps.empty() ?
437                     Constant::getNullValue(Ty) :
438                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
439     GepIndices.push_back(Scaled);
440
441     // Collect struct field index operands.
442     while (StructType *STy = dyn_cast<StructType>(ElTy)) {
443       bool FoundFieldNo = false;
444       // An empty struct has no fields.
445       if (STy->getNumElements() == 0) break;
446       if (SE.TD) {
447         // With TargetData, field offsets are known. See if a constant offset
448         // falls within any of the struct fields.
449         if (Ops.empty()) break;
450         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
451           if (SE.getTypeSizeInBits(C->getType()) <= 64) {
452             const StructLayout &SL = *SE.TD->getStructLayout(STy);
453             uint64_t FullOffset = C->getValue()->getZExtValue();
454             if (FullOffset < SL.getSizeInBytes()) {
455               unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
456               GepIndices.push_back(
457                   ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
458               ElTy = STy->getTypeAtIndex(ElIdx);
459               Ops[0] =
460                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
461               AnyNonZeroIndices = true;
462               FoundFieldNo = true;
463             }
464           }
465       } else {
466         // Without TargetData, just check for an offsetof expression of the
467         // appropriate struct type.
468         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
469           if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
470             Type *CTy;
471             Constant *FieldNo;
472             if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
473               GepIndices.push_back(FieldNo);
474               ElTy =
475                 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
476               Ops[i] = SE.getConstant(Ty, 0);
477               AnyNonZeroIndices = true;
478               FoundFieldNo = true;
479               break;
480             }
481           }
482       }
483       // If no struct field offsets were found, tentatively assume that
484       // field zero was selected (since the zero offset would obviously
485       // be folded away).
486       if (!FoundFieldNo) {
487         ElTy = STy->getTypeAtIndex(0u);
488         GepIndices.push_back(
489           Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
490       }
491     }
492
493     if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
494       ElTy = ATy->getElementType();
495     else
496       break;
497   }
498
499   // If none of the operands were convertible to proper GEP indices, cast
500   // the base to i8* and do an ugly getelementptr with that. It's still
501   // better than ptrtoint+arithmetic+inttoptr at least.
502   if (!AnyNonZeroIndices) {
503     // Cast the base to i8*.
504     V = InsertNoopCastOfTo(V,
505        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
506
507     // Expand the operands for a plain byte offset.
508     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
509
510     // Fold a GEP with constant operands.
511     if (Constant *CLHS = dyn_cast<Constant>(V))
512       if (Constant *CRHS = dyn_cast<Constant>(Idx))
513         return ConstantExpr::getGetElementPtr(CLHS, CRHS);
514
515     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
516     unsigned ScanLimit = 6;
517     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
518     // Scanning starts from the last instruction before the insertion point.
519     BasicBlock::iterator IP = Builder.GetInsertPoint();
520     if (IP != BlockBegin) {
521       --IP;
522       for (; ScanLimit; --IP, --ScanLimit) {
523         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
524         // generated code.
525         if (isa<DbgInfoIntrinsic>(IP))
526           ScanLimit++;
527         if (IP->getOpcode() == Instruction::GetElementPtr &&
528             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
529           return IP;
530         if (IP == BlockBegin) break;
531       }
532     }
533
534     // Save the original insertion point so we can restore it when we're done.
535     BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
536     BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
537
538     // Move the insertion point out of as many loops as we can.
539     while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
540       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
541       BasicBlock *Preheader = L->getLoopPreheader();
542       if (!Preheader) break;
543
544       // Ok, move up a level.
545       Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
546     }
547
548     // Emit a GEP.
549     Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
550     rememberInstruction(GEP);
551
552     // Restore the original insert point.
553     if (SaveInsertBB)
554       restoreInsertPoint(SaveInsertBB, SaveInsertPt);
555
556     return GEP;
557   }
558
559   // Save the original insertion point so we can restore it when we're done.
560   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
561   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
562
563   // Move the insertion point out of as many loops as we can.
564   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
565     if (!L->isLoopInvariant(V)) break;
566
567     bool AnyIndexNotLoopInvariant = false;
568     for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
569          E = GepIndices.end(); I != E; ++I)
570       if (!L->isLoopInvariant(*I)) {
571         AnyIndexNotLoopInvariant = true;
572         break;
573       }
574     if (AnyIndexNotLoopInvariant)
575       break;
576
577     BasicBlock *Preheader = L->getLoopPreheader();
578     if (!Preheader) break;
579
580     // Ok, move up a level.
581     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
582   }
583
584   // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
585   // because ScalarEvolution may have changed the address arithmetic to
586   // compute a value which is beyond the end of the allocated object.
587   Value *Casted = V;
588   if (V->getType() != PTy)
589     Casted = InsertNoopCastOfTo(Casted, PTy);
590   Value *GEP = Builder.CreateGEP(Casted,
591                                  GepIndices,
592                                  "scevgep");
593   Ops.push_back(SE.getUnknown(GEP));
594   rememberInstruction(GEP);
595
596   // Restore the original insert point.
597   if (SaveInsertBB)
598     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
599
600   return expand(SE.getAddExpr(Ops));
601 }
602
603 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
604 /// SCEV expansion. If they are nested, this is the most nested. If they are
605 /// neighboring, pick the later.
606 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
607                                         DominatorTree &DT) {
608   if (!A) return B;
609   if (!B) return A;
610   if (A->contains(B)) return B;
611   if (B->contains(A)) return A;
612   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
613   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
614   return A; // Arbitrarily break the tie.
615 }
616
617 /// getRelevantLoop - Get the most relevant loop associated with the given
618 /// expression, according to PickMostRelevantLoop.
619 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
620   // Test whether we've already computed the most relevant loop for this SCEV.
621   std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
622     RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
623   if (!Pair.second)
624     return Pair.first->second;
625
626   if (isa<SCEVConstant>(S))
627     // A constant has no relevant loops.
628     return 0;
629   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
630     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
631       return Pair.first->second = SE.LI->getLoopFor(I->getParent());
632     // A non-instruction has no relevant loops.
633     return 0;
634   }
635   if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
636     const Loop *L = 0;
637     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
638       L = AR->getLoop();
639     for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
640          I != E; ++I)
641       L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
642     return RelevantLoops[N] = L;
643   }
644   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
645     const Loop *Result = getRelevantLoop(C->getOperand());
646     return RelevantLoops[C] = Result;
647   }
648   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
649     const Loop *Result =
650       PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
651                            getRelevantLoop(D->getRHS()),
652                            *SE.DT);
653     return RelevantLoops[D] = Result;
654   }
655   llvm_unreachable("Unexpected SCEV type!");
656 }
657
658 namespace {
659
660 /// LoopCompare - Compare loops by PickMostRelevantLoop.
661 class LoopCompare {
662   DominatorTree &DT;
663 public:
664   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
665
666   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
667                   std::pair<const Loop *, const SCEV *> RHS) const {
668     // Keep pointer operands sorted at the end.
669     if (LHS.second->getType()->isPointerTy() !=
670         RHS.second->getType()->isPointerTy())
671       return LHS.second->getType()->isPointerTy();
672
673     // Compare loops with PickMostRelevantLoop.
674     if (LHS.first != RHS.first)
675       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
676
677     // If one operand is a non-constant negative and the other is not,
678     // put the non-constant negative on the right so that a sub can
679     // be used instead of a negate and add.
680     if (LHS.second->isNonConstantNegative()) {
681       if (!RHS.second->isNonConstantNegative())
682         return false;
683     } else if (RHS.second->isNonConstantNegative())
684       return true;
685
686     // Otherwise they are equivalent according to this comparison.
687     return false;
688   }
689 };
690
691 }
692
693 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
694   Type *Ty = SE.getEffectiveSCEVType(S->getType());
695
696   // Collect all the add operands in a loop, along with their associated loops.
697   // Iterate in reverse so that constants are emitted last, all else equal, and
698   // so that pointer operands are inserted first, which the code below relies on
699   // to form more involved GEPs.
700   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
701   for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
702        E(S->op_begin()); I != E; ++I)
703     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
704
705   // Sort by loop. Use a stable sort so that constants follow non-constants and
706   // pointer operands precede non-pointer operands.
707   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
708
709   // Emit instructions to add all the operands. Hoist as much as possible
710   // out of loops, and form meaningful getelementptrs where possible.
711   Value *Sum = 0;
712   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
713        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
714     const Loop *CurLoop = I->first;
715     const SCEV *Op = I->second;
716     if (!Sum) {
717       // This is the first operand. Just expand it.
718       Sum = expand(Op);
719       ++I;
720     } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
721       // The running sum expression is a pointer. Try to form a getelementptr
722       // at this level with that as the base.
723       SmallVector<const SCEV *, 4> NewOps;
724       for (; I != E && I->first == CurLoop; ++I) {
725         // If the operand is SCEVUnknown and not instructions, peek through
726         // it, to enable more of it to be folded into the GEP.
727         const SCEV *X = I->second;
728         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
729           if (!isa<Instruction>(U->getValue()))
730             X = SE.getSCEV(U->getValue());
731         NewOps.push_back(X);
732       }
733       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
734     } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
735       // The running sum is an integer, and there's a pointer at this level.
736       // Try to form a getelementptr. If the running sum is instructions,
737       // use a SCEVUnknown to avoid re-analyzing them.
738       SmallVector<const SCEV *, 4> NewOps;
739       NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
740                                                SE.getSCEV(Sum));
741       for (++I; I != E && I->first == CurLoop; ++I)
742         NewOps.push_back(I->second);
743       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
744     } else if (Op->isNonConstantNegative()) {
745       // Instead of doing a negate and add, just do a subtract.
746       Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
747       Sum = InsertNoopCastOfTo(Sum, Ty);
748       Sum = InsertBinop(Instruction::Sub, Sum, W);
749       ++I;
750     } else {
751       // A simple add.
752       Value *W = expandCodeFor(Op, Ty);
753       Sum = InsertNoopCastOfTo(Sum, Ty);
754       // Canonicalize a constant to the RHS.
755       if (isa<Constant>(Sum)) std::swap(Sum, W);
756       Sum = InsertBinop(Instruction::Add, Sum, W);
757       ++I;
758     }
759   }
760
761   return Sum;
762 }
763
764 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
765   Type *Ty = SE.getEffectiveSCEVType(S->getType());
766
767   // Collect all the mul operands in a loop, along with their associated loops.
768   // Iterate in reverse so that constants are emitted last, all else equal.
769   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
770   for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
771        E(S->op_begin()); I != E; ++I)
772     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
773
774   // Sort by loop. Use a stable sort so that constants follow non-constants.
775   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
776
777   // Emit instructions to mul all the operands. Hoist as much as possible
778   // out of loops.
779   Value *Prod = 0;
780   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
781        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
782     const SCEV *Op = I->second;
783     if (!Prod) {
784       // This is the first operand. Just expand it.
785       Prod = expand(Op);
786       ++I;
787     } else if (Op->isAllOnesValue()) {
788       // Instead of doing a multiply by negative one, just do a negate.
789       Prod = InsertNoopCastOfTo(Prod, Ty);
790       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
791       ++I;
792     } else {
793       // A simple mul.
794       Value *W = expandCodeFor(Op, Ty);
795       Prod = InsertNoopCastOfTo(Prod, Ty);
796       // Canonicalize a constant to the RHS.
797       if (isa<Constant>(Prod)) std::swap(Prod, W);
798       Prod = InsertBinop(Instruction::Mul, Prod, W);
799       ++I;
800     }
801   }
802
803   return Prod;
804 }
805
806 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
807   Type *Ty = SE.getEffectiveSCEVType(S->getType());
808
809   Value *LHS = expandCodeFor(S->getLHS(), Ty);
810   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
811     const APInt &RHS = SC->getValue()->getValue();
812     if (RHS.isPowerOf2())
813       return InsertBinop(Instruction::LShr, LHS,
814                          ConstantInt::get(Ty, RHS.logBase2()));
815   }
816
817   Value *RHS = expandCodeFor(S->getRHS(), Ty);
818   return InsertBinop(Instruction::UDiv, LHS, RHS);
819 }
820
821 /// Move parts of Base into Rest to leave Base with the minimal
822 /// expression that provides a pointer operand suitable for a
823 /// GEP expansion.
824 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
825                               ScalarEvolution &SE) {
826   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
827     Base = A->getStart();
828     Rest = SE.getAddExpr(Rest,
829                          SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
830                                           A->getStepRecurrence(SE),
831                                           A->getLoop(),
832                                           // FIXME: A->getNoWrapFlags(FlagNW)
833                                           SCEV::FlagAnyWrap));
834   }
835   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
836     Base = A->getOperand(A->getNumOperands()-1);
837     SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
838     NewAddOps.back() = Rest;
839     Rest = SE.getAddExpr(NewAddOps);
840     ExposePointerBase(Base, Rest, SE);
841   }
842 }
843
844 /// Determine if this is a well-behaved chain of instructions leading back to
845 /// the PHI. If so, it may be reused by expanded expressions.
846 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
847                                          const Loop *L) {
848   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
849       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
850     return false;
851   // If any of the operands don't dominate the insert position, bail.
852   // Addrec operands are always loop-invariant, so this can only happen
853   // if there are instructions which haven't been hoisted.
854   if (L == IVIncInsertLoop) {
855     for (User::op_iterator OI = IncV->op_begin()+1,
856            OE = IncV->op_end(); OI != OE; ++OI)
857       if (Instruction *OInst = dyn_cast<Instruction>(OI))
858         if (!SE.DT->dominates(OInst, IVIncInsertPos))
859           return false;
860   }
861   // Advance to the next instruction.
862   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
863   if (!IncV)
864     return false;
865
866   if (IncV->mayHaveSideEffects())
867     return false;
868
869   if (IncV != PN)
870     return true;
871
872   return isNormalAddRecExprPHI(PN, IncV, L);
873 }
874
875 /// getIVIncOperand returns an induction variable increment's induction
876 /// variable operand.
877 ///
878 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
879 /// operands dominate InsertPos.
880 ///
881 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
882 /// simple patterns generated by getAddRecExprPHILiterally and
883 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
884 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
885                                            Instruction *InsertPos,
886                                            bool allowScale) {
887   if (IncV == InsertPos)
888     return NULL;
889
890   switch (IncV->getOpcode()) {
891   default:
892     return NULL;
893   // Check for a simple Add/Sub or GEP of a loop invariant step.
894   case Instruction::Add:
895   case Instruction::Sub: {
896     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
897     if (!OInst || SE.DT->properlyDominates(OInst, InsertPos))
898       return dyn_cast<Instruction>(IncV->getOperand(0));
899     return NULL;
900   }
901   case Instruction::BitCast:
902     return dyn_cast<Instruction>(IncV->getOperand(0));
903   case Instruction::GetElementPtr:
904     for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
905          I != E; ++I) {
906       if (isa<Constant>(*I))
907         continue;
908       if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
909         if (!SE.DT->properlyDominates(OInst, InsertPos))
910           return NULL;
911       }
912       if (allowScale) {
913         // allow any kind of GEP as long as it can be hoisted.
914         continue;
915       }
916       // This must be a pointer addition of constants (pretty), which is already
917       // handled, or some number of address-size elements (ugly). Ugly geps
918       // have 2 operands. i1* is used by the expander to represent an
919       // address-size element.
920       if (IncV->getNumOperands() != 2)
921         return NULL;
922       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
923       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
924           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
925         return NULL;
926       break;
927     }
928     return dyn_cast<Instruction>(IncV->getOperand(0));
929   }
930 }
931
932 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
933 /// it available to other uses in this loop. Recursively hoist any operands,
934 /// until we reach a value that dominates InsertPos.
935 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
936   if (SE.DT->properlyDominates(IncV, InsertPos))
937       return true;
938
939   // InsertPos must itself dominate IncV so that IncV's new position satisfies
940   // its existing users.
941   if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
942     return false;
943
944   // Check that the chain of IV operands leading back to Phi can be hoisted.
945   SmallVector<Instruction*, 4> IVIncs;
946   for(;;) {
947     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
948     if (!Oper)
949       return false;
950     // IncV is safe to hoist.
951     IVIncs.push_back(IncV);
952     IncV = Oper;
953     if (SE.DT->properlyDominates(IncV, InsertPos))
954       break;
955   }
956   for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
957          E = IVIncs.rend(); I != E; ++I) {
958     (*I)->moveBefore(InsertPos);
959   }
960   return true;
961 }
962
963 /// Determine if this cyclic phi is in a form that would have been generated by
964 /// LSR. We don't care if the phi was actually expanded in this pass, as long
965 /// as it is in a low-cost form, for example, no implied multiplication. This
966 /// should match any patterns generated by getAddRecExprPHILiterally and
967 /// expandAddtoGEP.
968 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
969                                            const Loop *L) {
970   for(Instruction *IVOper = IncV;
971       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
972                                 /*allowScale=*/false));) {
973     if (IVOper == PN)
974       return true;
975   }
976   return false;
977 }
978
979 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
980 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
981 /// need to materialize IV increments elsewhere to handle difficult situations.
982 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
983                                  Type *ExpandTy, Type *IntTy,
984                                  bool useSubtract) {
985   Value *IncV;
986   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
987   if (ExpandTy->isPointerTy()) {
988     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
989     // If the step isn't constant, don't use an implicitly scaled GEP, because
990     // that would require a multiply inside the loop.
991     if (!isa<ConstantInt>(StepV))
992       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
993                                   GEPPtrTy->getAddressSpace());
994     const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
995     IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
996     if (IncV->getType() != PN->getType()) {
997       IncV = Builder.CreateBitCast(IncV, PN->getType());
998       rememberInstruction(IncV);
999     }
1000   } else {
1001     IncV = useSubtract ?
1002       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1003       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1004     rememberInstruction(IncV);
1005   }
1006   return IncV;
1007 }
1008
1009 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1010 /// the base addrec, which is the addrec without any non-loop-dominating
1011 /// values, and return the PHI.
1012 PHINode *
1013 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1014                                         const Loop *L,
1015                                         Type *ExpandTy,
1016                                         Type *IntTy) {
1017   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1018
1019   // Reuse a previously-inserted PHI, if present.
1020   BasicBlock *LatchBlock = L->getLoopLatch();
1021   if (LatchBlock) {
1022     for (BasicBlock::iterator I = L->getHeader()->begin();
1023          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1024       if (!SE.isSCEVable(PN->getType()) ||
1025           (SE.getEffectiveSCEVType(PN->getType()) !=
1026            SE.getEffectiveSCEVType(Normalized->getType())) ||
1027           SE.getSCEV(PN) != Normalized)
1028         continue;
1029
1030       Instruction *IncV =
1031         cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1032
1033       if (LSRMode) {
1034         if (!isExpandedAddRecExprPHI(PN, IncV, L))
1035           continue;
1036         if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1037           continue;
1038       }
1039       else {
1040         if (!isNormalAddRecExprPHI(PN, IncV, L))
1041           continue;
1042         if (L == IVIncInsertLoop)
1043           do {
1044             if (SE.DT->dominates(IncV, IVIncInsertPos))
1045               break;
1046             // Make sure the increment is where we want it. But don't move it
1047             // down past a potential existing post-inc user.
1048             IncV->moveBefore(IVIncInsertPos);
1049             IVIncInsertPos = IncV;
1050             IncV = cast<Instruction>(IncV->getOperand(0));
1051           } while (IncV != PN);
1052       }
1053       // Ok, the add recurrence looks usable.
1054       // Remember this PHI, even in post-inc mode.
1055       InsertedValues.insert(PN);
1056       // Remember the increment.
1057       rememberInstruction(IncV);
1058       return PN;
1059     }
1060   }
1061
1062   // Save the original insertion point so we can restore it when we're done.
1063   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1064   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1065
1066   // Another AddRec may need to be recursively expanded below. For example, if
1067   // this AddRec is quadratic, the StepV may itself be an AddRec in this
1068   // loop. Remove this loop from the PostIncLoops set before expanding such
1069   // AddRecs. Otherwise, we cannot find a valid position for the step
1070   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1071   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1072   // so it's not worth implementing SmallPtrSet::swap.
1073   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1074   PostIncLoops.clear();
1075
1076   // Expand code for the start value.
1077   Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1078                                 L->getHeader()->begin());
1079
1080   // StartV must be hoisted into L's preheader to dominate the new phi.
1081   assert(!isa<Instruction>(StartV) ||
1082          SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1083                                   L->getHeader()));
1084
1085   // Expand code for the step value. Do this before creating the PHI so that PHI
1086   // reuse code doesn't see an incomplete PHI.
1087   const SCEV *Step = Normalized->getStepRecurrence(SE);
1088   // If the stride is negative, insert a sub instead of an add for the increment
1089   // (unless it's a constant, because subtracts of constants are canonicalized
1090   // to adds).
1091   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1092   if (useSubtract)
1093     Step = SE.getNegativeSCEV(Step);
1094   // Expand the step somewhere that dominates the loop header.
1095   Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1096
1097   // Create the PHI.
1098   BasicBlock *Header = L->getHeader();
1099   Builder.SetInsertPoint(Header, Header->begin());
1100   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1101   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1102                                   Twine(IVName) + ".iv");
1103   rememberInstruction(PN);
1104
1105   // Create the step instructions and populate the PHI.
1106   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1107     BasicBlock *Pred = *HPI;
1108
1109     // Add a start value.
1110     if (!L->contains(Pred)) {
1111       PN->addIncoming(StartV, Pred);
1112       continue;
1113     }
1114
1115     // Create a step value and add it to the PHI.
1116     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1117     // instructions at IVIncInsertPos.
1118     Instruction *InsertPos = L == IVIncInsertLoop ?
1119       IVIncInsertPos : Pred->getTerminator();
1120     Builder.SetInsertPoint(InsertPos);
1121     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1122
1123     PN->addIncoming(IncV, Pred);
1124   }
1125
1126   // Restore the original insert point.
1127   if (SaveInsertBB)
1128     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1129
1130   // After expanding subexpressions, restore the PostIncLoops set so the caller
1131   // can ensure that IVIncrement dominates the current uses.
1132   PostIncLoops = SavedPostIncLoops;
1133
1134   // Remember this PHI, even in post-inc mode.
1135   InsertedValues.insert(PN);
1136
1137   return PN;
1138 }
1139
1140 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1141   Type *STy = S->getType();
1142   Type *IntTy = SE.getEffectiveSCEVType(STy);
1143   const Loop *L = S->getLoop();
1144
1145   // Determine a normalized form of this expression, which is the expression
1146   // before any post-inc adjustment is made.
1147   const SCEVAddRecExpr *Normalized = S;
1148   if (PostIncLoops.count(L)) {
1149     PostIncLoopSet Loops;
1150     Loops.insert(L);
1151     Normalized =
1152       cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1153                                                   Loops, SE, *SE.DT));
1154   }
1155
1156   // Strip off any non-loop-dominating component from the addrec start.
1157   const SCEV *Start = Normalized->getStart();
1158   const SCEV *PostLoopOffset = 0;
1159   if (!SE.properlyDominates(Start, L->getHeader())) {
1160     PostLoopOffset = Start;
1161     Start = SE.getConstant(Normalized->getType(), 0);
1162     Normalized = cast<SCEVAddRecExpr>(
1163       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1164                        Normalized->getLoop(),
1165                        // FIXME: Normalized->getNoWrapFlags(FlagNW)
1166                        SCEV::FlagAnyWrap));
1167   }
1168
1169   // Strip off any non-loop-dominating component from the addrec step.
1170   const SCEV *Step = Normalized->getStepRecurrence(SE);
1171   const SCEV *PostLoopScale = 0;
1172   if (!SE.dominates(Step, L->getHeader())) {
1173     PostLoopScale = Step;
1174     Step = SE.getConstant(Normalized->getType(), 1);
1175     Normalized =
1176       cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
1177                                             Normalized->getLoop(),
1178                                             // FIXME: Normalized
1179                                             // ->getNoWrapFlags(FlagNW)
1180                                             SCEV::FlagAnyWrap));
1181   }
1182
1183   // Expand the core addrec. If we need post-loop scaling, force it to
1184   // expand to an integer type to avoid the need for additional casting.
1185   Type *ExpandTy = PostLoopScale ? IntTy : STy;
1186   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1187
1188   // Accommodate post-inc mode, if necessary.
1189   Value *Result;
1190   if (!PostIncLoops.count(L))
1191     Result = PN;
1192   else {
1193     // In PostInc mode, use the post-incremented value.
1194     BasicBlock *LatchBlock = L->getLoopLatch();
1195     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1196     Result = PN->getIncomingValueForBlock(LatchBlock);
1197
1198     // For an expansion to use the postinc form, the client must call
1199     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1200     // or dominated by IVIncInsertPos.
1201     if (isa<Instruction>(Result)
1202         && !SE.DT->dominates(cast<Instruction>(Result),
1203                              Builder.GetInsertPoint())) {
1204       // The induction variable's postinc expansion does not dominate this use.
1205       // IVUsers tries to prevent this case, so it is rare. However, it can
1206       // happen when an IVUser outside the loop is not dominated by the latch
1207       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1208       // all cases. Consider a phi outide whose operand is replaced during
1209       // expansion with the value of the postinc user. Without fundamentally
1210       // changing the way postinc users are tracked, the only remedy is
1211       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1212       // but hopefully expandCodeFor handles that.
1213       bool useSubtract =
1214         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1215       if (useSubtract)
1216         Step = SE.getNegativeSCEV(Step);
1217       // Expand the step somewhere that dominates the loop header.
1218       BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1219       BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1220       Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1221       // Restore the insertion point to the place where the caller has
1222       // determined dominates all uses.
1223       restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1224       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1225     }
1226   }
1227
1228   // Re-apply any non-loop-dominating scale.
1229   if (PostLoopScale) {
1230     Result = InsertNoopCastOfTo(Result, IntTy);
1231     Result = Builder.CreateMul(Result,
1232                                expandCodeFor(PostLoopScale, IntTy));
1233     rememberInstruction(Result);
1234   }
1235
1236   // Re-apply any non-loop-dominating offset.
1237   if (PostLoopOffset) {
1238     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1239       const SCEV *const OffsetArray[1] = { PostLoopOffset };
1240       Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1241     } else {
1242       Result = InsertNoopCastOfTo(Result, IntTy);
1243       Result = Builder.CreateAdd(Result,
1244                                  expandCodeFor(PostLoopOffset, IntTy));
1245       rememberInstruction(Result);
1246     }
1247   }
1248
1249   return Result;
1250 }
1251
1252 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1253   if (!CanonicalMode) return expandAddRecExprLiterally(S);
1254
1255   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1256   const Loop *L = S->getLoop();
1257
1258   // First check for an existing canonical IV in a suitable type.
1259   PHINode *CanonicalIV = 0;
1260   if (PHINode *PN = L->getCanonicalInductionVariable())
1261     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1262       CanonicalIV = PN;
1263
1264   // Rewrite an AddRec in terms of the canonical induction variable, if
1265   // its type is more narrow.
1266   if (CanonicalIV &&
1267       SE.getTypeSizeInBits(CanonicalIV->getType()) >
1268       SE.getTypeSizeInBits(Ty)) {
1269     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1270     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1271       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1272     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1273                                        // FIXME: S->getNoWrapFlags(FlagNW)
1274                                        SCEV::FlagAnyWrap));
1275     BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1276     BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1277     BasicBlock::iterator NewInsertPt =
1278       llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1279     while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1280            isa<LandingPadInst>(NewInsertPt))
1281       ++NewInsertPt;
1282     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1283                       NewInsertPt);
1284     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1285     return V;
1286   }
1287
1288   // {X,+,F} --> X + {0,+,F}
1289   if (!S->getStart()->isZero()) {
1290     SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1291     NewOps[0] = SE.getConstant(Ty, 0);
1292     // FIXME: can use S->getNoWrapFlags()
1293     const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
1294
1295     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1296     // comments on expandAddToGEP for details.
1297     const SCEV *Base = S->getStart();
1298     const SCEV *RestArray[1] = { Rest };
1299     // Dig into the expression to find the pointer base for a GEP.
1300     ExposePointerBase(Base, RestArray[0], SE);
1301     // If we found a pointer, expand the AddRec with a GEP.
1302     if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1303       // Make sure the Base isn't something exotic, such as a multiplied
1304       // or divided pointer value. In those cases, the result type isn't
1305       // actually a pointer type.
1306       if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1307         Value *StartV = expand(Base);
1308         assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1309         return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1310       }
1311     }
1312
1313     // Just do a normal add. Pre-expand the operands to suppress folding.
1314     return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1315                                 SE.getUnknown(expand(Rest))));
1316   }
1317
1318   // If we don't yet have a canonical IV, create one.
1319   if (!CanonicalIV) {
1320     // Create and insert the PHI node for the induction variable in the
1321     // specified loop.
1322     BasicBlock *Header = L->getHeader();
1323     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1324     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1325                                   Header->begin());
1326     rememberInstruction(CanonicalIV);
1327
1328     Constant *One = ConstantInt::get(Ty, 1);
1329     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1330       BasicBlock *HP = *HPI;
1331       if (L->contains(HP)) {
1332         // Insert a unit add instruction right before the terminator
1333         // corresponding to the back-edge.
1334         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1335                                                      "indvar.next",
1336                                                      HP->getTerminator());
1337         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1338         rememberInstruction(Add);
1339         CanonicalIV->addIncoming(Add, HP);
1340       } else {
1341         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1342       }
1343     }
1344   }
1345
1346   // {0,+,1} --> Insert a canonical induction variable into the loop!
1347   if (S->isAffine() && S->getOperand(1)->isOne()) {
1348     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1349            "IVs with types different from the canonical IV should "
1350            "already have been handled!");
1351     return CanonicalIV;
1352   }
1353
1354   // {0,+,F} --> {0,+,1} * F
1355
1356   // If this is a simple linear addrec, emit it now as a special case.
1357   if (S->isAffine())    // {0,+,F} --> i*F
1358     return
1359       expand(SE.getTruncateOrNoop(
1360         SE.getMulExpr(SE.getUnknown(CanonicalIV),
1361                       SE.getNoopOrAnyExtend(S->getOperand(1),
1362                                             CanonicalIV->getType())),
1363         Ty));
1364
1365   // If this is a chain of recurrences, turn it into a closed form, using the
1366   // folders, then expandCodeFor the closed form.  This allows the folders to
1367   // simplify the expression without having to build a bunch of special code
1368   // into this folder.
1369   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
1370
1371   // Promote S up to the canonical IV type, if the cast is foldable.
1372   const SCEV *NewS = S;
1373   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1374   if (isa<SCEVAddRecExpr>(Ext))
1375     NewS = Ext;
1376
1377   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1378   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
1379
1380   // Truncate the result down to the original type, if needed.
1381   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1382   return expand(T);
1383 }
1384
1385 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1386   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1387   Value *V = expandCodeFor(S->getOperand(),
1388                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1389   Value *I = Builder.CreateTrunc(V, Ty);
1390   rememberInstruction(I);
1391   return I;
1392 }
1393
1394 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1395   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1396   Value *V = expandCodeFor(S->getOperand(),
1397                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1398   Value *I = Builder.CreateZExt(V, Ty);
1399   rememberInstruction(I);
1400   return I;
1401 }
1402
1403 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1404   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1405   Value *V = expandCodeFor(S->getOperand(),
1406                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1407   Value *I = Builder.CreateSExt(V, Ty);
1408   rememberInstruction(I);
1409   return I;
1410 }
1411
1412 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1413   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1414   Type *Ty = LHS->getType();
1415   for (int i = S->getNumOperands()-2; i >= 0; --i) {
1416     // In the case of mixed integer and pointer types, do the
1417     // rest of the comparisons as integer.
1418     if (S->getOperand(i)->getType() != Ty) {
1419       Ty = SE.getEffectiveSCEVType(Ty);
1420       LHS = InsertNoopCastOfTo(LHS, Ty);
1421     }
1422     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1423     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1424     rememberInstruction(ICmp);
1425     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1426     rememberInstruction(Sel);
1427     LHS = Sel;
1428   }
1429   // In the case of mixed integer and pointer types, cast the
1430   // final result back to the pointer type.
1431   if (LHS->getType() != S->getType())
1432     LHS = InsertNoopCastOfTo(LHS, S->getType());
1433   return LHS;
1434 }
1435
1436 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1437   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1438   Type *Ty = LHS->getType();
1439   for (int i = S->getNumOperands()-2; i >= 0; --i) {
1440     // In the case of mixed integer and pointer types, do the
1441     // rest of the comparisons as integer.
1442     if (S->getOperand(i)->getType() != Ty) {
1443       Ty = SE.getEffectiveSCEVType(Ty);
1444       LHS = InsertNoopCastOfTo(LHS, Ty);
1445     }
1446     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1447     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1448     rememberInstruction(ICmp);
1449     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1450     rememberInstruction(Sel);
1451     LHS = Sel;
1452   }
1453   // In the case of mixed integer and pointer types, cast the
1454   // final result back to the pointer type.
1455   if (LHS->getType() != S->getType())
1456     LHS = InsertNoopCastOfTo(LHS, S->getType());
1457   return LHS;
1458 }
1459
1460 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1461                                    Instruction *IP) {
1462   Builder.SetInsertPoint(IP->getParent(), IP);
1463   return expandCodeFor(SH, Ty);
1464 }
1465
1466 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1467   // Expand the code for this SCEV.
1468   Value *V = expand(SH);
1469   if (Ty) {
1470     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1471            "non-trivial casts should be done with the SCEVs directly!");
1472     V = InsertNoopCastOfTo(V, Ty);
1473   }
1474   return V;
1475 }
1476
1477 Value *SCEVExpander::expand(const SCEV *S) {
1478   // Compute an insertion point for this SCEV object. Hoist the instructions
1479   // as far out in the loop nest as possible.
1480   Instruction *InsertPt = Builder.GetInsertPoint();
1481   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1482        L = L->getParentLoop())
1483     if (SE.isLoopInvariant(S, L)) {
1484       if (!L) break;
1485       if (BasicBlock *Preheader = L->getLoopPreheader())
1486         InsertPt = Preheader->getTerminator();
1487       else {
1488         // LSR sets the insertion point for AddRec start/step values to the
1489         // block start to simplify value reuse, even though it's an invalid
1490         // position. SCEVExpander must correct for this in all cases.
1491         InsertPt = L->getHeader()->getFirstInsertionPt();
1492       }
1493     } else {
1494       // If the SCEV is computable at this level, insert it into the header
1495       // after the PHIs (and after any other instructions that we've inserted
1496       // there) so that it is guaranteed to dominate any user inside the loop.
1497       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1498         InsertPt = L->getHeader()->getFirstInsertionPt();
1499       while (InsertPt != Builder.GetInsertPoint()
1500              && (isInsertedInstruction(InsertPt)
1501                  || isa<DbgInfoIntrinsic>(InsertPt))) {
1502         InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1503       }
1504       break;
1505     }
1506
1507   // Check to see if we already expanded this here.
1508   std::map<std::pair<const SCEV *, Instruction *>,
1509            AssertingVH<Value> >::iterator I =
1510     InsertedExpressions.find(std::make_pair(S, InsertPt));
1511   if (I != InsertedExpressions.end())
1512     return I->second;
1513
1514   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1515   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1516   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1517
1518   // Expand the expression into instructions.
1519   Value *V = visit(S);
1520
1521   // Remember the expanded value for this SCEV at this location.
1522   //
1523   // This is independent of PostIncLoops. The mapped value simply materializes
1524   // the expression at this insertion point. If the mapped value happened to be
1525   // a postinc expansion, it could be reused by a non postinc user, but only if
1526   // its insertion point was already at the head of the loop.
1527   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1528
1529   restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1530   return V;
1531 }
1532
1533 void SCEVExpander::rememberInstruction(Value *I) {
1534   if (!PostIncLoops.empty())
1535     InsertedPostIncValues.insert(I);
1536   else
1537     InsertedValues.insert(I);
1538 }
1539
1540 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1541   Builder.SetInsertPoint(BB, I);
1542 }
1543
1544 /// getOrInsertCanonicalInductionVariable - This method returns the
1545 /// canonical induction variable of the specified type for the specified
1546 /// loop (inserting one if there is none).  A canonical induction variable
1547 /// starts at zero and steps by one on each iteration.
1548 PHINode *
1549 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1550                                                     Type *Ty) {
1551   assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1552
1553   // Build a SCEV for {0,+,1}<L>.
1554   // Conservatively use FlagAnyWrap for now.
1555   const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1556                                    SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1557
1558   // Emit code for it.
1559   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1560   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1561   PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
1562   if (SaveInsertBB)
1563     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1564
1565   return V;
1566 }
1567
1568 /// Sort values by integer width for replaceCongruentIVs.
1569 static bool width_descending(Value *lhs, Value *rhs) {
1570   // Put pointers at the back and make sure pointer < pointer = false.
1571   if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1572     return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1573   return rhs->getType()->getPrimitiveSizeInBits()
1574     < lhs->getType()->getPrimitiveSizeInBits();
1575 }
1576
1577 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1578 /// replace them with their most canonical representative. Return the number of
1579 /// phis eliminated.
1580 ///
1581 /// This does not depend on any SCEVExpander state but should be used in
1582 /// the same context that SCEVExpander is used.
1583 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1584                                            SmallVectorImpl<WeakVH> &DeadInsts,
1585                                            const TargetLowering *TLI) {
1586   // Find integer phis in order of increasing width.
1587   SmallVector<PHINode*, 8> Phis;
1588   for (BasicBlock::iterator I = L->getHeader()->begin();
1589        PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1590     Phis.push_back(Phi);
1591   }
1592   if (TLI)
1593     std::sort(Phis.begin(), Phis.end(), width_descending);
1594
1595   unsigned NumElim = 0;
1596   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1597   // Process phis from wide to narrow. Mapping wide phis to the their truncation
1598   // so narrow phis can reuse them.
1599   for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1600          PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1601     PHINode *Phi = *PIter;
1602
1603     if (!SE.isSCEVable(Phi->getType()))
1604       continue;
1605
1606     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1607     if (!OrigPhiRef) {
1608       OrigPhiRef = Phi;
1609       if (Phi->getType()->isIntegerTy() && TLI
1610           && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1611         // This phi can be freely truncated to the narrowest phi type. Map the
1612         // truncated expression to it so it will be reused for narrow types.
1613         const SCEV *TruncExpr =
1614           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1615         ExprToIVMap[TruncExpr] = Phi;
1616       }
1617       continue;
1618     }
1619
1620     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1621     // sense.
1622     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1623       continue;
1624
1625     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1626       Instruction *OrigInc =
1627         cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1628       Instruction *IsomorphicInc =
1629         cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1630
1631       // If this phi has the same width but is more canonical, replace the
1632       // original with it. As part of the "more canonical" determination,
1633       // respect a prior decision to use an IV chain.
1634       if (OrigPhiRef->getType() == Phi->getType()
1635           && !(ChainedPhis.count(Phi)
1636                || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1637           && (ChainedPhis.count(Phi)
1638               || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1639         std::swap(OrigPhiRef, Phi);
1640         std::swap(OrigInc, IsomorphicInc);
1641       }
1642       // Replacing the congruent phi is sufficient because acyclic redundancy
1643       // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1644       // that a phi is congruent, it's often the head of an IV user cycle that
1645       // is isomorphic with the original phi. It's worth eagerly cleaning up the
1646       // common case of a single IV increment so that DeleteDeadPHIs can remove
1647       // cycles that had postinc uses.
1648       const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1649                                                    IsomorphicInc->getType());
1650       if (OrigInc != IsomorphicInc
1651           && TruncExpr == SE.getSCEV(IsomorphicInc)
1652           && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1653               || hoistIVInc(OrigInc, IsomorphicInc))) {
1654         DEBUG_WITH_TYPE(DebugType, dbgs()
1655                         << "INDVARS: Eliminated congruent iv.inc: "
1656                         << *IsomorphicInc << '\n');
1657         Value *NewInc = OrigInc;
1658         if (OrigInc->getType() != IsomorphicInc->getType()) {
1659           Instruction *IP = isa<PHINode>(OrigInc)
1660             ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1661             : OrigInc->getNextNode();
1662           IRBuilder<> Builder(IP);
1663           Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1664           NewInc = Builder.
1665             CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1666         }
1667         IsomorphicInc->replaceAllUsesWith(NewInc);
1668         DeadInsts.push_back(IsomorphicInc);
1669       }
1670     }
1671     DEBUG_WITH_TYPE(DebugType, dbgs()
1672                     << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1673     ++NumElim;
1674     Value *NewIV = OrigPhiRef;
1675     if (OrigPhiRef->getType() != Phi->getType()) {
1676       IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1677       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1678       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1679     }
1680     Phi->replaceAllUsesWith(NewIV);
1681     DeadInsts.push_back(Phi);
1682   }
1683   return NumElim;
1684 }