LLVM API Documentation

ScalarEvolutionExpander.cpp

Go to the documentation of this file.
00001 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the scalar evolution expander,
00011 // which is used to generate the code corresponding to a given scalar evolution
00012 // expression.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00017 #include "llvm/Analysis/LoopInfo.h"
00018 using namespace llvm;
00019 
00020 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
00021 /// we can to share the casts.
00022 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V, 
00023                                     const Type *Ty) {
00024   // FIXME: keep track of the cast instruction.
00025   if (Constant *C = dyn_cast<Constant>(V))
00026     return ConstantExpr::getCast(opcode, C, Ty);
00027   
00028   if (Argument *A = dyn_cast<Argument>(V)) {
00029     // Check to see if there is already a cast!
00030     for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
00031          UI != E; ++UI) {
00032       if ((*UI)->getType() == Ty)
00033         if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
00034           if (CI->getOpcode() == opcode) {
00035             // If the cast isn't the first instruction of the function, move it.
00036             if (BasicBlock::iterator(CI) != 
00037                 A->getParent()->getEntryBlock().begin()) {
00038               CI->moveBefore(A->getParent()->getEntryBlock().begin());
00039             }
00040             return CI;
00041           }
00042     }
00043     return CastInst::Create(opcode, V, Ty, V->getName(), 
00044                             A->getParent()->getEntryBlock().begin());
00045   }
00046 
00047   Instruction *I = cast<Instruction>(V);
00048 
00049   // Check to see if there is already a cast.  If there is, use it.
00050   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
00051        UI != E; ++UI) {
00052     if ((*UI)->getType() == Ty)
00053       if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
00054         if (CI->getOpcode() == opcode) {
00055           BasicBlock::iterator It = I; ++It;
00056           if (isa<InvokeInst>(I))
00057             It = cast<InvokeInst>(I)->getNormalDest()->begin();
00058           while (isa<PHINode>(It)) ++It;
00059           if (It != BasicBlock::iterator(CI)) {
00060             // Splice the cast immediately after the operand in question.
00061             CI->moveBefore(It);
00062           }
00063           return CI;
00064         }
00065   }
00066   BasicBlock::iterator IP = I; ++IP;
00067   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
00068     IP = II->getNormalDest()->begin();
00069   while (isa<PHINode>(IP)) ++IP;
00070   return CastInst::Create(opcode, V, Ty, V->getName(), IP);
00071 }
00072 
00073 /// InsertBinop - Insert the specified binary operator, doing a small amount
00074 /// of work to avoid inserting an obviously redundant operation.
00075 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
00076                                  Value *RHS, Instruction *InsertPt) {
00077   // Fold a binop with constant operands.
00078   if (Constant *CLHS = dyn_cast<Constant>(LHS))
00079     if (Constant *CRHS = dyn_cast<Constant>(RHS))
00080       return ConstantExpr::get(Opcode, CLHS, CRHS);
00081 
00082   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
00083   unsigned ScanLimit = 6;
00084   BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
00085   if (InsertPt != BlockBegin) {
00086     // Scanning starts from the last instruction before InsertPt.
00087     BasicBlock::iterator IP = InsertPt;
00088     --IP;
00089     for (; ScanLimit; --IP, --ScanLimit) {
00090       if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
00091         if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
00092             BinOp->getOperand(1) == RHS)
00093           return BinOp;
00094       if (IP == BlockBegin) break;
00095     }
00096   }
00097   
00098   // If we haven't found this binop, insert it.
00099   return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
00100 }
00101 
00102 Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
00103   Value *V = expand(S->getOperand(S->getNumOperands()-1));
00104 
00105   // Emit a bunch of add instructions
00106   for (int i = S->getNumOperands()-2; i >= 0; --i)
00107     V = InsertBinop(Instruction::Add, V, expand(S->getOperand(i)),
00108                     InsertPt);
00109   return V;
00110 }
00111     
00112 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
00113   int FirstOp = 0;  // Set if we should emit a subtract.
00114   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
00115     if (SC->getValue()->isAllOnesValue())
00116       FirstOp = 1;
00117 
00118   int i = S->getNumOperands()-2;
00119   Value *V = expand(S->getOperand(i+1));
00120 
00121   // Emit a bunch of multiply instructions
00122   for (; i >= FirstOp; --i)
00123     V = InsertBinop(Instruction::Mul, V, expand(S->getOperand(i)),
00124                     InsertPt);
00125   // -1 * ...  --->  0 - ...
00126   if (FirstOp == 1)
00127     V = InsertBinop(Instruction::Sub, Constant::getNullValue(V->getType()), V,
00128                     InsertPt);
00129   return V;
00130 }
00131 
00132 Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
00133   Value *LHS = expand(S->getLHS());
00134   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
00135     const APInt &RHS = SC->getValue()->getValue();
00136     if (RHS.isPowerOf2())
00137       return InsertBinop(Instruction::LShr, LHS,
00138                          ConstantInt::get(S->getType(), RHS.logBase2()),
00139                          InsertPt);
00140   }
00141 
00142   Value *RHS = expand(S->getRHS());
00143   return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
00144 }
00145 
00146 Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
00147   const Type *Ty = S->getType();
00148   const Loop *L = S->getLoop();
00149   // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
00150   assert(Ty->isInteger() && "Cannot expand fp recurrences yet!");
00151 
00152   // {X,+,F} --> X + {0,+,F}
00153   if (!S->getStart()->isZero()) {
00154     Value *Start = expand(S->getStart());
00155     std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
00156     NewOps[0] = SE.getIntegerSCEV(0, Ty);
00157     Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
00158 
00159     // FIXME: look for an existing add to use.
00160     return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
00161   }
00162 
00163   // {0,+,1} --> Insert a canonical induction variable into the loop!
00164   if (S->isAffine() &&
00165       S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
00166     // Create and insert the PHI node for the induction variable in the
00167     // specified loop.
00168     BasicBlock *Header = L->getHeader();
00169     PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
00170     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
00171 
00172     pred_iterator HPI = pred_begin(Header);
00173     assert(HPI != pred_end(Header) && "Loop with zero preds???");
00174     if (!L->contains(*HPI)) ++HPI;
00175     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
00176            "No backedge in loop?");
00177 
00178     // Insert a unit add instruction right before the terminator corresponding
00179     // to the back-edge.
00180     Constant *One = ConstantInt::get(Ty, 1);
00181     Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
00182                                                  (*HPI)->getTerminator());
00183 
00184     pred_iterator PI = pred_begin(Header);
00185     if (*PI == L->getLoopPreheader())
00186       ++PI;
00187     PN->addIncoming(Add, *PI);
00188     return PN;
00189   }
00190 
00191   // Get the canonical induction variable I for this loop.
00192   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
00193 
00194   // If this is a simple linear addrec, emit it now as a special case.
00195   if (S->isAffine()) {   // {0,+,F} --> i*F
00196     Value *F = expand(S->getOperand(1));
00197     
00198     // IF the step is by one, just return the inserted IV.
00199     if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
00200       if (CI->getValue() == 1)
00201         return I;
00202     
00203     // If the insert point is directly inside of the loop, emit the multiply at
00204     // the insert point.  Otherwise, L is a loop that is a parent of the insert
00205     // point loop.  If we can, move the multiply to the outer most loop that it
00206     // is safe to be in.
00207     Instruction *MulInsertPt = InsertPt;
00208     Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
00209     if (InsertPtLoop != L && InsertPtLoop &&
00210         L->contains(InsertPtLoop->getHeader())) {
00211       do {
00212         // If we cannot hoist the multiply out of this loop, don't.
00213         if (!InsertPtLoop->isLoopInvariant(F)) break;
00214 
00215         BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
00216 
00217         // If this loop hasn't got a preheader, we aren't able to hoist the
00218         // multiply.
00219         if (!InsertPtLoopPH)
00220           break;
00221 
00222         // Otherwise, move the insert point to the preheader.
00223         MulInsertPt = InsertPtLoopPH->getTerminator();
00224         InsertPtLoop = InsertPtLoop->getParentLoop();
00225       } while (InsertPtLoop != L);
00226     }
00227     
00228     return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
00229   }
00230 
00231   // If this is a chain of recurrences, turn it into a closed form, using the
00232   // folders, then expandCodeFor the closed form.  This allows the folders to
00233   // simplify the expression without having to build a bunch of special code
00234   // into this folder.
00235   SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
00236 
00237   SCEVHandle V = S->evaluateAtIteration(IH, SE);
00238   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
00239 
00240   return expand(V);
00241 }
00242 
00243 Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
00244   Value *V = expand(S->getOperand());
00245   return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
00246 }
00247 
00248 Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
00249   Value *V = expand(S->getOperand());
00250   return CastInst::CreateZExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
00251 }
00252 
00253 Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
00254   Value *V = expand(S->getOperand());
00255   return CastInst::CreateSExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
00256 }
00257 
00258 Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
00259   Value *LHS = expand(S->getOperand(0));
00260   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
00261     Value *RHS = expand(S->getOperand(i));
00262     Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
00263     LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
00264   }
00265   return LHS;
00266 }
00267 
00268 Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
00269   Value *LHS = expand(S->getOperand(0));
00270   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
00271     Value *RHS = expand(S->getOperand(i));
00272     Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
00273     LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
00274   }
00275   return LHS;
00276 }
00277 
00278 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, Instruction *IP) {
00279   // Expand the code for this SCEV.
00280   this->InsertPt = IP;
00281   return expand(SH);
00282 }
00283 
00284 Value *SCEVExpander::expand(SCEV *S) {
00285   // Check to see if we already expanded this.
00286   std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
00287   if (I != InsertedExpressions.end())
00288     return I->second;
00289   
00290   Value *V = visit(S);
00291   InsertedExpressions[S] = V;
00292   return V;
00293 }