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