CodeGenModule.h revision 206084
1//===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===// 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 is the internal per-translation-unit state used for llvm translation. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef CLANG_CODEGEN_CODEGENMODULE_H 15#define CLANG_CODEGEN_CODEGENMODULE_H 16 17#include "clang/Basic/LangOptions.h" 18#include "clang/AST/Attr.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclObjC.h" 21#include "CGBlocks.h" 22#include "CGCall.h" 23#include "CGCXX.h" 24#include "CGVtable.h" 25#include "CodeGenTypes.h" 26#include "GlobalDecl.h" 27#include "Mangle.h" 28#include "llvm/Module.h" 29#include "llvm/ADT/DenseMap.h" 30#include "llvm/ADT/StringMap.h" 31#include "llvm/ADT/StringSet.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/Support/ValueHandle.h" 34 35namespace llvm { 36 class Module; 37 class Constant; 38 class Function; 39 class GlobalValue; 40 class TargetData; 41 class FunctionType; 42 class LLVMContext; 43} 44 45namespace clang { 46 class TargetCodeGenInfo; 47 class ASTContext; 48 class FunctionDecl; 49 class IdentifierInfo; 50 class ObjCMethodDecl; 51 class ObjCImplementationDecl; 52 class ObjCCategoryImplDecl; 53 class ObjCProtocolDecl; 54 class ObjCEncodeExpr; 55 class BlockExpr; 56 class CharUnits; 57 class Decl; 58 class Expr; 59 class Stmt; 60 class StringLiteral; 61 class NamedDecl; 62 class ValueDecl; 63 class VarDecl; 64 class LangOptions; 65 class CodeGenOptions; 66 class Diagnostic; 67 class AnnotateAttr; 68 class CXXDestructorDecl; 69 70namespace CodeGen { 71 72 class CodeGenFunction; 73 class CGDebugInfo; 74 class CGObjCRuntime; 75 class MangleBuffer; 76 77/// CodeGenModule - This class organizes the cross-function state that is used 78/// while generating LLVM code. 79class CodeGenModule : public BlockModule { 80 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT 81 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT 82 83 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList; 84 85 ASTContext &Context; 86 const LangOptions &Features; 87 const CodeGenOptions &CodeGenOpts; 88 llvm::Module &TheModule; 89 const llvm::TargetData &TheTargetData; 90 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 91 Diagnostic &Diags; 92 CodeGenTypes Types; 93 MangleContext MangleCtx; 94 95 /// VTables - Holds information about C++ vtables. 96 CodeGenVTables VTables; 97 98 CGObjCRuntime* Runtime; 99 CGDebugInfo* DebugInfo; 100 101 llvm::Function *MemCpyFn; 102 llvm::Function *MemMoveFn; 103 llvm::Function *MemSetFn; 104 105 // WeakRefReferences - A set of references that have only been seen via 106 // a weakref so far. This is used to remove the weak of the reference if we ever 107 // see a direct reference or a definition. 108 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 109 110 /// DeferredDecls - This contains all the decls which have definitions but 111 /// which are deferred for emission and therefore should only be output if 112 /// they are actually used. If a decl is in this, then it is known to have 113 /// not been referenced yet. 114 llvm::StringMap<GlobalDecl> DeferredDecls; 115 116 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen 117 /// that *are* actually referenced. These get code generated when the module 118 /// is done. 119 std::vector<GlobalDecl> DeferredDeclsToEmit; 120 121 /// LLVMUsed - List of global values which are required to be 122 /// present in the object file; bitcast to i8*. This is used for 123 /// forcing visibility of symbols which may otherwise be optimized 124 /// out. 125 std::vector<llvm::WeakVH> LLVMUsed; 126 127 /// GlobalCtors - Store the list of global constructors and their respective 128 /// priorities to be emitted when the translation unit is complete. 129 CtorList GlobalCtors; 130 131 /// GlobalDtors - Store the list of global destructors and their respective 132 /// priorities to be emitted when the translation unit is complete. 133 CtorList GlobalDtors; 134 135 std::vector<llvm::Constant*> Annotations; 136 137 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 138 llvm::StringMap<llvm::Constant*> ConstantStringMap; 139 140 /// CXXGlobalInits - Global variables with initializers that need to run 141 /// before main. 142 std::vector<llvm::Constant*> CXXGlobalInits; 143 144 /// CXXGlobalDtors - Global destructor functions and arguments that need to 145 /// run on termination. 146 std::vector<std::pair<llvm::Constant*,llvm::Constant*> > CXXGlobalDtors; 147 148 /// CFConstantStringClassRef - Cached reference to the class for constant 149 /// strings. This value has type int * but is actually an Obj-C class pointer. 150 llvm::Constant *CFConstantStringClassRef; 151 152 /// Lazily create the Objective-C runtime 153 void createObjCRuntime(); 154 155 llvm::LLVMContext &VMContext; 156public: 157 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 158 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags); 159 160 ~CodeGenModule(); 161 162 /// Release - Finalize LLVM code generation. 163 void Release(); 164 165 /// getObjCRuntime() - Return a reference to the configured 166 /// Objective-C runtime. 167 CGObjCRuntime &getObjCRuntime() { 168 if (!Runtime) createObjCRuntime(); 169 return *Runtime; 170 } 171 172 /// hasObjCRuntime() - Return true iff an Objective-C runtime has 173 /// been configured. 174 bool hasObjCRuntime() { return !!Runtime; } 175 176 CGDebugInfo *getDebugInfo() { return DebugInfo; } 177 ASTContext &getContext() const { return Context; } 178 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 179 const LangOptions &getLangOptions() const { return Features; } 180 llvm::Module &getModule() const { return TheModule; } 181 CodeGenTypes &getTypes() { return Types; } 182 MangleContext &getMangleContext() { return MangleCtx; } 183 CodeGenVTables &getVTables() { return VTables; } 184 Diagnostic &getDiags() const { return Diags; } 185 const llvm::TargetData &getTargetData() const { return TheTargetData; } 186 llvm::LLVMContext &getLLVMContext() { return VMContext; } 187 const TargetCodeGenInfo &getTargetCodeGenInfo() const; 188 bool isTargetDarwin() const; 189 190 /// getDeclVisibilityMode - Compute the visibility of the decl \arg D. 191 LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const; 192 193 /// setGlobalVisibility - Set the visibility for the given LLVM 194 /// GlobalValue. 195 void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const; 196 197 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 198 if (isa<CXXConstructorDecl>(GD.getDecl())) 199 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 200 GD.getCtorType()); 201 else if (isa<CXXDestructorDecl>(GD.getDecl())) 202 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 203 GD.getDtorType()); 204 else if (isa<FunctionDecl>(GD.getDecl())) 205 return GetAddrOfFunction(GD); 206 else 207 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 208 } 209 210 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 211 /// given global variable. If Ty is non-null and if the global doesn't exist, 212 /// then it will be greated with the specified type instead of whatever the 213 /// normal requested type would be. 214 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 215 const llvm::Type *Ty = 0); 216 217 /// GetAddrOfFunction - Return the address of the given function. If Ty is 218 /// non-null, then this function will use the specified type if it has to 219 /// create it. 220 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, 221 const llvm::Type *Ty = 0); 222 223 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 224 /// for the given type. 225 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty); 226 227 /// GetAddrOfThunk - Get the address of the thunk for the given global decl. 228 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 229 230 /// GetWeakRefReference - Get a reference to the target of VD. 231 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 232 233 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 234 /// its base class. Returns null if the offset is 0. 235 llvm::Constant * 236 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 237 const CXXRecordDecl *BaseClassDecl); 238 239 /// GetStringForStringLiteral - Return the appropriate bytes for a string 240 /// literal, properly padded to match the literal type. If only the address of 241 /// a constant is needed consider using GetAddrOfConstantStringLiteral. 242 std::string GetStringForStringLiteral(const StringLiteral *E); 243 244 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 245 /// for the given string. 246 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 247 248 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 249 /// for the given string literal. 250 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 251 252 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 253 /// array for the given ObjCEncodeExpr node. 254 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 255 256 /// GetAddrOfConstantString - Returns a pointer to a character array 257 /// containing the literal. This contents are exactly that of the given 258 /// string, i.e. it will not be null terminated automatically; see 259 /// GetAddrOfConstantCString. Note that whether the result is actually a 260 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 261 /// 262 /// The result has pointer to array type. 263 /// 264 /// \param GlobalName If provided, the name to use for the global 265 /// (if one is created). 266 llvm::Constant *GetAddrOfConstantString(const std::string& str, 267 const char *GlobalName=0); 268 269 /// GetAddrOfConstantCString - Returns a pointer to a character array 270 /// containing the literal and a terminating '\0' character. The result has 271 /// pointer to array type. 272 /// 273 /// \param GlobalName If provided, the name to use for the global (if one is 274 /// created). 275 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 276 const char *GlobalName=0); 277 278 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 279 /// given type. 280 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 281 CXXCtorType Type); 282 283 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 284 /// given type. 285 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 286 CXXDtorType Type); 287 288 /// getBuiltinLibFunction - Given a builtin id for a function like 289 /// "__builtin_fabsf", return a Function* for "fabsf". 290 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 291 unsigned BuiltinID); 292 293 llvm::Function *getMemCpyFn(); 294 llvm::Function *getMemMoveFn(); 295 llvm::Function *getMemSetFn(); 296 llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0, 297 unsigned NumTys = 0); 298 299 /// EmitTopLevelDecl - Emit code for a single top level declaration. 300 void EmitTopLevelDecl(Decl *D); 301 302 /// AddUsedGlobal - Add a global which should be forced to be 303 /// present in the object file; these are emitted to the llvm.used 304 /// metadata global. 305 void AddUsedGlobal(llvm::GlobalValue *GV); 306 307 void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); } 308 309 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global 310 /// destructor function. 311 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object); 312 313 /// CreateRuntimeFunction - Create a new runtime function with the specified 314 /// type and name. 315 llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty, 316 llvm::StringRef Name); 317 /// CreateRuntimeVariable - Create a new runtime global variable with the 318 /// specified type and name. 319 llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty, 320 llvm::StringRef Name); 321 322 void UpdateCompletedType(const TagDecl *TD) { 323 // Make sure that this type is translated. 324 Types.UpdateCompletedType(TD); 325 } 326 327 /// EmitConstantExpr - Try to emit the given expression as a 328 /// constant; returns 0 if the expression cannot be emitted as a 329 /// constant. 330 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 331 CodeGenFunction *CGF = 0); 332 333 /// EmitNullConstant - Return the result of value-initializing the given 334 /// type, i.e. a null expression of the given type. This is usually, 335 /// but not always, an LLVM null constant. 336 llvm::Constant *EmitNullConstant(QualType T); 337 338 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 339 const AnnotateAttr *AA, unsigned LineNo); 340 341 llvm::Constant *EmitPointerToDataMember(const FieldDecl *FD); 342 343 /// ErrorUnsupported - Print out an error that codegen doesn't support the 344 /// specified stmt yet. 345 /// \param OmitOnError - If true, then this error should only be emitted if no 346 /// other errors have been reported. 347 void ErrorUnsupported(const Stmt *S, const char *Type, 348 bool OmitOnError=false); 349 350 /// ErrorUnsupported - Print out an error that codegen doesn't support the 351 /// specified decl yet. 352 /// \param OmitOnError - If true, then this error should only be emitted if no 353 /// other errors have been reported. 354 void ErrorUnsupported(const Decl *D, const char *Type, 355 bool OmitOnError=false); 356 357 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 358 /// function for the given decl and function info. This applies 359 /// attributes necessary for handling the ABI as well as user 360 /// specified attributes like section. 361 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 362 const CGFunctionInfo &FI); 363 364 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 365 /// (sext, zext, etc). 366 void SetLLVMFunctionAttributes(const Decl *D, 367 const CGFunctionInfo &Info, 368 llvm::Function *F); 369 370 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 371 /// which only apply to a function definintion. 372 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 373 374 /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used 375 /// as a return type. 376 bool ReturnTypeUsesSret(const CGFunctionInfo &FI); 377 378 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 379 /// use for a particular function type. 380 /// 381 /// \param Info - The function type information. 382 /// \param TargetDecl - The decl these attributes are being constructed 383 /// for. If supplied the attributes applied to this decl may contribute to the 384 /// function attributes and calling convention. 385 /// \param PAL [out] - On return, the attribute list to use. 386 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 387 void ConstructAttributeList(const CGFunctionInfo &Info, 388 const Decl *TargetDecl, 389 AttributeListType &PAL, 390 unsigned &CallingConv); 391 392 void getMangledName(MangleBuffer &Buffer, GlobalDecl D); 393 void getMangledName(MangleBuffer &Buffer, const NamedDecl *ND); 394 void getMangledCXXCtorName(MangleBuffer &Buffer, 395 const CXXConstructorDecl *D, 396 CXXCtorType Type); 397 void getMangledCXXDtorName(MangleBuffer &Buffer, 398 const CXXDestructorDecl *D, 399 CXXDtorType Type); 400 401 void EmitTentativeDefinition(const VarDecl *D); 402 403 enum GVALinkage { 404 GVA_Internal, 405 GVA_C99Inline, 406 GVA_CXXInline, 407 GVA_StrongExternal, 408 GVA_TemplateInstantiation, 409 GVA_ExplicitTemplateInstantiation 410 }; 411 412 llvm::GlobalVariable::LinkageTypes 413 getFunctionLinkage(const FunctionDecl *FD); 414 415 /// getVtableLinkage - Return the appropriate linkage for the vtable, VTT, 416 /// and type information of the given class. 417 static llvm::GlobalVariable::LinkageTypes 418 getVtableLinkage(const CXXRecordDecl *RD); 419 420 /// GetTargetTypeStoreSize - Return the store size, in character units, of 421 /// the given LLVM type. 422 CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const; 423 424 std::vector<const CXXRecordDecl*> DeferredVtables; 425 426private: 427 llvm::GlobalValue *GetGlobalValue(llvm::StringRef Ref); 428 429 llvm::Constant *GetOrCreateLLVMFunction(llvm::StringRef MangledName, 430 const llvm::Type *Ty, 431 GlobalDecl D); 432 llvm::Constant *GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 433 const llvm::PointerType *PTy, 434 const VarDecl *D); 435 436 /// SetCommonAttributes - Set attributes which are common to any 437 /// form of a global definition (alias, Objective-C method, 438 /// function, global variable). 439 /// 440 /// NOTE: This should only be called for definitions. 441 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 442 443 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 444 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 445 llvm::GlobalValue *GV); 446 447 /// SetFunctionAttributes - Set function attributes for a function 448 /// declaration. 449 void SetFunctionAttributes(GlobalDecl GD, 450 llvm::Function *F, 451 bool IsIncompleteFunction); 452 453 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 454 /// declarations are emitted lazily. 455 void EmitGlobal(GlobalDecl D); 456 457 void EmitGlobalDefinition(GlobalDecl D); 458 459 void EmitGlobalFunctionDefinition(GlobalDecl GD); 460 void EmitGlobalVarDefinition(const VarDecl *D); 461 void EmitAliasDefinition(GlobalDecl GD); 462 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 463 464 // C++ related functions. 465 466 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target); 467 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 468 469 void EmitNamespace(const NamespaceDecl *D); 470 void EmitLinkageSpec(const LinkageSpecDecl *D); 471 472 /// EmitCXXConstructors - Emit constructors (base, complete) from a 473 /// C++ constructor Decl. 474 void EmitCXXConstructors(const CXXConstructorDecl *D); 475 476 /// EmitCXXConstructor - Emit a single constructor with the given type from 477 /// a C++ constructor Decl. 478 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 479 480 /// EmitCXXDestructors - Emit destructors (base, complete) from a 481 /// C++ destructor Decl. 482 void EmitCXXDestructors(const CXXDestructorDecl *D); 483 484 /// EmitCXXDestructor - Emit a single destructor with the given type from 485 /// a C++ destructor Decl. 486 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 487 488 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals. 489 void EmitCXXGlobalInitFunc(); 490 491 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals. 492 void EmitCXXGlobalDtorFunc(); 493 494 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D); 495 496 // FIXME: Hardcoding priority here is gross. 497 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 498 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 499 500 /// EmitCtorList - Generates a global array of functions and priorities using 501 /// the given list and name. This array will have appending linkage and is 502 /// suitable for use as a LLVM constructor or destructor array. 503 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 504 505 void EmitAnnotations(void); 506 507 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the 508 /// given type. 509 void EmitFundamentalRTTIDescriptor(QualType Type); 510 511 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the 512 /// builtin types. 513 void EmitFundamentalRTTIDescriptors(); 514 515 /// EmitDeferred - Emit any needed decls for which code generation 516 /// was deferred. 517 void EmitDeferred(void); 518 519 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 520 /// references to global which may otherwise be optimized out. 521 void EmitLLVMUsed(void); 522 523 /// MayDeferGeneration - Determine if the given decl can be emitted 524 /// lazily; this is only relevant for definitions. The given decl 525 /// must be either a function or var decl. 526 bool MayDeferGeneration(const ValueDecl *D); 527}; 528} // end namespace CodeGen 529} // end namespace clang 530 531#endif 532