db23a24d6068dab091703c784f701954948a0c7c
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- 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
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 using namespace llvm;
19
20 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21 /// we can to share the casts.
22 Value *SCEVExpander::InsertCastOfTo(Value *V, const Type *Ty) {
23   // 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
41   // FIXME: keep track of the cast instruction.
42   if (Constant *C = dyn_cast<Constant>(V))
43     return ConstantExpr::getCast(opcode, C, Ty);
44   
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))) {
51           // If the cast isn't the first instruction of the function, move it.
52           if (BasicBlock::iterator(CI) != 
53               A->getParent()->getEntryBlock().begin()) {
54             CI->moveBefore(A->getParent()->getEntryBlock().begin());
55           }
56           return CI;
57         }
58     }
59     return CastInst::create(opcode, V, Ty, V->getName(), 
60                             A->getParent()->getEntryBlock().begin());
61   }
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;
85   return CastInst::create(opcode, V, Ty, V->getName(), IP);
86 }
87
88 Value *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
108 Value *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
158   // If this is a simple linear addrec, emit it now as a special case.
159   if (S->getNumOperands() == 2) {   // {0,+,F} --> i*F
160     Value *F = expandInTy(S->getOperand(1), Ty);
161     
162     // IF the step is by one, just return the inserted IV.
163     if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(F))
164       if (CI->getZExtValue() == 1)
165         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);
186   }
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);
195   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
196
197   return expandInTy(V, Ty);
198 }