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/ABI.h" 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/GlobalDecl.h" 23 #include "clang/AST/Mangle.h" 24 #include "CGVTables.h" 25 #include "CodeGenTypes.h" 26 #include "llvm/Module.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/StringMap.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/Support/ValueHandle.h" 31 32 namespace llvm { 33 class Module; 34 class Constant; 35 class ConstantInt; 36 class Function; 37 class GlobalValue; 38 class TargetData; 39 class FunctionType; 40 class LLVMContext; 41 } 42 43 namespace clang { 44 class TargetCodeGenInfo; 45 class ASTContext; 46 class FunctionDecl; 47 class IdentifierInfo; 48 class ObjCMethodDecl; 49 class ObjCImplementationDecl; 50 class ObjCCategoryImplDecl; 51 class ObjCProtocolDecl; 52 class ObjCEncodeExpr; 53 class BlockExpr; 54 class CharUnits; 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 DiagnosticsEngine; 65 class AnnotateAttr; 66 class CXXDestructorDecl; 67 class MangleBuffer; 68 69 namespace CodeGen { 70 71 class CallArgList; 72 class CodeGenFunction; 73 class CodeGenTBAA; 74 class CGCXXABI; 75 class CGDebugInfo; 76 class CGObjCRuntime; 77 class CGOpenCLRuntime; 78 class CGCUDARuntime; 79 class BlockFieldFlags; 80 class FunctionArgList; 81 82 struct OrderGlobalInits { 83 unsigned int priority; 84 unsigned int lex_order; 85 OrderGlobalInits(unsigned int p, unsigned int l) 86 : priority(p), lex_order(l) {} 87 88 bool operator==(const OrderGlobalInits &RHS) const { 89 return priority == RHS.priority && 90 lex_order == RHS.lex_order; 91 } 92 93 bool operator<(const OrderGlobalInits &RHS) const { 94 if (priority < RHS.priority) 95 return true; 96 97 return priority == RHS.priority && lex_order < RHS.lex_order; 98 } 99 }; 100 101 struct CodeGenTypeCache { 102 /// void 103 llvm::Type *VoidTy; 104 105 /// i8, i16, i32, and i64 106 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty; 107 /// float, double 108 llvm::Type *FloatTy, *DoubleTy; 109 110 /// int 111 llvm::IntegerType *IntTy; 112 113 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size. 114 union { 115 llvm::IntegerType *IntPtrTy; 116 llvm::IntegerType *SizeTy; 117 llvm::IntegerType *PtrDiffTy; 118 }; 119 120 /// void* in address space 0 121 union { 122 llvm::PointerType *VoidPtrTy; 123 llvm::PointerType *Int8PtrTy; 124 }; 125 126 /// void** in address space 0 127 union { 128 llvm::PointerType *VoidPtrPtrTy; 129 llvm::PointerType *Int8PtrPtrTy; 130 }; 131 132 /// The width of a pointer into the generic address space. 133 unsigned char PointerWidthInBits; 134 135 /// The size and alignment of a pointer into the generic address 136 /// space. 137 union { 138 unsigned char PointerAlignInBytes; 139 unsigned char PointerSizeInBytes; 140 }; 141 }; 142 143 struct RREntrypoints { 144 RREntrypoints() { memset(this, 0, sizeof(*this)); } 145 /// void objc_autoreleasePoolPop(void*); 146 llvm::Constant *objc_autoreleasePoolPop; 147 148 /// void *objc_autoreleasePoolPush(void); 149 llvm::Constant *objc_autoreleasePoolPush; 150 }; 151 152 struct ARCEntrypoints { 153 ARCEntrypoints() { memset(this, 0, sizeof(*this)); } 154 155 /// id objc_autorelease(id); 156 llvm::Constant *objc_autorelease; 157 158 /// id objc_autoreleaseReturnValue(id); 159 llvm::Constant *objc_autoreleaseReturnValue; 160 161 /// void objc_copyWeak(id *dest, id *src); 162 llvm::Constant *objc_copyWeak; 163 164 /// void objc_destroyWeak(id*); 165 llvm::Constant *objc_destroyWeak; 166 167 /// id objc_initWeak(id*, id); 168 llvm::Constant *objc_initWeak; 169 170 /// id objc_loadWeak(id*); 171 llvm::Constant *objc_loadWeak; 172 173 /// id objc_loadWeakRetained(id*); 174 llvm::Constant *objc_loadWeakRetained; 175 176 /// void objc_moveWeak(id *dest, id *src); 177 llvm::Constant *objc_moveWeak; 178 179 /// id objc_retain(id); 180 llvm::Constant *objc_retain; 181 182 /// id objc_retainAutorelease(id); 183 llvm::Constant *objc_retainAutorelease; 184 185 /// id objc_retainAutoreleaseReturnValue(id); 186 llvm::Constant *objc_retainAutoreleaseReturnValue; 187 188 /// id objc_retainAutoreleasedReturnValue(id); 189 llvm::Constant *objc_retainAutoreleasedReturnValue; 190 191 /// id objc_retainBlock(id); 192 llvm::Constant *objc_retainBlock; 193 194 /// void objc_release(id); 195 llvm::Constant *objc_release; 196 197 /// id objc_storeStrong(id*, id); 198 llvm::Constant *objc_storeStrong; 199 200 /// id objc_storeWeak(id*, id); 201 llvm::Constant *objc_storeWeak; 202 203 /// A void(void) inline asm to use to mark that the return value of 204 /// a call will be immediately retain. 205 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 206 }; 207 208 /// CodeGenModule - This class organizes the cross-function state that is used 209 /// while generating LLVM code. 210 class CodeGenModule : public CodeGenTypeCache { 211 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT 212 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT 213 214 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList; 215 216 ASTContext &Context; 217 const LangOptions &Features; 218 const CodeGenOptions &CodeGenOpts; 219 llvm::Module &TheModule; 220 const llvm::TargetData &TheTargetData; 221 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 222 DiagnosticsEngine &Diags; 223 CGCXXABI &ABI; 224 CodeGenTypes Types; 225 CodeGenTBAA *TBAA; 226 227 /// VTables - Holds information about C++ vtables. 228 CodeGenVTables VTables; 229 friend class CodeGenVTables; 230 231 CGObjCRuntime* ObjCRuntime; 232 CGOpenCLRuntime* OpenCLRuntime; 233 CGCUDARuntime* CUDARuntime; 234 CGDebugInfo* DebugInfo; 235 ARCEntrypoints *ARCData; 236 RREntrypoints *RRData; 237 238 // WeakRefReferences - A set of references that have only been seen via 239 // a weakref so far. This is used to remove the weak of the reference if we ever 240 // see a direct reference or a definition. 241 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 242 243 /// DeferredDecls - This contains all the decls which have definitions but 244 /// which are deferred for emission and therefore should only be output if 245 /// they are actually used. If a decl is in this, then it is known to have 246 /// not been referenced yet. 247 llvm::StringMap<GlobalDecl> DeferredDecls; 248 249 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen 250 /// that *are* actually referenced. These get code generated when the module 251 /// is done. 252 std::vector<GlobalDecl> DeferredDeclsToEmit; 253 254 /// LLVMUsed - List of global values which are required to be 255 /// present in the object file; bitcast to i8*. This is used for 256 /// forcing visibility of symbols which may otherwise be optimized 257 /// out. 258 std::vector<llvm::WeakVH> LLVMUsed; 259 260 /// GlobalCtors - Store the list of global constructors and their respective 261 /// priorities to be emitted when the translation unit is complete. 262 CtorList GlobalCtors; 263 264 /// GlobalDtors - Store the list of global destructors and their respective 265 /// priorities to be emitted when the translation unit is complete. 266 CtorList GlobalDtors; 267 268 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names. 269 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames; 270 llvm::BumpPtrAllocator MangledNamesAllocator; 271 272 /// Global annotations. 273 std::vector<llvm::Constant*> Annotations; 274 275 /// Map used to get unique annotation strings. 276 llvm::StringMap<llvm::Constant*> AnnotationStrings; 277 278 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 279 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap; 280 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap; 281 282 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 283 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 284 285 /// CXXGlobalInits - Global variables with initializers that need to run 286 /// before main. 287 std::vector<llvm::Constant*> CXXGlobalInits; 288 289 /// When a C++ decl with an initializer is deferred, null is 290 /// appended to CXXGlobalInits, and the index of that null is placed 291 /// here so that the initializer will be performed in the correct 292 /// order. 293 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 294 295 /// - Global variables with initializers whose order of initialization 296 /// is set by init_priority attribute. 297 298 SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8> 299 PrioritizedCXXGlobalInits; 300 301 /// CXXGlobalDtors - Global destructor functions and arguments that need to 302 /// run on termination. 303 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors; 304 305 /// @name Cache for Objective-C runtime types 306 /// @{ 307 308 /// CFConstantStringClassRef - Cached reference to the class for constant 309 /// strings. This value has type int * but is actually an Obj-C class pointer. 310 llvm::Constant *CFConstantStringClassRef; 311 312 /// ConstantStringClassRef - Cached reference to the class for constant 313 /// strings. This value has type int * but is actually an Obj-C class pointer. 314 llvm::Constant *ConstantStringClassRef; 315 316 /// \brief The LLVM type corresponding to NSConstantString. 317 llvm::StructType *NSConstantStringType; 318 319 /// \brief The type used to describe the state of a fast enumeration in 320 /// Objective-C's for..in loop. 321 QualType ObjCFastEnumerationStateType; 322 323 /// @} 324 325 /// Lazily create the Objective-C runtime 326 void createObjCRuntime(); 327 328 void createOpenCLRuntime(); 329 void createCUDARuntime(); 330 331 bool isTriviallyRecursive(const FunctionDecl *F); 332 bool shouldEmitFunction(const FunctionDecl *F); 333 llvm::LLVMContext &VMContext; 334 335 /// @name Cache for Blocks Runtime Globals 336 /// @{ 337 338 llvm::Constant *NSConcreteGlobalBlock; 339 llvm::Constant *NSConcreteStackBlock; 340 341 llvm::Constant *BlockObjectAssign; 342 llvm::Constant *BlockObjectDispose; 343 344 llvm::Type *BlockDescriptorType; 345 llvm::Type *GenericBlockLiteralType; 346 347 struct { 348 int GlobalUniqueCount; 349 } Block; 350 351 /// @} 352 public: 353 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 354 llvm::Module &M, const llvm::TargetData &TD, 355 DiagnosticsEngine &Diags); 356 357 ~CodeGenModule(); 358 359 /// Release - Finalize LLVM code generation. 360 void Release(); 361 362 /// getObjCRuntime() - Return a reference to the configured 363 /// Objective-C runtime. 364 CGObjCRuntime &getObjCRuntime() { 365 if (!ObjCRuntime) createObjCRuntime(); 366 return *ObjCRuntime; 367 } 368 369 /// hasObjCRuntime() - Return true iff an Objective-C runtime has 370 /// been configured. 371 bool hasObjCRuntime() { return !!ObjCRuntime; } 372 373 /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime. 374 CGOpenCLRuntime &getOpenCLRuntime() { 375 assert(OpenCLRuntime != 0); 376 return *OpenCLRuntime; 377 } 378 379 /// getCUDARuntime() - Return a reference to the configured CUDA runtime. 380 CGCUDARuntime &getCUDARuntime() { 381 assert(CUDARuntime != 0); 382 return *CUDARuntime; 383 } 384 385 /// getCXXABI() - Return a reference to the configured C++ ABI. 386 CGCXXABI &getCXXABI() { return ABI; } 387 388 ARCEntrypoints &getARCEntrypoints() const { 389 assert(getLangOptions().ObjCAutoRefCount && ARCData != 0); 390 return *ARCData; 391 } 392 393 RREntrypoints &getRREntrypoints() const { 394 assert(RRData != 0); 395 return *RRData; 396 } 397 398 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) { 399 return StaticLocalDeclMap[VD]; 400 } 401 void setStaticLocalDeclAddress(const VarDecl *D, 402 llvm::GlobalVariable *GV) { 403 StaticLocalDeclMap[D] = GV; 404 } 405 406 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 407 return AtomicSetterHelperFnMap[Ty]; 408 } 409 void setAtomicSetterHelperFnMap(QualType Ty, 410 llvm::Constant *Fn) { 411 AtomicSetterHelperFnMap[Ty] = Fn; 412 } 413 414 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 415 return AtomicGetterHelperFnMap[Ty]; 416 } 417 void setAtomicGetterHelperFnMap(QualType Ty, 418 llvm::Constant *Fn) { 419 AtomicGetterHelperFnMap[Ty] = Fn; 420 } 421 422 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; } 423 424 ASTContext &getContext() const { return Context; } 425 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 426 const LangOptions &getLangOptions() const { return Features; } 427 llvm::Module &getModule() const { return TheModule; } 428 CodeGenTypes &getTypes() { return Types; } 429 CodeGenVTables &getVTables() { return VTables; } 430 VTableContext &getVTableContext() { return VTables.getVTableContext(); } 431 DiagnosticsEngine &getDiags() const { return Diags; } 432 const llvm::TargetData &getTargetData() const { return TheTargetData; } 433 const TargetInfo &getTarget() const { return Context.getTargetInfo(); } 434 llvm::LLVMContext &getLLVMContext() { return VMContext; } 435 const TargetCodeGenInfo &getTargetCodeGenInfo(); 436 bool isTargetDarwin() const; 437 438 bool shouldUseTBAA() const { return TBAA != 0; } 439 440 llvm::MDNode *getTBAAInfo(QualType QTy); 441 442 static void DecorateInstruction(llvm::Instruction *Inst, 443 llvm::MDNode *TBAAInfo); 444 445 /// getSize - Emit the given number of characters as a value of type size_t. 446 llvm::ConstantInt *getSize(CharUnits numChars); 447 448 /// setGlobalVisibility - Set the visibility for the given LLVM 449 /// GlobalValue. 450 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 451 452 /// TypeVisibilityKind - The kind of global variable that is passed to 453 /// setTypeVisibility 454 enum TypeVisibilityKind { 455 TVK_ForVTT, 456 TVK_ForVTable, 457 TVK_ForConstructionVTable, 458 TVK_ForRTTI, 459 TVK_ForRTTIName 460 }; 461 462 /// setTypeVisibility - Set the visibility for the given global 463 /// value which holds information about a type. 464 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D, 465 TypeVisibilityKind TVK) const; 466 467 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 468 switch (V) { 469 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 470 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 471 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 472 } 473 llvm_unreachable("unknown visibility!"); 474 } 475 476 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 477 if (isa<CXXConstructorDecl>(GD.getDecl())) 478 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 479 GD.getCtorType()); 480 else if (isa<CXXDestructorDecl>(GD.getDecl())) 481 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 482 GD.getDtorType()); 483 else if (isa<FunctionDecl>(GD.getDecl())) 484 return GetAddrOfFunction(GD); 485 else 486 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 487 } 488 489 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given 490 /// type. If a variable with a different type already exists then a new 491 /// variable with the right type will be created and all uses of the old 492 /// variable will be replaced with a bitcast to the new variable. 493 llvm::GlobalVariable * 494 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 495 llvm::GlobalValue::LinkageTypes Linkage); 496 497 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 498 /// given global variable. If Ty is non-null and if the global doesn't exist, 499 /// then it will be greated with the specified type instead of whatever the 500 /// normal requested type would be. 501 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 502 llvm::Type *Ty = 0); 503 504 505 /// GetAddrOfFunction - Return the address of the given function. If Ty is 506 /// non-null, then this function will use the specified type if it has to 507 /// create it. 508 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, 509 llvm::Type *Ty = 0, 510 bool ForVTable = false); 511 512 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 513 /// for the given type. 514 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 515 516 /// GetAddrOfThunk - Get the address of the thunk for the given global decl. 517 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 518 519 /// GetWeakRefReference - Get a reference to the target of VD. 520 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 521 522 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 523 /// a class. Returns null if the offset is 0. 524 llvm::Constant * 525 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 526 CastExpr::path_const_iterator PathBegin, 527 CastExpr::path_const_iterator PathEnd); 528 529 /// A pair of helper functions for a __block variable. 530 class ByrefHelpers : public llvm::FoldingSetNode { 531 public: 532 llvm::Constant *CopyHelper; 533 llvm::Constant *DisposeHelper; 534 535 /// The alignment of the field. This is important because 536 /// different offsets to the field within the byref struct need to 537 /// have different helper functions. 538 CharUnits Alignment; 539 540 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {} 541 virtual ~ByrefHelpers(); 542 543 void Profile(llvm::FoldingSetNodeID &id) const { 544 id.AddInteger(Alignment.getQuantity()); 545 profileImpl(id); 546 } 547 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 548 549 virtual bool needsCopy() const { return true; } 550 virtual void emitCopy(CodeGenFunction &CGF, 551 llvm::Value *dest, llvm::Value *src) = 0; 552 553 virtual bool needsDispose() const { return true; } 554 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0; 555 }; 556 557 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache; 558 559 /// getUniqueBlockCount - Fetches the global unique block count. 560 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 561 562 /// getBlockDescriptorType - Fetches the type of a generic block 563 /// descriptor. 564 llvm::Type *getBlockDescriptorType(); 565 566 /// getGenericBlockLiteralType - The type of a generic block literal. 567 llvm::Type *getGenericBlockLiteralType(); 568 569 /// GetAddrOfGlobalBlock - Gets the address of a block which 570 /// requires no captures. 571 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *); 572 573 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 574 /// for the given string. 575 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 576 577 /// GetAddrOfConstantString - Return a pointer to a constant NSString object 578 /// for the given string. Or a user defined String object as defined via 579 /// -fconstant-string-class=class_name option. 580 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal); 581 582 /// GetConstantArrayFromStringLiteral - Return a constant array for the given 583 /// string. 584 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 585 586 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 587 /// for the given string literal. 588 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 589 590 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 591 /// array for the given ObjCEncodeExpr node. 592 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 593 594 /// GetAddrOfConstantString - Returns a pointer to a character array 595 /// containing the literal. This contents are exactly that of the given 596 /// string, i.e. it will not be null terminated automatically; see 597 /// GetAddrOfConstantCString. Note that whether the result is actually a 598 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 599 /// 600 /// The result has pointer to array type. 601 /// 602 /// \param GlobalName If provided, the name to use for the global 603 /// (if one is created). 604 llvm::Constant *GetAddrOfConstantString(StringRef Str, 605 const char *GlobalName=0, 606 unsigned Alignment=1); 607 608 /// GetAddrOfConstantCString - Returns a pointer to a character array 609 /// containing the literal and a terminating '\0' character. The result has 610 /// pointer to array type. 611 /// 612 /// \param GlobalName If provided, the name to use for the global (if one is 613 /// created). 614 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 615 const char *GlobalName=0, 616 unsigned Alignment=1); 617 618 /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global 619 /// variable for the given file-scope compound literal expression. 620 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 621 622 /// \brief Retrieve the record type that describes the state of an 623 /// Objective-C fast enumeration loop (for..in). 624 QualType getObjCFastEnumerationStateType(); 625 626 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 627 /// given type. 628 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 629 CXXCtorType ctorType, 630 const CGFunctionInfo *fnInfo = 0); 631 632 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 633 /// given type. 634 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 635 CXXDtorType dtorType, 636 const CGFunctionInfo *fnInfo = 0); 637 638 /// getBuiltinLibFunction - Given a builtin id for a function like 639 /// "__builtin_fabsf", return a Function* for "fabsf". 640 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 641 unsigned BuiltinID); 642 643 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = 644 ArrayRef<llvm::Type*>()); 645 646 /// EmitTopLevelDecl - Emit code for a single top level declaration. 647 void EmitTopLevelDecl(Decl *D); 648 649 /// AddUsedGlobal - Add a global which should be forced to be 650 /// present in the object file; these are emitted to the llvm.used 651 /// metadata global. 652 void AddUsedGlobal(llvm::GlobalValue *GV); 653 654 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global 655 /// destructor function. 656 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) { 657 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object)); 658 } 659 660 /// CreateRuntimeFunction - Create a new runtime function with the specified 661 /// type and name. 662 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty, 663 StringRef Name, 664 llvm::Attributes ExtraAttrs = 665 llvm::Attribute::None); 666 /// CreateRuntimeVariable - Create a new runtime global variable with the 667 /// specified type and name. 668 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 669 StringRef Name); 670 671 ///@name Custom Blocks Runtime Interfaces 672 ///@{ 673 674 llvm::Constant *getNSConcreteGlobalBlock(); 675 llvm::Constant *getNSConcreteStackBlock(); 676 llvm::Constant *getBlockObjectAssign(); 677 llvm::Constant *getBlockObjectDispose(); 678 679 ///@} 680 681 // UpdateCompleteType - Make sure that this type is translated. 682 void UpdateCompletedType(const TagDecl *TD); 683 684 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 685 686 /// EmitConstantInit - Try to emit the initializer for the given declaration 687 /// as a constant; returns 0 if the expression cannot be emitted as a 688 /// constant. 689 llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0); 690 691 /// EmitConstantExpr - Try to emit the given expression as a 692 /// constant; returns 0 if the expression cannot be emitted as a 693 /// constant. 694 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 695 CodeGenFunction *CGF = 0); 696 697 /// EmitConstantValue - Try to emit the given constant value as a 698 /// constant; returns 0 if the value cannot be emitted as a constant. 699 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType, 700 CodeGenFunction *CGF = 0); 701 702 /// EmitNullConstant - Return the result of value-initializing the given 703 /// type, i.e. a null expression of the given type. This is usually, 704 /// but not always, an LLVM null constant. 705 llvm::Constant *EmitNullConstant(QualType T); 706 707 /// EmitNullConstantForBase - Return a null constant appropriate for 708 /// zero-initializing a base class with the given type. This is usually, 709 /// but not always, an LLVM null constant. 710 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 711 712 /// Error - Emit a general error that something can't be done. 713 void Error(SourceLocation loc, StringRef error); 714 715 /// ErrorUnsupported - Print out an error that codegen doesn't support the 716 /// specified stmt yet. 717 /// \param OmitOnError - If true, then this error should only be emitted if no 718 /// other errors have been reported. 719 void ErrorUnsupported(const Stmt *S, const char *Type, 720 bool OmitOnError=false); 721 722 /// ErrorUnsupported - Print out an error that codegen doesn't support the 723 /// specified decl yet. 724 /// \param OmitOnError - If true, then this error should only be emitted if no 725 /// other errors have been reported. 726 void ErrorUnsupported(const Decl *D, const char *Type, 727 bool OmitOnError=false); 728 729 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 730 /// function for the given decl and function info. This applies 731 /// attributes necessary for handling the ABI as well as user 732 /// specified attributes like section. 733 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 734 const CGFunctionInfo &FI); 735 736 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 737 /// (sext, zext, etc). 738 void SetLLVMFunctionAttributes(const Decl *D, 739 const CGFunctionInfo &Info, 740 llvm::Function *F); 741 742 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 743 /// which only apply to a function definintion. 744 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 745 746 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used 747 /// as a return type. 748 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 749 750 /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when 751 /// used as a return type. 752 bool ReturnTypeUsesFPRet(QualType ResultType); 753 754 /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when 755 /// used as a return type. 756 bool ReturnTypeUsesFP2Ret(QualType ResultType); 757 758 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 759 /// use for a particular function type. 760 /// 761 /// \param Info - The function type information. 762 /// \param TargetDecl - The decl these attributes are being constructed 763 /// for. If supplied the attributes applied to this decl may contribute to the 764 /// function attributes and calling convention. 765 /// \param PAL [out] - On return, the attribute list to use. 766 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 767 void ConstructAttributeList(const CGFunctionInfo &Info, 768 const Decl *TargetDecl, 769 AttributeListType &PAL, 770 unsigned &CallingConv); 771 772 StringRef getMangledName(GlobalDecl GD); 773 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 774 const BlockDecl *BD); 775 776 void EmitTentativeDefinition(const VarDecl *D); 777 778 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired); 779 780 llvm::GlobalVariable::LinkageTypes 781 getFunctionLinkage(const FunctionDecl *FD); 782 783 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) { 784 V->setLinkage(getFunctionLinkage(FD)); 785 } 786 787 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT, 788 /// and type information of the given class. 789 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 790 791 /// GetTargetTypeStoreSize - Return the store size, in character units, of 792 /// the given LLVM type. 793 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 794 795 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global 796 /// variable. 797 llvm::GlobalValue::LinkageTypes 798 GetLLVMLinkageVarDefinition(const VarDecl *D, 799 llvm::GlobalVariable *GV); 800 801 std::vector<const CXXRecordDecl*> DeferredVTables; 802 803 /// Emit all the global annotations. 804 void EmitGlobalAnnotations(); 805 806 /// Emit an annotation string. 807 llvm::Constant *EmitAnnotationString(llvm::StringRef Str); 808 809 /// Emit the annotation's translation unit. 810 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 811 812 /// Emit the annotation line number. 813 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 814 815 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 816 /// annotation information for a given GlobalValue. The annotation struct is 817 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 818 /// GlobalValue being annotated. The second field is the constant string 819 /// created from the AnnotateAttr's annotation. The third field is a constant 820 /// string containing the name of the translation unit. The fourth field is 821 /// the line number in the file of the annotated value declaration. 822 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 823 const AnnotateAttr *AA, 824 SourceLocation L); 825 826 /// Add global annotations that are set on D, for the global GV. Those 827 /// annotations are emitted during finalization of the LLVM code. 828 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 829 830 private: 831 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 832 833 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName, 834 llvm::Type *Ty, 835 GlobalDecl D, 836 bool ForVTable, 837 llvm::Attributes ExtraAttrs = 838 llvm::Attribute::None); 839 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 840 llvm::PointerType *PTy, 841 const VarDecl *D, 842 bool UnnamedAddr = false); 843 844 /// SetCommonAttributes - Set attributes which are common to any 845 /// form of a global definition (alias, Objective-C method, 846 /// function, global variable). 847 /// 848 /// NOTE: This should only be called for definitions. 849 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 850 851 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 852 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 853 llvm::GlobalValue *GV); 854 855 /// SetFunctionAttributes - Set function attributes for a function 856 /// declaration. 857 void SetFunctionAttributes(GlobalDecl GD, 858 llvm::Function *F, 859 bool IsIncompleteFunction); 860 861 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 862 /// declarations are emitted lazily. 863 void EmitGlobal(GlobalDecl D); 864 865 void EmitGlobalDefinition(GlobalDecl D); 866 867 void EmitGlobalFunctionDefinition(GlobalDecl GD); 868 void EmitGlobalVarDefinition(const VarDecl *D); 869 void EmitAliasDefinition(GlobalDecl GD); 870 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 871 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 872 873 // C++ related functions. 874 875 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target); 876 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 877 878 void EmitNamespace(const NamespaceDecl *D); 879 void EmitLinkageSpec(const LinkageSpecDecl *D); 880 881 /// EmitCXXConstructors - Emit constructors (base, complete) from a 882 /// C++ constructor Decl. 883 void EmitCXXConstructors(const CXXConstructorDecl *D); 884 885 /// EmitCXXConstructor - Emit a single constructor with the given type from 886 /// a C++ constructor Decl. 887 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 888 889 /// EmitCXXDestructors - Emit destructors (base, complete) from a 890 /// C++ destructor Decl. 891 void EmitCXXDestructors(const CXXDestructorDecl *D); 892 893 /// EmitCXXDestructor - Emit a single destructor with the given type from 894 /// a C++ destructor Decl. 895 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 896 897 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals. 898 void EmitCXXGlobalInitFunc(); 899 900 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals. 901 void EmitCXXGlobalDtorFunc(); 902 903 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 904 llvm::GlobalVariable *Addr); 905 906 // FIXME: Hardcoding priority here is gross. 907 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 908 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 909 910 /// EmitCtorList - Generates a global array of functions and priorities using 911 /// the given list and name. This array will have appending linkage and is 912 /// suitable for use as a LLVM constructor or destructor array. 913 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 914 915 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the 916 /// given type. 917 void EmitFundamentalRTTIDescriptor(QualType Type); 918 919 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the 920 /// builtin types. 921 void EmitFundamentalRTTIDescriptors(); 922 923 /// EmitDeferred - Emit any needed decls for which code generation 924 /// was deferred. 925 void EmitDeferred(void); 926 927 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 928 /// references to global which may otherwise be optimized out. 929 void EmitLLVMUsed(void); 930 931 void EmitDeclMetadata(); 932 933 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where 934 /// to emit the .gcno and .gcda files in a way that persists in .bc files. 935 void EmitCoverageFile(); 936 937 /// MayDeferGeneration - Determine if the given decl can be emitted 938 /// lazily; this is only relevant for definitions. The given decl 939 /// must be either a function or var decl. 940 bool MayDeferGeneration(const ValueDecl *D); 941 942 /// SimplifyPersonality - Check whether we can use a "simpler", more 943 /// core exceptions personality function. 944 void SimplifyPersonality(); 945 }; 946 } // end namespace CodeGen 947 } // end namespace clang 948 949 #endif 950