clang API Documentation

CodeGenModule.h
Go to the documentation of this file.
00001 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- 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 is the internal per-translation-unit state used for llvm translation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef CLANG_CODEGEN_CODEGENMODULE_H
00015 #define CLANG_CODEGEN_CODEGENMODULE_H
00016 
00017 #include "clang/Basic/ABI.h"
00018 #include "clang/Basic/LangOptions.h"
00019 #include "clang/AST/Attr.h"
00020 #include "clang/AST/DeclCXX.h"
00021 #include "clang/AST/DeclObjC.h"
00022 #include "clang/AST/GlobalDecl.h"
00023 #include "clang/AST/Mangle.h"
00024 #include "CGVTables.h"
00025 #include "CodeGenTypes.h"
00026 #include "llvm/Module.h"
00027 #include "llvm/ADT/DenseMap.h"
00028 #include "llvm/ADT/StringMap.h"
00029 #include "llvm/ADT/SmallPtrSet.h"
00030 #include "llvm/Support/ValueHandle.h"
00031 
00032 namespace llvm {
00033   class Module;
00034   class Constant;
00035   class ConstantInt;
00036   class Function;
00037   class GlobalValue;
00038   class TargetData;
00039   class FunctionType;
00040   class LLVMContext;
00041 }
00042 
00043 namespace clang {
00044   class TargetCodeGenInfo;
00045   class ASTContext;
00046   class FunctionDecl;
00047   class IdentifierInfo;
00048   class ObjCMethodDecl;
00049   class ObjCImplementationDecl;
00050   class ObjCCategoryImplDecl;
00051   class ObjCProtocolDecl;
00052   class ObjCEncodeExpr;
00053   class BlockExpr;
00054   class CharUnits;
00055   class Decl;
00056   class Expr;
00057   class Stmt;
00058   class InitListExpr;
00059   class StringLiteral;
00060   class NamedDecl;
00061   class ValueDecl;
00062   class VarDecl;
00063   class LangOptions;
00064   class CodeGenOptions;
00065   class DiagnosticsEngine;
00066   class AnnotateAttr;
00067   class CXXDestructorDecl;
00068   class MangleBuffer;
00069 
00070 namespace CodeGen {
00071 
00072   class CallArgList;
00073   class CodeGenFunction;
00074   class CodeGenTBAA;
00075   class CGCXXABI;
00076   class CGDebugInfo;
00077   class CGObjCRuntime;
00078   class CGOpenCLRuntime;
00079   class CGCUDARuntime;
00080   class BlockFieldFlags;
00081   class FunctionArgList;
00082   
00083   struct OrderGlobalInits {
00084     unsigned int priority;
00085     unsigned int lex_order;
00086     OrderGlobalInits(unsigned int p, unsigned int l) 
00087       : priority(p), lex_order(l) {}
00088     
00089     bool operator==(const OrderGlobalInits &RHS) const {
00090       return priority == RHS.priority &&
00091              lex_order == RHS.lex_order;
00092     }
00093     
00094     bool operator<(const OrderGlobalInits &RHS) const {
00095       if (priority < RHS.priority)
00096         return true;
00097       
00098       return priority == RHS.priority && lex_order < RHS.lex_order;
00099     }
00100   };
00101 
00102   struct CodeGenTypeCache {
00103     /// void
00104     llvm::Type *VoidTy;
00105 
00106     /// i8, i16, i32, and i64
00107     llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
00108     /// float, double
00109     llvm::Type *FloatTy, *DoubleTy;
00110 
00111     /// int
00112     llvm::IntegerType *IntTy;
00113 
00114     /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
00115     union {
00116       llvm::IntegerType *IntPtrTy;
00117       llvm::IntegerType *SizeTy;
00118       llvm::IntegerType *PtrDiffTy;
00119     };
00120 
00121     /// void* in address space 0
00122     union {
00123       llvm::PointerType *VoidPtrTy;
00124       llvm::PointerType *Int8PtrTy;
00125     };
00126 
00127     /// void** in address space 0
00128     union {
00129       llvm::PointerType *VoidPtrPtrTy;
00130       llvm::PointerType *Int8PtrPtrTy;
00131     };
00132 
00133     /// The width of a pointer into the generic address space.
00134     unsigned char PointerWidthInBits;
00135 
00136     /// The size and alignment of a pointer into the generic address
00137     /// space.
00138     union {
00139       unsigned char PointerAlignInBytes;
00140       unsigned char PointerSizeInBytes;
00141       unsigned char SizeSizeInBytes;     // sizeof(size_t)
00142     };
00143   };
00144 
00145 struct RREntrypoints {
00146   RREntrypoints() { memset(this, 0, sizeof(*this)); }
00147   /// void objc_autoreleasePoolPop(void*);
00148   llvm::Constant *objc_autoreleasePoolPop;
00149 
00150   /// void *objc_autoreleasePoolPush(void);
00151   llvm::Constant *objc_autoreleasePoolPush;
00152 };
00153 
00154 struct ARCEntrypoints {
00155   ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
00156 
00157   /// id objc_autorelease(id);
00158   llvm::Constant *objc_autorelease;
00159 
00160   /// id objc_autoreleaseReturnValue(id);
00161   llvm::Constant *objc_autoreleaseReturnValue;
00162 
00163   /// void objc_copyWeak(id *dest, id *src);
00164   llvm::Constant *objc_copyWeak;
00165 
00166   /// void objc_destroyWeak(id*);
00167   llvm::Constant *objc_destroyWeak;
00168 
00169   /// id objc_initWeak(id*, id);
00170   llvm::Constant *objc_initWeak;
00171 
00172   /// id objc_loadWeak(id*);
00173   llvm::Constant *objc_loadWeak;
00174 
00175   /// id objc_loadWeakRetained(id*);
00176   llvm::Constant *objc_loadWeakRetained;
00177 
00178   /// void objc_moveWeak(id *dest, id *src);
00179   llvm::Constant *objc_moveWeak;
00180 
00181   /// id objc_retain(id);
00182   llvm::Constant *objc_retain;
00183 
00184   /// id objc_retainAutorelease(id);
00185   llvm::Constant *objc_retainAutorelease;
00186 
00187   /// id objc_retainAutoreleaseReturnValue(id);
00188   llvm::Constant *objc_retainAutoreleaseReturnValue;
00189 
00190   /// id objc_retainAutoreleasedReturnValue(id);
00191   llvm::Constant *objc_retainAutoreleasedReturnValue;
00192 
00193   /// id objc_retainBlock(id);
00194   llvm::Constant *objc_retainBlock;
00195 
00196   /// void objc_release(id);
00197   llvm::Constant *objc_release;
00198 
00199   /// id objc_storeStrong(id*, id);
00200   llvm::Constant *objc_storeStrong;
00201 
00202   /// id objc_storeWeak(id*, id);
00203   llvm::Constant *objc_storeWeak;
00204 
00205   /// A void(void) inline asm to use to mark that the return value of
00206   /// a call will be immediately retain.
00207   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
00208 };
00209   
00210 /// CodeGenModule - This class organizes the cross-function state that is used
00211 /// while generating LLVM code.
00212 class CodeGenModule : public CodeGenTypeCache {
00213   CodeGenModule(const CodeGenModule&);  // DO NOT IMPLEMENT
00214   void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
00215 
00216   typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
00217 
00218   ASTContext &Context;
00219   const LangOptions &LangOpts;
00220   const CodeGenOptions &CodeGenOpts;
00221   llvm::Module &TheModule;
00222   const llvm::TargetData &TheTargetData;
00223   mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
00224   DiagnosticsEngine &Diags;
00225   CGCXXABI &ABI;
00226   CodeGenTypes Types;
00227   CodeGenTBAA *TBAA;
00228 
00229   /// VTables - Holds information about C++ vtables.
00230   CodeGenVTables VTables;
00231   friend class CodeGenVTables;
00232 
00233   CGObjCRuntime* ObjCRuntime;
00234   CGOpenCLRuntime* OpenCLRuntime;
00235   CGCUDARuntime* CUDARuntime;
00236   CGDebugInfo* DebugInfo;
00237   ARCEntrypoints *ARCData;
00238   llvm::MDNode *NoObjCARCExceptionsMetadata;
00239   RREntrypoints *RRData;
00240 
00241   // WeakRefReferences - A set of references that have only been seen via
00242   // a weakref so far. This is used to remove the weak of the reference if we ever
00243   // see a direct reference or a definition.
00244   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
00245 
00246   /// DeferredDecls - This contains all the decls which have definitions but
00247   /// which are deferred for emission and therefore should only be output if
00248   /// they are actually used.  If a decl is in this, then it is known to have
00249   /// not been referenced yet.
00250   llvm::StringMap<GlobalDecl> DeferredDecls;
00251 
00252   /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
00253   /// that *are* actually referenced.  These get code generated when the module
00254   /// is done.
00255   std::vector<GlobalDecl> DeferredDeclsToEmit;
00256 
00257   /// LLVMUsed - List of global values which are required to be
00258   /// present in the object file; bitcast to i8*. This is used for
00259   /// forcing visibility of symbols which may otherwise be optimized
00260   /// out.
00261   std::vector<llvm::WeakVH> LLVMUsed;
00262 
00263   /// GlobalCtors - Store the list of global constructors and their respective
00264   /// priorities to be emitted when the translation unit is complete.
00265   CtorList GlobalCtors;
00266 
00267   /// GlobalDtors - Store the list of global destructors and their respective
00268   /// priorities to be emitted when the translation unit is complete.
00269   CtorList GlobalDtors;
00270 
00271   /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
00272   llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
00273   llvm::BumpPtrAllocator MangledNamesAllocator;
00274   
00275   /// Global annotations.
00276   std::vector<llvm::Constant*> Annotations;
00277 
00278   /// Map used to get unique annotation strings.
00279   llvm::StringMap<llvm::Constant*> AnnotationStrings;
00280 
00281   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
00282   llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
00283   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
00284   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
00285   
00286   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
00287   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
00288 
00289   /// CXXGlobalInits - Global variables with initializers that need to run
00290   /// before main.
00291   std::vector<llvm::Constant*> CXXGlobalInits;
00292 
00293   /// When a C++ decl with an initializer is deferred, null is
00294   /// appended to CXXGlobalInits, and the index of that null is placed
00295   /// here so that the initializer will be performed in the correct
00296   /// order.
00297   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
00298   
00299   /// - Global variables with initializers whose order of initialization
00300   /// is set by init_priority attribute.
00301   
00302   SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8> 
00303     PrioritizedCXXGlobalInits;
00304 
00305   /// CXXGlobalDtors - Global destructor functions and arguments that need to
00306   /// run on termination.
00307   std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
00308 
00309   /// @name Cache for Objective-C runtime types
00310   /// @{
00311 
00312   /// CFConstantStringClassRef - Cached reference to the class for constant
00313   /// strings. This value has type int * but is actually an Obj-C class pointer.
00314   llvm::Constant *CFConstantStringClassRef;
00315 
00316   /// ConstantStringClassRef - Cached reference to the class for constant
00317   /// strings. This value has type int * but is actually an Obj-C class pointer.
00318   llvm::Constant *ConstantStringClassRef;
00319 
00320   /// \brief The LLVM type corresponding to NSConstantString.
00321   llvm::StructType *NSConstantStringType;
00322   
00323   /// \brief The type used to describe the state of a fast enumeration in
00324   /// Objective-C's for..in loop.
00325   QualType ObjCFastEnumerationStateType;
00326   
00327   /// @}
00328 
00329   /// Lazily create the Objective-C runtime
00330   void createObjCRuntime();
00331 
00332   void createOpenCLRuntime();
00333   void createCUDARuntime();
00334 
00335   bool isTriviallyRecursive(const FunctionDecl *F);
00336   bool shouldEmitFunction(const FunctionDecl *F);
00337   llvm::LLVMContext &VMContext;
00338 
00339   /// @name Cache for Blocks Runtime Globals
00340   /// @{
00341 
00342   llvm::Constant *NSConcreteGlobalBlock;
00343   llvm::Constant *NSConcreteStackBlock;
00344 
00345   llvm::Constant *BlockObjectAssign;
00346   llvm::Constant *BlockObjectDispose;
00347 
00348   llvm::Type *BlockDescriptorType;
00349   llvm::Type *GenericBlockLiteralType;
00350 
00351   struct {
00352     int GlobalUniqueCount;
00353   } Block;
00354 
00355   /// @}
00356 public:
00357   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
00358                 llvm::Module &M, const llvm::TargetData &TD,
00359                 DiagnosticsEngine &Diags);
00360 
00361   ~CodeGenModule();
00362 
00363   /// Release - Finalize LLVM code generation.
00364   void Release();
00365 
00366   /// getObjCRuntime() - Return a reference to the configured
00367   /// Objective-C runtime.
00368   CGObjCRuntime &getObjCRuntime() {
00369     if (!ObjCRuntime) createObjCRuntime();
00370     return *ObjCRuntime;
00371   }
00372 
00373   /// hasObjCRuntime() - Return true iff an Objective-C runtime has
00374   /// been configured.
00375   bool hasObjCRuntime() { return !!ObjCRuntime; }
00376 
00377   /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime.
00378   CGOpenCLRuntime &getOpenCLRuntime() {
00379     assert(OpenCLRuntime != 0);
00380     return *OpenCLRuntime;
00381   }
00382 
00383   /// getCUDARuntime() - Return a reference to the configured CUDA runtime.
00384   CGCUDARuntime &getCUDARuntime() {
00385     assert(CUDARuntime != 0);
00386     return *CUDARuntime;
00387   }
00388 
00389   /// getCXXABI() - Return a reference to the configured C++ ABI.
00390   CGCXXABI &getCXXABI() { return ABI; }
00391 
00392   ARCEntrypoints &getARCEntrypoints() const {
00393     assert(getLangOpts().ObjCAutoRefCount && ARCData != 0);
00394     return *ARCData;
00395   }
00396 
00397   RREntrypoints &getRREntrypoints() const {
00398     assert(RRData != 0);
00399     return *RRData;
00400   }
00401 
00402   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
00403     return StaticLocalDeclMap[D];
00404   }
00405   void setStaticLocalDeclAddress(const VarDecl *D, 
00406                                  llvm::Constant *C) {
00407     StaticLocalDeclMap[D] = C;
00408   }
00409 
00410   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
00411     return StaticLocalDeclGuardMap[D];
00412   }
00413   void setStaticLocalDeclGuardAddress(const VarDecl *D, 
00414                                       llvm::GlobalVariable *C) {
00415     StaticLocalDeclGuardMap[D] = C;
00416   }
00417 
00418   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
00419     return AtomicSetterHelperFnMap[Ty];
00420   }
00421   void setAtomicSetterHelperFnMap(QualType Ty,
00422                             llvm::Constant *Fn) {
00423     AtomicSetterHelperFnMap[Ty] = Fn;
00424   }
00425 
00426   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
00427     return AtomicGetterHelperFnMap[Ty];
00428   }
00429   void setAtomicGetterHelperFnMap(QualType Ty,
00430                             llvm::Constant *Fn) {
00431     AtomicGetterHelperFnMap[Ty] = Fn;
00432   }
00433 
00434   CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
00435 
00436   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
00437     if (!NoObjCARCExceptionsMetadata)
00438       NoObjCARCExceptionsMetadata =
00439         llvm::MDNode::get(getLLVMContext(),
00440                           SmallVector<llvm::Value*,1>());
00441     return NoObjCARCExceptionsMetadata;
00442   }
00443 
00444   ASTContext &getContext() const { return Context; }
00445   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
00446   const LangOptions &getLangOpts() const { return LangOpts; }
00447   llvm::Module &getModule() const { return TheModule; }
00448   CodeGenTypes &getTypes() { return Types; }
00449   CodeGenVTables &getVTables() { return VTables; }
00450   VTableContext &getVTableContext() { return VTables.getVTableContext(); }
00451   DiagnosticsEngine &getDiags() const { return Diags; }
00452   const llvm::TargetData &getTargetData() const { return TheTargetData; }
00453   const TargetInfo &getTarget() const { return Context.getTargetInfo(); }
00454   llvm::LLVMContext &getLLVMContext() { return VMContext; }
00455   const TargetCodeGenInfo &getTargetCodeGenInfo();
00456   bool isTargetDarwin() const;
00457 
00458   bool shouldUseTBAA() const { return TBAA != 0; }
00459 
00460   llvm::MDNode *getTBAAInfo(QualType QTy);
00461   llvm::MDNode *getTBAAInfoForVTablePtr();
00462 
00463   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
00464 
00465   static void DecorateInstruction(llvm::Instruction *Inst,
00466                                   llvm::MDNode *TBAAInfo);
00467 
00468   /// getSize - Emit the given number of characters as a value of type size_t.
00469   llvm::ConstantInt *getSize(CharUnits numChars);
00470 
00471   /// setGlobalVisibility - Set the visibility for the given LLVM
00472   /// GlobalValue.
00473   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
00474 
00475   /// TypeVisibilityKind - The kind of global variable that is passed to 
00476   /// setTypeVisibility
00477   enum TypeVisibilityKind {
00478     TVK_ForVTT,
00479     TVK_ForVTable,
00480     TVK_ForConstructionVTable,
00481     TVK_ForRTTI,
00482     TVK_ForRTTIName
00483   };
00484 
00485   /// setTypeVisibility - Set the visibility for the given global
00486   /// value which holds information about a type.
00487   void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
00488                          TypeVisibilityKind TVK) const;
00489 
00490   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
00491     switch (V) {
00492     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
00493     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
00494     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
00495     }
00496     llvm_unreachable("unknown visibility!");
00497   }
00498 
00499   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
00500     if (isa<CXXConstructorDecl>(GD.getDecl()))
00501       return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
00502                                      GD.getCtorType());
00503     else if (isa<CXXDestructorDecl>(GD.getDecl()))
00504       return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
00505                                      GD.getDtorType());
00506     else if (isa<FunctionDecl>(GD.getDecl()))
00507       return GetAddrOfFunction(GD);
00508     else
00509       return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
00510   }
00511 
00512   /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given
00513   /// type. If a variable with a different type already exists then a new 
00514   /// variable with the right type will be created and all uses of the old
00515   /// variable will be replaced with a bitcast to the new variable.
00516   llvm::GlobalVariable *
00517   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
00518                                     llvm::GlobalValue::LinkageTypes Linkage);
00519 
00520   /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
00521   /// given global variable.  If Ty is non-null and if the global doesn't exist,
00522   /// then it will be greated with the specified type instead of whatever the
00523   /// normal requested type would be.
00524   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
00525                                      llvm::Type *Ty = 0);
00526 
00527 
00528   /// GetAddrOfFunction - Return the address of the given function.  If Ty is
00529   /// non-null, then this function will use the specified type if it has to
00530   /// create it.
00531   llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
00532                                     llvm::Type *Ty = 0,
00533                                     bool ForVTable = false);
00534 
00535   /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 
00536   /// for the given type.
00537   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
00538 
00539   /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
00540   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
00541 
00542   /// GetWeakRefReference - Get a reference to the target of VD.
00543   llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
00544 
00545   /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 
00546   /// a class. Returns null if the offset is 0. 
00547   llvm::Constant *
00548   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
00549                                CastExpr::path_const_iterator PathBegin,
00550                                CastExpr::path_const_iterator PathEnd);
00551 
00552   /// A pair of helper functions for a __block variable.
00553   class ByrefHelpers : public llvm::FoldingSetNode {
00554   public:
00555     llvm::Constant *CopyHelper;
00556     llvm::Constant *DisposeHelper;
00557 
00558     /// The alignment of the field.  This is important because
00559     /// different offsets to the field within the byref struct need to
00560     /// have different helper functions.
00561     CharUnits Alignment;
00562 
00563     ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
00564     virtual ~ByrefHelpers();
00565 
00566     void Profile(llvm::FoldingSetNodeID &id) const {
00567       id.AddInteger(Alignment.getQuantity());
00568       profileImpl(id);
00569     }
00570     virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
00571 
00572     virtual bool needsCopy() const { return true; }
00573     virtual void emitCopy(CodeGenFunction &CGF,
00574                           llvm::Value *dest, llvm::Value *src) = 0;
00575 
00576     virtual bool needsDispose() const { return true; }
00577     virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
00578   };
00579 
00580   llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
00581 
00582   /// getUniqueBlockCount - Fetches the global unique block count.
00583   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
00584 
00585   /// getBlockDescriptorType - Fetches the type of a generic block
00586   /// descriptor.
00587   llvm::Type *getBlockDescriptorType();
00588 
00589   /// getGenericBlockLiteralType - The type of a generic block literal.
00590   llvm::Type *getGenericBlockLiteralType();
00591 
00592   /// GetAddrOfGlobalBlock - Gets the address of a block which
00593   /// requires no captures.
00594   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
00595   
00596   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
00597   /// for the given string.
00598   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
00599   
00600   /// GetAddrOfConstantString - Return a pointer to a constant NSString object
00601   /// for the given string. Or a user defined String object as defined via
00602   /// -fconstant-string-class=class_name option.
00603   llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
00604 
00605   /// GetConstantArrayFromStringLiteral - Return a constant array for the given
00606   /// string.
00607   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
00608 
00609   /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
00610   /// for the given string literal.
00611   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
00612 
00613   /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
00614   /// array for the given ObjCEncodeExpr node.
00615   llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
00616 
00617   /// GetAddrOfConstantString - Returns a pointer to a character array
00618   /// containing the literal. This contents are exactly that of the given
00619   /// string, i.e. it will not be null terminated automatically; see
00620   /// GetAddrOfConstantCString. Note that whether the result is actually a
00621   /// pointer to an LLVM constant depends on Feature.WriteableStrings.
00622   ///
00623   /// The result has pointer to array type.
00624   ///
00625   /// \param GlobalName If provided, the name to use for the global
00626   /// (if one is created).
00627   llvm::Constant *GetAddrOfConstantString(StringRef Str,
00628                                           const char *GlobalName=0,
00629                                           unsigned Alignment=1);
00630 
00631   /// GetAddrOfConstantCString - Returns a pointer to a character array
00632   /// containing the literal and a terminating '\0' character. The result has
00633   /// pointer to array type.
00634   ///
00635   /// \param GlobalName If provided, the name to use for the global (if one is
00636   /// created).
00637   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
00638                                            const char *GlobalName=0,
00639                                            unsigned Alignment=1);
00640 
00641   /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global
00642   /// variable for the given file-scope compound literal expression.
00643   llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
00644   
00645   /// \brief Retrieve the record type that describes the state of an
00646   /// Objective-C fast enumeration loop (for..in).
00647   QualType getObjCFastEnumerationStateType();
00648   
00649   /// GetAddrOfCXXConstructor - Return the address of the constructor of the
00650   /// given type.
00651   llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
00652                                              CXXCtorType ctorType,
00653                                              const CGFunctionInfo *fnInfo = 0);
00654 
00655   /// GetAddrOfCXXDestructor - Return the address of the constructor of the
00656   /// given type.
00657   llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
00658                                             CXXDtorType dtorType,
00659                                             const CGFunctionInfo *fnInfo = 0);
00660 
00661   /// getBuiltinLibFunction - Given a builtin id for a function like
00662   /// "__builtin_fabsf", return a Function* for "fabsf".
00663   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
00664                                      unsigned BuiltinID);
00665 
00666   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys =
00667                                                  ArrayRef<llvm::Type*>());
00668 
00669   /// EmitTopLevelDecl - Emit code for a single top level declaration.
00670   void EmitTopLevelDecl(Decl *D);
00671 
00672   /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
00673   // variable has been instantiated.
00674   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
00675 
00676   /// AddUsedGlobal - Add a global which should be forced to be
00677   /// present in the object file; these are emitted to the llvm.used
00678   /// metadata global.
00679   void AddUsedGlobal(llvm::GlobalValue *GV);
00680 
00681   /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
00682   /// destructor function.
00683   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
00684     CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
00685   }
00686 
00687   /// CreateRuntimeFunction - Create a new runtime function with the specified
00688   /// type and name.
00689   llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
00690                                         StringRef Name,
00691                                         llvm::Attributes ExtraAttrs =
00692                                           llvm::Attribute::None);
00693   /// CreateRuntimeVariable - Create a new runtime global variable with the
00694   /// specified type and name.
00695   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
00696                                         StringRef Name);
00697 
00698   ///@name Custom Blocks Runtime Interfaces
00699   ///@{
00700 
00701   llvm::Constant *getNSConcreteGlobalBlock();
00702   llvm::Constant *getNSConcreteStackBlock();
00703   llvm::Constant *getBlockObjectAssign();
00704   llvm::Constant *getBlockObjectDispose();
00705 
00706   ///@}
00707 
00708   // UpdateCompleteType - Make sure that this type is translated.
00709   void UpdateCompletedType(const TagDecl *TD);
00710 
00711   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
00712 
00713   /// EmitConstantInit - Try to emit the initializer for the given declaration
00714   /// as a constant; returns 0 if the expression cannot be emitted as a
00715   /// constant.
00716   llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0);
00717 
00718   /// EmitConstantExpr - Try to emit the given expression as a
00719   /// constant; returns 0 if the expression cannot be emitted as a
00720   /// constant.
00721   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
00722                                    CodeGenFunction *CGF = 0);
00723 
00724   /// EmitConstantValue - Emit the given constant value as a constant, in the
00725   /// type's scalar representation.
00726   llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
00727                                     CodeGenFunction *CGF = 0);
00728 
00729   /// EmitConstantValueForMemory - Emit the given constant value as a constant,
00730   /// in the type's memory representation.
00731   llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
00732                                              QualType DestType,
00733                                              CodeGenFunction *CGF = 0);
00734 
00735   /// EmitNullConstant - Return the result of value-initializing the given
00736   /// type, i.e. a null expression of the given type.  This is usually,
00737   /// but not always, an LLVM null constant.
00738   llvm::Constant *EmitNullConstant(QualType T);
00739 
00740   /// EmitNullConstantForBase - Return a null constant appropriate for 
00741   /// zero-initializing a base class with the given type.  This is usually,
00742   /// but not always, an LLVM null constant.
00743   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
00744 
00745   /// Error - Emit a general error that something can't be done.
00746   void Error(SourceLocation loc, StringRef error);
00747 
00748   /// ErrorUnsupported - Print out an error that codegen doesn't support the
00749   /// specified stmt yet.
00750   /// \param OmitOnError - If true, then this error should only be emitted if no
00751   /// other errors have been reported.
00752   void ErrorUnsupported(const Stmt *S, const char *Type,
00753                         bool OmitOnError=false);
00754 
00755   /// ErrorUnsupported - Print out an error that codegen doesn't support the
00756   /// specified decl yet.
00757   /// \param OmitOnError - If true, then this error should only be emitted if no
00758   /// other errors have been reported.
00759   void ErrorUnsupported(const Decl *D, const char *Type,
00760                         bool OmitOnError=false);
00761 
00762   /// SetInternalFunctionAttributes - Set the attributes on the LLVM
00763   /// function for the given decl and function info. This applies
00764   /// attributes necessary for handling the ABI as well as user
00765   /// specified attributes like section.
00766   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
00767                                      const CGFunctionInfo &FI);
00768 
00769   /// SetLLVMFunctionAttributes - Set the LLVM function attributes
00770   /// (sext, zext, etc).
00771   void SetLLVMFunctionAttributes(const Decl *D,
00772                                  const CGFunctionInfo &Info,
00773                                  llvm::Function *F);
00774 
00775   /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
00776   /// which only apply to a function definintion.
00777   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
00778 
00779   /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
00780   /// as a return type.
00781   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
00782 
00783   /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when
00784   /// used as a return type.
00785   bool ReturnTypeUsesFPRet(QualType ResultType);
00786 
00787   /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when
00788   /// used as a return type.
00789   bool ReturnTypeUsesFP2Ret(QualType ResultType);
00790 
00791   /// ConstructAttributeList - Get the LLVM attributes and calling convention to
00792   /// use for a particular function type.
00793   ///
00794   /// \param Info - The function type information.
00795   /// \param TargetDecl - The decl these attributes are being constructed
00796   /// for. If supplied the attributes applied to this decl may contribute to the
00797   /// function attributes and calling convention.
00798   /// \param PAL [out] - On return, the attribute list to use.
00799   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
00800   void ConstructAttributeList(const CGFunctionInfo &Info,
00801                               const Decl *TargetDecl,
00802                               AttributeListType &PAL,
00803                               unsigned &CallingConv);
00804 
00805   StringRef getMangledName(GlobalDecl GD);
00806   void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
00807                            const BlockDecl *BD);
00808 
00809   void EmitTentativeDefinition(const VarDecl *D);
00810 
00811   void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
00812 
00813   llvm::GlobalVariable::LinkageTypes
00814   getFunctionLinkage(const FunctionDecl *FD);
00815 
00816   void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
00817     V->setLinkage(getFunctionLinkage(FD));
00818   }
00819 
00820   /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
00821   /// and type information of the given class.
00822   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
00823 
00824   /// GetTargetTypeStoreSize - Return the store size, in character units, of
00825   /// the given LLVM type.
00826   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
00827   
00828   /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global 
00829   /// variable.
00830   llvm::GlobalValue::LinkageTypes 
00831   GetLLVMLinkageVarDefinition(const VarDecl *D,
00832                               llvm::GlobalVariable *GV);
00833   
00834   std::vector<const CXXRecordDecl*> DeferredVTables;
00835 
00836   /// Emit all the global annotations.
00837   void EmitGlobalAnnotations();
00838 
00839   /// Emit an annotation string.
00840   llvm::Constant *EmitAnnotationString(llvm::StringRef Str);
00841 
00842   /// Emit the annotation's translation unit.
00843   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
00844 
00845   /// Emit the annotation line number.
00846   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
00847 
00848   /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
00849   /// annotation information for a given GlobalValue. The annotation struct is
00850   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
00851   /// GlobalValue being annotated. The second field is the constant string
00852   /// created from the AnnotateAttr's annotation. The third field is a constant
00853   /// string containing the name of the translation unit. The fourth field is
00854   /// the line number in the file of the annotated value declaration.
00855   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
00856                                    const AnnotateAttr *AA,
00857                                    SourceLocation L);
00858 
00859   /// Add global annotations that are set on D, for the global GV. Those
00860   /// annotations are emitted during finalization of the LLVM code.
00861   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
00862 
00863 private:
00864   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
00865 
00866   llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName,
00867                                           llvm::Type *Ty,
00868                                           GlobalDecl D,
00869                                           bool ForVTable,
00870                                           llvm::Attributes ExtraAttrs =
00871                                             llvm::Attribute::None);
00872   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
00873                                         llvm::PointerType *PTy,
00874                                         const VarDecl *D,
00875                                         bool UnnamedAddr = false);
00876 
00877   /// SetCommonAttributes - Set attributes which are common to any
00878   /// form of a global definition (alias, Objective-C method,
00879   /// function, global variable).
00880   ///
00881   /// NOTE: This should only be called for definitions.
00882   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
00883 
00884   /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
00885   void SetFunctionDefinitionAttributes(const FunctionDecl *D,
00886                                        llvm::GlobalValue *GV);
00887 
00888   /// SetFunctionAttributes - Set function attributes for a function
00889   /// declaration.
00890   void SetFunctionAttributes(GlobalDecl GD,
00891                              llvm::Function *F,
00892                              bool IsIncompleteFunction);
00893 
00894   /// EmitGlobal - Emit code for a singal global function or var decl. Forward
00895   /// declarations are emitted lazily.
00896   void EmitGlobal(GlobalDecl D);
00897 
00898   void EmitGlobalDefinition(GlobalDecl D);
00899 
00900   void EmitGlobalFunctionDefinition(GlobalDecl GD);
00901   void EmitGlobalVarDefinition(const VarDecl *D);
00902   llvm::Constant *MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
00903                                                               const Expr *init);
00904   void EmitAliasDefinition(GlobalDecl GD);
00905   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
00906   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
00907   
00908   // C++ related functions.
00909 
00910   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
00911   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
00912 
00913   void EmitNamespace(const NamespaceDecl *D);
00914   void EmitLinkageSpec(const LinkageSpecDecl *D);
00915 
00916   /// EmitCXXConstructors - Emit constructors (base, complete) from a
00917   /// C++ constructor Decl.
00918   void EmitCXXConstructors(const CXXConstructorDecl *D);
00919 
00920   /// EmitCXXConstructor - Emit a single constructor with the given type from
00921   /// a C++ constructor Decl.
00922   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
00923 
00924   /// EmitCXXDestructors - Emit destructors (base, complete) from a
00925   /// C++ destructor Decl.
00926   void EmitCXXDestructors(const CXXDestructorDecl *D);
00927 
00928   /// EmitCXXDestructor - Emit a single destructor with the given type from
00929   /// a C++ destructor Decl.
00930   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
00931 
00932   /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
00933   void EmitCXXGlobalInitFunc();
00934 
00935   /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
00936   void EmitCXXGlobalDtorFunc();
00937 
00938   /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the
00939   /// specified global (if PerformInit is true) and registers its destructor.
00940   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
00941                                     llvm::GlobalVariable *Addr,
00942                                     bool PerformInit);
00943 
00944   // FIXME: Hardcoding priority here is gross.
00945   void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
00946   void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
00947 
00948   /// EmitCtorList - Generates a global array of functions and priorities using
00949   /// the given list and name. This array will have appending linkage and is
00950   /// suitable for use as a LLVM constructor or destructor array.
00951   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
00952 
00953   /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
00954   /// given type.
00955   void EmitFundamentalRTTIDescriptor(QualType Type);
00956 
00957   /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
00958   /// builtin types.
00959   void EmitFundamentalRTTIDescriptors();
00960 
00961   /// EmitDeferred - Emit any needed decls for which code generation
00962   /// was deferred.
00963   void EmitDeferred(void);
00964 
00965   /// EmitLLVMUsed - Emit the llvm.used metadata used to force
00966   /// references to global which may otherwise be optimized out.
00967   void EmitLLVMUsed(void);
00968 
00969   void EmitDeclMetadata();
00970 
00971   /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
00972   /// to emit the .gcno and .gcda files in a way that persists in .bc files.
00973   void EmitCoverageFile();
00974 
00975   /// MayDeferGeneration - Determine if the given decl can be emitted
00976   /// lazily; this is only relevant for definitions. The given decl
00977   /// must be either a function or var decl.
00978   bool MayDeferGeneration(const ValueDecl *D);
00979 
00980   /// SimplifyPersonality - Check whether we can use a "simpler", more
00981   /// core exceptions personality function.
00982   void SimplifyPersonality();
00983 };
00984 }  // end namespace CodeGen
00985 }  // end namespace clang
00986 
00987 #endif