blob: db23a24d6068dab091703c784f701954948a0c7c [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
Nate Begeman36f891b2005-07-30 00:12:19 +000018using namespace llvm;
19
Chris Lattnerca1a4be2006-02-04 09:51:53 +000020/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21/// we can to share the casts.
22Value *SCEVExpander::InsertCastOfTo(Value *V, const Type *Ty) {
Reid Spencerd977d862006-12-12 23:36:14 +000023 // Compute the Cast opcode to use
24 Instruction::CastOps opcode = Instruction::BitCast;
25 if (Ty->isIntegral()) {
26 if (V->getType()->getTypeID() == Type::PointerTyID)
27 opcode = Instruction::PtrToInt;
28 else {
29 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
30 unsigned DstBits = Ty->getPrimitiveSizeInBits();
31 opcode = (SrcBits > DstBits ? Instruction::Trunc :
32 (SrcBits == DstBits ? Instruction::BitCast :
33 (V->getType()->isSigned() ? Instruction::SExt :
34 Instruction::ZExt)));
35 }
36 } else if (Ty->isFloatingPoint())
37 opcode = Instruction::UIToFP;
38 else if (Ty->getTypeID() == Type::PointerTyID && V->getType()->isIntegral())
39 opcode = Instruction::IntToPtr;
40
Chris Lattnerca1a4be2006-02-04 09:51:53 +000041 // FIXME: keep track of the cast instruction.
42 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000043 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000044
45 if (Argument *A = dyn_cast<Argument>(V)) {
46 // Check to see if there is already a cast!
47 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
48 UI != E; ++UI) {
49 if ((*UI)->getType() == Ty)
50 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
Reid Spencer3da59db2006-11-27 01:05:10 +000051 // If the cast isn't the first instruction of the function, move it.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000052 if (BasicBlock::iterator(CI) !=
53 A->getParent()->getEntryBlock().begin()) {
54 CI->moveBefore(A->getParent()->getEntryBlock().begin());
55 }
56 return CI;
57 }
58 }
Reid Spencerd977d862006-12-12 23:36:14 +000059 return CastInst::create(opcode, V, Ty, V->getName(),
60 A->getParent()->getEntryBlock().begin());
Chris Lattnerca1a4be2006-02-04 09:51:53 +000061 }
62
63 Instruction *I = cast<Instruction>(V);
64
65 // Check to see if there is already a cast. If there is, use it.
66 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
67 UI != E; ++UI) {
68 if ((*UI)->getType() == Ty)
69 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
70 BasicBlock::iterator It = I; ++It;
71 if (isa<InvokeInst>(I))
72 It = cast<InvokeInst>(I)->getNormalDest()->begin();
73 while (isa<PHINode>(It)) ++It;
74 if (It != BasicBlock::iterator(CI)) {
75 // Splice the cast immediately after the operand in question.
76 CI->moveBefore(It);
77 }
78 return CI;
79 }
80 }
81 BasicBlock::iterator IP = I; ++IP;
82 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
83 IP = II->getNormalDest()->begin();
84 while (isa<PHINode>(IP)) ++IP;
Reid Spencerd977d862006-12-12 23:36:14 +000085 return CastInst::create(opcode, V, Ty, V->getName(), IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000086}
87
Nate Begeman36f891b2005-07-30 00:12:19 +000088Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
89 const Type *Ty = S->getType();
90 int FirstOp = 0; // Set if we should emit a subtract.
91 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
92 if (SC->getValue()->isAllOnesValue())
93 FirstOp = 1;
94
95 int i = S->getNumOperands()-2;
96 Value *V = expandInTy(S->getOperand(i+1), Ty);
97
98 // Emit a bunch of multiply instructions
99 for (; i >= FirstOp; --i)
100 V = BinaryOperator::createMul(V, expandInTy(S->getOperand(i), Ty),
101 "tmp.", InsertPt);
102 // -1 * ... ---> 0 - ...
103 if (FirstOp == 1)
104 V = BinaryOperator::createNeg(V, "tmp.", InsertPt);
105 return V;
106}
107
108Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
109 const Type *Ty = S->getType();
110 const Loop *L = S->getLoop();
111 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
112 assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
113
114 // {X,+,F} --> X + {0,+,F}
115 if (!isa<SCEVConstant>(S->getStart()) ||
116 !cast<SCEVConstant>(S->getStart())->getValue()->isNullValue()) {
117 Value *Start = expandInTy(S->getStart(), Ty);
118 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
119 NewOps[0] = SCEVUnknown::getIntegerSCEV(0, Ty);
120 Value *Rest = expandInTy(SCEVAddRecExpr::get(NewOps, L), Ty);
121
122 // FIXME: look for an existing add to use.
123 return BinaryOperator::createAdd(Rest, Start, "tmp.", InsertPt);
124 }
125
126 // {0,+,1} --> Insert a canonical induction variable into the loop!
127 if (S->getNumOperands() == 2 &&
128 S->getOperand(1) == SCEVUnknown::getIntegerSCEV(1, Ty)) {
129 // Create and insert the PHI node for the induction variable in the
130 // specified loop.
131 BasicBlock *Header = L->getHeader();
132 PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
133 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
134
135 pred_iterator HPI = pred_begin(Header);
136 assert(HPI != pred_end(Header) && "Loop with zero preds???");
137 if (!L->contains(*HPI)) ++HPI;
138 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
139 "No backedge in loop?");
140
141 // Insert a unit add instruction right before the terminator corresponding
142 // to the back-edge.
143 Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
144 : ConstantInt::get(Ty, 1);
145 Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
146 (*HPI)->getTerminator());
147
148 pred_iterator PI = pred_begin(Header);
149 if (*PI == L->getLoopPreheader())
150 ++PI;
151 PN->addIncoming(Add, *PI);
152 return PN;
153 }
154
155 // Get the canonical induction variable I for this loop.
156 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
157
Chris Lattnerdf14a042005-10-30 06:24:33 +0000158 // If this is a simple linear addrec, emit it now as a special case.
Nate Begeman36f891b2005-07-30 00:12:19 +0000159 if (S->getNumOperands() == 2) { // {0,+,F} --> i*F
160 Value *F = expandInTy(S->getOperand(1), Ty);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000161
162 // IF the step is by one, just return the inserted IV.
163 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(F))
Reid Spencerb83eb642006-10-20 07:07:24 +0000164 if (CI->getZExtValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000165 return I;
166
167 // If the insert point is directly inside of the loop, emit the multiply at
168 // the insert point. Otherwise, L is a loop that is a parent of the insert
169 // point loop. If we can, move the multiply to the outer most loop that it
170 // is safe to be in.
171 Instruction *MulInsertPt = InsertPt;
172 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
173 if (InsertPtLoop != L && InsertPtLoop &&
174 L->contains(InsertPtLoop->getHeader())) {
175 while (InsertPtLoop != L) {
176 // If we cannot hoist the multiply out of this loop, don't.
177 if (!InsertPtLoop->isLoopInvariant(F)) break;
178
179 // Otherwise, move the insert point to the preheader of the loop.
180 MulInsertPt = InsertPtLoop->getLoopPreheader()->getTerminator();
181 InsertPtLoop = InsertPtLoop->getParentLoop();
182 }
183 }
184
185 return BinaryOperator::createMul(I, F, "tmp.", MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000186 }
187
188 // If this is a chain of recurrences, turn it into a closed form, using the
189 // folders, then expandCodeFor the closed form. This allows the folders to
190 // simplify the expression without having to build a bunch of special code
191 // into this folder.
192 SCEVHandle IH = SCEVUnknown::get(I); // Get I as a "symbolic" SCEV.
193
194 SCEVHandle V = S->evaluateAtIteration(IH);
Bill Wendlinge8156192006-12-07 01:30:32 +0000195 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000196
197 return expandInTy(V, Ty);
198}