ScalarEvolutionExpander.cpp revision f8fd841a4bb7a59f81cf4642169e8251e039acfe
136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//                     The LLVM Compiler Infrastructure
436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// This file contains the implementation of the scalar evolution expander,
1136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// which is used to generate the code corresponding to a given scalar evolution
1236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman// expression.
1336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//
1436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman//===----------------------------------------------------------------------===//
1536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman#include "llvm/Analysis/ScalarEvolutionExpander.h"
17e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling#include "llvm/Analysis/LoopInfo.h"
188d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen#include "llvm/IntrinsicInst.h"
1976f600b205606a055ec35e7d3fd1a99602329d67Owen Anderson#include "llvm/LLVMContext.h"
20c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick#include "llvm/Support/Debug.h"
215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman#include "llvm/Target/TargetData.h"
224d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman#include "llvm/ADT/STLExtras.h"
23d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
2436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
2536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
2619e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
27485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// reusing an existing cast if a suitable one exists, moving an existing
28485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// cast if a suitable one exists but isn't in the right place, or
2919e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// creating a new one.
30db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
31485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       Instruction::CastOps Op,
32485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       BasicBlock::iterator IP) {
33485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Check to see if there is already a cast!
34485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
35f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif       UI != E; ++UI) {
36f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    User *U = *UI;
37f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    if (U->getType() == Ty)
3819e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif      if (CastInst *CI = dyn_cast<CastInst>(U))
39485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        if (CI->getOpcode() == Op) {
40485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          // If the cast isn't where we want it, fix it.
41485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          if (BasicBlock::iterator(CI) != IP) {
42485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // Create a new cast, and leave the old cast in place in case
43485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // it is being used as an insert point. Clear its operand
44485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // so that it doesn't hold anything live.
45485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
46485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            NewCI->takeName(CI);
47485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->replaceAllUsesWith(NewCI);
48485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->setOperand(0, UndefValue::get(V->getType()));
49485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            rememberInstruction(NewCI);
50485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            return NewCI;
51485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          }
526f5fed253f58645bf45448893a585ffbd9914989Dan Gohman          rememberInstruction(CI);
53485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          return CI;
54485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        }
55f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif  }
56485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
57485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Create a new cast.
58485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
59485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  rememberInstruction(I);
60485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return I;
61485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman}
62485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
63267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
64267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
65267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
66db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
67267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
68267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
69267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
70267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
71267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
72267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
73267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
74267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
752d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
7619154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  if (Op == Instruction::BitCast) {
7719154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (V->getType() == Ty)
7819154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      return V;
7919154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (CastInst *CI = dyn_cast<CastInst>(V)) {
8019154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      if (CI->getOperand(0)->getType() == Ty)
8119154f457696f286b4a597179fa07e3b38ea0310Andrew Trick        return CI->getOperand(0);
8219154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    }
8319154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  }
84f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
85267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
8680dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
87af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
88af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
89af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
90af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
91af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
92af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
9380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
9480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
9580dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
9680dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
9780dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
9880dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
9980dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
100f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
101485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Fold a cast of a constant.
102ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
103baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
1044c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
105485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the argument at the beginning of the entry block, after
106485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // any bitcasts of other arguments.
107ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
108485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
109485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    while ((isa<BitCastInst>(IP) &&
110485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
111485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            cast<BitCastInst>(IP)->getOperand(0) != A) ||
112a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<DbgInfoIntrinsic>(IP) ||
113a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(IP))
114485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman      ++IP;
115485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    return ReuseOrCreateCast(A, Ty, Op, IP);
116ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
1173913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
118485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the instruction immediately after the instruction.
119ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
120ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  BasicBlock::iterator IP = I; ++IP;
121ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(I))
122ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner    IP = II->getNormalDest()->begin();
123a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling  while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
124a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling         isa<LandingPadInst>(IP))
125a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    ++IP;
126485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return ReuseOrCreateCast(I, Ty, Op, IP);
127ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
128ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1297fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1307fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
131267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
132267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1330f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1340f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1350f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
136baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1370f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1387fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1397fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
140267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
141267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
142267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
143267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1448a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1458a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1468d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1478d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1488d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1498d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1505be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
1525be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        return IP;
1538a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1548a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1557fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
156267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
157087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
158087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
159087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
160087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
161087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
162087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
163087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
164087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
165087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
166087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
167087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
168087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
169087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
170087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
1718a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
172a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
173df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel  BO->setDebugLoc(SaveInsertPt->getDebugLoc());
174a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
175087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
176087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
177087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
178087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
179087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
180cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
1817fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
1827fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
1834a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
184453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
1853f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
1864a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
187453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
188453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
189453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
1900bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic bool FactorOutConstant(const SCEV *&S,
1910bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                              const SCEV *&Remainder,
192c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const SCEV *Factor,
193c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              ScalarEvolution &SE,
194c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                              const TargetData *TD) {
195453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
196c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
197c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
198c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
199c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
200c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
201deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    S = SE.getConstant(S->getType(), 1);
202453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
203c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
204453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
205453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2064a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
207c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
208c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
209453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
210c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
211c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
212c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
213c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ConstantInt::get(SE.getContext(),
214c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         C->getValue()->getValue().sdiv(
215c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
216c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
217c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
218c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
219c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
220c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
221c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
222c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Remainder =
223c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          SE.getAddExpr(Remainder,
224c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                        SE.getConstant(C->getValue()->getValue().srem(
225c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                  FC->getValue()->getValue())));
226c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
227c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
228453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2294a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
230453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
231453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
232453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (TD) {
235c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // With TargetData, the size is known. Check if there is a constant
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // operand which is a multiple of the given factor. If so, we can
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // factor it.
238c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEVConstant *FC = cast<SCEVConstant>(Factor);
239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
240c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
241f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[0] =
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            SE.getConstant(C->getValue()->getValue().sdiv(
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                                   FC->getValue()->getValue()));
245c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
247c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    } else {
249c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Without TargetData, check if Factor can be factored out of any of the
250c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Mul's operands. If so, we can just remove it.
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *SOp = M->getOperand(i);
253deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman        const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
254c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
255c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            Remainder->isZero()) {
256f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman          SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          NewMulOps[i] = SOp;
258c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          S = SE.getMulExpr(NewMulOps);
259c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          return true;
260c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        }
261453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
262c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
264453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
265453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
266453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2670bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
268deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
269c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
2704a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2714a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2724a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2730bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
274c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
275453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
2763228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use A->getNoWrapFlags(FlagNW)
2773228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
278453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
279453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
280453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
281453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
282453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
283453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
284c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
285c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
286c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
287c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
288c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
289db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                Type *Ty,
290c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
291c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
292c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
293c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
294c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
296c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
299deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                    SE.getConstant(Ty, 0) :
300c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
303f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
305403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(Add->op_begin(), Add->op_end());
306f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
307f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
309403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman  Ops.append(AddRecs.begin(), AddRecs.end());
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
316c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
318db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                         Type *Ty,
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
320c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
323c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
324c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
325c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
326deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman      const SCEV *Zero = SE.getConstant(Ty, 0);
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
328c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
3293228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         A->getLoop(),
3303228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         // FIXME: A->getNoWrapFlags(FlagNW)
3313228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         SCEV::FlagAnyWrap));
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
334403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman        Ops.append(Add->op_begin(), Add->op_end());
335c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
336c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
337c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
339c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
340c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
341c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
342403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(AddRecs.begin(), AddRecs.end());
343c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
344c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
345c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
346c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
347c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3484c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3494c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3504c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3514c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3524c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3534c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
35413c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3553abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3564c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3574c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3584c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
359453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
360453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
361453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
362453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
363453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
364453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
365453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
366453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
367453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
368453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
369453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
370453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
371453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
372453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
373453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
374453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3750bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3760bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
377db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    PointerType *PTy,
378db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    Type *Ty,
3795be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
380db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ElTy = PTy->getElementType();
3815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3820bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
385c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
386c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
387c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
388c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
389eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
3905be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
3915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
3925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
3935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
3945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
395c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
396c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
3970bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
398150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
3994f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
400150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
401150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
402150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
403150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          const SCEV *Op = Ops[i];
404deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman          const SCEV *Remainder = SE.getConstant(Ty, 0);
405150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
406150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
407150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
408150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
409150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
410150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
411150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
412150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
413150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
414150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            NewOps.push_back(Ops[i]);
415150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
416150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
417150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
418150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
419150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
420150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
422c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
424c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
425c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
426c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
427c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
428c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4295be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
430a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4315be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4325be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4335be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4345be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
435db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    while (StructType *STy = dyn_cast<StructType>(ElTy)) {
436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
437c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
438c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (SE.TD) {
440c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // With TargetData, field offsets are known. See if a constant offset
441c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // falls within any of the struct fields.
442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        if (Ops.empty()) break;
4435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            const StructLayout &SL = *SE.TD->getStructLayout(STy);
4465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            uint64_t FullOffset = C->getValue()->getZExtValue();
4475be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            if (FullOffset < SL.getSizeInBytes()) {
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4491d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson              GepIndices.push_back(
4501d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                  ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              ElTy = STy->getTypeAtIndex(ElIdx);
4525be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              Ops[0] =
4536de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4545be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman              AnyNonZeroIndices = true;
455c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
4565be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            }
4575be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          }
458c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
4590f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman        // Without TargetData, just check for an offsetof expression of the
460c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        // appropriate struct type.
461c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4620f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
463db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner            Type *CTy;
4640f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman            Constant *FieldNo;
4654f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman            if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
4660f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              GepIndices.push_back(FieldNo);
4670f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman              ElTy =
4680f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman                STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
469c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              Ops[i] = SE.getConstant(Ty, 0);
470c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              AnyNonZeroIndices = true;
471c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              FoundFieldNo = true;
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman              break;
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman            }
4740f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
476c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
478c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
479c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
480c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
481c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
482c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
483c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
484c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
486db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
488c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
489c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4905be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4923f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
4935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
496c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4975be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
498ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
499c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
500c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
50192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
5045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
5055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
506dab3d29605a5c83db41b28176273ef55961120c1Jay Foad        return ConstantExpr::getGetElementPtr(CLHS, CRHS);
5075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
510267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
511267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
512267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
513267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
5145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
5155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
5168d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5178d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // generated code.
5188d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        if (isa<DbgInfoIntrinsic>(IP))
5198d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen          ScanLimit++;
5205be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
5215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
5225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          return IP;
5235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
5245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
5255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
5265be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
527087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Save the original insertion point so we can restore it when we're done.
528087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
529087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
530087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
531087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
532087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
533087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
534087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
535087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
536087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
537087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
538087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
539087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
540087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
541c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
542c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
543a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
544087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
545087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Restore the original insert point.
546087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (SaveInsertBB)
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
548087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5495be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5505be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5515be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
552087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
553087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
554087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
555087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
556087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
557087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(V)) break;
559087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
560087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    bool AnyIndexNotLoopInvariant = false;
561087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
562087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         E = GepIndices.end(); I != E; ++I)
563087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(*I)) {
564087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        AnyIndexNotLoopInvariant = true;
565087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        break;
566087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      }
567087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (AnyIndexNotLoopInvariant)
568087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      break;
569087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
570087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
571087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
572087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
573087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
574087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
575087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
576087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
577d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
578d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
579d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
580a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
581a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
582a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
583a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *GEP = Builder.CreateGEP(Casted,
5840a2a60ace9b79164b71794ce7ff981171c61e442Jay Foad                                 GepIndices,
585267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 "scevgep");
5865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
587a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
588087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
589087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Restore the original insert point.
590087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (SaveInsertBB)
591087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
592087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
596087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
597087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
598087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
599087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
600087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
601087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
602087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
603087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
604087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
605087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
606087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
607087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
608087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
609087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
6109c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman/// getRelevantLoop - Get the most relevant loop associated with the given
611087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
6129c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohmanconst Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
6139c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  // Test whether we've already computed the most relevant loop for this SCEV.
6149c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
6159c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
6169c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (!Pair.second)
6179c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return Pair.first->second;
6189c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman
619087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
6209c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A constant has no relevant loops.
621087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
622087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
623087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
6249c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      return Pair.first->second = SE.LI->getLoopFor(I->getParent());
6259c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A non-instruction has no relevant loops.
626087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return 0;
627087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
628087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
629087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *L = 0;
630087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
631087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
632087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
633087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman         I != E; ++I)
6349c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
6359c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[N] = L;
6369c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6379c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6389c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result = getRelevantLoop(C->getOperand());
6399c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[C] = Result;
6409c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6419c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
6429c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result =
6439c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman      PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
6449c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           getRelevantLoop(D->getRHS()),
6459c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman                           *SE.DT);
6469c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[D] = Result;
647087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
648087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
6499c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  return 0;
650087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
651c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
652b35798347ea87b8b6d36155b211016a7769f01abDan Gohmannamespace {
653b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
654087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
655087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
656087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
657087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
658087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
659087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
660087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
661087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
662bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    // Keep pointer operands sorted at the end.
663bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    if (LHS.second->getType()->isPointerTy() !=
664bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        RHS.second->getType()->isPointerTy())
665bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      return LHS.second->getType()->isPointerTy();
666bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman
667087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
668087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
669087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
670087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
671087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
672087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
673087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
674f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    if (LHS.second->isNonConstantNegative()) {
675f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick      if (!RHS.second->isNonConstantNegative())
676087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
677f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (RHS.second->isNonConstantNegative())
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
680087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
681087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
682c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
683087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
6845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
685b35798347ea87b8b6d36155b211016a7769f01abDan Gohman}
686b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
687087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
688db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
689e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
690087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
692087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
693087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
694087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
695087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
696087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
6979c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
698087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
699087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
700087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
701087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
702087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
703087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
704087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
705087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Sum = 0;
706087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
707087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
708087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
709087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
710087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
711087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
712087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
713087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
714db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
715087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
716087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
718bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      for (; I != E && I->first == CurLoop; ++I) {
719bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // If the operand is SCEVUnknown and not instructions, peek through
720bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // it, to enable more of it to be folded into the GEP.
721bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        const SCEV *X = I->second;
722bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
723bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman          if (!isa<Instruction>(U->getValue()))
724bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman            X = SE.getSCEV(U->getValue());
725bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        NewOps.push_back(X);
726bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      }
727087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
728db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
729087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
730f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
731f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
732087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
733f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
734f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
735087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
736087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
737087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
738f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (Op->isNonConstantNegative()) {
739087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
740a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
741087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
742087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
743087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
744a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
745087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
746a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
747087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
748087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
749087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
750087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
751087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
752a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7532d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
754087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
755087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
756e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7575be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
758890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
759db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
760087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
761087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
763087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
764087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
765087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7669c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
767087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
768087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
769087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
770087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
771087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
772087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
773087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  Value *Prod = 0;
774087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
775087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
776087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
777087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
778087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
779087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
780087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
781087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
782087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
783087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
784087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
785087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
786087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
787087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
788087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
789087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
790087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
791087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
792087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Mul, Prod, W);
793087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
794087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
7952d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
7962d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
797087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
79836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
79936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
800890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
801db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
8022d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
80392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
804890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
8056177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    const APInt &RHS = SC->getValue()->getValue();
8066177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
8076177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
808eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
8096177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
8106177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
81192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
812267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
8136177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
8146177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
815453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
816453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
817453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
8180bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
819453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
820453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
821453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
822453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
823deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                         SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
824453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
8253228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          A->getLoop(),
8263228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          // FIXME: A->getNoWrapFlags(FlagNW)
8273228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          SCEV::FlagAnyWrap));
828453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
829453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
830453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8310bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
832453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
833453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
834453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
835453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
836453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
837453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
838c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// Determine if this is a well-behaved chain of instructions leading back to
839c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// the PHI. If so, it may be reused by expanded expressions.
840c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trickbool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
841c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick                                         const Loop *L) {
842c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
843c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
844c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
845c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // If any of the operands don't dominate the insert position, bail.
846c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Addrec operands are always loop-invariant, so this can only happen
847c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // if there are instructions which haven't been hoisted.
848c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (L == IVIncInsertLoop) {
849c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (User::op_iterator OI = IncV->op_begin()+1,
850c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           OE = IncV->op_end(); OI != OE; ++OI)
851c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(OI))
852c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        if (!SE.DT->dominates(OInst, IVIncInsertPos))
853c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          return false;
854c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
855c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Advance to the next instruction.
856c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
857c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (!IncV)
858c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
859c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
860c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->mayHaveSideEffects())
861c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
862c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
863c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV != PN)
864c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return true;
865c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
866c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  return isNormalAddRecExprPHI(PN, IncV, L);
867c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
868c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
869c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// Determine if this cyclic phi is in a form that would have been generated by
870c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// LSR. We don't care if the phi was actually expanded in this pass, as long
871c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// as it is in a low-cost form, for example, no implied multiplication. This
872c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// should match any patterns generated by getAddRecExprPHILiterally and
873c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// expandAddtoGEP.
874c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trickbool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
875365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick                                           const Loop *L) {
876c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  switch (IncV->getOpcode()) {
877c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Check for a simple Add/Sub or GEP of a loop invariant step.
878c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::Add:
879c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::Sub:
880c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return IncV->getOperand(0) == PN
881c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      && L->isLoopInvariant(IncV->getOperand(1));
882c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::BitCast:
883c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    IncV = dyn_cast<GetElementPtrInst>(IncV->getOperand(0));
884c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    if (!IncV)
885c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      return false;
886c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    // fall-thru to GEP handling
887c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::GetElementPtr: {
888c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    // This must be a pointer addition of constants (pretty) or some number of
889c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    // address-size elements (ugly).
890c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
891c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick         I != E; ++I) {
892c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (isa<Constant>(*I))
893c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
894c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // ugly geps have 2 operands.
895c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // i1* is used by the expander to represent an address-size element.
896c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getNumOperands() != 2)
897c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        return false;
898365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick      unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
899c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
900c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
901c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        return false;
90294794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick      // Ensure the operands dominate the insertion point. I don't know of a
90394794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick      // case when this would not be true, so this is somewhat untested.
90494794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick      if (L == IVIncInsertLoop) {
90594794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick        for (User::op_iterator OI = IncV->op_begin()+1,
90694794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick               OE = IncV->op_end(); OI != OE; ++OI)
90794794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick          if (Instruction *OInst = dyn_cast<Instruction>(OI))
90894794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick            if (!SE.DT->dominates(OInst, IVIncInsertPos))
90994794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick              return false;
91094794dd8d38d2572896625fc58e6b0f37809edfaAndrew Trick      }
911c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      break;
912c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
913c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    IncV = dyn_cast<Instruction>(IncV->getOperand(0));
914c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    if (IncV && IncV->getOpcode() == Instruction::BitCast)
915c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      IncV = dyn_cast<Instruction>(IncV->getOperand(0));
916c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return IncV == PN;
917c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
918c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  default:
919c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
920c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
921c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
922c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
923553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
924553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
925553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// need to materialize IV increments elsewhere to handle difficult situations.
926553fe05f236f46fe27b7fcfa822b06367d50183eAndrew TrickValue *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
927553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 Type *ExpandTy, Type *IntTy,
928553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 bool useSubtract) {
929553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  Value *IncV;
930553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
931553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (ExpandTy->isPointerTy()) {
932553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
933553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If the step isn't constant, don't use an implicitly scaled GEP, because
934553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // that would require a multiply inside the loop.
935553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (!isa<ConstantInt>(StepV))
936553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
937553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                  GEPPtrTy->getAddressSpace());
938553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
939553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
940553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (IncV->getType() != PN->getType()) {
941553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      IncV = Builder.CreateBitCast(IncV, PN->getType());
942553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      rememberInstruction(IncV);
943553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
944553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  } else {
945553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = useSubtract ?
946553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
947553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
948553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    rememberInstruction(IncV);
949553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  }
950553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  return IncV;
951553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick}
952553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
953a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
954a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
955a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
956a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
957a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
958a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
959db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *ExpandTy,
960db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *IntTy) {
96193a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
962d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
963a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
964c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  BasicBlock *LatchBlock = L->getLoopLatch();
965c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (LatchBlock) {
966c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (BasicBlock::iterator I = L->getHeader()->begin();
967c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick         PHINode *PN = dyn_cast<PHINode>(I); ++I) {
968c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (!SE.isSCEVable(PN->getType()) ||
969c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          (SE.getEffectiveSCEVType(PN->getType()) !=
970c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           SE.getEffectiveSCEVType(Normalized->getType())) ||
971c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          SE.getSCEV(PN) != Normalized)
972c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
973c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
974c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      Instruction *IncV =
975c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
976c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
977c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (LSRMode) {
978365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick        if (!isExpandedAddRecExprPHI(PN, IncV, L))
979c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
980c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
981c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      else {
982c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        if (!isNormalAddRecExprPHI(PN, IncV, L))
983c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
984c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
985c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Ok, the add recurrence looks usable.
986c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember this PHI, even in post-inc mode.
987c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      InsertedValues.insert(PN);
988c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember the increment.
989c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      rememberInstruction(IncV);
990c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (L == IVIncInsertLoop)
99122e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        do {
992c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          if (SE.DT->dominates(IncV, IVIncInsertPos))
9939feae9f0de032c66d01d16399a4c5296e38870e3Dan Gohman            break;
994c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          // Make sure the increment is where we want it. But don't move it
995c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          // down past a potential existing post-inc user.
996c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          IncV->moveBefore(IVIncInsertPos);
997c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          IVIncInsertPos = IncV;
998c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          IncV = cast<Instruction>(IncV->getOperand(0));
99922e621908fdb121474f4806f15ec5c0ce2efeb0aDan Gohman        } while (IncV != PN);
1000c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      return PN;
1001c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
1002c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
1003a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1004a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
1005a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1006a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1007a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1008ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // Another AddRec may need to be recursively expanded below. For example, if
1009ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1010ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // loop. Remove this loop from the PostIncLoops set before expanding such
1011ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // AddRecs. Otherwise, we cannot find a valid position for the step
1012ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1013ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1014ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // so it's not worth implementing SmallPtrSet::swap.
1015ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1016ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops.clear();
1017ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1018a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
1019a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1020a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                L->getHeader()->begin());
1021a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1022d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick  // StartV must be hoisted into L's preheader to dominate the new phi.
102393a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert(!isa<Instruction>(StartV) ||
102493a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer         SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
102593a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer                                  L->getHeader()));
1026d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1027553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand code for the step value. Do this before creating the PHI so that PHI
1028553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // reuse code doesn't see an incomplete PHI.
1029a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1030553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the stride is negative, insert a sub instead of an add for the increment
1031553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // (unless it's a constant, because subtracts of constants are canonicalized
1032553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // to adds).
1033f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1034553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (useSubtract)
1035a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
1036553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand the step somewhere that dominates the loop header.
1037a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1038a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1039a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
1040d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  BasicBlock *Header = L->getHeader();
1041d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  Builder.SetInsertPoint(Header, Header->begin());
1042d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
10435e7645be4c9dd2193add44d30b5fef8036d7a3ceAndrew Trick  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1044dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick                                  Twine(IVName) + ".iv");
1045a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
1046a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1047a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
1048d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1049a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
1050a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1051a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
1052a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
1053a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
1054a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
1055a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1056a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1057553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // Create a step value and add it to the PHI.
1058553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1059553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // instructions at IVIncInsertPos.
1060a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
1061a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
1062c5ecbdc1896f1cc089372feef3191ace2f840898Devang Patel    Builder.SetInsertPoint(InsertPos);
1063553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1064553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
1065a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
1066a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1067a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1068a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Restore the original insert point.
1069a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (SaveInsertBB)
1070455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1071a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1072ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // After expanding subexpressions, restore the PostIncLoops set so the caller
1073ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // can ensure that IVIncrement dominates the current uses.
1074ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops = SavedPostIncLoops;
1075ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1076a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
1077a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
1078a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1079a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
1080a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1081a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1082a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1083db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *STy = S->getType();
1084db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *IntTy = SE.getEffectiveSCEVType(STy);
1085a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
1086a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1087a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
1088a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
1089a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
1090448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
1091448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
1092448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
1093448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Normalized =
1094448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman      cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1095448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman                                                  Loops, SE, *SE.DT));
1096a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1097a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1098a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
1099a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
1100a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopOffset = 0;
1101dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.properlyDominates(Start, L->getHeader())) {
1102a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
1103deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Start = SE.getConstant(Normalized->getType(), 0);
11043228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Normalized = cast<SCEVAddRecExpr>(
11053228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick      SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
11063228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       Normalized->getLoop(),
11073228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       // FIXME: Normalized->getNoWrapFlags(FlagNW)
11083228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       SCEV::FlagAnyWrap));
1109a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1110a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1111a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
1112a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1113a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *PostLoopScale = 0;
1114dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.dominates(Step, L->getHeader())) {
1115a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
1116deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Step = SE.getConstant(Normalized->getType(), 1);
1117a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
1118a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
11193228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            Normalized->getLoop(),
11203228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // FIXME: Normalized
11213228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            // ->getNoWrapFlags(FlagNW)
11223228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                            SCEV::FlagAnyWrap));
1123a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1124a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1125a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1126a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1127db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ExpandTy = PostLoopScale ? IntTy : STy;
1128a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1129a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
11303f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1131a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1132448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1133a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1134a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1135a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1136a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1137a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1138a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
113948ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick
114048ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // For an expansion to use the postinc form, the client must call
114148ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
114248ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // or dominated by IVIncInsertPos.
1143553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (isa<Instruction>(Result)
1144553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        && !SE.DT->dominates(cast<Instruction>(Result),
1145553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                             Builder.GetInsertPoint())) {
1146553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // The induction variable's postinc expansion does not dominate this use.
1147553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // IVUsers tries to prevent this case, so it is rare. However, it can
1148553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // happen when an IVUser outside the loop is not dominated by the latch
1149553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1150553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // all cases. Consider a phi outide whose operand is replaced during
1151553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // expansion with the value of the postinc user. Without fundamentally
1152553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // changing the way postinc users are tracked, the only remedy is
1153553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1154553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // but hopefully expandCodeFor handles that.
1155553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      bool useSubtract =
1156f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick        !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1157553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      if (useSubtract)
1158553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        Step = SE.getNegativeSCEV(Step);
1159553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // Expand the step somewhere that dominates the loop header.
1160553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1161553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1162553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1163553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // Restore the insertion point to the place where the caller has
1164553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // determined dominates all uses.
1165553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1166553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1167553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
1168a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1169a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1170a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1171a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
11720a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1173a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1174a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1175a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1176a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1177a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1178a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1179a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1180db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1181a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1182a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1183a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
11840a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1185a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1186a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1187a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1188a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1189a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1190a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1191a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1192a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1193a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1194890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1195a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1196a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1197db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
119836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
119936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12004d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
12014d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  PHINode *CanonicalIV = 0;
12024d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
1203133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman    if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
12044d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
12054d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
12064d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
12074d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
12084d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
12094d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
12104d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1211f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1212f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1213f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
12143228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
12153228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       // FIXME: S->getNoWrapFlags(FlagNW)
12163228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                       SCEV::FlagAnyWrap));
1217267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1218267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
12194d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
12207896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner      llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1221a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling    while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1222a4c86ab073d4b7a36477fc7c54c9d52499f04586Bill Wendling           isa<LandingPadInst>(NewInsertPt))
122308f55d02da2cd24f3b4297259ef6429b8bf1ef97Jim Grosbach      ++NewInsertPt;
12244d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
12254d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman                      NewInsertPt);
1226455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
12274d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
12284d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
12294d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
123036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1231cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1232f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1233deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    NewOps[0] = SE.getConstant(Ty, 0);
12343228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    // FIXME: can use S->getNoWrapFlags()
12353228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
1236453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1237453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1238453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1240c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1241c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1244db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1245c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1247c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1249c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1250c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1252453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1253453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1254453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
125540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
125640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
125740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
125836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
125936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12606ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // If we don't yet have a canonical IV, create one.
12616ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (!CanonicalIV) {
126236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
126336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
126436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1265d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
12663ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
12673ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                  Header->begin());
12686ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    rememberInstruction(CanonicalIV);
126936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1270eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
1271d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
12727656018c2268285907cfdc106071462a01a73878Gabor Greif      BasicBlock *HP = *HPI;
12737656018c2268285907cfdc106071462a01a73878Gabor Greif      if (L->contains(HP)) {
12743abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
12753abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
12766ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
12776ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     "indvar.next",
12786ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     HP->getTerminator());
1279df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel        Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1280a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
12816ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Add, HP);
128283d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
12836ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
128483d577490b1473213b6973236110c28e59127956Dan Gohman      }
12857656018c2268285907cfdc106071462a01a73878Gabor Greif    }
128636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
128736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
12886ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // {0,+,1} --> Insert a canonical induction variable into the loop!
12896ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (S->isAffine() && S->getOperand(1)->isOne()) {
12906ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
12916ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "IVs with types different from the canonical IV should "
12926ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "already have been handled!");
12936ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    return CanonicalIV;
12946ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  }
12956ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman
12964d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
129736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1298df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
129940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
130040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
130140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
13026ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        SE.getMulExpr(SE.getUnknown(CanonicalIV),
130340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
13046ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                            CanonicalIV->getType())),
130540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
130636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
130736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
130836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
130936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
131036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
13116ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
131236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
13140bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
13156ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
13164d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
13174d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
13184d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
13190bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1320e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
132136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13224d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
13230bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1324469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
132536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
132696fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1327890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1328db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
132992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
133092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1331a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateTrunc(V, Ty);
1332a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1333cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
133411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
133511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1336890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1337db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
133892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
133992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1340a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateZExt(V, Ty);
1341a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1342cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
134311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
134411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1345890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1346db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
134792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
134892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1349a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateSExt(V, Ty);
1350a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1351cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
135211f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
135311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1354890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
13550196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1356db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
13570196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
13580196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
13590196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
13600196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
13610196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
13620196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
13630196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
136492fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1365a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1366a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1367267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1368a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1369cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1370c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
13710196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
13720196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
13730196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
13740196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1375c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1376c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1377c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1378890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
13790196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1380db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
13810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
13820196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
13830196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
13840196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
13850196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
13860196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
13870196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
138892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1389a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1390a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1391267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1392a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1393cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
13943e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
13950196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
13960196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
13970196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
13980196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
13993e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
14003e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
14013e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
1402db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
14036c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                                   Instruction *I) {
14046c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  BasicBlock::iterator IP = I;
14056c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
14066c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    ++IP;
14076c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  Builder.SetInsertPoint(IP->getParent(), IP);
14086c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
14096c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
14106c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
1411db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
141211f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
14132d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
14145be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
14155be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
14165be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
14175be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
14185be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
14195be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
142011f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
142111f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1422890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
142340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
142440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1425267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction *InsertPt = Builder.GetInsertPoint();
1426267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
142740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
142817ead4ff4baceb2c5503f233d0288d363ae44165Dan Gohman    if (SE.isLoopInvariant(S, L)) {
142940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1430e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
143140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
14320f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      else {
14330f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // LSR sets the insertion point for AddRec start/step values to the
14340f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // block start to simplify value reuse, even though it's an invalid
14350f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // position. SCEVExpander must correct for this in all cases.
14360f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        InsertPt = L->getHeader()->getFirstInsertionPt();
14370f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      }
143840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
143940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
144040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
144140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
14425b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling      if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
14435b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling        InsertPt = L->getHeader()->getFirstInsertionPt();
14446c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman      while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
14457896c9f436a4eda5ec15e882a7505ba482a2fcd0Chris Lattner        InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
144640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
144740a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
144840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1449667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1450667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  std::map<std::pair<const SCEV *, Instruction *>,
1451667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman           AssertingVH<Value> >::iterator I =
1452667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    InsertedExpressions.find(std::make_pair(S, InsertPt));
1453267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1454667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1455267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1456267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1457267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1458267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1459667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1460667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
146196fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
146240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1463667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
146448ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  //
146548ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // This is independent of PostIncLoops. The mapped value simply materializes
146648ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // the expression at this insertion point. If the mapped value happened to be
146748ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // a postinc expansion, it could be reused by a non postinc user, but only if
146848ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // its insertion point was already at the head of the loop.
146948ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1470667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1471455985501381777db03534c925a35e261e356395Dan Gohman  restoreInsertPoint(SaveInsertBB, SaveInsertPt);
147296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
147396fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
14741d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
14751d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
147625fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  if (!PostIncLoops.empty())
147725fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman    InsertedPostIncValues.insert(I);
147825fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  else
14791d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
14801d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
14811d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // If we just claimed an existing instruction and that instruction had
14823228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // been the insert point, adjust the insert point forward so that
14831d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  // subsequently inserted code will be dominated.
14841d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  if (Builder.GetInsertPoint() == I) {
14851d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    BasicBlock::iterator It = cast<Instruction>(I);
14866c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman    do { ++It; } while (isInsertedInstruction(It) ||
14876c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman                        isa<DbgInfoIntrinsic>(It));
14881d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
14891d826a76f591afea445489b9a5485c345e66bf87Dan Gohman  }
14901d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
14911d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
1492455985501381777db03534c925a35e261e356395Dan Gohmanvoid SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
14933f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If we acquired more instructions since the old insert point was saved,
1494455985501381777db03534c925a35e261e356395Dan Gohman  // advance past them.
14956c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1496455985501381777db03534c925a35e261e356395Dan Gohman
1497455985501381777db03534c925a35e261e356395Dan Gohman  Builder.SetInsertPoint(BB, I);
1498455985501381777db03534c925a35e261e356395Dan Gohman}
1499455985501381777db03534c925a35e261e356395Dan Gohman
15001d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
15011d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
15021d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
15031d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
15047c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan GohmanPHINode *
15051d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1506db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                                    Type *Ty) {
1507b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1508133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1509133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Build a SCEV for {0,+,1}<L>.
15103228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // Conservatively use FlagAnyWrap for now.
1511deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
15123228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                   SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1513133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1514133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Emit code for it.
1515267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1516267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
15177c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan Gohman  PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
1518267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (SaveInsertBB)
1519455985501381777db03534c925a35e261e356395Dan Gohman    restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1520133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
152140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
15221d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1523204494149b6f846e8f173f525b129f5508076049Andrew Trick
1524204494149b6f846e8f173f525b129f5508076049Andrew Trick/// hoistStep - Attempt to hoist an IV increment above a potential use.
1525204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1526204494149b6f846e8f173f525b129f5508076049Andrew Trick/// To successfully hoist, two criteria must be met:
1527204494149b6f846e8f173f525b129f5508076049Andrew Trick/// - IncV operands dominate InsertPos and
1528204494149b6f846e8f173f525b129f5508076049Andrew Trick/// - InsertPos dominates IncV
1529204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1530204494149b6f846e8f173f525b129f5508076049Andrew Trick/// Meeting the second condition means that we don't need to check all of IncV's
1531204494149b6f846e8f173f525b129f5508076049Andrew Trick/// existing uses (it's moving up in the domtree).
1532204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1533204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not yet recursively hoist the operands, although that would
1534204494149b6f846e8f173f525b129f5508076049Andrew Trick/// not be difficult.
1535204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1536204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not require a SCEVExpander instance and could be replaced by a
1537204494149b6f846e8f173f525b129f5508076049Andrew Trick/// general code-insertion helper.
1538204494149b6f846e8f173f525b129f5508076049Andrew Trickbool SCEVExpander::hoistStep(Instruction *IncV, Instruction *InsertPos,
1539204494149b6f846e8f173f525b129f5508076049Andrew Trick                             const DominatorTree *DT) {
1540204494149b6f846e8f173f525b129f5508076049Andrew Trick  if (DT->dominates(IncV, InsertPos))
1541204494149b6f846e8f173f525b129f5508076049Andrew Trick    return true;
1542204494149b6f846e8f173f525b129f5508076049Andrew Trick
1543204494149b6f846e8f173f525b129f5508076049Andrew Trick  if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
1544204494149b6f846e8f173f525b129f5508076049Andrew Trick    return false;
1545204494149b6f846e8f173f525b129f5508076049Andrew Trick
1546204494149b6f846e8f173f525b129f5508076049Andrew Trick  if (IncV->mayHaveSideEffects())
1547204494149b6f846e8f173f525b129f5508076049Andrew Trick    return false;
1548204494149b6f846e8f173f525b129f5508076049Andrew Trick
1549204494149b6f846e8f173f525b129f5508076049Andrew Trick  // Attempt to hoist IncV
1550204494149b6f846e8f173f525b129f5508076049Andrew Trick  for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
1551204494149b6f846e8f173f525b129f5508076049Andrew Trick       OI != OE; ++OI) {
1552204494149b6f846e8f173f525b129f5508076049Andrew Trick    Instruction *OInst = dyn_cast<Instruction>(OI);
15533326ec18423716da3a768caae2691e7858913548Andrew Trick    if (OInst && (OInst == InsertPos || !DT->dominates(OInst, InsertPos)))
1554204494149b6f846e8f173f525b129f5508076049Andrew Trick      return false;
1555204494149b6f846e8f173f525b129f5508076049Andrew Trick  }
1556204494149b6f846e8f173f525b129f5508076049Andrew Trick  IncV->moveBefore(InsertPos);
1557204494149b6f846e8f173f525b129f5508076049Andrew Trick  return true;
1558204494149b6f846e8f173f525b129f5508076049Andrew Trick}
1559204494149b6f846e8f173f525b129f5508076049Andrew Trick
1560204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replaceCongruentIVs - Check for congruent phis in this loop header and
1561204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replace them with their most canonical representative. Return the number of
1562204494149b6f846e8f173f525b129f5508076049Andrew Trick/// phis eliminated.
1563204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1564204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not depend on any SCEVExpander state but should be used in
1565204494149b6f846e8f173f525b129f5508076049Andrew Trick/// the same context that SCEVExpander is used.
1566204494149b6f846e8f173f525b129f5508076049Andrew Trickunsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1567204494149b6f846e8f173f525b129f5508076049Andrew Trick                                           SmallVectorImpl<WeakVH> &DeadInsts) {
1568204494149b6f846e8f173f525b129f5508076049Andrew Trick  unsigned NumElim = 0;
1569204494149b6f846e8f173f525b129f5508076049Andrew Trick  DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1570204494149b6f846e8f173f525b129f5508076049Andrew Trick  for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1571204494149b6f846e8f173f525b129f5508076049Andrew Trick    PHINode *Phi = cast<PHINode>(I);
1572204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!SE.isSCEVable(Phi->getType()))
1573204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1574204494149b6f846e8f173f525b129f5508076049Andrew Trick
1575204494149b6f846e8f173f525b129f5508076049Andrew Trick    PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1576204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!OrigPhiRef) {
1577204494149b6f846e8f173f525b129f5508076049Andrew Trick      OrigPhiRef = Phi;
1578204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1579204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1580204494149b6f846e8f173f525b129f5508076049Andrew Trick
1581204494149b6f846e8f173f525b129f5508076049Andrew Trick    // If one phi derives from the other via GEPs, types may differ.
1582204494149b6f846e8f173f525b129f5508076049Andrew Trick    // We could consider adding a bitcast here to handle it.
1583204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (OrigPhiRef->getType() != Phi->getType())
1584204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1585204494149b6f846e8f173f525b129f5508076049Andrew Trick
1586204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1587204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *OrigInc =
1588204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1589204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *IsomorphicInc =
1590204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1591204494149b6f846e8f173f525b129f5508076049Andrew Trick
1592204494149b6f846e8f173f525b129f5508076049Andrew Trick      // If this phi is more canonical, swap it with the original.
1593365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick      if (!isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)
1594365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick          && isExpandedAddRecExprPHI(Phi, IsomorphicInc, L)) {
1595204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigPhiRef, Phi);
1596204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigInc, IsomorphicInc);
1597204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1598204494149b6f846e8f173f525b129f5508076049Andrew Trick      // Replacing the congruent phi is sufficient because acyclic redundancy
1599204494149b6f846e8f173f525b129f5508076049Andrew Trick      // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1600204494149b6f846e8f173f525b129f5508076049Andrew Trick      // that a phi is congruent, it's often the head of an IV user cycle that
1601204494149b6f846e8f173f525b129f5508076049Andrew Trick      // is isomorphic with the original phi. So it's worth eagerly cleaning up
1602204494149b6f846e8f173f525b129f5508076049Andrew Trick      // the common case of a single IV increment.
1603204494149b6f846e8f173f525b129f5508076049Andrew Trick      if (OrigInc != IsomorphicInc &&
1604204494149b6f846e8f173f525b129f5508076049Andrew Trick          OrigInc->getType() == IsomorphicInc->getType() &&
1605204494149b6f846e8f173f525b129f5508076049Andrew Trick          SE.getSCEV(OrigInc) == SE.getSCEV(IsomorphicInc) &&
1606204494149b6f846e8f173f525b129f5508076049Andrew Trick          hoistStep(OrigInc, IsomorphicInc, DT)) {
1607204494149b6f846e8f173f525b129f5508076049Andrew Trick        DEBUG_WITH_TYPE(DebugType, dbgs()
1608204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << "INDVARS: Eliminated congruent iv.inc: "
1609204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << *IsomorphicInc << '\n');
1610204494149b6f846e8f173f525b129f5508076049Andrew Trick        IsomorphicInc->replaceAllUsesWith(OrigInc);
1611204494149b6f846e8f173f525b129f5508076049Andrew Trick        DeadInsts.push_back(IsomorphicInc);
1612204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1613204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1614204494149b6f846e8f173f525b129f5508076049Andrew Trick    DEBUG_WITH_TYPE(DebugType, dbgs()
1615204494149b6f846e8f173f525b129f5508076049Andrew Trick                    << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1616204494149b6f846e8f173f525b129f5508076049Andrew Trick    ++NumElim;
1617204494149b6f846e8f173f525b129f5508076049Andrew Trick    Phi->replaceAllUsesWith(OrigPhiRef);
1618204494149b6f846e8f173f525b129f5508076049Andrew Trick    DeadInsts.push_back(Phi);
1619204494149b6f846e8f173f525b129f5508076049Andrew Trick  }
1620204494149b6f846e8f173f525b129f5508076049Andrew Trick  return NumElim;
1621204494149b6f846e8f173f525b129f5508076049Andrew Trick}
1622