1de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
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"
27f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama 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;
32f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama 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.
66f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama 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)
78f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama 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).
83f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  assert(SE.DT.dominates(Ret, &*BIP));
8423b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola
8523b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  rememberInstruction(Ret);
8623b6ec906a081259dad4672ec386ddfb52cd0d9fRafael Espindola  return Ret;
87485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman}
88485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman
89f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainarstatic BasicBlock::iterator findInsertPointAfter(Instruction *I,
90f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                                 BasicBlock *MustDominate) {
91f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  BasicBlock::iterator IP = ++I->getIterator();
92f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  if (auto *II = dyn_cast<InvokeInst>(I))
93f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    IP = II->getNormalDest()->begin();
94f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
95f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  while (isa<PHINode>(IP))
96f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    ++IP;
97f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
98de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
99de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    ++IP;
100de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  } else if (isa<CatchSwitchInst>(IP)) {
101de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    IP = MustDominate->getFirstInsertionPt();
102de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  } else {
103de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    assert(!IP->isEHPad() && "unexpected eh pad!");
104f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  }
105f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
106f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  return IP;
107f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar}
108f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
109267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
110267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// which must be possible with a noop cast, doing what we can to share
111267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman/// the casts.
112db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
113267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
114267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert((Op == Instruction::BitCast ||
115267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::PtrToInt ||
116267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman          Op == Instruction::IntToPtr) &&
117267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot perform non-noop casts!");
118267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
119267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman         "InsertNoopCastOfTo cannot change sizes!");
120267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1212d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  // Short-circuit unnecessary bitcasts.
12219154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  if (Op == Instruction::BitCast) {
12319154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (V->getType() == Ty)
12419154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      return V;
12519154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    if (CastInst *CI = dyn_cast<CastInst>(V)) {
12619154f457696f286b4a597179fa07e3b38ea0310Andrew Trick      if (CI->getOperand(0)->getType() == Ty)
12719154f457696f286b4a597179fa07e3b38ea0310Andrew Trick        return CI->getOperand(0);
12819154f457696f286b4a597179fa07e3b38ea0310Andrew Trick    }
12919154f457696f286b4a597179fa07e3b38ea0310Andrew Trick  }
130f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
131267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
13280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
133af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman    if (CastInst *CI = dyn_cast<CastInst>(V))
134af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman      if ((CI->getOpcode() == Instruction::PtrToInt ||
135af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman           CI->getOpcode() == Instruction::IntToPtr) &&
136af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getType()) ==
137af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman          SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
138af79fb5f47b0088c6a8973a7fdbaea96973a429dDan Gohman        return CI->getOperand(0);
13980dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
14080dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman      if ((CE->getOpcode() == Instruction::PtrToInt ||
14180dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman           CE->getOpcode() == Instruction::IntToPtr) &&
14280dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getType()) ==
14380dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman          SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
14480dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman        return CE->getOperand(0);
14580dcdee0f48820ecea86c15768324945bb0d68d1Dan Gohman  }
146f04fa483b83227c570bc58e1684ea096430a6697Dan Gohman
147485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Fold a cast of a constant.
148ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Constant *C = dyn_cast<Constant>(V))
149baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Op, C, Ty);
1504c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman
151485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the argument at the beginning of the entry block, after
152485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // any bitcasts of other arguments.
153ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  if (Argument *A = dyn_cast<Argument>(V)) {
154485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
155485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    while ((isa<BitCastInst>(IP) &&
156485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
157485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman            cast<BitCastInst>(IP)->getOperand(0) != A) ||
158f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           isa<DbgInfoIntrinsic>(IP))
159485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman      ++IP;
160485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman    return ReuseOrCreateCast(A, Ty, Op, IP);
161ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  }
1623913187bf6135e6a71260c65eed664095c8f9ce9Wojciech Matyjewicz
163485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  // Cast the instruction immediately after the instruction.
164ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner  Instruction *I = cast<Instruction>(V);
165f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
166485c43fc478d5e16c55e14cb2586b56cc1c4c91fDan Gohman  return ReuseOrCreateCast(I, Ty, Op, IP);
167ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner}
168ca1a4bebb3928ba18fb8751e2f0c0f88fad54cfdChris Lattner
1697fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// InsertBinop - Insert the specified binary operator, doing a small amount
1707fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner/// of work to avoid inserting an obviously redundant operation.
171267a385342f2e7388f178b327dd87c5f29afd51bDan GohmanValue *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman                                 Value *LHS, Value *RHS) {
1730f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  // Fold a binop with constant operands.
1740f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman  if (Constant *CLHS = dyn_cast<Constant>(LHS))
1750f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman    if (Constant *CRHS = dyn_cast<Constant>(RHS))
176baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::get(Opcode, CLHS, CRHS);
1770f0eb18addc94bf3d8179fbce162c8c4622b9866Dan Gohman
1787fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
1797fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  unsigned ScanLimit = 6;
180267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
181267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  // Scanning starts from the last instruction before the insertion point.
182267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  BasicBlock::iterator IP = Builder.GetInsertPoint();
183267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (IP != BlockBegin) {
1848a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    --IP;
1858a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    for (; ScanLimit; --IP, --ScanLimit) {
1868d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // Don't count dbg.value against the ScanLimit, to avoid perturbing the
1878d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      // generated code.
1888d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen      if (isa<DbgInfoIntrinsic>(IP))
1898d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        ScanLimit++;
1905be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
1915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman          IP->getOperand(1) == RHS)
192f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        return &*IP;
1938a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz      if (IP == BlockBegin) break;
1948a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz    }
1957fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner  }
196267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
197087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Save the original insertion point so we can restore it when we're done.
198d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
199de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SCEVInsertPointGuard Guard(Builder, this);
200087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
201087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Move the insertion point out of as many loops as we can.
202f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
203087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
204087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    BasicBlock *Preheader = L->getLoopPreheader();
205087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Preheader) break;
206087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
207087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Ok, move up a level.
208f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    Builder.SetInsertPoint(Preheader->getTerminator());
209087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
210087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
2118a08769bad43a22fae2845bb0ba0fd1266cd55c8Wojciech Matyjewicz  // If we haven't found this binop, insert it.
212a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
213d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer  BO->setDebugLoc(Loc);
214a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(BO);
215087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
216cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return BO;
2177fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner}
2187fec90ebf4ebe7aa73a6dd7d275c255587c041adChris Lattner
2194a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// FactorOutConstant - Test if S is divisible by Factor, using signed
220453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// division. If so, update S with Factor divided out and return true.
2213f46a3abeedba8d517b4182de34c821d752db058Dan Gohman/// S need not be evenly divisible if a reasonable remainder can be
2224a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman/// computed.
223453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
224453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
225453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// check to see if the divide was folded.
2264c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarstatic bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
2274c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                              const SCEV *Factor, ScalarEvolution &SE,
2284c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                              const DataLayout &DL) {
229453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // Everything is divisible by one.
230c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (Factor->isOne())
231c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    return true;
232c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
233c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // x/x == 1.
234c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (S == Factor) {
235deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    S = SE.getConstant(S->getType(), 1);
236453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
237c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
238453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
239453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // For a Constant, check for a multiple of the given factor.
2404a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
241c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // 0/x == 0.
242c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (C->isZero())
243453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return true;
244c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Check for divisibility.
245c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
246c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      ConstantInt *CI =
247f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar          ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
248c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If the quotient is zero and the remainder is non-zero, reject
249c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // the value at this scale. It will be considered for subsequent
250c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // smaller scales.
251c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!CI->isZero()) {
252c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        const SCEV *Div = SE.getConstant(CI);
253c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        S = Div;
254f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        Remainder = SE.getAddExpr(
255f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
256c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return true;
257c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
258453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
2594a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman  }
260453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
261453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In a Mul, check if there is a constant operand which is a multiple
262453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // of the given factor.
263c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2644c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    // Size is known, check if there is a constant operand which is a multiple
2654c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    // of the given factor. If so, we can factor it.
2664c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    const SCEVConstant *FC = cast<SCEVConstant>(Factor);
2674c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
268f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (!C->getAPInt().srem(FC->getAPInt())) {
2694c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
270f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
2714c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        S = SE.getMulExpr(NewMulOps);
2724c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        return true;
273453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
274c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
275453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
276453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  // In an AddRec, check if both start and step are divisible.
277453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2780bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Step = A->getStepRecurrence(SE);
279deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
28036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
2814a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2824a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman    if (!StepRem->isZero())
2834a4f767235dac50965fc266fb822d9a2e37d5212Dan Gohman      return false;
2840bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    const SCEV *Start = A->getStart();
28536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
286453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      return false;
2876f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick    S = SE.getAddRecExpr(Start, Step, A->getLoop(),
2886f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                         A->getNoWrapFlags(SCEV::FlagNW));
289453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    return true;
290453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
291453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
292453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  return false;
293453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
294453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
295c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
296c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// is the number of SCEVAddRecExprs present, which are kept at the end of
297c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// the list.
298c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
299c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
300db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                Type *Ty,
301c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                ScalarEvolution &SE) {
302c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  unsigned NumAddRecs = 0;
303c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
304c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ++NumAddRecs;
305c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Group Ops into non-addrecs and addrecs.
306c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
307c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
308c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Let ScalarEvolution sort and simplify the non-addrecs list.
309c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  const SCEV *Sum = NoAddRecs.empty() ?
310deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                    SE.getConstant(Ty, 0) :
311c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                    SE.getAddExpr(NoAddRecs);
312c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // If it returned an add, use the operands. Otherwise it simplified
313c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // the sum into a single value, so just use that.
314f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  Ops.clear();
315c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
316403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(Add->op_begin(), Add->op_end());
317f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman  else if (!Sum->isZero())
318f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    Ops.push_back(Sum);
319c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Then append the addrecs.
320403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman  Ops.append(AddRecs.begin(), AddRecs.end());
321c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
322c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
323c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
324c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
325c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// This helps expose more opportunities for folding parts of the expressions
326c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman/// into GEP indices.
327c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman///
328c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohmanstatic void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
329db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                         Type *Ty,
330c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                         ScalarEvolution &SE) {
331c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Find the addrecs.
332c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SmallVector<const SCEV *, 8> AddRecs;
333c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
334c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
335c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      const SCEV *Start = A->getStart();
336c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (Start->isZero()) break;
337deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman      const SCEV *Zero = SE.getConstant(Ty, 0);
338c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      AddRecs.push_back(SE.getAddRecExpr(Zero,
339c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman                                         A->getStepRecurrence(SE),
3403228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                         A->getLoop(),
3416f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                         A->getNoWrapFlags(SCEV::FlagNW)));
342c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
343c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Zero;
344403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman        Ops.append(Add->op_begin(), Add->op_end());
345c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        e += Add->getNumOperands();
346c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      } else {
347c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Ops[i] = Start;
348c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
349c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
350c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  if (!AddRecs.empty()) {
351c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Add the addrecs onto the end of the list.
352403a8cdda5e76ea689693de16474650b4b0df818Dan Gohman    Ops.append(AddRecs.begin(), AddRecs.end());
353c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Resort the operand list, moving any constants to the front.
354c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    SimplifyAddOperands(Ops, Ty, SE);
355c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
356c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman}
357c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
3584c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// expandAddToGEP - Expand an addition expression with a pointer type into
3594c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
3604c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// BasicAliasAnalysis and other passes analyze the result. See the rules
3614c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for getelementptr vs. inttoptr in
3624c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// http://llvm.org/docs/LangRef.html#pointeraliasing
3634c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// for details.
36413c5e35222afe0895f0c5e68aa9f22f134ea437aDan Gohman///
3653abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman/// Design note: The correctness of using getelementptr here depends on
3664c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
3674c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// they may introduce pointer arithmetic which may not be safely converted
3684c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman/// into getelementptr.
369453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
370453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Design note: It might seem desirable for this function to be more
371453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-aware. If some of the indices are loop-invariant while others
372453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// aren't, it might seem desirable to emit multiple GEPs, keeping the
373453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of the overall computation outside the loop.
374453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// However, there are a few reasons this is not done here. Hoisting simple
375453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// arithmetic is a low-level optimization that often isn't very
376453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// important until late in the optimization process. In fact, passes
377453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// like InstructionCombining will combine GEPs, even if it means
378453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// pushing loop-invariant computation down into loops, so even if the
379453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEPs were split here, the work would quickly be undone. The
380453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// LoopStrengthReduction pass, which is usually run quite late (and
381453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// after the last InstructionCombining pass), takes care of hoisting
382453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// loop-invariant portions of expressions, after considering what
383453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// can be folded using target addressing modes.
384453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman///
3850bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan GohmanValue *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
3860bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman                                    const SCEV *const *op_end,
387db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    PointerType *PTy,
388db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                    Type *Ty,
3895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                                    Value *V) {
3904c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *OriginalElTy = PTy->getElementType();
3914c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *ElTy = OriginalElTy;
3925be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  SmallVector<Value *, 4> GepIndices;
3930bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
3945be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  bool AnyNonZeroIndices = false;
3955be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
396c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // Split AddRecs up into parts as either of the parts may be usable
397c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  // without the other.
398c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  SplitAddRecs(Ops, Ty, SE);
399c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
4004c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  Type *IntPtrTy = DL.getIntPtrType(PTy);
40114807bd8c801f976c999e5a6699f31ee9642021aMatt Arsenault
402eb35699e642f2c021f04154bdb4bd90a1afb3baaBob Wilson  // Descend down the pointer's type and attempt to convert the other
4035be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // operands into GEP indices, at each level. The first index in a GEP
4045be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // indexes into the array implied by the pointer operand; the rest of
4055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the indices index into the element or field type selected by the
4065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // preceding index.
4075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  for (;;) {
408c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If the scale size is not 0, attempt to factor out a scale for
409c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // array indexing.
4100bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> ScaledOps;
411150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman    if (ElTy->isSized()) {
41214807bd8c801f976c999e5a6699f31ee9642021aMatt Arsenault      const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
413150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman      if (!ElSize->isZero()) {
414150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        SmallVector<const SCEV *, 8> NewOps;
415f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        for (const SCEV *Op : Ops) {
416deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman          const SCEV *Remainder = SE.getConstant(Ty, 0);
4174c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
418150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // Op now has ElSize factored out.
419150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            ScaledOps.push_back(Op);
420150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            if (!Remainder->isZero())
421150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman              NewOps.push_back(Remainder);
422150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            AnyNonZeroIndices = true;
423150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          } else {
424150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // The operand was not divisible, so add it to the list of operands
425150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman            // we'll scan next iteration.
426f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            NewOps.push_back(Op);
427150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          }
428150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        }
429150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        // If we made any changes, update Ops.
430150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman        if (!ScaledOps.empty()) {
431150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          Ops = NewOps;
432150dfa87113e51881c75676edd8e3549eb702d99Dan Gohman          SimplifyAddOperands(Ops, Ty, SE);
4335be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        }
434c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
4355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
437c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Record the scaled array index for this level of the type. If
438c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // we didn't find any operands that could be factored, tentatively
439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // assume that element zero was selected (since the zero offset
440c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // would obviously be folded away).
4415be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    Value *Scaled = ScaledOps.empty() ?
442a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson                    Constant::getNullValue(Ty) :
4435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman                    expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
4445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    GepIndices.push_back(Scaled);
4455be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4465be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Collect struct field index operands.
447db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    while (StructType *STy = dyn_cast<StructType>(ElTy)) {
448c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      bool FoundFieldNo = false;
449c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // An empty struct has no fields.
450c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (STy->getNumElements() == 0) break;
4514c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      // Field offsets are known. See if a constant offset falls within any of
4524c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      // the struct fields.
4534c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (Ops.empty())
4544c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        break;
4554c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
4564c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        if (SE.getTypeSizeInBits(C->getType()) <= 64) {
4574c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          const StructLayout &SL = *DL.getStructLayout(STy);
4584c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          uint64_t FullOffset = C->getValue()->getZExtValue();
4594c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar          if (FullOffset < SL.getSizeInBytes()) {
4604c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
4614c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            GepIndices.push_back(
4624c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
4634c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            ElTy = STy->getTypeAtIndex(ElIdx);
4644c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            Ops[0] =
4656de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman                SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
4664c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            AnyNonZeroIndices = true;
4674c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            FoundFieldNo = true;
4680f5efe56258f8cd6ceff4d7955a5d80144cd9cb0Dan Gohman          }
4694c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        }
470c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // If no struct field offsets were found, tentatively assume that
471c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // field zero was selected (since the zero offset would obviously
472c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // be folded away).
473c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!FoundFieldNo) {
474c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        ElTy = STy->getTypeAtIndex(0u);
475c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        GepIndices.push_back(
476c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman          Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      }
478c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    }
4795be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
480db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
4815be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      ElTy = ATy->getElementType();
482c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    else
483c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      break;
4845be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
4855be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
4863f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // If none of the operands were convertible to proper GEP indices, cast
4875be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // the base to i8* and do an ugly getelementptr with that. It's still
4885be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  // better than ptrtoint+arithmetic+inttoptr at least.
4895be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (!AnyNonZeroIndices) {
490c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Cast the base to i8*.
4915be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V,
492ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands       Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
493c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman
494705b48d960dff1a96ac40d0cf932eb465b9a550aRafael Espindola    assert(!isa<Instruction>(V) ||
495f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
4964b04578d65e38cdb5077de2498889e4a174ccdfdRafael Espindola
497c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Expand the operands for a plain byte offset.
49892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
4995be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5005be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Fold a GEP with constant operands.
5015be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    if (Constant *CLHS = dyn_cast<Constant>(V))
5025be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      if (Constant *CRHS = dyn_cast<Constant>(Idx))
5030c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
5040c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar                                              CLHS, CRHS);
5055be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
5065be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5075be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    unsigned ScanLimit = 6;
508267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
509267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    // Scanning starts from the last instruction before the insertion point.
510267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    BasicBlock::iterator IP = Builder.GetInsertPoint();
511267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    if (IP != BlockBegin) {
5125be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      --IP;
5135be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      for (; ScanLimit; --IP, --ScanLimit) {
5148d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5158d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        // generated code.
5168d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen        if (isa<DbgInfoIntrinsic>(IP))
5178d50ea760322630dbb9ab6436ca356b279adee10Dale Johannesen          ScanLimit++;
5185be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP->getOpcode() == Instruction::GetElementPtr &&
5195be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman            IP->getOperand(0) == V && IP->getOperand(1) == Idx)
520f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar          return &*IP;
5215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman        if (IP == BlockBegin) break;
5225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman      }
5235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    }
5245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
525087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Save the original insertion point so we can restore it when we're done.
526de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    SCEVInsertPointGuard Guard(Builder, this);
527087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
528087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Move the insertion point out of as many loops as we can.
529f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
530087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
531087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      BasicBlock *Preheader = L->getLoopPreheader();
532087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (!Preheader) break;
533087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
534087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Ok, move up a level.
535f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      Builder.SetInsertPoint(Preheader->getTerminator());
536087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
537087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
538c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Emit a GEP.
5390c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
540a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(GEP);
541087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5425be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    return GEP;
5435be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
5445be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
545de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  {
546de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    SCEVInsertPointGuard Guard(Builder, this);
547087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
548de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // Move the insertion point out of as many loops as we can.
549de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
550de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (!L->isLoopInvariant(V)) break;
551f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
552de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      bool AnyIndexNotLoopInvariant =
553de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          std::any_of(GepIndices.begin(), GepIndices.end(),
554de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                      [L](Value *Op) { return !L->isLoopInvariant(Op); });
555087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
556de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (AnyIndexNotLoopInvariant)
557de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        break;
558087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
559de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      BasicBlock *Preheader = L->getLoopPreheader();
560de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (!Preheader) break;
561087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
562de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // Ok, move up a level.
563de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Builder.SetInsertPoint(Preheader->getTerminator());
564de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    }
565087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
566de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
567de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // because ScalarEvolution may have changed the address arithmetic to
568de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // compute a value which is beyond the end of the allocated object.
569de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    Value *Casted = V;
570de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (V->getType() != PTy)
571de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Casted = InsertNoopCastOfTo(Casted, PTy);
572de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
573de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    Ops.push_back(SE.getUnknown(GEP));
574de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    rememberInstruction(GEP);
575de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  }
576341562b9fb6574b1c9492e52cec24106cd31ce51Benjamin Kramer
5775be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return expand(SE.getAddExpr(Ops));
5785be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman}
5795be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
580087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
581087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// SCEV expansion. If they are nested, this is the most nested. If they are
582087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// neighboring, pick the later.
583087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanstatic const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
584087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                                        DominatorTree &DT) {
585087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!A) return B;
586087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (!B) return A;
587087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (A->contains(B)) return B;
588087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (B->contains(A)) return A;
589087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
590087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
591087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return A; // Arbitrarily break the tie.
592087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
593087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
5949c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman/// getRelevantLoop - Get the most relevant loop associated with the given
595087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// expression, according to PickMostRelevantLoop.
5969c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohmanconst Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
5979c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  // Test whether we've already computed the most relevant loop for this SCEV.
598f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
5999c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (!Pair.second)
6009c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return Pair.first->second;
6019c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman
602087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (isa<SCEVConstant>(S))
6039c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A constant has no relevant loops.
604dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
605087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
606087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
607f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      return Pair.first->second = SE.LI.getLoopFor(I->getParent());
6089c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    // A non-instruction has no relevant loops.
609dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
610087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
611087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
612dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    const Loop *L = nullptr;
613087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
614087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      L = AR->getLoop();
615f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    for (const SCEV *Op : N->operands())
616f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
6179c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[N] = L;
6189c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6199c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6209c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    const Loop *Result = getRelevantLoop(C->getOperand());
6219c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[C] = Result;
6229c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  }
6239c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
624f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    const Loop *Result = PickMostRelevantLoop(
625f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
6269c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    return RelevantLoops[D] = Result;
627087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  }
628087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  llvm_unreachable("Unexpected SCEV type!");
629087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman}
630c4f7ec85ecb760fff2b702c6deb06506b968ba4fDan Gohman
631b35798347ea87b8b6d36155b211016a7769f01abDan Gohmannamespace {
632b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
633087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman/// LoopCompare - Compare loops by PickMostRelevantLoop.
634087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanclass LoopCompare {
635087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  DominatorTree &DT;
636087bd1e3a12893873761736bf0f905a350e9e708Dan Gohmanpublic:
637087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
638087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
639087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
640087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman                  std::pair<const Loop *, const SCEV *> RHS) const {
641bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    // Keep pointer operands sorted at the end.
642bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman    if (LHS.second->getType()->isPointerTy() !=
643bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        RHS.second->getType()->isPointerTy())
644bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      return LHS.second->getType()->isPointerTy();
645bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman
646087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Compare loops with PickMostRelevantLoop.
647087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (LHS.first != RHS.first)
648087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
649087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
650087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // If one operand is a non-constant negative and the other is not,
651087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // put the non-constant negative on the right so that a sub can
652087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // be used instead of a negate and add.
653f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    if (LHS.second->isNonConstantNegative()) {
654f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick      if (!RHS.second->isNonConstantNegative())
655087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        return false;
656f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (RHS.second->isNonConstantNegative())
657087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      return true;
658087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
659087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    // Otherwise they are equivalent according to this comparison.
660087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    return false;
661c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman  }
662087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman};
6635be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
664b35798347ea87b8b6d36155b211016a7769f01abDan Gohman}
665b35798347ea87b8b6d36155b211016a7769f01abDan Gohman
666087bd1e3a12893873761736bf0f905a350e9e708Dan GohmanValue *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
667db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
668e24fa64d52330626553298f56ba5aa702624c282Dan Gohman
669087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the add operands in a loop, along with their associated loops.
670087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal, and
671087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // so that pointer operands are inserted first, which the code below relies on
672087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // to form more involved GEPs.
673087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
674087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
675087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
6769c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
677087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
678087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants and
679087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // pointer operands precede non-pointer operands.
680f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
681087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
682087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to add all the operands. Hoist as much as possible
683087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops, and form meaningful getelementptrs where possible.
684dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *Sum = nullptr;
685f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
686087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const Loop *CurLoop = I->first;
687087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    const SCEV *Op = I->second;
688087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Sum) {
689087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
690087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expand(Op);
691087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
692db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
693087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum expression is a pointer. Try to form a getelementptr
694087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // at this level with that as the base.
695087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
696bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      for (; I != E && I->first == CurLoop; ++I) {
697bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // If the operand is SCEVUnknown and not instructions, peek through
698bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        // it, to enable more of it to be folded into the GEP.
699bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        const SCEV *X = I->second;
700bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
701bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman          if (!isa<Instruction>(U->getValue()))
702bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman            X = SE.getSCEV(U->getValue());
703bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman        NewOps.push_back(X);
704bb5d92741b2835eff25e4524bc6a5b0fb4fda855Dan Gohman      }
705087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // The running sum is an integer, and there's a pointer at this level.
708f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // Try to form a getelementptr. If the running sum is instructions,
709f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      // use a SCEVUnknown to avoid re-analyzing them.
710087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      SmallVector<const SCEV *, 4> NewOps;
711f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman      NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
712f8d0578e4cbd5922696c92f5068c5513d8e8d60eDan Gohman                                               SE.getSCEV(Sum));
713087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      for (++I; I != E && I->first == CurLoop; ++I)
714087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman        NewOps.push_back(I->second);
715087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
716f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick    } else if (Op->isNonConstantNegative()) {
717087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a negate and add, just do a subtract.
718a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
719087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
720087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Sub, Sum, W);
721087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
722a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
723087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple add.
724a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Value *W = expandCodeFor(Op, Ty);
725087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertNoopCastOfTo(Sum, Ty);
726087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
727087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Sum)) std::swap(Sum, W);
728087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Sum = InsertBinop(Instruction::Add, Sum, W);
729087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      ++I;
730a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
7312d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
732087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
733087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Sum;
734e24fa64d52330626553298f56ba5aa702624c282Dan Gohman}
7355be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman
736890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
737db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
738087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
739087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Collect all the mul operands in a loop, along with their associated loops.
740087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Iterate in reverse so that constants are emitted last, all else equal.
741087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
742087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
743087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman       E(S->op_begin()); I != E; ++I)
7449c9fcfc719158a46cb2e41b66d7dc1a63cd48d74Dan Gohman    OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
745087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
746087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Sort by loop. Use a stable sort so that constants follow non-constants.
747f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
748087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman
749087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // Emit instructions to mul all the operands. Hoist as much as possible
750087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  // out of loops.
751dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Value *Prod = nullptr;
752f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (const auto &I : OpsAndLoops) {
753f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    const SCEV *Op = I.second;
754087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    if (!Prod) {
755087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // This is the first operand. Just expand it.
756087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = expand(Op);
757087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else if (Op->isAllOnesValue()) {
758087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Instead of doing a multiply by negative one, just do a negate.
759087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
760087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
761087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    } else {
762087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // A simple mul.
763087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Value *W = expandCodeFor(Op, Ty);
764087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      Prod = InsertNoopCastOfTo(Prod, Ty);
765087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      // Canonicalize a constant to the RHS.
766087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman      if (isa<Constant>(Prod)) std::swap(Prod, W);
767f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      const APInt *RHS;
768f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (match(W, m_Power2(RHS))) {
769f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        // Canonicalize Prod*(1<<C) to Prod<<C.
770f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        assert(!Ty->isVectorTy() && "vector types are not SCEVable");
771f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        Prod = InsertBinop(Instruction::Shl, Prod,
772f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                           ConstantInt::get(Ty, RHS->logBase2()));
773f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      } else {
774f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        Prod = InsertBinop(Instruction::Mul, Prod, W);
775f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      }
776087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman    }
7772d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  }
7782d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
779087bd1e3a12893873761736bf0f905a350e9e708Dan Gohman  return Prod;
78036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
78136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
782890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
783db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
7842d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman
78592fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *LHS = expandCodeFor(S->getLHS(), Ty);
786890f92b744fb074465bc2b7006ee753a181f62a4Dan Gohman  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
787f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    const APInt &RHS = SC->getAPInt();
7886177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky    if (RHS.isPowerOf2())
7896177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky      return InsertBinop(Instruction::LShr, LHS,
790eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson                         ConstantInt::get(Ty, RHS.logBase2()));
7916177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky  }
7926177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
79392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *RHS = expandCodeFor(S->getRHS(), Ty);
794267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  return InsertBinop(Instruction::UDiv, LHS, RHS);
7956177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky}
7966177fd4fcee4d82692c47e33754ffe285c38cc69Nick Lewycky
797453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// Move parts of Base into Rest to leave Base with the minimal
798453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// expression that provides a pointer operand suitable for a
799453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman/// GEP expansion.
8000bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohmanstatic void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
801453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                              ScalarEvolution &SE) {
802453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
803453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getStart();
804453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(Rest,
805deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman                         SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
806453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman                                          A->getStepRecurrence(SE),
8073228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                          A->getLoop(),
8086f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                          A->getNoWrapFlags(SCEV::FlagNW)));
809453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
810453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
811453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Base = A->getOperand(A->getNumOperands()-1);
8120bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman    SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
813453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    NewAddOps.back() = Rest;
814453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    Rest = SE.getAddExpr(NewAddOps);
815453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    ExposePointerBase(Base, Rest, SE);
816453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman  }
817453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman}
818453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
819c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// Determine if this is a well-behaved chain of instructions leading back to
820c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick/// the PHI. If so, it may be reused by expanded expressions.
821c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trickbool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
822c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick                                         const Loop *L) {
823c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
824c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
825c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
826c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // If any of the operands don't dominate the insert position, bail.
827c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Addrec operands are always loop-invariant, so this can only happen
828c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // if there are instructions which haven't been hoisted.
829c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (L == IVIncInsertLoop) {
830c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    for (User::op_iterator OI = IncV->op_begin()+1,
831c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick           OE = IncV->op_end(); OI != OE; ++OI)
832c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(OI))
833f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        if (!SE.DT.dominates(OInst, IVIncInsertPos))
834c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          return false;
835c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
836c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Advance to the next instruction.
837c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
838c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (!IncV)
839c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
840c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
841c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV->mayHaveSideEffects())
842c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
843c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
844c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (IncV != PN)
845c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return true;
846c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
847c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  return isNormalAddRecExprPHI(PN, IncV, L);
848c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
849c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
850b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// getIVIncOperand returns an induction variable increment's induction
851b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// variable operand.
852b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
853b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is set, any type of GEP is allowed as long as the nonIV
854b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// operands dominate InsertPos.
855b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick///
856b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// If allowScale is not set, ensure that a GEP increment conforms to one of the
857b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// simple patterns generated by getAddRecExprPHILiterally and
858b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
859b5c26ef9da16052597d59a412eaae32098aa1be0Andrew TrickInstruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
860b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           Instruction *InsertPos,
861b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           bool allowScale) {
862b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  if (IncV == InsertPos)
863dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
86464925c55c65f9345a69fb67db07aa62cfb723577Andrew Trick
865c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  switch (IncV->getOpcode()) {
866b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  default:
867dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
868c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  // Check for a simple Add/Sub or GEP of a loop invariant step.
869c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::Add:
870b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::Sub: {
871b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
872f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (!OInst || SE.DT.dominates(OInst, InsertPos))
873b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return dyn_cast<Instruction>(IncV->getOperand(0));
874dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
875b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
876c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  case Instruction::BitCast:
877b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
878b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  case Instruction::GetElementPtr:
879f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
880c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (isa<Constant>(*I))
881c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
882b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
883f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        if (!SE.DT.dominates(OInst, InsertPos))
884dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          return nullptr;
885b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
886b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      if (allowScale) {
887b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        // allow any kind of GEP as long as it can be hoisted.
888b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick        continue;
889b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
890b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // This must be a pointer addition of constants (pretty), which is already
891b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // handled, or some number of address-size elements (ugly). Ugly geps
892b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // have 2 operands. i1* is used by the expander to represent an
893b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      // address-size element.
894c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getNumOperands() != 2)
895dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
896365c9f1ff55bef134c6b9707f7df44d680ddabeaAndrew Trick      unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
897c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
898c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
899dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
900c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      break;
901c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
902b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    return dyn_cast<Instruction>(IncV->getOperand(0));
903c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
904b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
905b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
906de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// If the insert point of the current builder or any of the builders on the
907de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// stack of saved builders has 'I' as its insert point, update it to point to
908de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// the instruction after 'I'.  This is intended to be used when the instruction
909de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
910de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// different block, the inconsistent insert point (with a mismatched
911de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// Instruction and Block) can lead to an instruction being inserted in a block
912de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar/// other than its parent.
913de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarvoid SCEVExpander::fixupInsertPoints(Instruction *I) {
914de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  BasicBlock::iterator It(*I);
915de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  BasicBlock::iterator NewInsertPt = std::next(It);
916de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Builder.GetInsertPoint() == It)
917de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    Builder.SetInsertPoint(&*NewInsertPt);
918de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  for (auto *InsertPtGuard : InsertPointGuards)
919de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (InsertPtGuard->GetInsertPoint() == It)
920de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      InsertPtGuard->SetInsertPoint(NewInsertPt);
921de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar}
922de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
923b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
924b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// it available to other uses in this loop. Recursively hoist any operands,
925b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// until we reach a value that dominates InsertPos.
926b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
927f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  if (SE.DT.dominates(IncV, InsertPos))
928b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
929b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
930b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // InsertPos must itself dominate IncV so that IncV's new position satisfies
931b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // its existing users.
932f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  if (isa<PHINode>(InsertPos) ||
933f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
934f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    return false;
935f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
936f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
937c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    return false;
938b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
939b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  // Check that the chain of IV operands leading back to Phi can be hoisted.
940b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  SmallVector<Instruction*, 4> IVIncs;
941b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(;;) {
942b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
943b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (!Oper)
944b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return false;
945b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    // IncV is safe to hoist.
946b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IVIncs.push_back(IncV);
947b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    IncV = Oper;
948f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (SE.DT.dominates(IncV, InsertPos))
949b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      break;
950b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
951f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
952de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    fixupInsertPoints(*I);
953b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    (*I)->moveBefore(InsertPos);
954b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  }
955b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return true;
956b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick}
957b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick
958b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// Determine if this cyclic phi is in a form that would have been generated by
959b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// LSR. We don't care if the phi was actually expanded in this pass, as long
960b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// as it is in a low-cost form, for example, no implied multiplication. This
961b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// should match any patterns generated by getAddRecExprPHILiterally and
962b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick/// expandAddtoGEP.
963b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trickbool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
964b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                           const Loop *L) {
965b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  for(Instruction *IVOper = IncV;
966b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
967b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                /*allowScale=*/false));) {
968b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick    if (IVOper == PN)
969b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      return true;
970c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
971b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick  return false;
972c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick}
973c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
974553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
975553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
976553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick/// need to materialize IV increments elsewhere to handle difficult situations.
977553fe05f236f46fe27b7fcfa822b06367d50183eAndrew TrickValue *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
978553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 Type *ExpandTy, Type *IntTy,
979553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                 bool useSubtract) {
980553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  Value *IncV;
981553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
982553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (ExpandTy->isPointerTy()) {
983553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
984553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If the step isn't constant, don't use an implicitly scaled GEP, because
985553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // that would require a multiply inside the loop.
986553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (!isa<ConstantInt>(StepV))
987553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
988553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick                                  GEPPtrTy->getAddressSpace());
989553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
990553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
991553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    if (IncV->getType() != PN->getType()) {
992553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      IncV = Builder.CreateBitCast(IncV, PN->getType());
993553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      rememberInstruction(IncV);
994553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
995553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  } else {
996553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    IncV = useSubtract ?
997553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
998553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
999553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    rememberInstruction(IncV);
1000553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  }
1001553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  return IncV;
1002553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick}
1003553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick
100436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
100536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// position. This routine assumes that this is possible (has been checked).
1006de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarvoid SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1007de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                  Instruction *Pos, PHINode *LoopPhi) {
100836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  do {
100936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (DT->dominates(InstToHoist, Pos))
101036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      break;
101136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Make sure the increment is where we want it. But don't move it
101236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // down past a potential existing post-inc user.
1013de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    fixupInsertPoints(InstToHoist);
101436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InstToHoist->moveBefore(Pos);
101536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Pos = InstToHoist;
101636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
101736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  } while (InstToHoist != LoopPhi);
101836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
101936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
102036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// \brief Check whether we can cheaply express the requested SCEV in terms of
1021f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar/// the available PHI SCEV by truncation and/or inversion of the step.
102236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesstatic bool canBeCheaplyTransformed(ScalarEvolution &SE,
102336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    const SCEVAddRecExpr *Phi,
102436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    const SCEVAddRecExpr *Requested,
102536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                    bool &InvertStep) {
102636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
102736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
102836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
102936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
103036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return false;
103136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
103236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Try truncate it if necessary.
103336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
103436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (!Phi)
103536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return false;
103636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
103736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Check whether truncation will help.
103836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (Phi == Requested) {
103936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = false;
104036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return true;
104136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
104236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
104336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
104436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (SE.getAddExpr(Requested->getStart(),
104536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                    SE.getNegativeSCEV(Requested)) == Phi) {
104636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = true;
104736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return true;
104836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
104936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
105036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  return false;
105136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
105236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1053ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesstatic bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1054ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (!isa<IntegerType>(AR->getType()))
1055ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    return false;
1056ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1057ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1058ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1059ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *Step = AR->getStepRecurrence(SE);
1060ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1061ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                                            SE.getSignExtendExpr(AR, WideTy));
1062ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *ExtendAfterOp =
1063ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1064ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  return ExtendAfterOp == OpAfterExtend;
1065ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines}
1066ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1067ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesstatic bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1068ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (!isa<IntegerType>(AR->getType()))
1069ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    return false;
1070ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1071ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1072ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1073ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *Step = AR->getStepRecurrence(SE);
1074ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1075ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                                            SE.getZeroExtendExpr(AR, WideTy));
1076ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  const SCEV *ExtendAfterOp =
1077ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1078ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  return ExtendAfterOp == OpAfterExtend;
1079ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines}
1080ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1081a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1082a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// the base addrec, which is the addrec without any non-loop-dominating
1083a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman/// values, and return the PHI.
1084a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanPHINode *
1085a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanSCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1086a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                        const Loop *L,
1087db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                        Type *ExpandTy,
108836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        Type *IntTy,
108936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        Type *&TruncTy,
109036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                        bool &InvertStep) {
109193a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1092d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1093a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Reuse a previously-inserted PHI, if present.
1094c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  BasicBlock *LatchBlock = L->getLoopLatch();
1095c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  if (LatchBlock) {
1096dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    PHINode *AddRecPhiMatch = nullptr;
1097dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    Instruction *IncV = nullptr;
1098dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    TruncTy = nullptr;
109936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InvertStep = false;
110036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
110136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Only try partially matching scevs that need truncation and/or
110236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // step-inversion if we know this loop is outside the current loop.
1103f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    bool TryNonMatchingSCEV =
1104f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        IVIncInsertLoop &&
1105f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
110636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1107f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    for (auto &I : *L->getHeader()) {
1108f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      auto *PN = dyn_cast<PHINode>(&I);
1109f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (!PN || !SE.isSCEVable(PN->getType()))
111036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        continue;
111136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
111236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
111336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!PhiSCEV)
1114c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick        continue;
1115c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
111636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      bool IsMatchingSCEV = PhiSCEV == Normalized;
111736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // We only handle truncation and inversion of phi recurrences for the
111836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // expanded expression if the expanded expression's loop dominates the
111936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // loop we insert to. Check now, so we can bail out early.
112036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!IsMatchingSCEV && !TryNonMatchingSCEV)
112136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          continue;
112236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
112336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Instruction *TempIncV =
112436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1125c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick
112636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Check whether we can reuse this PHI node.
1127c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      if (LSRMode) {
112836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1129c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
113036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1131b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick          continue;
113236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } else {
113336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1134c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick          continue;
1135c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      }
113636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
113736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Stop if we have found an exact match SCEV.
113836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (IsMatchingSCEV) {
113936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        IncV = TempIncV;
1140dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        TruncTy = nullptr;
114136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        InvertStep = false;
114236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        AddRecPhiMatch = PN;
114336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        break;
114436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      }
114536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
114636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Try whether the phi can be translated into the requested form
114736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // (truncated and/or offset by a constant).
114836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if ((!TruncTy || InvertStep) &&
114936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
115036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Record the phi node. But don't stop we might find an exact match
115136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // later.
115236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        AddRecPhiMatch = PN;
115336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        IncV = TempIncV;
115436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
115536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      }
115636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
115736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
115836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (AddRecPhiMatch) {
115936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Potentially, move the increment. We have made sure in
116036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
116136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (L == IVIncInsertLoop)
1162f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
116336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1164c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Ok, the add recurrence looks usable.
1165c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember this PHI, even in post-inc mode.
116636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      InsertedValues.insert(AddRecPhiMatch);
1167c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      // Remember the increment.
1168c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick      rememberInstruction(IncV);
116936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return AddRecPhiMatch;
1170c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick    }
1171c5701910604cdf65811fabd31d41e38f1d1d4eb1Andrew Trick  }
1172a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1173a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Save the original insertion point so we can restore it when we're done.
1174de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SCEVInsertPointGuard Guard(Builder, this);
1175a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1176ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // Another AddRec may need to be recursively expanded below. For example, if
1177ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1178ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // loop. Remove this loop from the PostIncLoops set before expanding such
1179ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // AddRecs. Otherwise, we cannot find a valid position for the step
1180ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1181ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1182ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // so it's not worth implementing SmallPtrSet::swap.
1183ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1184ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops.clear();
1185ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1186a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand code for the start value.
1187f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Value *StartV =
1188f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1189a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1190d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick  // StartV must be hoisted into L's preheader to dominate the new phi.
119193a896e2e36480d55de3bab53e68581e08526344Benjamin Kramer  assert(!isa<Instruction>(StartV) ||
1192f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1193f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                 L->getHeader()));
1194d152d03a476b8d0d4b26577db26e2ba76034b0f3Andrew Trick
1195553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand code for the step value. Do this before creating the PHI so that PHI
1196553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // reuse code doesn't see an incomplete PHI.
1197a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1198553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // If the stride is negative, insert a sub instead of an add for the increment
1199553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // (unless it's a constant, because subtracts of constants are canonicalized
1200553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // to adds).
1201f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1202553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  if (useSubtract)
1203a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Step = SE.getNegativeSCEV(Step);
1204553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick  // Expand the step somewhere that dominates the loop header.
1205f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1206a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1207ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1208ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // we actually do emit an addition.  It does not apply if we emit a
1209ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  // subtraction.
1210ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1211ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1212ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1213a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the PHI.
1214d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  BasicBlock *Header = L->getHeader();
1215d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  Builder.SetInsertPoint(Header, Header->begin());
1216d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
12175e7645be4c9dd2193add44d30b5fef8036d7a3ceAndrew Trick  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1218dc8e546048db2f7ff5656742b2b26975098a11a0Andrew Trick                                  Twine(IVName) + ".iv");
1219a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(PN);
1220a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1221a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Create the step instructions and populate the PHI.
1222d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1223a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *Pred = *HPI;
1224a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1225a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // Add a start value.
1226a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    if (!L->contains(Pred)) {
1227a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      PN->addIncoming(StartV, Pred);
1228a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      continue;
1229a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1230a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1231553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // Create a step value and add it to the PHI.
1232553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1233553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    // instructions at IVIncInsertPos.
1234a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Instruction *InsertPos = L == IVIncInsertLoop ?
1235a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      IVIncInsertPos : Pred->getTerminator();
1236c5ecbdc1896f1cc089372feef3191ace2f840898Devang Patel    Builder.SetInsertPoint(InsertPos);
1237553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1238ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1239409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick    if (isa<OverflowingBinaryOperator>(IncV)) {
1240ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      if (IncrementIsNUW)
1241409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick        cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1242ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      if (IncrementIsNSW)
1243409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick        cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1244409443b1c6415e55c2bd4f0662e14cbc52d16686Andrew Trick    }
1245a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PN->addIncoming(IncV, Pred);
1246a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1247a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1248ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // After expanding subexpressions, restore the PostIncLoops set so the caller
1249ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  // can ensure that IVIncrement dominates the current uses.
1250ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick  PostIncLoops = SavedPostIncLoops;
1251ba3c0bc364a31bfbcc570504aae2172914b1fe9fAndrew Trick
1252a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Remember this PHI, even in post-inc mode.
1253a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  InsertedValues.insert(PN);
1254a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1255a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return PN;
1256a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1257a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1258a10756ee657a4d43a48cca5c166919093930ed6bDan GohmanValue *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1259db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *STy = S->getType();
1260db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *IntTy = SE.getEffectiveSCEVType(STy);
1261a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const Loop *L = S->getLoop();
1262a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1263a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Determine a normalized form of this expression, which is the expression
1264a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // before any post-inc adjustment is made.
1265a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEVAddRecExpr *Normalized = S;
1266448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (PostIncLoops.count(L)) {
1267448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    PostIncLoopSet Loops;
1268448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman    Loops.insert(L);
1269f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1270f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1271a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1272a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1273a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec start.
1274a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Start = Normalized->getStart();
1275dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  const SCEV *PostLoopOffset = nullptr;
1276dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.properlyDominates(Start, L->getHeader())) {
1277a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopOffset = Start;
1278deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Start = SE.getConstant(Normalized->getType(), 0);
12793228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Normalized = cast<SCEVAddRecExpr>(
12803228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick      SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
12813228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                       Normalized->getLoop(),
12826f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                       Normalized->getNoWrapFlags(SCEV::FlagNW)));
1283a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1284a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1285a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Strip off any non-loop-dominating component from the addrec step.
1286a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  const SCEV *Step = Normalized->getStepRecurrence(SE);
1287dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  const SCEV *PostLoopScale = nullptr;
1288dc0e8fb9f9512622f55f73e1a434caa5c0915694Dan Gohman  if (!SE.dominates(Step, L->getHeader())) {
1289a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    PostLoopScale = Step;
1290deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    Step = SE.getConstant(Normalized->getType(), 1);
1291de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (!Start->isZero()) {
1292de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // The normalization below assumes that Start is constant zero, so if
1293de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // it isn't re-associate Start to PostLoopOffset.
1294de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1295de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        PostLoopOffset = Start;
1296de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        Start = SE.getConstant(Normalized->getType(), 0);
1297de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    }
1298a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Normalized =
12996f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick      cast<SCEVAddRecExpr>(SE.getAddRecExpr(
13006f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                             Start, Step, Normalized->getLoop(),
13016f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                             Normalized->getNoWrapFlags(SCEV::FlagNW)));
1302a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1303a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1304a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Expand the core addrec. If we need post-loop scaling, force it to
1305a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // expand to an integer type to avoid the need for additional casting.
1306db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *ExpandTy = PostLoopScale ? IntTy : STy;
130736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // In some cases, we decide to reuse an existing phi node but need to truncate
130836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // it and/or invert the step.
1309dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *TruncTy = nullptr;
131036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  bool InvertStep = false;
131136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
131236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                          TruncTy, InvertStep);
1313a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
13143f46a3abeedba8d517b4182de34c821d752db058Dan Gohman  // Accommodate post-inc mode, if necessary.
1315a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  Value *Result;
1316448db1cdef5872713ef77beffacf502ae3450cd7Dan Gohman  if (!PostIncLoops.count(L))
1317a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN;
1318a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  else {
1319a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    // In PostInc mode, use the post-incremented value.
1320a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    BasicBlock *LatchBlock = L->getLoopLatch();
1321a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1322a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = PN->getIncomingValueForBlock(LatchBlock);
132348ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick
132448ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // For an expansion to use the postinc form, the client must call
132548ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
132648ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick    // or dominated by IVIncInsertPos.
1327f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (isa<Instruction>(Result) &&
1328f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        !SE.DT.dominates(cast<Instruction>(Result),
1329f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                         &*Builder.GetInsertPoint())) {
1330553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // The induction variable's postinc expansion does not dominate this use.
1331553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // IVUsers tries to prevent this case, so it is rare. However, it can
1332553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // happen when an IVUser outside the loop is not dominated by the latch
1333553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1334553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // all cases. Consider a phi outide whose operand is replaced during
1335553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // expansion with the value of the postinc user. Without fundamentally
1336553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // changing the way postinc users are tracked, the only remedy is
1337553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1338553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      // but hopefully expandCodeFor handles that.
1339553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      bool useSubtract =
1340f8fd841a4bb7a59f81cf4642169e8251e039acfeAndrew Trick        !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1341553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      if (useSubtract)
1342553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick        Step = SE.getNegativeSCEV(Step);
1343d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      Value *StepV;
1344d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      {
1345d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer        // Expand the step somewhere that dominates the loop header.
1346de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        SCEVInsertPointGuard Guard(Builder, this);
1347f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1348d4278821665aa97f5fc0d19a32ff1fb39a22d395Benjamin Kramer      }
1349553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick      Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1350553fe05f236f46fe27b7fcfa822b06367d50183eAndrew Trick    }
1351a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1352a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
135336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // We have decided to reuse an induction variable of a dominating loop. Apply
135436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // truncation and/or invertion of the step.
135536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (TruncTy) {
135636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Type *ResTy = Result->getType();
135736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Normalize the result type.
135836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (ResTy != SE.getEffectiveSCEVType(ResTy))
135936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
136036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Truncate the result.
136136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (TruncTy != Result->getType()) {
136236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = Builder.CreateTrunc(Result, TruncTy);
136336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      rememberInstruction(Result);
136436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
136536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Invert the result.
136636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (InvertStep) {
136736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
136836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                                 Result);
136936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      rememberInstruction(Result);
137036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
137136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
137236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1373a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating scale.
1374a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopScale) {
13754d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
13760a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman    Result = InsertNoopCastOfTo(Result, IntTy);
1377a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    Result = Builder.CreateMul(Result,
1378a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                               expandCodeFor(PostLoopScale, IntTy));
1379a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Result);
1380a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1381a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1382a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  // Re-apply any non-loop-dominating offset.
1383a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (PostLoopOffset) {
1384db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1385a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      const SCEV *const OffsetArray[1] = { PostLoopOffset };
1386a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1387a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    } else {
13880a799ab15801d4ebf68eeb151d6375a799c87d9aDan Gohman      Result = InsertNoopCastOfTo(Result, IntTy);
1389a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      Result = Builder.CreateAdd(Result,
1390a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman                                 expandCodeFor(PostLoopOffset, IntTy));
1391a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman      rememberInstruction(Result);
1392a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    }
1393a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  }
1394a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1395a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  return Result;
1396a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman}
1397a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1398890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1399a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1400a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman
1401db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
140236f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  const Loop *L = S->getLoop();
140336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14044d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // First check for an existing canonical IV in a suitable type.
1405dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  PHINode *CanonicalIV = nullptr;
14064d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (PHINode *PN = L->getCanonicalInductionVariable())
1407133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman    if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
14084d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      CanonicalIV = PN;
14094d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
14104d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Rewrite an AddRec in terms of the canonical induction variable, if
14114d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // its type is more narrow.
14124d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (CanonicalIV &&
14134d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(CanonicalIV->getType()) >
14144d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman      SE.getTypeSizeInBits(Ty)) {
1415f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1416f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1417f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman      NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
14183228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick    Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
14196f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                       S->getNoWrapFlags(SCEV::FlagNW)));
14204d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    BasicBlock::iterator NewInsertPt =
1421f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1422dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1423f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                      &*NewInsertPt);
14244d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    return V;
14254d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  }
14264d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
142736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // {X,+,F} --> X + {0,+,F}
1428cfeb6a450632f2a6cd05302633c8c2b8c90cfdfdDan Gohman  if (!S->getStart()->isZero()) {
1429f9e64729afec646fe93b51417e66e552e8e630a4Dan Gohman    SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1430deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman    NewOps[0] = SE.getConstant(Ty, 0);
14316f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick    const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
14326f71dd765ae9e1d1d0ba01d98a05627ffe3bfc8aAndrew Trick                                        S->getNoWrapFlags(SCEV::FlagNW));
1433453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
1434453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1435453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    // comments on expandAddToGEP for details.
1436c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *Base = S->getStart();
1437c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    const SCEV *RestArray[1] = { Rest };
1438c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // Dig into the expression to find the pointer base for a GEP.
1439c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    ExposePointerBase(Base, RestArray[0], SE);
1440c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman    // If we found a pointer, expand the AddRec with a GEP.
1441db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1442c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // Make sure the Base isn't something exotic, such as a multiplied
1443c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // or divided pointer value. In those cases, the result type isn't
1444c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      // actually a pointer type.
1445c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman      if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1446c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        Value *StartV = expand(Base);
1447c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1448c40f17b08774c2dcc5787fd83241e3c64ba82974Dan Gohman        return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1449453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman      }
1450453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman    }
1451453aa4fbf1083cc7f646a0ac21e2bcc384a91ae9Dan Gohman
145240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    // Just do a normal add. Pre-expand the operands to suppress folding.
1453de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    //
1454de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // The LHS and RHS values are factored out of the expand call to make the
1455de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // output independent of the argument evaluation order.
1456de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1457de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1458de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
145936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
146036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14616ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // If we don't yet have a canonical IV, create one.
14626ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (!CanonicalIV) {
146336f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // Create and insert the PHI node for the induction variable in the
146436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    // specified loop.
146536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman    BasicBlock *Header = L->getHeader();
1466d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
14673ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1468f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                  &Header->front());
14696ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    rememberInstruction(CanonicalIV);
147036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
147119046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel    SmallSet<BasicBlock *, 4> PredSeen;
1472eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson    Constant *One = ConstantInt::get(Ty, 1);
1473d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad    for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
14747656018c2268285907cfdc106071462a01a73878Gabor Greif      BasicBlock *HP = *HPI;
147537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (!PredSeen.insert(HP).second) {
147637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // There must be an incoming value for each predecessor, even the
147737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // duplicates!
147837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
147919046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel        continue;
148037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      }
148119046ec19c4931f025cd4730eb43e9203ada6bb7Hal Finkel
14827656018c2268285907cfdc106071462a01a73878Gabor Greif      if (L->contains(HP)) {
14833abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // Insert a unit add instruction right before the terminator
14843abf905b50f33340ae81913da81b0eda96fa4616Dan Gohman        // corresponding to the back-edge.
14856ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
14866ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     "indvar.next",
14876ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                                     HP->getTerminator());
1488df3ad6697bb849e514c0881ca8700ea36678cbdaDevang Patel        Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1489a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman        rememberInstruction(Add);
14906ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Add, HP);
149183d577490b1473213b6973236110c28e59127956Dan Gohman      } else {
14926ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
149383d577490b1473213b6973236110c28e59127956Dan Gohman      }
14947656018c2268285907cfdc106071462a01a73878Gabor Greif    }
149536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  }
149636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
14976ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  // {0,+,1} --> Insert a canonical induction variable into the loop!
14986ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  if (S->isAffine() && S->getOperand(1)->isOne()) {
14996ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
15006ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "IVs with types different from the canonical IV should "
15016ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman           "already have been handled!");
15026ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman    return CanonicalIV;
15036ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  }
15046ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman
15054d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // {0,+,F} --> {0,+,1} * F
150636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
1507df14a04b5ccbbe6a46c2ccb93e27b12a36ff163eChris Lattner  // If this is a simple linear addrec, emit it now as a special case.
150840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  if (S->isAffine())    // {0,+,F} --> i*F
150940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    return
151040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      expand(SE.getTruncateOrNoop(
15116ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman        SE.getMulExpr(SE.getUnknown(CanonicalIV),
151240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman                      SE.getNoopOrAnyExtend(S->getOperand(1),
15136ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman                                            CanonicalIV->getType())),
151440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        Ty));
151536f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
151636f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // If this is a chain of recurrences, turn it into a closed form, using the
151736f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // folders, then expandCodeFor the closed form.  This allows the folders to
151836f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // simplify the expression without having to build a bunch of special code
151936f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman  // into this folder.
15206ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
152136f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
15224d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Promote S up to the canonical IV type, if the cast is foldable.
15230bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *NewS = S;
15246ebfd72f37325a1ebceb53e5ecad524d359d8d0bDan Gohman  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
15254d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  if (isa<SCEVAddRecExpr>(Ext))
15264d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman    NewS = Ext;
15274d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman
15280bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1529e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
153036f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman
15314d8414f42033a5e744e8e60d2ca188b424c76168Dan Gohman  // Truncate the result down to the original type, if needed.
15320bba49cebc50c7bd4662a4807bcb3ee7f42cb470Dan Gohman  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1533469f3cdc13851914f3a766cbd8f701cf8431cacaDan Gohman  return expand(T);
153436f891bdf6cf38fcc655a0930ca18664e18518d4Nate Begeman}
153596fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov
1536890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1537db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
153892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
153992fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1540a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateTrunc(V, Ty);
1541a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1542cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
154311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
154411f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1545890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1546db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
154792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
154892fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1549a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateZExt(V, Ty);
1550a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1551cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
155211f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
155311f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1554890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1555db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = SE.getEffectiveSCEVType(S->getType());
155692fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman  Value *V = expandCodeFor(S->getOperand(),
155792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman                           SE.getEffectiveSCEVType(S->getOperand()->getType()));
1558a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer  Value *I = Builder.CreateSExt(V, Ty);
1559a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman  rememberInstruction(I);
1560cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman  return I;
156111f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
156211f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1563890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
15640196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1565db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
15660196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
15670196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
15680196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
15690196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
15700196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
15710196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
15720196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
157392fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1574a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1575a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1576267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1577a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1578cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
1579c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  }
15800196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
15810196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
15820196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
15830196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
1584c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky  return LHS;
1585c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky}
1586c54c561c9f7270c055dd7ba75a3a003b771a42d9Nick Lewycky
1587890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
15880196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1589db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *Ty = LHS->getType();
15900196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  for (int i = S->getNumOperands()-2; i >= 0; --i) {
15910196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // In the case of mixed integer and pointer types, do the
15920196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    // rest of the comparisons as integer.
15930196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    if (S->getOperand(i)->getType() != Ty) {
15940196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      Ty = SE.getEffectiveSCEVType(Ty);
15950196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman      LHS = InsertNoopCastOfTo(LHS, Ty);
15960196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    }
159792fcdcac543653a62949fe9e5a7bd008500c1380Dan Gohman    Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1598a9390a4d5f5d568059a80970d22194b165d097a7Benjamin Kramer    Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1599a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(ICmp);
1600267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman    Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1601a10756ee657a4d43a48cca5c166919093930ed6bDan Gohman    rememberInstruction(Sel);
1602cf5ab820227dedd77fb91d0904b6dc3694a7c196Dan Gohman    LHS = Sel;
16033e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  }
16040196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // In the case of mixed integer and pointer types, cast the
16050196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  // final result back to the pointer type.
16060196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman  if (LHS->getType() != S->getType())
16070196dc5733bf3c6a71f7de1f631f2c43e5809fd9Dan Gohman    LHS = InsertNoopCastOfTo(LHS, S->getType());
16083e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky  return LHS;
16093e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky}
16103e6307698084e7adfc10b739442ae29742beefd0Nick Lewycky
1611db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1612b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick                                   Instruction *IP) {
1613f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  assert(IP);
1614f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Builder.SetInsertPoint(IP);
16156c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman  return expandCodeFor(SH, Ty);
16166c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman}
16176c7ed6b54949949806797bafdf545fbfecb2cef5Dan Gohman
1618db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris LattnerValue *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
161911f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman  // Expand the code for this SCEV.
16202d1be87ee40a4a0241d94448173879d9df2bc5b3Dan Gohman  Value *V = expand(SH);
16215be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  if (Ty) {
16225be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
16235be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman           "non-trivial casts should be done with the SCEVs directly!");
16245be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman    V = InsertNoopCastOfTo(V, Ty);
16255be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  }
16265be18e84766fb495b0bde3c8244c1df459a18683Dan Gohman  return V;
162711f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman}
162811f6d3b478c4fa09d126833c57fbac1d795ead31Dan Gohman
1629de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga NainarValue *SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1630de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                             const Instruction *InsertPt) {
1631de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SetVector<Value *> *Set = SE.getSCEVValues(S);
1632de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // If the expansion is not in CanonicalMode, and the SCEV contains any
1633de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1634de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1635de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    // If S is scConstant, it may be worse to reuse an existing Value.
1636de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    if (S->getSCEVType() != scConstant && Set) {
1637de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // Choose a Value from the set which dominates the insertPt.
1638de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // insertPt should be inside the Value's parent loop so as not to break
1639de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      // the LCSSA form.
1640de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      for (auto const &Ent : *Set) {
1641de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        Instruction *EntInst = nullptr;
1642de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        if (Ent && isa<Instruction>(Ent) &&
1643de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            (EntInst = cast<Instruction>(Ent)) &&
1644de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            S->getType() == Ent->getType() &&
1645de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            EntInst->getFunction() == InsertPt->getFunction() &&
1646de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            SE.DT.dominates(EntInst, InsertPt) &&
1647de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1648de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar             SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) {
1649de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          return Ent;
1650de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        }
1651de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      }
1652de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    }
1653de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  }
1654de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  return nullptr;
1655de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar}
1656de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1657de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1658de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1659de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1660de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1661de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// the expansion will try to reuse Value from ExprValueMap, and only when it
1662de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// fails, expand the SCEV literally.
1663890f92b744fb074465bc2b7006ee753a181f62a4Dan GohmanValue *SCEVExpander::expand(const SCEV *S) {
166440a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // Compute an insertion point for this SCEV object. Hoist the instructions
166540a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  // as far out in the loop nest as possible.
1666f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Instruction *InsertPt = &*Builder.GetInsertPoint();
1667f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
166840a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman       L = L->getParentLoop())
166917ead4ff4baceb2c5503f233d0288d363ae44165Dan Gohman    if (SE.isLoopInvariant(S, L)) {
167040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      if (!L) break;
1671e059ee832ca36d65a5fb87b0ac5bcdb0490b15cbDan Gohman      if (BasicBlock *Preheader = L->getLoopPreheader())
167240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman        InsertPt = Preheader->getTerminator();
16730f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      else {
16740f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // LSR sets the insertion point for AddRec start/step values to the
16750f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // block start to simplify value reuse, even though it's an invalid
16760f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick        // position. SCEVExpander must correct for this in all cases.
1677f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        InsertPt = &*L->getHeader()->getFirstInsertionPt();
16780f8cd56bfdd32af4edb253654db02fb3143b25a8Andrew Trick      }
167940a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    } else {
168040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // If the SCEV is computable at this level, insert it into the header
168140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // after the PHIs (and after any other instructions that we've inserted
168240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      // there) so that it is guaranteed to dominate any user inside the loop.
16835b6f42f57e730c2d968c313a27fa505a3c3e5efaBill Wendling      if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1684f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        InsertPt = &*L->getHeader()->getFirstInsertionPt();
1685de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1686de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar             (isInsertedInstruction(InsertPt) ||
1687de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar              isa<DbgInfoIntrinsic>(InsertPt))) {
1688f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        InsertPt = &*std::next(InsertPt->getIterator());
1689b5c26ef9da16052597d59a412eaae32098aa1be0Andrew Trick      }
169040a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman      break;
169140a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman    }
169240a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1693667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Check to see if we already expanded this here.
1694f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1695267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman  if (I != InsertedExpressions.end())
1696667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman    return I->second;
1697267a385342f2e7388f178b327dd87c5f29afd51bDan Gohman
1698de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SCEVInsertPointGuard Guard(Builder, this);
1699f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Builder.SetInsertPoint(InsertPt);
1700667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman
1701667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Expand the expression into instructions.
1702de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *V = FindValueInExprValueMap(S, InsertPt);
1703de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1704de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (!V)
1705de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    V = visit(S);
170640a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman
1707667d787c0a21cf3f5dfcde03ca471162ba35b614Dan Gohman  // Remember the expanded value for this SCEV at this location.
170848ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  //
170948ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // This is independent of PostIncLoops. The mapped value simply materializes
171048ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // the expression at this insertion point. If the mapped value happened to be
171136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // a postinc expansion, it could be reused by a non-postinc user, but only if
171248ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  // its insertion point was already at the head of the loop.
171348ba0e45ed68689ce7b384578e6272410e4e23feAndrew Trick  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
171496fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov  return V;
171596fea337d27357e9b62abbf3d2d5ce29f1c8e870Anton Korobeynikov}
17161d09de3eca23267855e28297fcb40de3632ea47bDan Gohman
17171d826a76f591afea445489b9a5485c345e66bf87Dan Gohmanvoid SCEVExpander::rememberInstruction(Value *I) {
171825fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  if (!PostIncLoops.empty())
171925fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman    InsertedPostIncValues.insert(I);
172025fcaff409f5c4c6da08f148ffb9404a71e8e4a7Dan Gohman  else
17211d826a76f591afea445489b9a5485c345e66bf87Dan Gohman    InsertedValues.insert(I);
17221d826a76f591afea445489b9a5485c345e66bf87Dan Gohman}
17231d826a76f591afea445489b9a5485c345e66bf87Dan Gohman
17241d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// getOrInsertCanonicalInductionVariable - This method returns the
17251d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// canonical induction variable of the specified type for the specified
17261d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// loop (inserting one if there is none).  A canonical induction variable
17271d09de3eca23267855e28297fcb40de3632ea47bDan Gohman/// starts at zero and steps by one on each iteration.
17287c58dbd88c36c5d6c411ea6c046ddcff4c5841e9Dan GohmanPHINode *
17291d09de3eca23267855e28297fcb40de3632ea47bDan GohmanSCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1730db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner                                                    Type *Ty) {
1731b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1732133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1733133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Build a SCEV for {0,+,1}<L>.
17343228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick  // Conservatively use FlagAnyWrap for now.
1735deff621abdd48bd70434bd4d7ef30f08ddba1cd8Dan Gohman  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
17363228cc259b5ca00e46af36da369a451f5736cbf4Andrew Trick                                   SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1737133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
1738133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman  // Emit code for it.
1739de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SCEVInsertPointGuard Guard(Builder, this);
1740f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  PHINode *V =
1741f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1742133e295b363c89b6a3da7aba3ac5ae6332429e46Dan Gohman
174340a5a1b39ee1cd40ff9d04740386b667fb27b340Dan Gohman  return V;
17441d09de3eca23267855e28297fcb40de3632ea47bDan Gohman}
1745204494149b6f846e8f173f525b129f5508076049Andrew Trick
1746204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replaceCongruentIVs - Check for congruent phis in this loop header and
1747204494149b6f846e8f173f525b129f5508076049Andrew Trick/// replace them with their most canonical representative. Return the number of
1748204494149b6f846e8f173f525b129f5508076049Andrew Trick/// phis eliminated.
1749204494149b6f846e8f173f525b129f5508076049Andrew Trick///
1750204494149b6f846e8f173f525b129f5508076049Andrew Trick/// This does not depend on any SCEVExpander state but should be used in
1751204494149b6f846e8f173f525b129f5508076049Andrew Trick/// the same context that SCEVExpander is used.
1752204494149b6f846e8f173f525b129f5508076049Andrew Trickunsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1753a04a4a79ea365d1ba96ed4b5861e879b267162e2Nadav Rotem                                           SmallVectorImpl<WeakVH> &DeadInsts,
1754e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth                                           const TargetTransformInfo *TTI) {
1755ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // Find integer phis in order of increasing width.
1756ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  SmallVector<PHINode*, 8> Phis;
1757f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (auto &I : *L->getHeader()) {
1758f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (auto *PN = dyn_cast<PHINode>(&I))
1759f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      Phis.push_back(PN);
1760f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    else
1761f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      break;
1762ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  }
1763f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1764e4ba75f43e2ab1480d119d2d4eb878256274e0fbChandler Carruth  if (TTI)
176536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
176636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Put pointers at the back and make sure pointer < pointer = false.
176736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
176836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
176936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return RHS->getType()->getPrimitiveSizeInBits() <
177036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines             LHS->getType()->getPrimitiveSizeInBits();
177136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    });
1772ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1773204494149b6f846e8f173f525b129f5508076049Andrew Trick  unsigned NumElim = 0;
1774204494149b6f846e8f173f525b129f5508076049Andrew Trick  DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1775f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // Process phis from wide to narrow. Map wide phis to their truncation
1776ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick  // so narrow phis can reuse them.
1777f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (PHINode *Phi : Phis) {
1778f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1779f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1780f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        return V;
1781f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (!SE.isSCEVable(PN->getType()))
1782f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        return nullptr;
1783f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1784f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (!Const)
1785f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        return nullptr;
1786f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      return Const->getValue();
1787f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    };
1788ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick
1789239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    // Fold constant phis. They may be congruent to other constant phis and
1790239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    // would confuse the logic below that expects proper IVs.
1791f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (Value *V = SimplifyPHINode(Phi)) {
1792f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (V->getType() != Phi->getType())
1793f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar        continue;
1794239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      Phi->replaceAllUsesWith(V);
17956948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      DeadInsts.emplace_back(Phi);
1796239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      ++NumElim;
1797239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      DEBUG_WITH_TYPE(DebugType, dbgs()
1798239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer                      << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1799239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer      continue;
1800239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer    }
1801239fd44f7a68aae4b2e8b6f1738ef9e8fd4ddc01Benjamin Kramer
1802204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!SE.isSCEVable(Phi->getType()))
1803204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1804204494149b6f846e8f173f525b129f5508076049Andrew Trick
1805204494149b6f846e8f173f525b129f5508076049Andrew Trick    PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1806204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (!OrigPhiRef) {
1807204494149b6f846e8f173f525b129f5508076049Andrew Trick      OrigPhiRef = Phi;
1808de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (Phi->getType()->isIntegerTy() && TTI &&
1809de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1810ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // This phi can be freely truncated to the narrowest phi type. Map the
1811ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        // truncated expression to it so it will be reused for narrow types.
1812ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        const SCEV *TruncExpr =
1813ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick          SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1814ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        ExprToIVMap[TruncExpr] = Phi;
1815ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      }
1816204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1817204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1818204494149b6f846e8f173f525b129f5508076049Andrew Trick
1819ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1820ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    // sense.
1821ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1822204494149b6f846e8f173f525b129f5508076049Andrew Trick      continue;
1823204494149b6f846e8f173f525b129f5508076049Andrew Trick
1824204494149b6f846e8f173f525b129f5508076049Andrew Trick    if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1825de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Instruction *OrigInc = dyn_cast<Instruction>(
1826de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1827204494149b6f846e8f173f525b129f5508076049Andrew Trick      Instruction *IsomorphicInc =
1828de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1829de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1830de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (OrigInc && IsomorphicInc) {
1831de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // If this phi has the same width but is more canonical, replace the
1832de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // original with it. As part of the "more canonical" determination,
1833de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // respect a prior decision to use an IV chain.
1834de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        if (OrigPhiRef->getType() == Phi->getType() &&
1835de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            !(ChainedPhis.count(Phi) ||
1836de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar              isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1837de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            (ChainedPhis.count(Phi) ||
1838de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar             isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1839de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          std::swap(OrigPhiRef, Phi);
1840de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          std::swap(OrigInc, IsomorphicInc);
1841de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        }
1842de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // Replacing the congruent phi is sufficient because acyclic
1843de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // redundancy elimination, CSE/GVN, should handle the
1844de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // rest. However, once SCEV proves that a phi is congruent,
1845de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // it's often the head of an IV user cycle that is isomorphic
1846de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // with the original phi. It's worth eagerly cleaning up the
1847de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // common case of a single IV increment so that DeleteDeadPHIs
1848de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        // can remove cycles that had postinc uses.
1849de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        const SCEV *TruncExpr =
1850de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1851de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        if (OrigInc != IsomorphicInc &&
1852de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            TruncExpr == SE.getSCEV(IsomorphicInc) &&
1853de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1854de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            hoistIVInc(OrigInc, IsomorphicInc)) {
1855de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          DEBUG_WITH_TYPE(DebugType,
1856de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                          dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1857de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                 << *IsomorphicInc << '\n');
1858de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          Value *NewInc = OrigInc;
1859de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          if (OrigInc->getType() != IsomorphicInc->getType()) {
1860de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            Instruction *IP = nullptr;
1861de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1862de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar              IP = &*PN->getParent()->getFirstInsertionPt();
1863de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            else
1864de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar              IP = OrigInc->getNextNode();
1865de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1866de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            IRBuilder<> Builder(IP);
1867de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1868de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            NewInc = Builder.CreateTruncOrBitCast(
1869de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                OrigInc, IsomorphicInc->getType(), IVName);
1870de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          }
1871de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          IsomorphicInc->replaceAllUsesWith(NewInc);
1872de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar          DeadInsts.emplace_back(IsomorphicInc);
1873ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick        }
1874204494149b6f846e8f173f525b129f5508076049Andrew Trick      }
1875204494149b6f846e8f173f525b129f5508076049Andrew Trick    }
1876de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
1877de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                      << *Phi << '\n');
1878204494149b6f846e8f173f525b129f5508076049Andrew Trick    ++NumElim;
1879ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Value *NewIV = OrigPhiRef;
1880ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    if (OrigPhiRef->getType() != Phi->getType()) {
1881f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1882ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1883ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick      NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1884ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    }
1885ee98aa87434d9d49a8e4dab41d873888ac9c4805Andrew Trick    Phi->replaceAllUsesWith(NewIV);
18866948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    DeadInsts.emplace_back(Phi);
1887204494149b6f846e8f173f525b129f5508076049Andrew Trick  }
1888204494149b6f846e8f173f525b129f5508076049Andrew Trick  return NumElim;
1889204494149b6f846e8f173f525b129f5508076049Andrew Trick}
1890e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
1891f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga NainarValue *SCEVExpander::findExistingExpansion(const SCEV *S,
1892f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                           const Instruction *At, Loop *L) {
1893f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  using namespace llvm::PatternMatch;
1894f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1895f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  SmallVector<BasicBlock *, 4> ExitingBlocks;
1896f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  L->getExitingBlocks(ExitingBlocks);
1897f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1898f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // Look for suitable value in simple conditions at the loop exits.
1899f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (BasicBlock *BB : ExitingBlocks) {
1900f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    ICmpInst::Predicate Pred;
1901f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    Instruction *LHS, *RHS;
1902f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    BasicBlock *TrueBB, *FalseBB;
1903f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1904f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (!match(BB->getTerminator(),
1905f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar               m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1906f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                    TrueBB, FalseBB)))
1907f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      continue;
1908f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1909f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1910f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      return LHS;
1911f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1912f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1913f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      return RHS;
1914f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  }
1915f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1916de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Use expand's logic which is used for reusing a previous Value in
1917de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // ExprValueMap.
1918de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Value *Val = FindValueInExprValueMap(S, At))
1919de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return Val;
1920de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1921f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // There is potential to make this significantly smarter, but this simple
1922f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // heuristic already gets some interesting cases.
1923f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1924f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // Can not find suitable value.
1925f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  return nullptr;
1926f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar}
1927f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
19280c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainarbool SCEVExpander::isHighCostExpansionHelper(
1929f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    const SCEV *S, Loop *L, const Instruction *At,
1930f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    SmallPtrSetImpl<const SCEV *> &Processed) {
1931f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
1932f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // If we can find an existing value for this scev avaliable at the point "At"
1933f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // then consider the expression cheap.
1934f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  if (At && findExistingExpansion(S, At, L) != nullptr)
1935f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    return false;
19366948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
19376948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // Zero/One operand expressions
19386948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  switch (S->getSCEVType()) {
19396948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scUnknown:
19406948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scConstant:
19416948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return false;
19426948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scTruncate:
1943f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1944f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                     L, At, Processed);
19456948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scZeroExtend:
19466948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1947f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                     L, At, Processed);
19486948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  case scSignExtend:
19496948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1950f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                     L, At, Processed);
19516948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  }
19526948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
19530c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  if (!Processed.insert(S).second)
19540c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    return false;
19550c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
19560c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
19570c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // If the divisor is a power of two and the SCEV type fits in a native
1958f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    // integer, consider the division cheap irrespective of whether it occurs in
19590c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // the user code since it can be lowered into a right shift.
19600c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1961f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (SC->getAPInt().isPowerOf2()) {
19620c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        const DataLayout &DL =
19630c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar            L->getHeader()->getParent()->getParent()->getDataLayout();
19640c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
19650c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return DL.isIllegalInteger(Width);
19660c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      }
19670c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
19680c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
19690c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // HowManyLessThans produced to compute a precise expression, rather than a
19700c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // UDiv from the user's code. If we can't find a UDiv in the code with some
19710c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // simple searching, assume the former consider UDivExpr expensive to
19720c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    // compute.
19730c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    BasicBlock *ExitingBB = L->getExitingBlock();
19740c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    if (!ExitingBB)
19750c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      return true;
19760c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
1977f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    // At the beginning of this function we already tried to find existing value
1978f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1979f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    // involving division. This is just a simple search heuristic.
1980f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (!At)
1981f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      At = &ExitingBB->back();
1982f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    if (!findExistingExpansion(
1983f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
19840c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      return true;
19850c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  }
19860c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
19876948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // HowManyLessThans uses a Max expression whenever the loop is not guarded by
19886948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // the exit condition.
19896948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
19906948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    return true;
19916948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
19926948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  // Recurse past nary expressions, which commonly occur in the
19930c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // BackedgeTakenCount. They may already exist in program code, and if not,
19940c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // they are not too expensive rematerialize.
19956948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1996f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    for (auto *Op : NAry->operands())
1997f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (isHighCostExpansionHelper(Op, L, At, Processed))
19980c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar        return true;
19990c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  }
20000c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
20010c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // If we haven't recognized an expensive SCEV pattern, assume it's an
20020c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  // expression produced by program code.
20030c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar  return false;
20040c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar}
20050c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar
2006f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga NainarValue *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2007f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                            Instruction *IP) {
2008f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  assert(IP);
2009f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  switch (Pred->getKind()) {
2010f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  case SCEVPredicate::P_Union:
2011f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2012f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  case SCEVPredicate::P_Equal:
2013f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
2014de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  case SCEVPredicate::P_Wrap: {
2015de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2016de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return expandWrapPredicate(AddRecPred, IP);
2017de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  }
2018f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  }
2019f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  llvm_unreachable("Unknown SCEV predicate type");
2020f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar}
2021f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2022f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga NainarValue *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
2023f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                          Instruction *IP) {
2024f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2025f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2026f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2027f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Builder.SetInsertPoint(IP);
2028f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2029f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  return I;
2030f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar}
2031f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2032de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga NainarValue *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2033de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                           Instruction *Loc, bool Signed) {
2034de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  assert(AR->isAffine() && "Cannot generate RT check for "
2035de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                           "non-affine expression");
2036de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2037de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  SCEVUnionPredicate Pred;
2038de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  const SCEV *ExitCount =
2039de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2040de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2041de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2042de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2043de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  const SCEV *Step = AR->getStepRecurrence(SE);
2044de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  const SCEV *Start = AR->getStart();
2045de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2046de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2047de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  unsigned DstBits = SE.getTypeSizeInBits(AR->getType());
2048de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2049de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // The expression {Start,+,Step} has nusw/nssw if
2050de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //   Step < 0, Start - |Step| * Backedge <= Start
2051de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //   Step >= 0, Start + |Step| * Backedge > Start
2052de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // and |Step| * Backedge doesn't unsigned overflow.
2053de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2054de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2055de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Builder.SetInsertPoint(Loc);
2056de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2057de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2058de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  IntegerType *Ty =
2059de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(AR->getType()));
2060de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2061de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *StepValue = expandCodeFor(Step, Ty, Loc);
2062de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2063de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *StartValue = expandCodeFor(Start, Ty, Loc);
2064de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2065de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  ConstantInt *Zero =
2066de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
2067de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2068de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Builder.SetInsertPoint(Loc);
2069de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Compute |Step|
2070de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2071de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2072de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2073de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Get the backedge taken count and truncate or extended to the AR type.
2074de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2075de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2076de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                         Intrinsic::umul_with_overflow, Ty);
2077de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2078de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Compute |Step| * Backedge
2079de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2080de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2081de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2082de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2083de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Compute:
2084de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //   Start + |Step| * Backedge < Start
2085de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  //   Start - |Step| * Backedge > Start
2086de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *Add = Builder.CreateAdd(StartValue, MulV);
2087de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *Sub = Builder.CreateSub(StartValue, MulV);
2088de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2089de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *EndCompareGT = Builder.CreateICmp(
2090de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2091de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2092de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *EndCompareLT = Builder.CreateICmp(
2093de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2094de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2095de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Select the answer based on the sign of Step.
2096de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *EndCheck =
2097de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2098de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2099de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // If the backedge taken count type is larger than the AR type,
2100de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // check that we don't drop any bits by truncating it. If we are
2101de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // droping bits, then we have overflow (unless the step is zero).
2102de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2103de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2104de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    auto *BackedgeCheck =
2105de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2106de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                           ConstantInt::get(Loc->getContext(), MaxVal));
2107de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    BackedgeCheck = Builder.CreateAnd(
2108de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar        BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2109de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2110de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2111de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  }
2112de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2113de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  EndCheck = Builder.CreateOr(EndCheck, OfMul);
2114de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  return EndCheck;
2115de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar}
2116de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2117de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga NainarValue *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2118de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                                         Instruction *IP) {
2119de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2120de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2121de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2122de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Add a check for NUSW
2123de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2124de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    NUSWCheck = generateOverflowCheck(A, IP, false);
2125de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2126de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  // Add a check for NSSW
2127de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2128de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    NSSWCheck = generateOverflowCheck(A, IP, true);
2129de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2130de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (NUSWCheck && NSSWCheck)
2131de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return Builder.CreateOr(NUSWCheck, NSSWCheck);
2132de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2133de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (NUSWCheck)
2134de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return NUSWCheck;
2135de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2136de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  if (NSSWCheck)
2137de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar    return NSSWCheck;
2138de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2139de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar  return ConstantInt::getFalse(IP->getContext());
2140de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar}
2141de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
2142f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga NainarValue *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2143f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                                          Instruction *IP) {
2144f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  auto *BoolType = IntegerType::get(IP->getContext(), 1);
2145f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  Value *Check = ConstantInt::getNullValue(BoolType);
2146f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2147f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  // Loop over all checks in this set.
2148f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  for (auto Pred : Union->getPredicates()) {
2149f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    auto *NextCheck = expandCodeForPredicate(Pred, IP);
2150f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    Builder.SetInsertPoint(IP);
2151f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar    Check = Builder.CreateOr(Check, NextCheck);
2152f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  }
2153f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2154f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar  return Check;
2155f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar}
2156f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
2157e08c32249fca32cd7b122024a4ca252fcb235694Andrew Tricknamespace {
2158e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// Search for a SCEV subexpression that is not safe to expand.  Any expression
2159e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2160e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2161e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// instruction, but the important thing is that we prove the denominator is
2162e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// nonzero before expansion.
2163e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick//
2164e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// IVUsers already checks that IV-derived expressions are safe. So this check is
2165e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// only needed when the expression includes some subexpression that is not IV
2166e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// derived.
2167e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick//
2168e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// Currently, we only allow division by a nonzero constant here. If this is
2169e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// inadequate, we could easily allow division by SCEVUnknown by using
2170e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick// ValueTracking to check isKnownNonZero().
21714d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick//
21724d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// We cannot generally expand recurrences unless the step dominates the loop
21734d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// header. The expander handles the special case of affine recurrences by
21744d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// scaling the recurrence outside the loop, but this technique isn't generally
21754d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// applicable. Expanding a nested recurrence outside a loop requires computing
21764d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// binomial coefficients. This could be done, but the recurrence has to be in a
21774d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick// perfectly reduced form, which can't be guaranteed.
2178e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trickstruct SCEVFindUnsafe {
21794d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  ScalarEvolution &SE;
2180e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool IsUnsafe;
2181e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
21824d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2183e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
2184e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool follow(const SCEV *S) {
21854d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
21864d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
21874d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      if (!SC || SC->getValue()->isZero()) {
21884d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        IsUnsafe = true;
21894d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        return false;
21904d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      }
21914d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    }
21924d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
21934d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      const SCEV *Step = AR->getStepRecurrence(SE);
21944d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
21954d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        IsUnsafe = true;
21964d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick        return false;
21974d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick      }
21984d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    }
21994d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick    return true;
2200e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  }
2201e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  bool isDone() const { return IsUnsafe; }
2202e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick};
2203e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2204e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick
2205e08c32249fca32cd7b122024a4ca252fcb235694Andrew Tricknamespace llvm {
22064d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trickbool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
22074d4bbaf997c16f9e79503bd640306d784efd090eAndrew Trick  SCEVFindUnsafe Search(SE);
2208e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  visitAll(S, Search);
2209e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick  return !Search.IsUnsafe;
2210e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2211e08c32249fca32cd7b122024a4ca252fcb235694Andrew Trick}
2212