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