LLVM API Documentation

IPConstantPropagation.cpp

Go to the documentation of this file.
00001 //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
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 pass implements an _extremely_ simple interprocedural constant
00011 // propagation pass.  It could certainly be improved in many different ways,
00012 // like using a worklist.  This pass makes arguments dead, but does not remove
00013 // them.  The existing dead argument elimination pass should be run after this
00014 // to clean up the mess.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #define DEBUG_TYPE "ipconstprop"
00019 #include "llvm/Transforms/IPO.h"
00020 #include "llvm/Constants.h"
00021 #include "llvm/Instructions.h"
00022 #include "llvm/Module.h"
00023 #include "llvm/Pass.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/Support/CallSite.h"
00026 #include "llvm/Support/Compiler.h"
00027 #include "llvm/ADT/Statistic.h"
00028 #include "llvm/ADT/SmallVector.h"
00029 using namespace llvm;
00030 
00031 STATISTIC(NumArgumentsProped, "Number of args turned into constants");
00032 STATISTIC(NumReturnValProped, "Number of return values turned into constants");
00033 
00034 namespace {
00035   /// IPCP - The interprocedural constant propagation pass
00036   ///
00037   struct VISIBILITY_HIDDEN IPCP : public ModulePass {
00038     static char ID; // Pass identification, replacement for typeid
00039     IPCP() : ModulePass(&ID) {}
00040 
00041     bool runOnModule(Module &M);
00042   private:
00043     bool PropagateConstantsIntoArguments(Function &F);
00044     bool PropagateConstantReturn(Function &F);
00045   };
00046 }
00047 
00048 char IPCP::ID = 0;
00049 static RegisterPass<IPCP>
00050 X("ipconstprop", "Interprocedural constant propagation");
00051 
00052 ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
00053 
00054 bool IPCP::runOnModule(Module &M) {
00055   bool Changed = false;
00056   bool LocalChange = true;
00057 
00058   // FIXME: instead of using smart algorithms, we just iterate until we stop
00059   // making changes.
00060   while (LocalChange) {
00061     LocalChange = false;
00062     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00063       if (!I->isDeclaration()) {
00064         // Delete any klingons.
00065         I->removeDeadConstantUsers();
00066         if (I->hasLocalLinkage())
00067           LocalChange |= PropagateConstantsIntoArguments(*I);
00068         Changed |= PropagateConstantReturn(*I);
00069       }
00070     Changed |= LocalChange;
00071   }
00072   return Changed;
00073 }
00074 
00075 /// PropagateConstantsIntoArguments - Look at all uses of the specified
00076 /// function.  If all uses are direct call sites, and all pass a particular
00077 /// constant in for an argument, propagate that constant in as the argument.
00078 ///
00079 bool IPCP::PropagateConstantsIntoArguments(Function &F) {
00080   if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
00081 
00082   // For each argument, keep track of its constant value and whether it is a
00083   // constant or not.  The bool is driven to true when found to be non-constant.
00084   SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
00085   ArgumentConstants.resize(F.arg_size());
00086 
00087   unsigned NumNonconstant = 0;
00088   for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
00089     // Used by a non-instruction, or not the callee of a function, do not
00090     // transform.
00091     if (!isa<CallInst>(*UI) && !isa<InvokeInst>(*UI))
00092       return false;
00093     
00094     CallSite CS = CallSite::get(cast<Instruction>(*UI));
00095     if (!CS.isCallee(UI))
00096       return false;
00097 
00098     // Check out all of the potentially constant arguments.  Note that we don't
00099     // inspect varargs here.
00100     CallSite::arg_iterator AI = CS.arg_begin();
00101     Function::arg_iterator Arg = F.arg_begin();
00102     for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
00103          ++i, ++AI, ++Arg) {
00104       
00105       // If this argument is known non-constant, ignore it.
00106       if (ArgumentConstants[i].second)
00107         continue;
00108       
00109       Constant *C = dyn_cast<Constant>(*AI);
00110       if (C && ArgumentConstants[i].first == 0) {
00111         ArgumentConstants[i].first = C;   // First constant seen.
00112       } else if (C && ArgumentConstants[i].first == C) {
00113         // Still the constant value we think it is.
00114       } else if (*AI == &*Arg) {
00115         // Ignore recursive calls passing argument down.
00116       } else {
00117         // Argument became non-constant.  If all arguments are non-constant now,
00118         // give up on this function.
00119         if (++NumNonconstant == ArgumentConstants.size())
00120           return false;
00121         ArgumentConstants[i].second = true;
00122       }
00123     }
00124   }
00125 
00126   // If we got to this point, there is a constant argument!
00127   assert(NumNonconstant != ArgumentConstants.size());
00128   bool MadeChange = false;
00129   Function::arg_iterator AI = F.arg_begin();
00130   for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
00131     // Do we have a constant argument?
00132     if (ArgumentConstants[i].second || AI->use_empty())
00133       continue;
00134   
00135     Value *V = ArgumentConstants[i].first;
00136     if (V == 0) V = UndefValue::get(AI->getType());
00137     AI->replaceAllUsesWith(V);
00138     ++NumArgumentsProped;
00139     MadeChange = true;
00140   }
00141   return MadeChange;
00142 }
00143 
00144 
00145 // Check to see if this function returns one or more constants. If so, replace
00146 // all callers that use those return values with the constant value. This will
00147 // leave in the actual return values and instructions, but deadargelim will
00148 // clean that up.
00149 //
00150 // Additionally if a function always returns one of its arguments directly,
00151 // callers will be updated to use the value they pass in directly instead of
00152 // using the return value.
00153 bool IPCP::PropagateConstantReturn(Function &F) {
00154   if (F.getReturnType() == Type::VoidTy)
00155     return false; // No return value.
00156 
00157   // If this function could be overridden later in the link stage, we can't
00158   // propagate information about its results into callers.
00159   if (F.mayBeOverridden())
00160     return false;
00161   
00162   // Check to see if this function returns a constant.
00163   SmallVector<Value *,4> RetVals;
00164   const StructType *STy = dyn_cast<StructType>(F.getReturnType());
00165   if (STy)
00166     for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i) 
00167       RetVals.push_back(UndefValue::get(STy->getElementType(i)));
00168   else
00169     RetVals.push_back(UndefValue::get(F.getReturnType()));
00170 
00171   unsigned NumNonConstant = 0;
00172   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00173     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00174       for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
00175         // Already found conflicting return values?
00176         Value *RV = RetVals[i];
00177         if (!RV)
00178           continue;
00179 
00180         // Find the returned value
00181         Value *V;
00182         if (!STy)
00183           V = RI->getOperand(i);
00184         else
00185           V = FindInsertedValue(RI->getOperand(0), i);
00186 
00187         if (V) {
00188           // Ignore undefs, we can change them into anything
00189           if (isa<UndefValue>(V))
00190             continue;
00191           
00192           // Try to see if all the rets return the same constant or argument.
00193           if (isa<Constant>(V) || isa<Argument>(V)) {
00194             if (isa<UndefValue>(RV)) {
00195               // No value found yet? Try the current one.
00196               RetVals[i] = V;
00197               continue;
00198             }
00199             // Returning the same value? Good.
00200             if (RV == V)
00201               continue;
00202           }
00203         }
00204         // Different or no known return value? Don't propagate this return
00205         // value.
00206         RetVals[i] = 0;
00207         // All values non constant? Stop looking.
00208         if (++NumNonConstant == RetVals.size())
00209           return false;
00210       }
00211     }
00212 
00213   // If we got here, the function returns at least one constant value.  Loop
00214   // over all users, replacing any uses of the return value with the returned
00215   // constant.
00216   bool MadeChange = false;
00217   for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
00218     CallSite CS = CallSite::get(*UI);
00219     Instruction* Call = CS.getInstruction();
00220 
00221     // Not a call instruction or a call instruction that's not calling F
00222     // directly?
00223     if (!Call || !CS.isCallee(UI))
00224       continue;
00225     
00226     // Call result not used?
00227     if (Call->use_empty())
00228       continue;
00229 
00230     MadeChange = true;
00231 
00232     if (STy == 0) {
00233       Value* New = RetVals[0];
00234       if (Argument *A = dyn_cast<Argument>(New))
00235         // Was an argument returned? Then find the corresponding argument in
00236         // the call instruction and use that.
00237         New = CS.getArgument(A->getArgNo());
00238       Call->replaceAllUsesWith(New);
00239       continue;
00240     }
00241    
00242     for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
00243          I != E;) {
00244       Instruction *Ins = dyn_cast<Instruction>(*I);
00245 
00246       // Increment now, so we can remove the use
00247       ++I;
00248 
00249       // Not an instruction? Ignore
00250       if (!Ins)
00251         continue;
00252 
00253       // Find the index of the retval to replace with
00254       int index = -1;
00255       if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
00256         if (EV->hasIndices())
00257           index = *EV->idx_begin();
00258 
00259       // If this use uses a specific return value, and we have a replacement,
00260       // replace it.
00261       if (index != -1) {
00262         Value *New = RetVals[index];
00263         if (New) {
00264           if (Argument *A = dyn_cast<Argument>(New))
00265             // Was an argument returned? Then find the corresponding argument in
00266             // the call instruction and use that.
00267             New = CS.getArgument(A->getArgNo());
00268           Ins->replaceAllUsesWith(New);
00269           Ins->eraseFromParent();
00270         }
00271       }
00272     }
00273   }
00274 
00275   if (MadeChange) ++NumReturnValProped;
00276   return MadeChange;
00277 }