blob: d110385fb3ef447d5cd64e9e028d0311e52115ff [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman36f891b2005-07-30 00:12:19 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution expander,
11// which is used to generate the code corresponding to a given scalar evolution
12// expression.
13//
14//===----------------------------------------------------------------------===//
15
Nate Begeman36f891b2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000017#include "llvm/Analysis/LoopInfo.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000018#include "llvm/Target/TargetData.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000019using namespace llvm;
20
Chris Lattnerca1a4be2006-02-04 09:51:53 +000021/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000023Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
24 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +000025 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
27 return V;
28
Dan Gohmanf04fa482009-04-16 15:52:57 +000029 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohmanaf79fb52009-04-21 01:07:12 +000030 if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000031 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000032 if (CastInst *CI = dyn_cast<CastInst>(V))
33 if ((CI->getOpcode() == Instruction::PtrToInt ||
34 CI->getOpcode() == Instruction::IntToPtr) &&
35 SE.getTypeSizeInBits(CI->getType()) ==
36 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
37 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000038 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
39 if ((CE->getOpcode() == Instruction::PtrToInt ||
40 CE->getOpcode() == Instruction::IntToPtr) &&
41 SE.getTypeSizeInBits(CE->getType()) ==
42 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
43 return CE->getOperand(0);
44 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000045
Chris Lattnerca1a4be2006-02-04 09:51:53 +000046 // FIXME: keep track of the cast instruction.
47 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000048 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000049
50 if (Argument *A = dyn_cast<Argument>(V)) {
51 // Check to see if there is already a cast!
52 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
53 UI != E; ++UI) {
54 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000055 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
56 if (CI->getOpcode() == opcode) {
57 // If the cast isn't the first instruction of the function, move it.
58 if (BasicBlock::iterator(CI) !=
59 A->getParent()->getEntryBlock().begin()) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000060 // If the CastInst is the insert point, change the insert point.
61 if (CI == InsertPt) ++InsertPt;
62 // Splice the cast at the beginning of the entry block.
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000063 CI->moveBefore(A->getParent()->getEntryBlock().begin());
64 }
65 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000066 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000067 }
Dan Gohmancf5ab822009-05-01 17:13:31 +000068 Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
69 A->getParent()->getEntryBlock().begin());
70 InsertedValues.insert(I);
71 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000072 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000073
Chris Lattnerca1a4be2006-02-04 09:51:53 +000074 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000075
Chris Lattnerca1a4be2006-02-04 09:51:53 +000076 // Check to see if there is already a cast. If there is, use it.
77 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
78 UI != E; ++UI) {
79 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000080 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
81 if (CI->getOpcode() == opcode) {
82 BasicBlock::iterator It = I; ++It;
83 if (isa<InvokeInst>(I))
84 It = cast<InvokeInst>(I)->getNormalDest()->begin();
85 while (isa<PHINode>(It)) ++It;
86 if (It != BasicBlock::iterator(CI)) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000087 // If the CastInst is the insert point, change the insert point.
88 if (CI == InsertPt) ++InsertPt;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000089 // Splice the cast immediately after the operand in question.
90 CI->moveBefore(It);
91 }
92 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000093 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000094 }
95 BasicBlock::iterator IP = I; ++IP;
96 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
97 IP = II->getNormalDest()->begin();
98 while (isa<PHINode>(IP)) ++IP;
Dan Gohmancf5ab822009-05-01 17:13:31 +000099 Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
100 InsertedValues.insert(CI);
101 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000102}
103
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000104/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
105/// which must be possible with a noop cast.
106Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
107 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
108 assert((Op == Instruction::BitCast ||
Devang Patele2a17462009-04-22 18:51:05 +0000109 Op == Instruction::PtrToInt ||
110 Op == Instruction::IntToPtr) &&
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000111 "InsertNoopCastOfTo cannot perform non-noop casts!");
112 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
113 "InsertNoopCastOfTo cannot change sizes!");
114 return InsertCastOfTo(Op, V, Ty);
115}
116
Chris Lattner7fec90e2007-04-13 05:04:18 +0000117/// InsertBinop - Insert the specified binary operator, doing a small amount
118/// of work to avoid inserting an obviously redundant operation.
119Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Dan Gohman6cdc7272009-04-22 16:05:50 +0000120 Value *RHS, BasicBlock::iterator InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000121 // Fold a binop with constant operands.
122 if (Constant *CLHS = dyn_cast<Constant>(LHS))
123 if (Constant *CRHS = dyn_cast<Constant>(RHS))
124 return ConstantExpr::get(Opcode, CLHS, CRHS);
125
Chris Lattner7fec90e2007-04-13 05:04:18 +0000126 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
127 unsigned ScanLimit = 6;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000128 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
129 if (InsertPt != BlockBegin) {
130 // Scanning starts from the last instruction before InsertPt.
131 BasicBlock::iterator IP = InsertPt;
132 --IP;
133 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000134 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
135 IP->getOperand(1) == RHS)
136 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000137 if (IP == BlockBegin) break;
138 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000139 }
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000140
141 // If we haven't found this binop, insert it.
Dan Gohmancf5ab822009-05-01 17:13:31 +0000142 Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
143 InsertedValues.insert(BO);
144 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000145}
146
Dan Gohman5be18e82009-05-19 02:15:55 +0000147/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
148/// instead of using ptrtoint+arithmetic+inttoptr.
149Value *SCEVExpander::expandAddToGEP(const SCEVAddExpr *S,
150 const PointerType *PTy,
151 const Type *Ty,
152 Value *V) {
153 const Type *ElTy = PTy->getElementType();
154 SmallVector<Value *, 4> GepIndices;
155 std::vector<SCEVHandle> Ops = S->getOperands();
156 bool AnyNonZeroIndices = false;
157 Ops.pop_back();
158
159 // Decend down the pointer's type and attempt to convert the other
160 // operands into GEP indices, at each level. The first index in a GEP
161 // indexes into the array implied by the pointer operand; the rest of
162 // the indices index into the element or field type selected by the
163 // preceding index.
164 for (;;) {
165 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
166 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
167 std::vector<SCEVHandle> NewOps;
168 std::vector<SCEVHandle> ScaledOps;
169 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
170 if (ElSize != 0) {
171 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i]))
172 if (!C->getValue()->getValue().srem(ElSize)) {
173 ConstantInt *CI =
174 ConstantInt::get(C->getValue()->getValue().sdiv(ElSize));
175 SCEVHandle Div = SE.getConstant(CI);
176 ScaledOps.push_back(Div);
177 continue;
178 }
179 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i]))
180 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
181 if (C->getValue()->getValue() == ElSize) {
182 for (unsigned j = 1, f = M->getNumOperands(); j != f; ++j)
183 ScaledOps.push_back(M->getOperand(j));
184 continue;
185 }
186 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i]))
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getValue()))
188 if (BO->getOpcode() == Instruction::Mul)
189 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
190 if (CI->getValue() == ElSize) {
191 ScaledOps.push_back(SE.getUnknown(BO->getOperand(0)));
192 continue;
193 }
194 if (ElSize == 1) {
195 ScaledOps.push_back(Ops[i]);
196 continue;
197 }
198 }
199 NewOps.push_back(Ops[i]);
200 }
201 Ops = NewOps;
202 AnyNonZeroIndices |= !ScaledOps.empty();
203 Value *Scaled = ScaledOps.empty() ?
204 Constant::getNullValue(Ty) :
205 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
206 GepIndices.push_back(Scaled);
207
208 // Collect struct field index operands.
209 if (!Ops.empty())
210 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
211 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
212 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
213 const StructLayout &SL = *SE.TD->getStructLayout(STy);
214 uint64_t FullOffset = C->getValue()->getZExtValue();
215 if (FullOffset < SL.getSizeInBytes()) {
216 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
217 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
218 ElTy = STy->getTypeAtIndex(ElIdx);
219 Ops[0] =
220 SE.getConstant(ConstantInt::get(Ty,
221 FullOffset -
222 SL.getElementOffset(ElIdx)));
223 AnyNonZeroIndices = true;
224 continue;
225 }
226 }
227 break;
228 }
229
230 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
231 ElTy = ATy->getElementType();
232 continue;
233 }
234 break;
235 }
236
237 // If none of the operands were convertable to proper GEP indices, cast
238 // the base to i8* and do an ugly getelementptr with that. It's still
239 // better than ptrtoint+arithmetic+inttoptr at least.
240 if (!AnyNonZeroIndices) {
241 V = InsertNoopCastOfTo(V,
242 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
243 Value *Idx = expand(SE.getAddExpr(Ops));
244 Idx = InsertNoopCastOfTo(Idx, Ty);
245
246 // Fold a GEP with constant operands.
247 if (Constant *CLHS = dyn_cast<Constant>(V))
248 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000249 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000250
251 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
252 unsigned ScanLimit = 6;
253 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
254 if (InsertPt != BlockBegin) {
255 // Scanning starts from the last instruction before InsertPt.
256 BasicBlock::iterator IP = InsertPt;
257 --IP;
258 for (; ScanLimit; --IP, --ScanLimit) {
259 if (IP->getOpcode() == Instruction::GetElementPtr &&
260 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
261 return IP;
262 if (IP == BlockBegin) break;
263 }
264 }
265
266 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
267 InsertedValues.insert(GEP);
268 return GEP;
269 }
270
271 // Insert a pretty getelementptr.
272 Value *GEP = GetElementPtrInst::Create(V,
273 GepIndices.begin(),
274 GepIndices.end(),
275 "scevgep", InsertPt);
276 Ops.push_back(SE.getUnknown(GEP));
277 InsertedValues.insert(GEP);
278 return expand(SE.getAddExpr(Ops));
279}
280
Dan Gohman890f92b2009-04-18 17:56:28 +0000281Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000282 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000283 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000284
285 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. This helps
286 // BasicAliasAnalysis analyze the result. However, it suffers from the
287 // underlying bug described in PR2831. Addition in LLVM currently always
288 // has two's complement wrapping guaranteed. However, the semantics for
289 // getelementptr overflow are ambiguous. In the common case though, this
290 // expansion gets used when a GEP in the original code has been converted
291 // into integer arithmetic, in which case the resulting code will be no
292 // more undefined than it was originally.
293 if (SE.TD)
294 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
295 return expandAddToGEP(S, PTy, Ty, V);
296
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000297 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000298
299 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000300 for (int i = S->getNumOperands()-2; i >= 0; --i) {
301 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000302 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000303 V = InsertBinop(Instruction::Add, V, W, InsertPt);
304 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000305 return V;
306}
Dan Gohman5be18e82009-05-19 02:15:55 +0000307
Dan Gohman890f92b2009-04-18 17:56:28 +0000308Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000309 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000310 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000312 if (SC->getValue()->isAllOnesValue())
313 FirstOp = 1;
314
315 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000316 Value *V = expand(S->getOperand(i+1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000317 V = InsertNoopCastOfTo(V, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000318
319 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000320 for (; i >= FirstOp; --i) {
321 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000322 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000323 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
324 }
325
Nate Begeman36f891b2005-07-30 00:12:19 +0000326 // -1 * ... ---> 0 - ...
327 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000328 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000329 return V;
330}
331
Dan Gohman890f92b2009-04-18 17:56:28 +0000332Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000333 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000334
Nick Lewycky6177fd42008-07-08 05:05:37 +0000335 Value *LHS = expand(S->getLHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000336 LHS = InsertNoopCastOfTo(LHS, Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000337 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000338 const APInt &RHS = SC->getValue()->getValue();
339 if (RHS.isPowerOf2())
340 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000341 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000342 InsertPt);
343 }
344
345 Value *RHS = expand(S->getRHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000346 RHS = InsertNoopCastOfTo(RHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000347 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
348}
349
Dan Gohman890f92b2009-04-18 17:56:28 +0000350Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000351 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000352 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000353
354 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000355 if (!S->getStart()->isZero()) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000356 std::vector<SCEVHandle> NewOps(S->getOperands());
Dan Gohman246b2562007-10-22 18:31:58 +0000357 NewOps[0] = SE.getIntegerSCEV(0, Ty);
358 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Dan Gohman5be18e82009-05-19 02:15:55 +0000359 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(Rest)));
Nate Begeman36f891b2005-07-30 00:12:19 +0000360 }
361
362 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000363 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000364 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000365 // Create and insert the PHI node for the induction variable in the
366 // specified loop.
367 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000368 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000369 InsertedValues.insert(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000370 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
371
372 pred_iterator HPI = pred_begin(Header);
373 assert(HPI != pred_end(Header) && "Loop with zero preds???");
374 if (!L->contains(*HPI)) ++HPI;
375 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
376 "No backedge in loop?");
377
378 // Insert a unit add instruction right before the terminator corresponding
379 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000380 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000381 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000382 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000383 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000384
385 pred_iterator PI = pred_begin(Header);
386 if (*PI == L->getLoopPreheader())
387 ++PI;
388 PN->addIncoming(Add, *PI);
389 return PN;
390 }
391
392 // Get the canonical induction variable I for this loop.
393 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
394
Chris Lattnerdf14a042005-10-30 06:24:33 +0000395 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000396 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000397 Value *F = expand(S->getOperand(1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000398 F = InsertNoopCastOfTo(F, Ty);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000399
400 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000401 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000402 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000403 return I;
404
405 // If the insert point is directly inside of the loop, emit the multiply at
406 // the insert point. Otherwise, L is a loop that is a parent of the insert
407 // point loop. If we can, move the multiply to the outer most loop that it
408 // is safe to be in.
Dan Gohman6cdc7272009-04-22 16:05:50 +0000409 BasicBlock::iterator MulInsertPt = getInsertionPoint();
Dan Gohman5be18e82009-05-19 02:15:55 +0000410 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
Chris Lattnerdf14a042005-10-30 06:24:33 +0000411 if (InsertPtLoop != L && InsertPtLoop &&
412 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000413 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000414 // If we cannot hoist the multiply out of this loop, don't.
415 if (!InsertPtLoop->isLoopInvariant(F)) break;
416
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000417 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
418
419 // If this loop hasn't got a preheader, we aren't able to hoist the
420 // multiply.
421 if (!InsertPtLoopPH)
422 break;
423
424 // Otherwise, move the insert point to the preheader.
425 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000426 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000427 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000428 }
429
Chris Lattner7fec90e2007-04-13 05:04:18 +0000430 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000431 }
432
433 // If this is a chain of recurrences, turn it into a closed form, using the
434 // folders, then expandCodeFor the closed form. This allows the folders to
435 // simplify the expression without having to build a bunch of special code
436 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000437 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000438
Dan Gohman246b2562007-10-22 18:31:58 +0000439 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000440 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000441
Dan Gohmand19534a2007-06-15 14:38:12 +0000442 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000443}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000444
Dan Gohman890f92b2009-04-18 17:56:28 +0000445Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000446 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000447 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000448 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000449 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
450 InsertedValues.insert(I);
451 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000452}
453
Dan Gohman890f92b2009-04-18 17:56:28 +0000454Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000455 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000456 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000457 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000458 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
459 InsertedValues.insert(I);
460 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000461}
462
Dan Gohman890f92b2009-04-18 17:56:28 +0000463Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000464 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000465 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000466 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000467 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
468 InsertedValues.insert(I);
469 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000470}
471
Dan Gohman890f92b2009-04-18 17:56:28 +0000472Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000473 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000474 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000475 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000476 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
477 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000478 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000479 Instruction *ICmp =
480 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
481 InsertedValues.insert(ICmp);
482 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
483 InsertedValues.insert(Sel);
484 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000485 }
486 return LHS;
487}
488
Dan Gohman890f92b2009-04-18 17:56:28 +0000489Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000490 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000491 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000492 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000493 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
494 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000495 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000496 Instruction *ICmp =
497 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
498 InsertedValues.insert(ICmp);
499 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
500 InsertedValues.insert(Sel);
501 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000502 }
503 return LHS;
504}
505
Dan Gohman752ec7d2009-04-23 15:16:49 +0000506Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000507 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000508 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000509 if (Ty) {
510 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
511 "non-trivial casts should be done with the SCEVs directly!");
512 V = InsertNoopCastOfTo(V, Ty);
513 }
514 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000515}
516
Dan Gohman890f92b2009-04-18 17:56:28 +0000517Value *SCEVExpander::expand(const SCEV *S) {
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000518 // Check to see if we already expanded this.
519 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
520 if (I != InsertedExpressions.end())
521 return I->second;
522
523 Value *V = visit(S);
524 InsertedExpressions[S] = V;
525 return V;
526}