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"
17d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/STLExtras.h"
1836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/ADT/SmallSet.h"
19c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines#include "llvm/Analysis/InstructionSimplify.h"
20e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling#include "llvm/Analysis/LoopInfo.h"
21e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth#include "llvm/Analysis/TargetTransformInfo.h"
220b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
2336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/Dominators.h"
240b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
250b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/LLVMContext.h"
260c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar#include "llvm/IR/Module.h"
27cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar#include "llvm/IR/PatternMatch.h"
28c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick#include "llvm/Support/Debug.h"
294c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar#include "llvm/Support/raw_ostream.h"
30d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
3136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begemanusing namespace llvm;
32cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarusing namespace PatternMatch;
3336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
3419e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
35485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// reusing an existing cast if a suitable one exists, moving an existing
36485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman/// cast if a suitable one exists but isn't in the right place, or
3719e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif/// creating a new one.
38db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
39485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       Instruction::CastOps Op,
40485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman                                       BasicBlock::iterator IP) {
41919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // This function must be called with the builder having a valid insertion
42919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // point. It doesn't need to be the actual IP where the uses of the returned
43919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // cast will be added, but it must dominate such IP.
4423b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // We use this precondition to produce a cast that will dominate all its
4523b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // uses. In particular, this is crucial for the case where the builder's
4623b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // insertion point *is* the point where we were asked to put the cast.
47c8e41c591741b3da1077f7000274ad040bef8002Sylvestre Ledru  // Since we don't know the builder's insertion point is actually
48919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // where the uses will be added (only that it dominates it), we are
49919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  // not allowed to move it.
50919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola  BasicBlock::iterator BIP = Builder.GetInsertPoint();
51919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola
52dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Instruction *Ret = nullptr;
53ef4c80e07baf02dd2a8f08db49c5634a06d3ca1eRafael Espindola
54485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Check to see if there is already a cast!
5536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (User *U : V->users())
56f64f9cf7ec39ae91bca84dc6ad3c8fc3343b358aGabor Greif    if (U->getType() == Ty)
5719e5ada58a8a07d3d6d67312550f6d0791d84c3cGabor Greif      if (CastInst *CI = dyn_cast<CastInst>(U))
58485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        if (CI->getOpcode() == Op) {
59b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // If the cast isn't where we want it, create a new cast at IP.
60b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // Likewise, do not reuse a cast at BIP because it must dominate
61b84d540bc9d70de00b791d0e0deab410d6ba3ad5Rafael Espindola          // instructions that might be inserted before BIP.
62919a503458c18472984c7c37b305110c9ba3a782Rafael Espindola          if (BasicBlock::iterator(CI) != IP || BIP == IP) {
63485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // Create a new cast, and leave the old cast in place in case
64485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // it is being used as an insert point. Clear its operand
65485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            // so that it doesn't hold anything live.
66cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            Ret = CastInst::Create(Op, V, Ty, "", &*IP);
6723b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola            Ret->takeName(CI);
6823b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola            CI->replaceAllUsesWith(Ret);
69485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            CI->setOperand(0, UndefValue::get(V->getType()));
7023b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola            break;
71485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman          }
7223b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola          Ret = CI;
7323b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola          break;
74485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman        }
75485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
76485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Create a new cast.
7723b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  if (!Ret)
78cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
7923b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola
8023b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // We assert at the end of the function since IP might point to an
8123b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // instruction with different dominance properties than a cast
8223b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  // (an invoke for example) and not dominate BIP (but the cast does).
83cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  assert(SE.DT.dominates(Ret, &*BIP));
8423b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola
8523b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  rememberInstruction(Ret);
8623b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  return Ret;
87485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman}
88485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
89cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarstatic BasicBlock::iterator findInsertPointAfter(Instruction *I,
90cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                                 BasicBlock *MustDominate) {
91cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  BasicBlock::iterator IP = ++I->getIterator();
92cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (auto *II = dyn_cast<InvokeInst>(I))
93cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    IP = II->getNormalDest()->begin();
94cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
95cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  while (isa<PHINode>(IP))
96cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    ++IP;
97cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
98cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  while (IP->isEHPad()) {
99cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
100cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      ++IP;
101cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    } else if (isa<CatchSwitchInst>(IP)) {
102cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      IP = MustDominate->getFirstInsertionPt();
103cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    } else {
104cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      llvm_unreachable("unexpected eh pad!");
105cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
106cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
107cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
108cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return IP;
109cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
110cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
111267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
112267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
113267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
114db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
115267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
116267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
117267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
118267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
119267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
120267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
121267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
122267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1232d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
12419154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  if (Op == Instruction::BitCast) {
12519154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (V->getType() == Ty)
12619154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      return V;
12719154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (CastInst *CI = dyn_cast<CastInst>(V)) {
12819154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      if (CI->getOperand(0)->getType() == Ty)
12919154f457696f286b4a597179fa07e3b38ea0310Andrew Trick        return CI->getOperand(0);
13019154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    }
13119154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  }
132f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
133267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
13480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
135af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
136af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
137af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
138af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
139af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
140af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
14180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
14280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
14380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
14480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
14580dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
14680dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
14780dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
148f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
149485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Fold a cast of a constant.
150ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
151baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
1524c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
153485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the argument at the beginning of the entry block, after
154485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // any bitcasts of other arguments.
155ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
156485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
157485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    while ((isa<BitCastInst>(IP) &&
158485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
159485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            cast<BitCastInst>(IP)->getOperand(0) != A) ||
160cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar           isa<DbgInfoIntrinsic>(IP))
161485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman      ++IP;
162485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    return ReuseOrCreateCast(A, Ty, Op, IP);
163ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
1643913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
165485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the instruction immediately after the instruction.
166ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
167cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
168485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return ReuseOrCreateCast(I, Ty, Op, IP);
169ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
170ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1717fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1727fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
173267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
174267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1750f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1760f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1770f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
178baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1790f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1807fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1817fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
182267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
183267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
184267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
185267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1868a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1878a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1888d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1898d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1908d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1918d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
194cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        return &*IP;
1958a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1968a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1977fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
198267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
199087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
200d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
201d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BuilderType::InsertPointGuard Guard(Builder);
202087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
203087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
204cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
205087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
206087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
207087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
208087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
209087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
210cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Builder.SetInsertPoint(Preheader->getTerminator());
211087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
212087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
2138a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
214a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
215d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BO->setDebugLoc(Loc);
216a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
217087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
218cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
2197fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
2207fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
2214a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
222453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
2233f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
2244a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
225453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
226453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
227453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
2284c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarstatic bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
2294c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                              const SCEV *Factor, ScalarEvolution &SE,
2304c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                              const DataLayout &DL) {
231453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
235c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
236c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
237deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    S = SE.getConstant(S->getType(), 1);
238453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
239c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
240453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
241453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2424a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
243c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
245453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
247c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
249cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
250c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
253c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
254c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
255c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
256cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        Remainder = SE.getAddExpr(
257cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
258c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
259c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
260453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2614a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
262453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
263453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
264453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
265c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2664c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    // Size is known, check if there is a constant operand which is a multiple
2674c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    // of the given factor. If so, we can factor it.
2684c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    const SCEVConstant *FC = cast<SCEVConstant>(Factor);
2694c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
270cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (!C->getAPInt().srem(FC->getAPInt())) {
2714c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
272cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
2734c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        S = SE.getMulExpr(NewMulOps);
2744c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        return true;
275453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
276c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
277453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
278453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
279453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2800bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
281deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
28236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
2834a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2844a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2854a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2860bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
28736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
288453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
2896f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick    S = SE.getAddRecExpr(Start, Step, A->getLoop(),
2906f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                         A->getNoWrapFlags(SCEV::FlagNW));
291453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
292453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
293453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
294453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
295453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
296453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
299c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
300c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
302db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                Type *Ty,
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
310c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
312deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                    SE.getConstant(Ty, 0) :
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
314c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
316f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
317c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
318403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(Add->op_begin(), Add->op_end());
319f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
320f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
322403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman  Ops.append(AddRecs.begin(), AddRecs.end());
323c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
324c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
325c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
326c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
328c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
329c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
330c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
331db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                         Type *Ty,
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
334c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
335c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
336c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
337c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
339deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman      const SCEV *Zero = SE.getConstant(Ty, 0);
340c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
341c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
3423228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         A->getLoop(),
3436f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                         A->getNoWrapFlags(SCEV::FlagNW)));
344c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
345c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
346403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman        Ops.append(Add->op_begin(), Add->op_end());
347c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
348c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
349c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
350c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
351c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
352c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
353c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
354403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(AddRecs.begin(), AddRecs.end());
355c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
356c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
357c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
358c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
359c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3604c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3614c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3624c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3634c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3644c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3654c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
36613c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3673abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3684c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3694c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3704c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
371453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
372453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
373453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
374453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
375453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
376453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
377453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
378453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
379453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
380453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
381453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
382453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
383453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
384453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
385453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
386453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3870bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3880bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
389db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    PointerType *PTy,
390db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    Type *Ty,
3915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
3924c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *OriginalElTy = PTy->getElementType();
3934c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *ElTy = OriginalElTy;
3945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3950bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3975be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
398c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
399c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
400c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
401c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
4024c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *IntPtrTy = DL.getIntPtrType(PTy);
40314807bd8c801f976c999e5a6699f31ee9642021aMatt Arsenault
404eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
4055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
4065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
4075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
4085be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
4095be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
410c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
411c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
4120bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
413150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
41414807bd8c801f976c999e5a6699f31ee9642021aMatt Arsenault      const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
415150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
416150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
417cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        for (const SCEV *Op : Ops) {
418deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman          const SCEV *Remainder = SE.getConstant(Ty, 0);
4194c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
420150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
421150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
422150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
423150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
424150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
425150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
426150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
427150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
428cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            NewOps.push_back(Op);
429150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
430150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
431150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
432150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
433150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
434150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4375be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
438c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
440c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
441c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
444a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4475be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4485be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
449db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    while (StructType *STy = dyn_cast<StructType>(ElTy)) {
450c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
451c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
452c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
4534c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      // Field offsets are known. See if a constant offset falls within any of
4544c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      // the struct fields.
4554c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (Ops.empty())
4564c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        break;
4574c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4584c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4594c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          const StructLayout &SL = *DL.getStructLayout(STy);
4604c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          uint64_t FullOffset = C->getValue()->getZExtValue();
4614c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          if (FullOffset < SL.getSizeInBytes()) {
4624c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4634c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            GepIndices.push_back(
4644c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4654c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            ElTy = STy->getTypeAtIndex(ElIdx);
4664c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            Ops[0] =
4676de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4684c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            AnyNonZeroIndices = true;
4694c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            FoundFieldNo = true;
4700f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4714c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        }
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
474c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
475c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
476c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
478c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
479c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
480c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
482db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
484c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
485c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4865be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4883f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
4895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4905be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
492c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4935be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
494ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
495c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
496705b48d960dff1a96ac40d0cf932eb465b9a550aRafael Espindola    assert(!isa<Instruction>(V) ||
497cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar           SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
4984b04578d65e38cdb5077de2498889e4a174ccdfdRafael Espindola
499c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
50092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
5015be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
5035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
5045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
5050c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
5060c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar                                              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)
522cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          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.
528d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer    BuilderType::InsertPointGuard Guard(Builder);
529087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
530087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
531cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
532087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
533087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
534087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
535087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
536087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
537cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      Builder.SetInsertPoint(Preheader->getTerminator());
538087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
539087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
540c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
5410c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
542a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
543087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
548341562b9fb6574b1c9492e52cec24106cd31ce51Benjamin Kramer  BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
549087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
550087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
551cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
552087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(V)) break;
553087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
554cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    bool AnyIndexNotLoopInvariant =
555cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        std::any_of(GepIndices.begin(), GepIndices.end(),
556cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                    [L](Value *Op) { return !L->isLoopInvariant(Op); });
557cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (AnyIndexNotLoopInvariant)
559087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      break;
560087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
561087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
562087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
563087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
564087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
565cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Builder.SetInsertPoint(Preheader->getTerminator());
566087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
567087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
568d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
569d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // because ScalarEvolution may have changed the address arithmetic to
570d6aa02de1076c801ac41295156a2379637976918Dan Gohman  // compute a value which is beyond the end of the allocated object.
571a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Casted = V;
572a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (V->getType() != PTy)
573a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Casted = InsertNoopCastOfTo(Casted, PTy);
574cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
5755be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  Ops.push_back(SE.getUnknown(GEP));
576a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(GEP);
577087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
578341562b9fb6574b1c9492e52cec24106cd31ce51Benjamin Kramer  // Restore the original insert point.
579341562b9fb6574b1c9492e52cec24106cd31ce51Benjamin Kramer  Builder.restoreIP(SaveInsertPt);
580341562b9fb6574b1c9492e52cec24106cd31ce51Benjamin Kramer
5815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5825be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5835be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
584087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
585087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
586087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
587087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
588087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
589087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
590087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
591087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
592087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
593087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
594087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
595087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
596087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
597087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5989c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman/// getRelevantLoop - Get the most relevant loop associated with the given
599087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
6009c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohmanconst Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
6019c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  // Test whether we've already computed the most relevant loop for this SCEV.
602cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
6039c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (!Pair.second)
6049c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return Pair.first->second;
6059c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman
606087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
6079c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A constant has no relevant loops.
608dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
609087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
610087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
611cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return Pair.first->second = SE.LI.getLoopFor(I->getParent());
6129c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A non-instruction has no relevant loops.
613dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
614087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
615087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
616dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    const Loop *L = nullptr;
617087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
618087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
619cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (const SCEV *Op : N->operands())
620cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
6219c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[N] = L;
6229c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6239c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6249c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result = getRelevantLoop(C->getOperand());
6259c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[C] = Result;
6269c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6279c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
628cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    const Loop *Result = PickMostRelevantLoop(
629cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
6309c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[D] = Result;
631087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
632087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
633087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
634c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
635b35798347ea87b8b6d36155b211016a7769f01abDan Gohmannamespace {
636b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
637087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
638087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
639087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
640087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
641087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
642087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
643087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
644087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
645bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    // Keep pointer operands sorted at the end.
646bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    if (LHS.second->getType()->isPointerTy() !=
647bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        RHS.second->getType()->isPointerTy())
648bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      return LHS.second->getType()->isPointerTy();
649bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman
650087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
651087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
652087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
653087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
654087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
655087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
656087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
657f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    if (LHS.second->isNonConstantNegative()) {
658f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick      if (!RHS.second->isNonConstantNegative())
659087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
660f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (RHS.second->isNonConstantNegative())
661087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
662087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
663087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
664087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
665c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
666087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
6675be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
668b35798347ea87b8b6d36155b211016a7769f01abDan Gohman}
669b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
670087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
671db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
672e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
673087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
674087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
675087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
676087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
677087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
6809c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
681087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
682087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
683087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
684cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
685087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
686087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
687087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
688dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *Sum = nullptr;
689cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
690087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
692087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
693087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
694087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
695087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
696db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
697087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
698087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
699087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
700bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      for (; I != E && I->first == CurLoop; ++I) {
701bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // If the operand is SCEVUnknown and not instructions, peek through
702bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // it, to enable more of it to be folded into the GEP.
703bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        const SCEV *X = I->second;
704bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
705bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman          if (!isa<Instruction>(U->getValue()))
706bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman            X = SE.getSCEV(U->getValue());
707bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        NewOps.push_back(X);
708bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      }
709087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
710db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
711087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
712f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
713f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
714087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
715f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
716f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
718087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
719087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
720f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (Op->isNonConstantNegative()) {
721087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
722a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
723087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
724087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
725087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
726a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
727087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
728a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
729087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
730087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
731087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
732087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
733087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
734a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7352d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
736087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
737087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
738e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7395be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
740890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
741db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
742087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
743087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
744087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
745087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
746087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
747087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7489c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
749087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
750087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
751cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
752087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
753087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
754087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
755dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *Prod = nullptr;
756cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (const auto &I : OpsAndLoops) {
757cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    const SCEV *Op = I.second;
758087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
759087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
760087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
761087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
763087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
764087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
765087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
766087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
767087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
768087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
769087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
770087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
771cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      const APInt *RHS;
772cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (match(W, m_Power2(RHS))) {
773cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        // Canonicalize Prod*(1<<C) to Prod<<C.
774cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        assert(!Ty->isVectorTy() && "vector types are not SCEVable");
775cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        Prod = InsertBinop(Instruction::Shl, Prod,
776cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                           ConstantInt::get(Ty, RHS->logBase2()));
777cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      } else {
778cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        Prod = InsertBinop(Instruction::Mul, Prod, W);
779cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      }
780087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
7812d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
7822d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
783087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
78436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
78536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
786890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
787db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
7882d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
78992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
790890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
791cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    const APInt &RHS = SC->getAPInt();
7926177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
7936177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
794eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
7956177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
7966177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
79792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
798267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
7996177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
8006177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
801453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
802453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
803453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
8040bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
805453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
806453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
807453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
808453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
809deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                         SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
810453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
8113228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          A->getLoop(),
8126f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                          A->getNoWrapFlags(SCEV::FlagNW)));
813453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
814453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
815453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8160bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
817453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
818453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
819453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
820453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
821453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
822453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
823c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// Determine if this is a well-behaved chain of instructions leading back to
824c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// the PHI. If so, it may be reused by expanded expressions.
825c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trickbool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
826c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick                                         const Loop *L) {
827c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
828c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
829c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
830c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // If any of the operands don't dominate the insert position, bail.
831c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Addrec operands are always loop-invariant, so this can only happen
832c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // if there are instructions which haven't been hoisted.
833c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (L == IVIncInsertLoop) {
834c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (User::op_iterator OI = IncV->op_begin()+1,
835c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           OE = IncV->op_end(); OI != OE; ++OI)
836c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(OI))
837cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        if (!SE.DT.dominates(OInst, IVIncInsertPos))
838c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          return false;
839c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
840c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Advance to the next instruction.
841c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
842c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (!IncV)
843c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
844c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
845c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->mayHaveSideEffects())
846c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
847c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
848c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV != PN)
849c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return true;
850c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
851c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  return isNormalAddRecExprPHI(PN, IncV, L);
852c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
853c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
854b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// getIVIncOperand returns an induction variable increment's induction
855b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// variable operand.
856b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
857b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is set, any type of GEP is allowed as long as the nonIV
858b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// operands dominate InsertPos.
859b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
860b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is not set, ensure that a GEP increment conforms to one of the
861b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// simple patterns generated by getAddRecExprPHILiterally and
862b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
863b5c26ef9da16052597d59a412eaae32098aa1be0Andrew TrickInstruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
864b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           Instruction *InsertPos,
865b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           bool allowScale) {
866b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  if (IncV == InsertPos)
867dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
86864925c55c65f9345a69fb67db07aa62cfb723577Andrew Trick
869c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  switch (IncV->getOpcode()) {
870b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  default:
871dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
872c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Check for a simple Add/Sub or GEP of a loop invariant step.
873c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::Add:
874b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::Sub: {
875b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
876cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!OInst || SE.DT.dominates(OInst, InsertPos))
877b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return dyn_cast<Instruction>(IncV->getOperand(0));
878dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
879b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
880c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::BitCast:
881b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
882b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::GetElementPtr:
883cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
884c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (isa<Constant>(*I))
885c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
886b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
887cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        if (!SE.DT.dominates(OInst, InsertPos))
888dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          return nullptr;
889b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
890b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (allowScale) {
891b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        // allow any kind of GEP as long as it can be hoisted.
892b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        continue;
893b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
894b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // This must be a pointer addition of constants (pretty), which is already
895b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // handled, or some number of address-size elements (ugly). Ugly geps
896b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // have 2 operands. i1* is used by the expander to represent an
897b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // address-size element.
898c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getNumOperands() != 2)
899dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
900365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick      unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
901c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
902c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
903dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
904c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      break;
905c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
906b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
907c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
908b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
909b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
910b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
911b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// it available to other uses in this loop. Recursively hoist any operands,
912b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// until we reach a value that dominates InsertPos.
913b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
914cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (SE.DT.dominates(IncV, InsertPos))
915b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
916b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
917b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // InsertPos must itself dominate IncV so that IncV's new position satisfies
918b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // its existing users.
919cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (isa<PHINode>(InsertPos) ||
920cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
921cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return false;
922cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
923cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
924c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
925b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
926b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // Check that the chain of IV operands leading back to Phi can be hoisted.
927b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  SmallVector<Instruction*, 4> IVIncs;
928b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(;;) {
929b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
930b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (!Oper)
931b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return false;
932b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    // IncV is safe to hoist.
933b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IVIncs.push_back(IncV);
934b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IncV = Oper;
935cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (SE.DT.dominates(IncV, InsertPos))
936b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      break;
937b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
938cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
939b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    (*I)->moveBefore(InsertPos);
940b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
941b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return true;
942b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
943b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
944b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// Determine if this cyclic phi is in a form that would have been generated by
945b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// LSR. We don't care if the phi was actually expanded in this pass, as long
946b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// as it is in a low-cost form, for example, no implied multiplication. This
947b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// should match any patterns generated by getAddRecExprPHILiterally and
948b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP.
949b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
950b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           const Loop *L) {
951b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(Instruction *IVOper = IncV;
952b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
953b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                /*allowScale=*/false));) {
954b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (IVOper == PN)
955b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
956c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
957b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return false;
958c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
959c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
960553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
961553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
962553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// need to materialize IV increments elsewhere to handle difficult situations.
963553fe05f236f46fe27b7fcfa822b06367d50183eAndrew TrickValue *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
964553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 Type *ExpandTy, Type *IntTy,
965553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 bool useSubtract) {
966553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  Value *IncV;
967553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
968553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (ExpandTy->isPointerTy()) {
969553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
970553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If the step isn't constant, don't use an implicitly scaled GEP, because
971553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // that would require a multiply inside the loop.
972553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (!isa<ConstantInt>(StepV))
973553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
974553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                  GEPPtrTy->getAddressSpace());
975553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
976553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
977553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (IncV->getType() != PN->getType()) {
978553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      IncV = Builder.CreateBitCast(IncV, PN->getType());
979553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      rememberInstruction(IncV);
980553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
981553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  } else {
982553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = useSubtract ?
983553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
984553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
985553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    rememberInstruction(IncV);
986553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  }
987553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  return IncV;
988553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick}
989553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
99036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
99136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// position. This routine assumes that this is possible (has been checked).
99236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesstatic void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
99336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                           Instruction *Pos, PHINode *LoopPhi) {
99436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  do {
99536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (DT->dominates(InstToHoist, Pos))
99636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      break;
99736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Make sure the increment is where we want it. But don't move it
99836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // down past a potential existing post-inc user.
99936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InstToHoist->moveBefore(Pos);
100036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Pos = InstToHoist;
100136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
100236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  } while (InstToHoist != LoopPhi);
100336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
100436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
100536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// \brief Check whether we can cheaply express the requested SCEV in terms of
1006cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar/// the available PHI SCEV by truncation and/or inversion of the step.
100736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesstatic bool canBeCheaplyTransformed(ScalarEvolution &SE,
100836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    const SCEVAddRecExpr *Phi,
100936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    const SCEVAddRecExpr *Requested,
101036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    bool &InvertStep) {
101136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
101236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
101336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
101436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
101536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return false;
101636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
101736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Try truncate it if necessary.
101836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
101936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (!Phi)
102036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return false;
102136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
102236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Check whether truncation will help.
102336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (Phi == Requested) {
102436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = false;
102536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return true;
102636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
102736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
102836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
102936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (SE.getAddExpr(Requested->getStart(),
103036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                    SE.getNegativeSCEV(Requested)) == Phi) {
103136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = true;
103236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return true;
103336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
103436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
103536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  return false;
103636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
103736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1038ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesstatic bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1039ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (!isa<IntegerType>(AR->getType()))
1040ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    return false;
1041ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1042ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1043ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1044ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *Step = AR->getStepRecurrence(SE);
1045ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1046ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                                            SE.getSignExtendExpr(AR, WideTy));
1047ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *ExtendAfterOp =
1048ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1049ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  return ExtendAfterOp == OpAfterExtend;
1050ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines}
1051ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1052ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesstatic bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1053ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (!isa<IntegerType>(AR->getType()))
1054ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    return false;
1055ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1056ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1057ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1058ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *Step = AR->getStepRecurrence(SE);
1059ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1060ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                                            SE.getZeroExtendExpr(AR, WideTy));
1061ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *ExtendAfterOp =
1062ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1063ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  return ExtendAfterOp == OpAfterExtend;
1064ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines}
1065ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1066a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1067a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
1068a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
1069a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
1070a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1071a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
1072db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *ExpandTy,
107336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        Type *IntTy,
107436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        Type *&TruncTy,
107536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        bool &InvertStep) {
107693a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1077d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1078a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
1079c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  BasicBlock *LatchBlock = L->getLoopLatch();
1080c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (LatchBlock) {
1081dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    PHINode *AddRecPhiMatch = nullptr;
1082dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    Instruction *IncV = nullptr;
1083dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    TruncTy = nullptr;
108436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = false;
108536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
108636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Only try partially matching scevs that need truncation and/or
108736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // step-inversion if we know this loop is outside the current loop.
1088cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    bool TryNonMatchingSCEV =
1089cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        IVIncInsertLoop &&
1090cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
109136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1092cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (auto &I : *L->getHeader()) {
1093cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      auto *PN = dyn_cast<PHINode>(&I);
1094cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (!PN || !SE.isSCEVable(PN->getType()))
109536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        continue;
109636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
109736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
109836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!PhiSCEV)
1099c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
1100c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
110136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      bool IsMatchingSCEV = PhiSCEV == Normalized;
110236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // We only handle truncation and inversion of phi recurrences for the
110336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // expanded expression if the expanded expression's loop dominates the
110436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // loop we insert to. Check now, so we can bail out early.
110536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!IsMatchingSCEV && !TryNonMatchingSCEV)
110636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          continue;
110736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
110836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Instruction *TempIncV =
110936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1110c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
111136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Check whether we can reuse this PHI node.
1112c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (LSRMode) {
111336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1114c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
111536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1116b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          continue;
111736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } else {
111836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1119c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
1120c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
112136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
112236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Stop if we have found an exact match SCEV.
112336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (IsMatchingSCEV) {
112436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        IncV = TempIncV;
1125dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        TruncTy = nullptr;
112636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        InvertStep = false;
112736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        AddRecPhiMatch = PN;
112836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        break;
112936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      }
113036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
113136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Try whether the phi can be translated into the requested form
113236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // (truncated and/or offset by a constant).
113336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if ((!TruncTy || InvertStep) &&
113436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
113536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Record the phi node. But don't stop we might find an exact match
113636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // later.
113736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        AddRecPhiMatch = PN;
113836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        IncV = TempIncV;
113936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
114036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      }
114136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
114236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
114336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (AddRecPhiMatch) {
114436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Potentially, move the increment. We have made sure in
114536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
114636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (L == IVIncInsertLoop)
1147cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
114836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1149c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Ok, the add recurrence looks usable.
1150c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember this PHI, even in post-inc mode.
115136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      InsertedValues.insert(AddRecPhiMatch);
1152c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember the increment.
1153c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      rememberInstruction(IncV);
115436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return AddRecPhiMatch;
1155c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
1156c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
1157a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1158a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
1159d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BuilderType::InsertPointGuard Guard(Builder);
1160a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1161ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // Another AddRec may need to be recursively expanded below. For example, if
1162ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1163ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // loop. Remove this loop from the PostIncLoops set before expanding such
1164ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // AddRecs. Otherwise, we cannot find a valid position for the step
1165ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1166ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1167ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // so it's not worth implementing SmallPtrSet::swap.
1168ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1169ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops.clear();
1170ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1171a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
1172cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *StartV =
1173cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1174a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1175d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick  // StartV must be hoisted into L's preheader to dominate the new phi.
117693a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert(!isa<Instruction>(StartV) ||
1177cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar         SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1178cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                 L->getHeader()));
1179d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1180553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand code for the step value. Do this before creating the PHI so that PHI
1181553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // reuse code doesn't see an incomplete PHI.
1182a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1183553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the stride is negative, insert a sub instead of an add for the increment
1184553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // (unless it's a constant, because subtracts of constants are canonicalized
1185553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // to adds).
1186f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1187553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (useSubtract)
1188a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
1189553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand the step somewhere that dominates the loop header.
1190cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1191a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1192ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1193ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // we actually do emit an addition.  It does not apply if we emit a
1194ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // subtraction.
1195ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1196ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1197ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1198a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
1199d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  BasicBlock *Header = L->getHeader();
1200d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  Builder.SetInsertPoint(Header, Header->begin());
1201d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
12025e7645be4c9dd2193add44d30b5fef8036d7a3ceAndrew Trick  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1203dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick                                  Twine(IVName) + ".iv");
1204a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
1205a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1206a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
1207d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1208a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
1209a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1210a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
1211a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
1212a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
1213a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
1214a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1215a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1216553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // Create a step value and add it to the PHI.
1217553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1218553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // instructions at IVIncInsertPos.
1219a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
1220a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
1221c5ecbdc1896f1cc089372feef3191ace2f840898Devang Patel    Builder.SetInsertPoint(InsertPos);
1222553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1223ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1224409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick    if (isa<OverflowingBinaryOperator>(IncV)) {
1225ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      if (IncrementIsNUW)
1226409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick        cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1227ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      if (IncrementIsNSW)
1228409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick        cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1229409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick    }
1230a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
1231a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1232a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1233ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // After expanding subexpressions, restore the PostIncLoops set so the caller
1234ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // can ensure that IVIncrement dominates the current uses.
1235ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops = SavedPostIncLoops;
1236ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1237a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
1238a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
1239a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1240a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
1241a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1242a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1243a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1244db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *STy = S->getType();
1245db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *IntTy = SE.getEffectiveSCEVType(STy);
1246a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
1247a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1248a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
1249a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
1250a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
1251448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
1252448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
1253448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
1254cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1255cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1256a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1257a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1258a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
1259a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
1260dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  const SCEV *PostLoopOffset = nullptr;
1261dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.properlyDominates(Start, L->getHeader())) {
1262a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
1263deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Start = SE.getConstant(Normalized->getType(), 0);
12643228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Normalized = cast<SCEVAddRecExpr>(
12653228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick      SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
12663228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       Normalized->getLoop(),
12676f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                       Normalized->getNoWrapFlags(SCEV::FlagNW)));
1268a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1269a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1270a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
1271a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1272dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  const SCEV *PostLoopScale = nullptr;
1273dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.dominates(Step, L->getHeader())) {
1274a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
1275deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Step = SE.getConstant(Normalized->getType(), 1);
1276a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
12776f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick      cast<SCEVAddRecExpr>(SE.getAddRecExpr(
12786f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                             Start, Step, Normalized->getLoop(),
12796f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                             Normalized->getNoWrapFlags(SCEV::FlagNW)));
1280a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1281a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1282a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1283a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1284db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ExpandTy = PostLoopScale ? IntTy : STy;
128536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // In some cases, we decide to reuse an existing phi node but need to truncate
128636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // it and/or invert the step.
1287dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *TruncTy = nullptr;
128836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  bool InvertStep = false;
128936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
129036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                          TruncTy, InvertStep);
1291a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
12923f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1293a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1294448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1295a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1296a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1297a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1298a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1299a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1300a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
130148ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick
130248ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // For an expansion to use the postinc form, the client must call
130348ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
130448ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // or dominated by IVIncInsertPos.
1305cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (isa<Instruction>(Result) &&
1306cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        !SE.DT.dominates(cast<Instruction>(Result),
1307cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                         &*Builder.GetInsertPoint())) {
1308553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // The induction variable's postinc expansion does not dominate this use.
1309553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // IVUsers tries to prevent this case, so it is rare. However, it can
1310553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // happen when an IVUser outside the loop is not dominated by the latch
1311553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1312553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // all cases. Consider a phi outide whose operand is replaced during
1313553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // expansion with the value of the postinc user. Without fundamentally
1314553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // changing the way postinc users are tracked, the only remedy is
1315553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1316553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // but hopefully expandCodeFor handles that.
1317553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      bool useSubtract =
1318f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick        !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1319553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      if (useSubtract)
1320553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        Step = SE.getNegativeSCEV(Step);
1321d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      Value *StepV;
1322d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      {
1323d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer        // Expand the step somewhere that dominates the loop header.
1324d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer        BuilderType::InsertPointGuard Guard(Builder);
1325cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1326d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      }
1327553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1328553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
1329a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1330a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
133136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // We have decided to reuse an induction variable of a dominating loop. Apply
133236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // truncation and/or invertion of the step.
133336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (TruncTy) {
133436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Type *ResTy = Result->getType();
133536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Normalize the result type.
133636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (ResTy != SE.getEffectiveSCEVType(ResTy))
133736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
133836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Truncate the result.
133936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (TruncTy != Result->getType()) {
134036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = Builder.CreateTrunc(Result, TruncTy);
134136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      rememberInstruction(Result);
134236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
134336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Invert the result.
134436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (InvertStep) {
134536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
134636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                 Result);
134736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      rememberInstruction(Result);
134836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
134936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
135036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1351a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1352a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
13534d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
13540a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1355a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1356a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1357a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1358a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1359a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1360a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1361a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1362db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1363a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1364a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1365a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
13660a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1367a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1368a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1369a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1370a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1371a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1372a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1373a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1374a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1375a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1376890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1377a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1378a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1379db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
138036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
138136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
13824d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
1383dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  PHINode *CanonicalIV = nullptr;
13844d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
1385133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman    if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
13864d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
13874d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
13884d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
13894d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
13904d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
13914d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
13924d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1393f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1394f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1395f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
13963228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
13976f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                       S->getNoWrapFlags(SCEV::FlagNW)));
13984d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
1399cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1400dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1401cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                      &*NewInsertPt);
14024d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
14034d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
14044d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
140536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1406cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1407f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1408deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    NewOps[0] = SE.getConstant(Ty, 0);
14096f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick    const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
14106f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                        S->getNoWrapFlags(SCEV::FlagNW));
1411453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1412453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1413453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1414c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1415c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1416c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1417c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1418c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1419db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1420c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1421c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1422c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1423c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1424c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1425c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1426c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1427453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1428453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1429453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
143040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
143140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
143240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                                SE.getUnknown(expand(Rest))));
143336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
143436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14356ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // If we don't yet have a canonical IV, create one.
14366ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (!CanonicalIV) {
143736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
143836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
143936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1440d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
14413ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1442cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                  &Header->front());
14436ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    rememberInstruction(CanonicalIV);
144436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
144519046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel    SmallSet<BasicBlock *, 4> PredSeen;
1446eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
1447d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
14487656018c2268285907cfdc106071462a01a73878Gabor Greif      BasicBlock *HP = *HPI;
144937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (!PredSeen.insert(HP).second) {
145037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // There must be an incoming value for each predecessor, even the
145137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // duplicates!
145237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
145319046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel        continue;
145437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      }
145519046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel
14567656018c2268285907cfdc106071462a01a73878Gabor Greif      if (L->contains(HP)) {
14573abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
14583abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
14596ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
14606ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     "indvar.next",
14616ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     HP->getTerminator());
1462df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel        Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1463a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
14646ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Add, HP);
146583d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
14666ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
146783d577490b1473213b6973236110c28e59127956Dan Gohman      }
14687656018c2268285907cfdc106071462a01a73878Gabor Greif    }
146936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
147036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14716ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // {0,+,1} --> Insert a canonical induction variable into the loop!
14726ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (S->isAffine() && S->getOperand(1)->isOne()) {
14736ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
14746ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "IVs with types different from the canonical IV should "
14756ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "already have been handled!");
14766ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    return CanonicalIV;
14776ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  }
14786ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman
14794d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
148036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1481df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
148240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
148340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
148440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
14856ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        SE.getMulExpr(SE.getUnknown(CanonicalIV),
148640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
14876ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                            CanonicalIV->getType())),
148840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
148936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
149036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
149136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
149236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
149336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
14946ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
149536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14964d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
14970bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
14986ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
14994d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
15004d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
15014d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
15020bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1503e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
150436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
15054d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
15060bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1507469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
150836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
150996fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1510890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1511db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
151292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
151392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1514a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateTrunc(V, Ty);
1515a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1516cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
151711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
151811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1519890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1520db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
152192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
152292fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1523a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateZExt(V, Ty);
1524a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1525cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
152611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
152711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1528890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1529db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
153092fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
153192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1532a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateSExt(V, Ty);
1533a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1534cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
153511f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
153611f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1537890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
15380196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1539db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
15400196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
15410196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
15420196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
15430196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
15440196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
15450196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
15460196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
154792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1548a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1549a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1550267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1551a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1552cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1553c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
15540196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
15550196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
15560196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
15570196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1558c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1559c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1560c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1561890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
15620196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1563db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
15640196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
15650196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
15660196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
15670196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
15680196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
15690196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
15700196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
157192fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1572a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1573a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1574267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1575a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1576cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
15773e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
15780196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
15790196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
15800196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
15810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
15823e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
15833e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
15843e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
1585db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1586b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                   Instruction *IP) {
1587cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  assert(IP);
1588cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Builder.SetInsertPoint(IP);
15896c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
15906c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
15916c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
1592db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
159311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
15942d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
15955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
15965be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
15975be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
15985be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
15995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
16005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
160111f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
160211f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1603890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
160440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
160540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1606cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Instruction *InsertPt = &*Builder.GetInsertPoint();
1607cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
160840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
160917ead4ff4baceb2c5503f233d0288d363ae44165Dan Gohman    if (SE.isLoopInvariant(S, L)) {
161040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1611e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
161240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
16130f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      else {
16140f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // LSR sets the insertion point for AddRec start/step values to the
16150f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // block start to simplify value reuse, even though it's an invalid
16160f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // position. SCEVExpander must correct for this in all cases.
1617cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        InsertPt = &*L->getHeader()->getFirstInsertionPt();
16180f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      }
161940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
162040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
162140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
162240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
16235b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling      if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1624cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        InsertPt = &*L->getHeader()->getFirstInsertionPt();
1625b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      while (InsertPt != Builder.GetInsertPoint()
1626b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick             && (isInsertedInstruction(InsertPt)
1627b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                 || isa<DbgInfoIntrinsic>(InsertPt))) {
1628cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        InsertPt = &*std::next(InsertPt->getIterator());
1629b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
163040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
163140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
163240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1633667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1634cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1635267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1636667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1637267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1638d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BuilderType::InsertPointGuard Guard(Builder);
1639cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Builder.SetInsertPoint(InsertPt);
1640667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1641667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
164296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  Value *V = visit(S);
164340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1644667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
164548ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  //
164648ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // This is independent of PostIncLoops. The mapped value simply materializes
164748ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // the expression at this insertion point. If the mapped value happened to be
164836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // a postinc expansion, it could be reused by a non-postinc user, but only if
164948ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // its insertion point was already at the head of the loop.
165048ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
165196fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
165296fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
16531d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
16541d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
165525fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  if (!PostIncLoops.empty())
165625fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman    InsertedPostIncValues.insert(I);
165725fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  else
16581d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
16591d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
16601d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
16611d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
16621d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
16631d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
16641d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
16657c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan GohmanPHINode *
16661d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1667db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                                    Type *Ty) {
1668b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1669133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1670133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Build a SCEV for {0,+,1}<L>.
16713228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // Conservatively use FlagAnyWrap for now.
1672deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
16733228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                   SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1674133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1675133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Emit code for it.
1676d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BuilderType::InsertPointGuard Guard(Builder);
1677cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  PHINode *V =
1678cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1679133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
168040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
16811d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1682204494149b6f846e8f173f525b129f5508076049Andrew Trick
1683204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replaceCongruentIVs - Check for congruent phis in this loop header and
1684204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replace them with their most canonical representative. Return the number of
1685204494149b6f846e8f173f525b129f5508076049Andrew Trick/// phis eliminated.
1686204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1687204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not depend on any SCEVExpander state but should be used in
1688204494149b6f846e8f173f525b129f5508076049Andrew Trick/// the same context that SCEVExpander is used.
1689204494149b6f846e8f173f525b129f5508076049Andrew Trickunsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1690a04a4a79ea365d1ba96ed4b5861e879b267162e2Nadav Rotem                                           SmallVectorImpl<WeakVH> &DeadInsts,
1691e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth                                           const TargetTransformInfo *TTI) {
1692ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // Find integer phis in order of increasing width.
1693ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  SmallVector<PHINode*, 8> Phis;
1694cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (auto &I : *L->getHeader()) {
1695cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (auto *PN = dyn_cast<PHINode>(&I))
1696cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      Phis.push_back(PN);
1697cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    else
1698cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      break;
1699ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  }
1700cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1701e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth  if (TTI)
170236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
170336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Put pointers at the back and make sure pointer < pointer = false.
170436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
170536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
170636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return RHS->getType()->getPrimitiveSizeInBits() <
170736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines             LHS->getType()->getPrimitiveSizeInBits();
170836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    });
1709ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1710204494149b6f846e8f173f525b129f5508076049Andrew Trick  unsigned NumElim = 0;
1711204494149b6f846e8f173f525b129f5508076049Andrew Trick  DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1712cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Process phis from wide to narrow. Map wide phis to their truncation
1713ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // so narrow phis can reuse them.
1714cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (PHINode *Phi : Phis) {
1715cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1716cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1717cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        return V;
1718cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (!SE.isSCEVable(PN->getType()))
1719cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        return nullptr;
1720cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1721cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (!Const)
1722cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        return nullptr;
1723cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return Const->getValue();
1724cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    };
1725ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1726239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    // Fold constant phis. They may be congruent to other constant phis and
1727239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    // would confuse the logic below that expects proper IVs.
1728cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (Value *V = SimplifyPHINode(Phi)) {
1729cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (V->getType() != Phi->getType())
1730cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        continue;
1731239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      Phi->replaceAllUsesWith(V);
17326948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      DeadInsts.emplace_back(Phi);
1733239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      ++NumElim;
1734239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      DEBUG_WITH_TYPE(DebugType, dbgs()
1735239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer                      << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1736239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      continue;
1737239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    }
1738239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer
1739204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!SE.isSCEVable(Phi->getType()))
1740204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1741204494149b6f846e8f173f525b129f5508076049Andrew Trick
1742204494149b6f846e8f173f525b129f5508076049Andrew Trick    PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1743204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!OrigPhiRef) {
1744204494149b6f846e8f173f525b129f5508076049Andrew Trick      OrigPhiRef = Phi;
1745e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth      if (Phi->getType()->isIntegerTy() && TTI
1746e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth          && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1747ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // This phi can be freely truncated to the narrowest phi type. Map the
1748ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // truncated expression to it so it will be reused for narrow types.
1749ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        const SCEV *TruncExpr =
1750ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1751ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        ExprToIVMap[TruncExpr] = Phi;
1752ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      }
1753204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1754204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1755204494149b6f846e8f173f525b129f5508076049Andrew Trick
1756ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1757ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // sense.
1758ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1759204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1760204494149b6f846e8f173f525b129f5508076049Andrew Trick
1761204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1762204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *OrigInc =
1763204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1764204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *IsomorphicInc =
1765204494149b6f846e8f173f525b129f5508076049Andrew Trick        cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1766204494149b6f846e8f173f525b129f5508076049Andrew Trick
1767ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      // If this phi has the same width but is more canonical, replace the
1768b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // original with it. As part of the "more canonical" determination,
1769b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // respect a prior decision to use an IV chain.
1770ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      if (OrigPhiRef->getType() == Phi->getType()
1771b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && !(ChainedPhis.count(Phi)
1772b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick               || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1773b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && (ChainedPhis.count(Phi)
1774b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick              || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1775204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigPhiRef, Phi);
1776204494149b6f846e8f173f525b129f5508076049Andrew Trick        std::swap(OrigInc, IsomorphicInc);
1777204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1778204494149b6f846e8f173f525b129f5508076049Andrew Trick      // Replacing the congruent phi is sufficient because acyclic redundancy
1779204494149b6f846e8f173f525b129f5508076049Andrew Trick      // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1780204494149b6f846e8f173f525b129f5508076049Andrew Trick      // that a phi is congruent, it's often the head of an IV user cycle that
1781139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // is isomorphic with the original phi. It's worth eagerly cleaning up the
1782139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // common case of a single IV increment so that DeleteDeadPHIs can remove
1783139f333f88fb9e0c39dfa3b56fd2a26b33837b70Andrew Trick      // cycles that had postinc uses.
1784ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1785ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick                                                   IsomorphicInc->getType());
1786ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      if (OrigInc != IsomorphicInc
178764925c55c65f9345a69fb67db07aa62cfb723577Andrew Trick          && TruncExpr == SE.getSCEV(IsomorphicInc)
1788b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1789b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick              || hoistIVInc(OrigInc, IsomorphicInc))) {
1790204494149b6f846e8f173f525b129f5508076049Andrew Trick        DEBUG_WITH_TYPE(DebugType, dbgs()
1791204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << "INDVARS: Eliminated congruent iv.inc: "
1792204494149b6f846e8f173f525b129f5508076049Andrew Trick                        << *IsomorphicInc << '\n');
1793ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        Value *NewInc = OrigInc;
1794ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        if (OrigInc->getType() != IsomorphicInc->getType()) {
17954c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          Instruction *IP = nullptr;
17964c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1797cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            IP = &*PN->getParent()->getFirstInsertionPt();
17984c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          else
17994c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            IP = OrigInc->getNextNode();
18004c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
1801dd1f22f25d8496b10cfddedb63d674dd39897bb0Andrew Trick          IRBuilder<> Builder(IP);
1802ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1803ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          NewInc = Builder.
1804ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick            CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1805ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        }
1806ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        IsomorphicInc->replaceAllUsesWith(NewInc);
18076948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar        DeadInsts.emplace_back(IsomorphicInc);
1808204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1809204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1810204494149b6f846e8f173f525b129f5508076049Andrew Trick    DEBUG_WITH_TYPE(DebugType, dbgs()
1811204494149b6f846e8f173f525b129f5508076049Andrew Trick                    << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1812204494149b6f846e8f173f525b129f5508076049Andrew Trick    ++NumElim;
1813ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Value *NewIV = OrigPhiRef;
1814ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType() != Phi->getType()) {
1815cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1816ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1817ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1818ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    }
1819ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Phi->replaceAllUsesWith(NewIV);
18206948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    DeadInsts.emplace_back(Phi);
1821204494149b6f846e8f173f525b129f5508076049Andrew Trick  }
1822204494149b6f846e8f173f525b129f5508076049Andrew Trick  return NumElim;
1823204494149b6f846e8f173f525b129f5508076049Andrew Trick}
1824e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
1825cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga NainarValue *SCEVExpander::findExistingExpansion(const SCEV *S,
1826cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                           const Instruction *At, Loop *L) {
1827cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  using namespace llvm::PatternMatch;
1828cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1829cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  SmallVector<BasicBlock *, 4> ExitingBlocks;
1830cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  L->getExitingBlocks(ExitingBlocks);
1831cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1832cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Look for suitable value in simple conditions at the loop exits.
1833cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (BasicBlock *BB : ExitingBlocks) {
1834cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    ICmpInst::Predicate Pred;
1835cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Instruction *LHS, *RHS;
1836cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    BasicBlock *TrueBB, *FalseBB;
1837cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1838cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!match(BB->getTerminator(),
1839cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar               m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1840cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                    TrueBB, FalseBB)))
1841cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      continue;
1842cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1843cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1844cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return LHS;
1845cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1846cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1847cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return RHS;
1848cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1849cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1850cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // There is potential to make this significantly smarter, but this simple
1851cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // heuristic already gets some interesting cases.
1852cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1853cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Can not find suitable value.
1854cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return nullptr;
1855cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1856cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
18570c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainarbool SCEVExpander::isHighCostExpansionHelper(
1858cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    const SCEV *S, Loop *L, const Instruction *At,
1859cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    SmallPtrSetImpl<const SCEV *> &Processed) {
1860cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1861cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // If we can find an existing value for this scev avaliable at the point "At"
1862cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // then consider the expression cheap.
1863cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (At && findExistingExpansion(S, At, L) != nullptr)
1864cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return false;
18656948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
18666948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // Zero/One operand expressions
18676948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  switch (S->getSCEVType()) {
18686948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scUnknown:
18696948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scConstant:
18706948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return false;
18716948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scTruncate:
1872cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1873cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                     L, At, Processed);
18746948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scZeroExtend:
18756948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1876cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                     L, At, Processed);
18776948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scSignExtend:
18786948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1879cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                     L, At, Processed);
18806948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  }
18816948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
18820c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  if (!Processed.insert(S).second)
18830c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    return false;
18840c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
18850c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
18860c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // If the divisor is a power of two and the SCEV type fits in a native
1887cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // integer, consider the division cheap irrespective of whether it occurs in
18880c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // the user code since it can be lowered into a right shift.
18890c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1890cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (SC->getAPInt().isPowerOf2()) {
18910c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        const DataLayout &DL =
18920c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar            L->getHeader()->getParent()->getParent()->getDataLayout();
18930c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
18940c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return DL.isIllegalInteger(Width);
18950c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      }
18960c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
18970c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
18980c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // HowManyLessThans produced to compute a precise expression, rather than a
18990c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // UDiv from the user's code. If we can't find a UDiv in the code with some
19000c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // simple searching, assume the former consider UDivExpr expensive to
19010c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // compute.
19020c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    BasicBlock *ExitingBB = L->getExitingBlock();
19030c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    if (!ExitingBB)
19040c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      return true;
19050c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
1906cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // At the beginning of this function we already tried to find existing value
1907cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1908cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // involving division. This is just a simple search heuristic.
1909cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!At)
1910cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      At = &ExitingBB->back();
1911cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!findExistingExpansion(
1912cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
19130c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      return true;
19140c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  }
19150c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
19166948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // HowManyLessThans uses a Max expression whenever the loop is not guarded by
19176948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // the exit condition.
19186948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
19196948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return true;
19206948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
19216948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // Recurse past nary expressions, which commonly occur in the
19220c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // BackedgeTakenCount. They may already exist in program code, and if not,
19230c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // they are not too expensive rematerialize.
19246948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1925cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (auto *Op : NAry->operands())
1926cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (isHighCostExpansionHelper(Op, L, At, Processed))
19270c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return true;
19280c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  }
19290c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
19300c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // If we haven't recognized an expensive SCEV pattern, assume it's an
19310c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // expression produced by program code.
19320c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  return false;
19330c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar}
19340c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
1935cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga NainarValue *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
1936cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                            Instruction *IP) {
1937cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  assert(IP);
1938cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  switch (Pred->getKind()) {
1939cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  case SCEVPredicate::P_Union:
1940cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
1941cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  case SCEVPredicate::P_Equal:
1942cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
1943cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1944cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  llvm_unreachable("Unknown SCEV predicate type");
1945cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1946cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1947cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga NainarValue *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
1948cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                          Instruction *IP) {
1949cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
1950cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
1951cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1952cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Builder.SetInsertPoint(IP);
1953cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
1954cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return I;
1955cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1956cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1957cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga NainarValue *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
1958cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                          Instruction *IP) {
1959cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  auto *BoolType = IntegerType::get(IP->getContext(), 1);
1960cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Value *Check = ConstantInt::getNullValue(BoolType);
1961cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1962cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Loop over all checks in this set.
1963cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (auto Pred : Union->getPredicates()) {
1964cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    auto *NextCheck = expandCodeForPredicate(Pred, IP);
1965cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Builder.SetInsertPoint(IP);
1966cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Check = Builder.CreateOr(Check, NextCheck);
1967cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1968cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1969cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return Check;
1970cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1971cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1972e08c32249fca32cd7b122024a4ca252fcb235694Andrew Tricknamespace {
1973e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// Search for a SCEV subexpression that is not safe to expand.  Any expression
1974e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1975e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1976e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// instruction, but the important thing is that we prove the denominator is
1977e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// nonzero before expansion.
1978e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick//
1979e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// IVUsers already checks that IV-derived expressions are safe. So this check is
1980e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// only needed when the expression includes some subexpression that is not IV
1981e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// derived.
1982e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick//
1983e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// Currently, we only allow division by a nonzero constant here. If this is
1984e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// inadequate, we could easily allow division by SCEVUnknown by using
1985e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// ValueTracking to check isKnownNonZero().
19864d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick//
19874d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// We cannot generally expand recurrences unless the step dominates the loop
19884d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// header. The expander handles the special case of affine recurrences by
19894d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// scaling the recurrence outside the loop, but this technique isn't generally
19904d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// applicable. Expanding a nested recurrence outside a loop requires computing
19914d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// binomial coefficients. This could be done, but the recurrence has to be in a
19924d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// perfectly reduced form, which can't be guaranteed.
1993e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trickstruct SCEVFindUnsafe {
19944d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  ScalarEvolution &SE;
1995e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool IsUnsafe;
1996e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
19974d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
1998e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
1999e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool follow(const SCEV *S) {
20004d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
20014d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
20024d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      if (!SC || SC->getValue()->isZero()) {
20034d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        IsUnsafe = true;
20044d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        return false;
20054d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      }
20064d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    }
20074d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
20084d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      const SCEV *Step = AR->getStepRecurrence(SE);
20094d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
20104d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        IsUnsafe = true;
20114d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        return false;
20124d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      }
20134d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    }
20144d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    return true;
2015e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  }
2016e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool isDone() const { return IsUnsafe; }
2017e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick};
2018e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2019e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
2020e08c32249fca32cd7b122024a4ca252fcb235694Andrew Tricknamespace llvm {
20214d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trickbool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
20224d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  SCEVFindUnsafe Search(SE);
2023e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  visitAll(S, Search);
2024e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  return !Search.IsUnsafe;
2025e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2026e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2027