blob: fc66ddb6f485742a7515d8c2e4e5b566c1f8cd90 [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) {
Dan Gohman0d56b062009-05-22 07:14:20 +0000171 // For a Constant, check for a multiple of the pointer type's
172 // scale size.
Dan Gohman5be18e82009-05-19 02:15:55 +0000173 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i]))
174 if (!C->getValue()->getValue().srem(ElSize)) {
175 ConstantInt *CI =
176 ConstantInt::get(C->getValue()->getValue().sdiv(ElSize));
177 SCEVHandle Div = SE.getConstant(CI);
178 ScaledOps.push_back(Div);
179 continue;
180 }
Dan Gohman0d56b062009-05-22 07:14:20 +0000181 // In a Mul, check if there is a constant operand which is a multiple
182 // of the pointer type's scale size.
Dan Gohman5be18e82009-05-19 02:15:55 +0000183 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i]))
184 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
Dan Gohman0d56b062009-05-22 07:14:20 +0000185 if (!C->getValue()->getValue().srem(ElSize)) {
186 std::vector<SCEVHandle> NewMulOps(M->getOperands());
187 NewMulOps[0] =
188 SE.getConstant(C->getValue()->getValue().sdiv(ElSize));
189 ScaledOps.push_back(SE.getMulExpr(NewMulOps));
Dan Gohman5be18e82009-05-19 02:15:55 +0000190 continue;
191 }
Dan Gohman0d56b062009-05-22 07:14:20 +0000192 // In an Unknown, check if the underlying value is a Mul by a constant
193 // which is equal to the pointer type's scale size.
Dan Gohman5be18e82009-05-19 02:15:55 +0000194 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i]))
195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getValue()))
196 if (BO->getOpcode() == Instruction::Mul)
197 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
198 if (CI->getValue() == ElSize) {
199 ScaledOps.push_back(SE.getUnknown(BO->getOperand(0)));
200 continue;
201 }
Dan Gohman0d56b062009-05-22 07:14:20 +0000202 // If the pointer type's scale size is 1, no scaling is necessary
203 // and any value can be used.
Dan Gohman5be18e82009-05-19 02:15:55 +0000204 if (ElSize == 1) {
205 ScaledOps.push_back(Ops[i]);
206 continue;
207 }
208 }
209 NewOps.push_back(Ops[i]);
210 }
211 Ops = NewOps;
212 AnyNonZeroIndices |= !ScaledOps.empty();
213 Value *Scaled = ScaledOps.empty() ?
214 Constant::getNullValue(Ty) :
215 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
216 GepIndices.push_back(Scaled);
217
218 // Collect struct field index operands.
219 if (!Ops.empty())
220 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
221 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
222 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
223 const StructLayout &SL = *SE.TD->getStructLayout(STy);
224 uint64_t FullOffset = C->getValue()->getZExtValue();
225 if (FullOffset < SL.getSizeInBytes()) {
226 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
227 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
228 ElTy = STy->getTypeAtIndex(ElIdx);
229 Ops[0] =
230 SE.getConstant(ConstantInt::get(Ty,
231 FullOffset -
232 SL.getElementOffset(ElIdx)));
233 AnyNonZeroIndices = true;
234 continue;
235 }
236 }
237 break;
238 }
239
240 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
241 ElTy = ATy->getElementType();
242 continue;
243 }
244 break;
245 }
246
247 // If none of the operands were convertable to proper GEP indices, cast
248 // the base to i8* and do an ugly getelementptr with that. It's still
249 // better than ptrtoint+arithmetic+inttoptr at least.
250 if (!AnyNonZeroIndices) {
251 V = InsertNoopCastOfTo(V,
252 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
253 Value *Idx = expand(SE.getAddExpr(Ops));
254 Idx = InsertNoopCastOfTo(Idx, Ty);
255
256 // Fold a GEP with constant operands.
257 if (Constant *CLHS = dyn_cast<Constant>(V))
258 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000259 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000260
261 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
262 unsigned ScanLimit = 6;
263 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
264 if (InsertPt != BlockBegin) {
265 // Scanning starts from the last instruction before InsertPt.
266 BasicBlock::iterator IP = InsertPt;
267 --IP;
268 for (; ScanLimit; --IP, --ScanLimit) {
269 if (IP->getOpcode() == Instruction::GetElementPtr &&
270 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
271 return IP;
272 if (IP == BlockBegin) break;
273 }
274 }
275
276 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
277 InsertedValues.insert(GEP);
278 return GEP;
279 }
280
281 // Insert a pretty getelementptr.
282 Value *GEP = GetElementPtrInst::Create(V,
283 GepIndices.begin(),
284 GepIndices.end(),
285 "scevgep", InsertPt);
286 Ops.push_back(SE.getUnknown(GEP));
287 InsertedValues.insert(GEP);
288 return expand(SE.getAddExpr(Ops));
289}
290
Dan Gohman890f92b2009-04-18 17:56:28 +0000291Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000292 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000293 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000294
295 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. This helps
296 // BasicAliasAnalysis analyze the result. However, it suffers from the
297 // underlying bug described in PR2831. Addition in LLVM currently always
298 // has two's complement wrapping guaranteed. However, the semantics for
299 // getelementptr overflow are ambiguous. In the common case though, this
300 // expansion gets used when a GEP in the original code has been converted
301 // into integer arithmetic, in which case the resulting code will be no
302 // more undefined than it was originally.
303 if (SE.TD)
304 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
305 return expandAddToGEP(S, PTy, Ty, V);
306
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000307 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000308
309 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000310 for (int i = S->getNumOperands()-2; i >= 0; --i) {
311 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000312 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000313 V = InsertBinop(Instruction::Add, V, W, InsertPt);
314 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000315 return V;
316}
Dan Gohman5be18e82009-05-19 02:15:55 +0000317
Dan Gohman890f92b2009-04-18 17:56:28 +0000318Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000319 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000320 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000321 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000322 if (SC->getValue()->isAllOnesValue())
323 FirstOp = 1;
324
325 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000326 Value *V = expand(S->getOperand(i+1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000327 V = InsertNoopCastOfTo(V, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000328
329 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000330 for (; i >= FirstOp; --i) {
331 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000332 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000333 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
334 }
335
Nate Begeman36f891b2005-07-30 00:12:19 +0000336 // -1 * ... ---> 0 - ...
337 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000338 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000339 return V;
340}
341
Dan Gohman890f92b2009-04-18 17:56:28 +0000342Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000343 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000344
Nick Lewycky6177fd42008-07-08 05:05:37 +0000345 Value *LHS = expand(S->getLHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000346 LHS = InsertNoopCastOfTo(LHS, Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000347 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000348 const APInt &RHS = SC->getValue()->getValue();
349 if (RHS.isPowerOf2())
350 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000351 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000352 InsertPt);
353 }
354
355 Value *RHS = expand(S->getRHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000356 RHS = InsertNoopCastOfTo(RHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000357 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
358}
359
Dan Gohman890f92b2009-04-18 17:56:28 +0000360Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000361 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000362 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000363
364 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000365 if (!S->getStart()->isZero()) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000366 std::vector<SCEVHandle> NewOps(S->getOperands());
Dan Gohman246b2562007-10-22 18:31:58 +0000367 NewOps[0] = SE.getIntegerSCEV(0, Ty);
368 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Dan Gohman5be18e82009-05-19 02:15:55 +0000369 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(Rest)));
Nate Begeman36f891b2005-07-30 00:12:19 +0000370 }
371
372 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000373 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000374 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000375 // Create and insert the PHI node for the induction variable in the
376 // specified loop.
377 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000378 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000379 InsertedValues.insert(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000380 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
381
382 pred_iterator HPI = pred_begin(Header);
383 assert(HPI != pred_end(Header) && "Loop with zero preds???");
384 if (!L->contains(*HPI)) ++HPI;
385 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
386 "No backedge in loop?");
387
388 // Insert a unit add instruction right before the terminator corresponding
389 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000390 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000391 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000392 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000393 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000394
395 pred_iterator PI = pred_begin(Header);
396 if (*PI == L->getLoopPreheader())
397 ++PI;
398 PN->addIncoming(Add, *PI);
399 return PN;
400 }
401
402 // Get the canonical induction variable I for this loop.
403 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
404
Chris Lattnerdf14a042005-10-30 06:24:33 +0000405 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000406 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000407 Value *F = expand(S->getOperand(1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000408 F = InsertNoopCastOfTo(F, Ty);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000409
410 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000411 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000412 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000413 return I;
414
415 // If the insert point is directly inside of the loop, emit the multiply at
416 // the insert point. Otherwise, L is a loop that is a parent of the insert
417 // point loop. If we can, move the multiply to the outer most loop that it
418 // is safe to be in.
Dan Gohman6cdc7272009-04-22 16:05:50 +0000419 BasicBlock::iterator MulInsertPt = getInsertionPoint();
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
Chris Lattnerdf14a042005-10-30 06:24:33 +0000421 if (InsertPtLoop != L && InsertPtLoop &&
422 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000423 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000424 // If we cannot hoist the multiply out of this loop, don't.
425 if (!InsertPtLoop->isLoopInvariant(F)) break;
426
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000427 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
428
429 // If this loop hasn't got a preheader, we aren't able to hoist the
430 // multiply.
431 if (!InsertPtLoopPH)
432 break;
433
434 // Otherwise, move the insert point to the preheader.
435 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000436 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000437 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000438 }
439
Chris Lattner7fec90e2007-04-13 05:04:18 +0000440 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000441 }
442
443 // If this is a chain of recurrences, turn it into a closed form, using the
444 // folders, then expandCodeFor the closed form. This allows the folders to
445 // simplify the expression without having to build a bunch of special code
446 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000447 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000448
Dan Gohman246b2562007-10-22 18:31:58 +0000449 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000450 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000451
Dan Gohmand19534a2007-06-15 14:38:12 +0000452 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000453}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000454
Dan Gohman890f92b2009-04-18 17:56:28 +0000455Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000456 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000457 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000458 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000459 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
460 InsertedValues.insert(I);
461 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000462}
463
Dan Gohman890f92b2009-04-18 17:56:28 +0000464Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000465 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000466 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000467 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000468 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
469 InsertedValues.insert(I);
470 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000471}
472
Dan Gohman890f92b2009-04-18 17:56:28 +0000473Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000474 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000475 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000476 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000477 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
478 InsertedValues.insert(I);
479 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000480}
481
Dan Gohman890f92b2009-04-18 17:56:28 +0000482Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000483 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000484 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000485 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000486 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
487 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000488 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000489 Instruction *ICmp =
490 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
491 InsertedValues.insert(ICmp);
492 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
493 InsertedValues.insert(Sel);
494 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000495 }
496 return LHS;
497}
498
Dan Gohman890f92b2009-04-18 17:56:28 +0000499Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000500 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000501 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000502 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000503 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
504 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000505 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000506 Instruction *ICmp =
507 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
508 InsertedValues.insert(ICmp);
509 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
510 InsertedValues.insert(Sel);
511 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000512 }
513 return LHS;
514}
515
Dan Gohman752ec7d2009-04-23 15:16:49 +0000516Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000517 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000518 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000519 if (Ty) {
520 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
521 "non-trivial casts should be done with the SCEVs directly!");
522 V = InsertNoopCastOfTo(V, Ty);
523 }
524 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000525}
526
Dan Gohman890f92b2009-04-18 17:56:28 +0000527Value *SCEVExpander::expand(const SCEV *S) {
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000528 // Check to see if we already expanded this.
Torok Edwinb679de22009-05-24 14:23:16 +0000529 std::map<SCEVHandle, AssertingVH<Value> >::iterator I = InsertedExpressions.find(S);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000530 if (I != InsertedExpressions.end())
531 return I->second;
532
533 Value *V = visit(S);
534 InsertedExpressions[S] = V;
535 return V;
536}