Home | History | Annotate | Download | only in VMCore
      1 //===-- Function.cpp - Implement the Global object classes ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Function class for the VMCore library.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/Module.h"
     15 #include "llvm/DerivedTypes.h"
     16 #include "llvm/IntrinsicInst.h"
     17 #include "llvm/LLVMContext.h"
     18 #include "llvm/CodeGen/ValueTypes.h"
     19 #include "llvm/Support/CallSite.h"
     20 #include "llvm/Support/InstIterator.h"
     21 #include "llvm/Support/LeakDetector.h"
     22 #include "llvm/Support/ManagedStatic.h"
     23 #include "llvm/Support/StringPool.h"
     24 #include "llvm/Support/RWMutex.h"
     25 #include "llvm/Support/Threading.h"
     26 #include "SymbolTableListTraitsImpl.h"
     27 #include "llvm/ADT/DenseMap.h"
     28 #include "llvm/ADT/STLExtras.h"
     29 #include "llvm/ADT/StringExtras.h"
     30 using namespace llvm;
     31 
     32 
     33 // Explicit instantiations of SymbolTableListTraits since some of the methods
     34 // are not in the public header file...
     35 template class llvm::SymbolTableListTraits<Argument, Function>;
     36 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
     37 
     38 //===----------------------------------------------------------------------===//
     39 // Argument Implementation
     40 //===----------------------------------------------------------------------===//
     41 
     42 void Argument::anchor() { }
     43 
     44 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
     45   : Value(Ty, Value::ArgumentVal) {
     46   Parent = 0;
     47 
     48   // Make sure that we get added to a function
     49   LeakDetector::addGarbageObject(this);
     50 
     51   if (Par)
     52     Par->getArgumentList().push_back(this);
     53   setName(Name);
     54 }
     55 
     56 void Argument::setParent(Function *parent) {
     57   if (getParent())
     58     LeakDetector::addGarbageObject(this);
     59   Parent = parent;
     60   if (getParent())
     61     LeakDetector::removeGarbageObject(this);
     62 }
     63 
     64 /// getArgNo - Return the index of this formal argument in its containing
     65 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
     66 unsigned Argument::getArgNo() const {
     67   const Function *F = getParent();
     68   assert(F && "Argument is not in a function");
     69 
     70   Function::const_arg_iterator AI = F->arg_begin();
     71   unsigned ArgIdx = 0;
     72   for (; &*AI != this; ++AI)
     73     ++ArgIdx;
     74 
     75   return ArgIdx;
     76 }
     77 
     78 /// hasByValAttr - Return true if this argument has the byval attribute on it
     79 /// in its containing function.
     80 bool Argument::hasByValAttr() const {
     81   if (!getType()->isPointerTy()) return false;
     82   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
     83 }
     84 
     85 unsigned Argument::getParamAlignment() const {
     86   assert(getType()->isPointerTy() && "Only pointers have alignments");
     87   return getParent()->getParamAlignment(getArgNo()+1);
     88 
     89 }
     90 
     91 /// hasNestAttr - Return true if this argument has the nest attribute on
     92 /// it in its containing function.
     93 bool Argument::hasNestAttr() const {
     94   if (!getType()->isPointerTy()) return false;
     95   return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
     96 }
     97 
     98 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
     99 /// it in its containing function.
    100 bool Argument::hasNoAliasAttr() const {
    101   if (!getType()->isPointerTy()) return false;
    102   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
    103 }
    104 
    105 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
    106 /// on it in its containing function.
    107 bool Argument::hasNoCaptureAttr() const {
    108   if (!getType()->isPointerTy()) return false;
    109   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
    110 }
    111 
    112 /// hasSRetAttr - Return true if this argument has the sret attribute on
    113 /// it in its containing function.
    114 bool Argument::hasStructRetAttr() const {
    115   if (!getType()->isPointerTy()) return false;
    116   if (this != getParent()->arg_begin())
    117     return false; // StructRet param must be first param
    118   return getParent()->paramHasAttr(1, Attribute::StructRet);
    119 }
    120 
    121 /// addAttr - Add a Attribute to an argument
    122 void Argument::addAttr(Attributes attr) {
    123   getParent()->addAttribute(getArgNo() + 1, attr);
    124 }
    125 
    126 /// removeAttr - Remove a Attribute from an argument
    127 void Argument::removeAttr(Attributes attr) {
    128   getParent()->removeAttribute(getArgNo() + 1, attr);
    129 }
    130 
    131 
    132 //===----------------------------------------------------------------------===//
    133 // Helper Methods in Function
    134 //===----------------------------------------------------------------------===//
    135 
    136 LLVMContext &Function::getContext() const {
    137   return getType()->getContext();
    138 }
    139 
    140 FunctionType *Function::getFunctionType() const {
    141   return cast<FunctionType>(getType()->getElementType());
    142 }
    143 
    144 bool Function::isVarArg() const {
    145   return getFunctionType()->isVarArg();
    146 }
    147 
    148 Type *Function::getReturnType() const {
    149   return getFunctionType()->getReturnType();
    150 }
    151 
    152 void Function::removeFromParent() {
    153   getParent()->getFunctionList().remove(this);
    154 }
    155 
    156 void Function::eraseFromParent() {
    157   getParent()->getFunctionList().erase(this);
    158 }
    159 
    160 //===----------------------------------------------------------------------===//
    161 // Function Implementation
    162 //===----------------------------------------------------------------------===//
    163 
    164 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
    165                    const Twine &name, Module *ParentModule)
    166   : GlobalValue(PointerType::getUnqual(Ty),
    167                 Value::FunctionVal, 0, 0, Linkage, name) {
    168   assert(FunctionType::isValidReturnType(getReturnType()) &&
    169          "invalid return type");
    170   SymTab = new ValueSymbolTable();
    171 
    172   // If the function has arguments, mark them as lazily built.
    173   if (Ty->getNumParams())
    174     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
    175 
    176   // Make sure that we get added to a function
    177   LeakDetector::addGarbageObject(this);
    178 
    179   if (ParentModule)
    180     ParentModule->getFunctionList().push_back(this);
    181 
    182   // Ensure intrinsics have the right parameter attributes.
    183   if (unsigned IID = getIntrinsicID())
    184     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
    185 
    186 }
    187 
    188 Function::~Function() {
    189   dropAllReferences();    // After this it is safe to delete instructions.
    190 
    191   // Delete all of the method arguments and unlink from symbol table...
    192   ArgumentList.clear();
    193   delete SymTab;
    194 
    195   // Remove the function from the on-the-side GC table.
    196   clearGC();
    197 }
    198 
    199 void Function::BuildLazyArguments() const {
    200   // Create the arguments vector, all arguments start out unnamed.
    201   FunctionType *FT = getFunctionType();
    202   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
    203     assert(!FT->getParamType(i)->isVoidTy() &&
    204            "Cannot have void typed arguments!");
    205     ArgumentList.push_back(new Argument(FT->getParamType(i)));
    206   }
    207 
    208   // Clear the lazy arguments bit.
    209   unsigned SDC = getSubclassDataFromValue();
    210   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
    211 }
    212 
    213 size_t Function::arg_size() const {
    214   return getFunctionType()->getNumParams();
    215 }
    216 bool Function::arg_empty() const {
    217   return getFunctionType()->getNumParams() == 0;
    218 }
    219 
    220 void Function::setParent(Module *parent) {
    221   if (getParent())
    222     LeakDetector::addGarbageObject(this);
    223   Parent = parent;
    224   if (getParent())
    225     LeakDetector::removeGarbageObject(this);
    226 }
    227 
    228 // dropAllReferences() - This function causes all the subinstructions to "let
    229 // go" of all references that they are maintaining.  This allows one to
    230 // 'delete' a whole class at a time, even though there may be circular
    231 // references... first all references are dropped, and all use counts go to
    232 // zero.  Then everything is deleted for real.  Note that no operations are
    233 // valid on an object that has "dropped all references", except operator
    234 // delete.
    235 //
    236 void Function::dropAllReferences() {
    237   for (iterator I = begin(), E = end(); I != E; ++I)
    238     I->dropAllReferences();
    239 
    240   // Delete all basic blocks. They are now unused, except possibly by
    241   // blockaddresses, but BasicBlock's destructor takes care of those.
    242   while (!BasicBlocks.empty())
    243     BasicBlocks.begin()->eraseFromParent();
    244 }
    245 
    246 void Function::addAttribute(unsigned i, Attributes attr) {
    247   AttrListPtr PAL = getAttributes();
    248   PAL = PAL.addAttr(i, attr);
    249   setAttributes(PAL);
    250 }
    251 
    252 void Function::removeAttribute(unsigned i, Attributes attr) {
    253   AttrListPtr PAL = getAttributes();
    254   PAL = PAL.removeAttr(i, attr);
    255   setAttributes(PAL);
    256 }
    257 
    258 // Maintain the GC name for each function in an on-the-side table. This saves
    259 // allocating an additional word in Function for programs which do not use GC
    260 // (i.e., most programs) at the cost of increased overhead for clients which do
    261 // use GC.
    262 static DenseMap<const Function*,PooledStringPtr> *GCNames;
    263 static StringPool *GCNamePool;
    264 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
    265 
    266 bool Function::hasGC() const {
    267   sys::SmartScopedReader<true> Reader(*GCLock);
    268   return GCNames && GCNames->count(this);
    269 }
    270 
    271 const char *Function::getGC() const {
    272   assert(hasGC() && "Function has no collector");
    273   sys::SmartScopedReader<true> Reader(*GCLock);
    274   return *(*GCNames)[this];
    275 }
    276 
    277 void Function::setGC(const char *Str) {
    278   sys::SmartScopedWriter<true> Writer(*GCLock);
    279   if (!GCNamePool)
    280     GCNamePool = new StringPool();
    281   if (!GCNames)
    282     GCNames = new DenseMap<const Function*,PooledStringPtr>();
    283   (*GCNames)[this] = GCNamePool->intern(Str);
    284 }
    285 
    286 void Function::clearGC() {
    287   sys::SmartScopedWriter<true> Writer(*GCLock);
    288   if (GCNames) {
    289     GCNames->erase(this);
    290     if (GCNames->empty()) {
    291       delete GCNames;
    292       GCNames = 0;
    293       if (GCNamePool->empty()) {
    294         delete GCNamePool;
    295         GCNamePool = 0;
    296       }
    297     }
    298   }
    299 }
    300 
    301 /// copyAttributesFrom - copy all additional attributes (those not needed to
    302 /// create a Function) from the Function Src to this one.
    303 void Function::copyAttributesFrom(const GlobalValue *Src) {
    304   assert(isa<Function>(Src) && "Expected a Function!");
    305   GlobalValue::copyAttributesFrom(Src);
    306   const Function *SrcF = cast<Function>(Src);
    307   setCallingConv(SrcF->getCallingConv());
    308   setAttributes(SrcF->getAttributes());
    309   if (SrcF->hasGC())
    310     setGC(SrcF->getGC());
    311   else
    312     clearGC();
    313 }
    314 
    315 /// getIntrinsicID - This method returns the ID number of the specified
    316 /// function, or Intrinsic::not_intrinsic if the function is not an
    317 /// intrinsic, or if the pointer is null.  This value is always defined to be
    318 /// zero to allow easy checking for whether a function is intrinsic or not.  The
    319 /// particular intrinsic functions which correspond to this value are defined in
    320 /// llvm/Intrinsics.h.
    321 ///
    322 unsigned Function::getIntrinsicID() const {
    323   const ValueName *ValName = this->getValueName();
    324   if (!ValName)
    325     return 0;
    326   unsigned Len = ValName->getKeyLength();
    327   const char *Name = ValName->getKeyData();
    328 
    329   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
    330       || Name[2] != 'v' || Name[3] != 'm')
    331     return 0;  // All intrinsics start with 'llvm.'
    332 
    333 #define GET_FUNCTION_RECOGNIZER
    334 #include "llvm/Intrinsics.gen"
    335 #undef GET_FUNCTION_RECOGNIZER
    336   return 0;
    337 }
    338 
    339 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
    340   assert(id < num_intrinsics && "Invalid intrinsic ID!");
    341   static const char * const Table[] = {
    342     "not_intrinsic",
    343 #define GET_INTRINSIC_NAME_TABLE
    344 #include "llvm/Intrinsics.gen"
    345 #undef GET_INTRINSIC_NAME_TABLE
    346   };
    347   if (Tys.empty())
    348     return Table[id];
    349   std::string Result(Table[id]);
    350   for (unsigned i = 0; i < Tys.size(); ++i) {
    351     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
    352       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
    353                 EVT::getEVT(PTyp->getElementType()).getEVTString();
    354     }
    355     else if (Tys[i])
    356       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
    357   }
    358   return Result;
    359 }
    360 
    361 FunctionType *Intrinsic::getType(LLVMContext &Context,
    362                                        ID id, ArrayRef<Type*> Tys) {
    363   Type *ResultTy = NULL;
    364   SmallVector<Type*, 8> ArgTys;
    365   bool IsVarArg = false;
    366 
    367 #define GET_INTRINSIC_GENERATOR
    368 #include "llvm/Intrinsics.gen"
    369 #undef GET_INTRINSIC_GENERATOR
    370 
    371   return FunctionType::get(ResultTy, ArgTys, IsVarArg);
    372 }
    373 
    374 bool Intrinsic::isOverloaded(ID id) {
    375 #define GET_INTRINSIC_OVERLOAD_TABLE
    376 #include "llvm/Intrinsics.gen"
    377 #undef GET_INTRINSIC_OVERLOAD_TABLE
    378 }
    379 
    380 /// This defines the "Intrinsic::getAttributes(ID id)" method.
    381 #define GET_INTRINSIC_ATTRIBUTES
    382 #include "llvm/Intrinsics.gen"
    383 #undef GET_INTRINSIC_ATTRIBUTES
    384 
    385 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
    386   // There can never be multiple globals with the same name of different types,
    387   // because intrinsics must be a specific type.
    388   return
    389     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
    390                                           getType(M->getContext(), id, Tys)));
    391 }
    392 
    393 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
    394 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
    395 #include "llvm/Intrinsics.gen"
    396 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
    397 
    398 /// hasAddressTaken - returns true if there are any uses of this function
    399 /// other than direct calls or invokes to it.
    400 bool Function::hasAddressTaken(const User* *PutOffender) const {
    401   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
    402     const User *U = *I;
    403     // FIXME: Check for blockaddress, which does not take the address.
    404     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
    405       return PutOffender ? (*PutOffender = U, true) : true;
    406     ImmutableCallSite CS(cast<Instruction>(U));
    407     if (!CS.isCallee(I))
    408       return PutOffender ? (*PutOffender = U, true) : true;
    409   }
    410   return false;
    411 }
    412 
    413 bool Function::isDefTriviallyDead() const {
    414   // Check the linkage
    415   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
    416       !hasAvailableExternallyLinkage())
    417     return false;
    418 
    419   // Check if the function is used by anything other than a blockaddress.
    420   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
    421     if (!isa<BlockAddress>(*I))
    422       return false;
    423 
    424   return true;
    425 }
    426 
    427 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
    428 /// setjmp or other function that gcc recognizes as "returning twice".
    429 bool Function::callsFunctionThatReturnsTwice() const {
    430   for (const_inst_iterator
    431          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
    432     const CallInst* callInst = dyn_cast<CallInst>(&*I);
    433     if (!callInst)
    434       continue;
    435     if (callInst->canReturnTwice())
    436       return true;
    437   }
    438 
    439   return false;
    440 }
    441 
    442 // vim: sw=2 ai
    443