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 "CGVTables.h" 18 #include "CodeGenTypes.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 "clang/Basic/ABI.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Basic/Module.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/SetVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/StringMap.h" 31 #include "llvm/IR/CallingConv.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ValueHandle.h" 34 #include "llvm/Transforms/Utils/SpecialCaseList.h" 35 36 namespace llvm { 37 class Module; 38 class Constant; 39 class ConstantInt; 40 class Function; 41 class GlobalValue; 42 class DataLayout; 43 class FunctionType; 44 class LLVMContext; 45 class IndexedInstrProfReader; 46 } 47 48 namespace clang { 49 class TargetCodeGenInfo; 50 class ASTContext; 51 class AtomicType; 52 class FunctionDecl; 53 class IdentifierInfo; 54 class ObjCMethodDecl; 55 class ObjCImplementationDecl; 56 class ObjCCategoryImplDecl; 57 class ObjCProtocolDecl; 58 class ObjCEncodeExpr; 59 class BlockExpr; 60 class CharUnits; 61 class Decl; 62 class Expr; 63 class Stmt; 64 class InitListExpr; 65 class StringLiteral; 66 class NamedDecl; 67 class ValueDecl; 68 class VarDecl; 69 class LangOptions; 70 class CodeGenOptions; 71 class DiagnosticsEngine; 72 class AnnotateAttr; 73 class CXXDestructorDecl; 74 class MangleBuffer; 75 class Module; 76 77 namespace CodeGen { 78 79 class CallArgList; 80 class CodeGenFunction; 81 class CodeGenTBAA; 82 class CGCXXABI; 83 class CGDebugInfo; 84 class CGObjCRuntime; 85 class CGOpenCLRuntime; 86 class CGOpenMPRuntime; 87 class CGCUDARuntime; 88 class BlockFieldFlags; 89 class FunctionArgList; 90 91 struct OrderGlobalInits { 92 unsigned int priority; 93 unsigned int lex_order; 94 OrderGlobalInits(unsigned int p, unsigned int l) 95 : priority(p), lex_order(l) {} 96 97 bool operator==(const OrderGlobalInits &RHS) const { 98 return priority == RHS.priority && lex_order == RHS.lex_order; 99 } 100 101 bool operator<(const OrderGlobalInits &RHS) const { 102 return std::tie(priority, lex_order) < 103 std::tie(RHS.priority, RHS.lex_order); 104 } 105 }; 106 107 struct CodeGenTypeCache { 108 /// void 109 llvm::Type *VoidTy; 110 111 /// i8, i16, i32, and i64 112 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty; 113 /// float, double 114 llvm::Type *FloatTy, *DoubleTy; 115 116 /// int 117 llvm::IntegerType *IntTy; 118 119 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size. 120 union { 121 llvm::IntegerType *IntPtrTy; 122 llvm::IntegerType *SizeTy; 123 llvm::IntegerType *PtrDiffTy; 124 }; 125 126 /// void* in address space 0 127 union { 128 llvm::PointerType *VoidPtrTy; 129 llvm::PointerType *Int8PtrTy; 130 }; 131 132 /// void** in address space 0 133 union { 134 llvm::PointerType *VoidPtrPtrTy; 135 llvm::PointerType *Int8PtrPtrTy; 136 }; 137 138 /// The width of a pointer into the generic address space. 139 unsigned char PointerWidthInBits; 140 141 /// The size and alignment of a pointer into the generic address 142 /// space. 143 union { 144 unsigned char PointerAlignInBytes; 145 unsigned char PointerSizeInBytes; 146 unsigned char SizeSizeInBytes; // sizeof(size_t) 147 }; 148 149 llvm::CallingConv::ID RuntimeCC; 150 llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; } 151 }; 152 153 struct RREntrypoints { 154 RREntrypoints() { memset(this, 0, sizeof(*this)); } 155 /// void objc_autoreleasePoolPop(void*); 156 llvm::Constant *objc_autoreleasePoolPop; 157 158 /// void *objc_autoreleasePoolPush(void); 159 llvm::Constant *objc_autoreleasePoolPush; 160 }; 161 162 struct ARCEntrypoints { 163 ARCEntrypoints() { memset(this, 0, sizeof(*this)); } 164 165 /// id objc_autorelease(id); 166 llvm::Constant *objc_autorelease; 167 168 /// id objc_autoreleaseReturnValue(id); 169 llvm::Constant *objc_autoreleaseReturnValue; 170 171 /// void objc_copyWeak(id *dest, id *src); 172 llvm::Constant *objc_copyWeak; 173 174 /// void objc_destroyWeak(id*); 175 llvm::Constant *objc_destroyWeak; 176 177 /// id objc_initWeak(id*, id); 178 llvm::Constant *objc_initWeak; 179 180 /// id objc_loadWeak(id*); 181 llvm::Constant *objc_loadWeak; 182 183 /// id objc_loadWeakRetained(id*); 184 llvm::Constant *objc_loadWeakRetained; 185 186 /// void objc_moveWeak(id *dest, id *src); 187 llvm::Constant *objc_moveWeak; 188 189 /// id objc_retain(id); 190 llvm::Constant *objc_retain; 191 192 /// id objc_retainAutorelease(id); 193 llvm::Constant *objc_retainAutorelease; 194 195 /// id objc_retainAutoreleaseReturnValue(id); 196 llvm::Constant *objc_retainAutoreleaseReturnValue; 197 198 /// id objc_retainAutoreleasedReturnValue(id); 199 llvm::Constant *objc_retainAutoreleasedReturnValue; 200 201 /// id objc_retainBlock(id); 202 llvm::Constant *objc_retainBlock; 203 204 /// void objc_release(id); 205 llvm::Constant *objc_release; 206 207 /// id objc_storeStrong(id*, id); 208 llvm::Constant *objc_storeStrong; 209 210 /// id objc_storeWeak(id*, id); 211 llvm::Constant *objc_storeWeak; 212 213 /// A void(void) inline asm to use to mark that the return value of 214 /// a call will be immediately retain. 215 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 216 217 /// void clang.arc.use(...); 218 llvm::Constant *clang_arc_use; 219 }; 220 221 /// This class records statistics on instrumentation based profiling. 222 struct InstrProfStats { 223 InstrProfStats() : Visited(0), Missing(0), Mismatched(0) {} 224 bool isOutOfDate() { return Missing || Mismatched; } 225 uint32_t Visited; 226 uint32_t Missing; 227 uint32_t Mismatched; 228 }; 229 230 /// This class organizes the cross-function state that is used while generating 231 /// LLVM code. 232 class CodeGenModule : public CodeGenTypeCache { 233 CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION; 234 void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION; 235 236 struct Structor { 237 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {} 238 Structor(int Priority, llvm::Constant *Initializer, 239 llvm::Constant *AssociatedData) 240 : Priority(Priority), Initializer(Initializer), 241 AssociatedData(AssociatedData) {} 242 int Priority; 243 llvm::Constant *Initializer; 244 llvm::Constant *AssociatedData; 245 }; 246 247 typedef std::vector<Structor> CtorList; 248 249 ASTContext &Context; 250 const LangOptions &LangOpts; 251 const CodeGenOptions &CodeGenOpts; 252 llvm::Module &TheModule; 253 DiagnosticsEngine &Diags; 254 const llvm::DataLayout &TheDataLayout; 255 const TargetInfo &Target; 256 std::unique_ptr<CGCXXABI> ABI; 257 llvm::LLVMContext &VMContext; 258 259 CodeGenTBAA *TBAA; 260 261 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 262 263 // This should not be moved earlier, since its initialization depends on some 264 // of the previous reference members being already initialized and also checks 265 // if TheTargetCodeGenInfo is NULL 266 CodeGenTypes Types; 267 268 /// Holds information about C++ vtables. 269 CodeGenVTables VTables; 270 271 CGObjCRuntime* ObjCRuntime; 272 CGOpenCLRuntime* OpenCLRuntime; 273 CGOpenMPRuntime* OpenMPRuntime; 274 CGCUDARuntime* CUDARuntime; 275 CGDebugInfo* DebugInfo; 276 ARCEntrypoints *ARCData; 277 llvm::MDNode *NoObjCARCExceptionsMetadata; 278 RREntrypoints *RRData; 279 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader; 280 InstrProfStats PGOStats; 281 282 // A set of references that have only been seen via a weakref so far. This is 283 // used to remove the weak of the reference if we ever see a direct reference 284 // or a definition. 285 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 286 287 /// This contains all the decls which have definitions but/ which are deferred 288 /// for emission and therefore should only be output if they are actually 289 /// used. If a decl is in this, then it is known to have not been referenced 290 /// yet. 291 llvm::StringMap<GlobalDecl> DeferredDecls; 292 293 /// This is a list of deferred decls which we have seen that *are* actually 294 /// referenced. These get code generated when the module is done. 295 struct DeferredGlobal { 296 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {} 297 llvm::AssertingVH<llvm::GlobalValue> GV; 298 GlobalDecl GD; 299 }; 300 std::vector<DeferredGlobal> DeferredDeclsToEmit; 301 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) { 302 DeferredDeclsToEmit.push_back(DeferredGlobal(GV, GD)); 303 } 304 305 /// List of alias we have emitted. Used to make sure that what they point to 306 /// is defined once we get to the end of the of the translation unit. 307 std::vector<GlobalDecl> Aliases; 308 309 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy; 310 ReplacementsTy Replacements; 311 312 /// A queue of (optional) vtables to consider emitting. 313 std::vector<const CXXRecordDecl*> DeferredVTables; 314 315 /// List of global values which are required to be present in the object file; 316 /// bitcast to i8*. This is used for forcing visibility of symbols which may 317 /// otherwise be optimized out. 318 std::vector<llvm::WeakVH> LLVMUsed; 319 std::vector<llvm::WeakVH> LLVMCompilerUsed; 320 321 /// Store the list of global constructors and their respective priorities to 322 /// be emitted when the translation unit is complete. 323 CtorList GlobalCtors; 324 325 /// Store the list of global destructors and their respective priorities to be 326 /// emitted when the translation unit is complete. 327 CtorList GlobalDtors; 328 329 /// A map of canonical GlobalDecls to their mangled names. 330 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames; 331 llvm::BumpPtrAllocator MangledNamesAllocator; 332 333 /// Global annotations. 334 std::vector<llvm::Constant*> Annotations; 335 336 /// Map used to get unique annotation strings. 337 llvm::StringMap<llvm::Constant*> AnnotationStrings; 338 339 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 340 341 llvm::StringMap<llvm::GlobalVariable *> Constant1ByteStringMap; 342 llvm::StringMap<llvm::GlobalVariable *> Constant2ByteStringMap; 343 llvm::StringMap<llvm::GlobalVariable *> Constant4ByteStringMap; 344 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap; 345 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap; 346 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap; 347 348 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 349 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 350 351 /// Map used to get unique type descriptor constants for sanitizers. 352 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap; 353 354 /// Map used to track internal linkage functions declared within 355 /// extern "C" regions. 356 typedef llvm::MapVector<IdentifierInfo *, 357 llvm::GlobalValue *> StaticExternCMap; 358 StaticExternCMap StaticExternCValues; 359 360 /// \brief thread_local variables defined or used in this TU. 361 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> > 362 CXXThreadLocals; 363 364 /// \brief thread_local variables with initializers that need to run 365 /// before any thread_local variable in this TU is odr-used. 366 std::vector<llvm::Constant*> CXXThreadLocalInits; 367 368 /// Global variables with initializers that need to run before main. 369 std::vector<llvm::Constant*> CXXGlobalInits; 370 371 /// When a C++ decl with an initializer is deferred, null is 372 /// appended to CXXGlobalInits, and the index of that null is placed 373 /// here so that the initializer will be performed in the correct 374 /// order. 375 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 376 377 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData; 378 379 struct GlobalInitPriorityCmp { 380 bool operator()(const GlobalInitData &LHS, 381 const GlobalInitData &RHS) const { 382 return LHS.first.priority < RHS.first.priority; 383 } 384 }; 385 386 /// Global variables with initializers whose order of initialization is set by 387 /// init_priority attribute. 388 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits; 389 390 /// Global destructor functions and arguments that need to run on termination. 391 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors; 392 393 /// \brief The complete set of modules that has been imported. 394 llvm::SetVector<clang::Module *> ImportedModules; 395 396 /// \brief A vector of metadata strings. 397 SmallVector<llvm::Value *, 16> LinkerOptionsMetadata; 398 399 /// @name Cache for Objective-C runtime types 400 /// @{ 401 402 /// Cached reference to the class for constant strings. This value has type 403 /// int * but is actually an Obj-C class pointer. 404 llvm::WeakVH CFConstantStringClassRef; 405 406 /// Cached reference to the class for constant strings. This value has type 407 /// int * but is actually an Obj-C class pointer. 408 llvm::WeakVH ConstantStringClassRef; 409 410 /// \brief The LLVM type corresponding to NSConstantString. 411 llvm::StructType *NSConstantStringType; 412 413 /// \brief The type used to describe the state of a fast enumeration in 414 /// Objective-C's for..in loop. 415 QualType ObjCFastEnumerationStateType; 416 417 /// @} 418 419 /// Lazily create the Objective-C runtime 420 void createObjCRuntime(); 421 422 void createOpenCLRuntime(); 423 void createOpenMPRuntime(); 424 void createCUDARuntime(); 425 426 bool isTriviallyRecursive(const FunctionDecl *F); 427 bool shouldEmitFunction(GlobalDecl GD); 428 429 /// @name Cache for Blocks Runtime Globals 430 /// @{ 431 432 llvm::Constant *NSConcreteGlobalBlock; 433 llvm::Constant *NSConcreteStackBlock; 434 435 llvm::Constant *BlockObjectAssign; 436 llvm::Constant *BlockObjectDispose; 437 438 llvm::Type *BlockDescriptorType; 439 llvm::Type *GenericBlockLiteralType; 440 441 struct { 442 int GlobalUniqueCount; 443 } Block; 444 445 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>) 446 llvm::Constant *LifetimeStartFn; 447 448 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>) 449 llvm::Constant *LifetimeEndFn; 450 451 GlobalDecl initializedGlobalDecl; 452 453 std::unique_ptr<llvm::SpecialCaseList> SanitizerBlacklist; 454 455 const SanitizerOptions &SanOpts; 456 457 /// @} 458 public: 459 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 460 llvm::Module &M, const llvm::DataLayout &TD, 461 DiagnosticsEngine &Diags); 462 463 ~CodeGenModule(); 464 465 void clear(); 466 467 /// Finalize LLVM code generation. 468 void Release(); 469 470 /// Return a reference to the configured Objective-C runtime. 471 CGObjCRuntime &getObjCRuntime() { 472 if (!ObjCRuntime) createObjCRuntime(); 473 return *ObjCRuntime; 474 } 475 476 /// Return true iff an Objective-C runtime has been configured. 477 bool hasObjCRuntime() { return !!ObjCRuntime; } 478 479 /// Return a reference to the configured OpenCL runtime. 480 CGOpenCLRuntime &getOpenCLRuntime() { 481 assert(OpenCLRuntime != nullptr); 482 return *OpenCLRuntime; 483 } 484 485 /// Return a reference to the configured OpenMP runtime. 486 CGOpenMPRuntime &getOpenMPRuntime() { 487 assert(OpenMPRuntime != nullptr); 488 return *OpenMPRuntime; 489 } 490 491 /// Return a reference to the configured CUDA runtime. 492 CGCUDARuntime &getCUDARuntime() { 493 assert(CUDARuntime != nullptr); 494 return *CUDARuntime; 495 } 496 497 ARCEntrypoints &getARCEntrypoints() const { 498 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr); 499 return *ARCData; 500 } 501 502 RREntrypoints &getRREntrypoints() const { 503 assert(RRData != nullptr); 504 return *RRData; 505 } 506 507 InstrProfStats &getPGOStats() { return PGOStats; } 508 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); } 509 510 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { 511 return StaticLocalDeclMap[D]; 512 } 513 void setStaticLocalDeclAddress(const VarDecl *D, 514 llvm::Constant *C) { 515 StaticLocalDeclMap[D] = C; 516 } 517 518 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { 519 return StaticLocalDeclGuardMap[D]; 520 } 521 void setStaticLocalDeclGuardAddress(const VarDecl *D, 522 llvm::GlobalVariable *C) { 523 StaticLocalDeclGuardMap[D] = C; 524 } 525 526 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 527 return AtomicSetterHelperFnMap[Ty]; 528 } 529 void setAtomicSetterHelperFnMap(QualType Ty, 530 llvm::Constant *Fn) { 531 AtomicSetterHelperFnMap[Ty] = Fn; 532 } 533 534 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 535 return AtomicGetterHelperFnMap[Ty]; 536 } 537 void setAtomicGetterHelperFnMap(QualType Ty, 538 llvm::Constant *Fn) { 539 AtomicGetterHelperFnMap[Ty] = Fn; 540 } 541 542 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) { 543 return TypeDescriptorMap[Ty]; 544 } 545 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) { 546 TypeDescriptorMap[Ty] = C; 547 } 548 549 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; } 550 551 llvm::MDNode *getNoObjCARCExceptionsMetadata() { 552 if (!NoObjCARCExceptionsMetadata) 553 NoObjCARCExceptionsMetadata = 554 llvm::MDNode::get(getLLVMContext(), 555 SmallVector<llvm::Value*,1>()); 556 return NoObjCARCExceptionsMetadata; 557 } 558 559 ASTContext &getContext() const { return Context; } 560 const LangOptions &getLangOpts() const { return LangOpts; } 561 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 562 llvm::Module &getModule() const { return TheModule; } 563 DiagnosticsEngine &getDiags() const { return Diags; } 564 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; } 565 const TargetInfo &getTarget() const { return Target; } 566 CGCXXABI &getCXXABI() const { return *ABI; } 567 llvm::LLVMContext &getLLVMContext() { return VMContext; } 568 569 bool shouldUseTBAA() const { return TBAA != nullptr; } 570 571 const TargetCodeGenInfo &getTargetCodeGenInfo(); 572 573 CodeGenTypes &getTypes() { return Types; } 574 575 CodeGenVTables &getVTables() { return VTables; } 576 577 ItaniumVTableContext &getItaniumVTableContext() { 578 return VTables.getItaniumVTableContext(); 579 } 580 581 MicrosoftVTableContext &getMicrosoftVTableContext() { 582 return VTables.getMicrosoftVTableContext(); 583 } 584 585 llvm::MDNode *getTBAAInfo(QualType QTy); 586 llvm::MDNode *getTBAAInfoForVTablePtr(); 587 llvm::MDNode *getTBAAStructInfo(QualType QTy); 588 /// Return the MDNode in the type DAG for the given struct type. 589 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy); 590 /// Return the path-aware tag for given base type, access node and offset. 591 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN, 592 uint64_t O); 593 594 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor); 595 596 bool isPaddedAtomicType(QualType type); 597 bool isPaddedAtomicType(const AtomicType *type); 598 599 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag 600 /// is the same as the type. For struct-path aware TBAA, the tag 601 /// is different from the type: base type, access type and offset. 602 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 603 void DecorateInstruction(llvm::Instruction *Inst, 604 llvm::MDNode *TBAAInfo, 605 bool ConvertTypeToTag = true); 606 607 /// Emit the given number of characters as a value of type size_t. 608 llvm::ConstantInt *getSize(CharUnits numChars); 609 610 /// Set the visibility for the given LLVM GlobalValue. 611 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 612 613 /// Set the TLS mode for the given LLVM GlobalVariable for the thread-local 614 /// variable declaration D. 615 void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const; 616 617 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 618 switch (V) { 619 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 620 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 621 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 622 } 623 llvm_unreachable("unknown visibility!"); 624 } 625 626 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 627 if (isa<CXXConstructorDecl>(GD.getDecl())) 628 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 629 GD.getCtorType()); 630 else if (isa<CXXDestructorDecl>(GD.getDecl())) 631 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 632 GD.getDtorType()); 633 else if (isa<FunctionDecl>(GD.getDecl())) 634 return GetAddrOfFunction(GD); 635 else 636 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 637 } 638 639 /// Will return a global variable of the given type. If a variable with a 640 /// different type already exists then a new variable with the right type 641 /// will be created and all uses of the old variable will be replaced with a 642 /// bitcast to the new variable. 643 llvm::GlobalVariable * 644 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 645 llvm::GlobalValue::LinkageTypes Linkage); 646 647 /// Return the address space of the underlying global variable for D, as 648 /// determined by its declaration. Normally this is the same as the address 649 /// space of D's type, but in CUDA, address spaces are associated with 650 /// declarations, not types. 651 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace); 652 653 /// Return the llvm::Constant for the address of the given global variable. 654 /// If Ty is non-null and if the global doesn't exist, then it will be greated 655 /// with the specified type instead of whatever the normal requested type 656 /// would be. 657 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 658 llvm::Type *Ty = nullptr); 659 660 /// Return the address of the given function. If Ty is non-null, then this 661 /// function will use the specified type if it has to create it. 662 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0, 663 bool ForVTable = false, 664 bool DontDefer = false); 665 666 /// Get the address of the RTTI descriptor for the given type. 667 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 668 669 /// Get the address of a uuid descriptor . 670 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E); 671 672 /// Get the address of the thunk for the given global decl. 673 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 674 675 /// Get a reference to the target of VD. 676 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 677 678 /// Returns the offset from a derived class to a class. Returns null if the 679 /// offset is 0. 680 llvm::Constant * 681 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 682 CastExpr::path_const_iterator PathBegin, 683 CastExpr::path_const_iterator PathEnd); 684 685 /// A pair of helper functions for a __block variable. 686 class ByrefHelpers : public llvm::FoldingSetNode { 687 public: 688 llvm::Constant *CopyHelper; 689 llvm::Constant *DisposeHelper; 690 691 /// The alignment of the field. This is important because 692 /// different offsets to the field within the byref struct need to 693 /// have different helper functions. 694 CharUnits Alignment; 695 696 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {} 697 virtual ~ByrefHelpers(); 698 699 void Profile(llvm::FoldingSetNodeID &id) const { 700 id.AddInteger(Alignment.getQuantity()); 701 profileImpl(id); 702 } 703 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 704 705 virtual bool needsCopy() const { return true; } 706 virtual void emitCopy(CodeGenFunction &CGF, 707 llvm::Value *dest, llvm::Value *src) = 0; 708 709 virtual bool needsDispose() const { return true; } 710 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0; 711 }; 712 713 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache; 714 715 /// Fetches the global unique block count. 716 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 717 718 /// Fetches the type of a generic block descriptor. 719 llvm::Type *getBlockDescriptorType(); 720 721 /// The type of a generic block literal. 722 llvm::Type *getGenericBlockLiteralType(); 723 724 /// \brief Gets or a creats a Microsoft TypeDescriptor. 725 llvm::Constant *getMSTypeDescriptor(QualType Ty); 726 /// \brief Gets or a creats a Microsoft CompleteObjectLocator. 727 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD, 728 const VPtrInfo *Info); 729 730 /// Gets the address of a block which requires no captures. 731 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *); 732 733 /// Return a pointer to a constant CFString object for the given string. 734 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 735 736 /// Return a pointer to a constant NSString object for the given string. Or a 737 /// user defined String object as defined via 738 /// -fconstant-string-class=class_name option. 739 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal); 740 741 /// Return a constant array for the given string. 742 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 743 744 /// Return a pointer to a constant array for the given string literal. 745 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 746 747 /// Return a pointer to a constant array for the given ObjCEncodeExpr node. 748 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 749 750 /// Returns a pointer to a character array containing the literal. This 751 /// contents are exactly that of the given string, i.e. it will not be null 752 /// terminated automatically; see GetAddrOfConstantCString. Note that whether 753 /// the result is actually a pointer to an LLVM constant depends on 754 /// Feature.WriteableStrings. 755 /// 756 /// The result has pointer to array type. 757 /// 758 /// \param GlobalName If provided, the name to use for the global 759 /// (if one is created). 760 llvm::Constant *GetAddrOfConstantString(StringRef Str, 761 const char *GlobalName=nullptr, 762 unsigned Alignment=0); 763 764 /// Returns a pointer to a character array containing the literal and a 765 /// terminating '\0' character. The result has pointer to array type. 766 /// 767 /// \param GlobalName If provided, the name to use for the global (if one is 768 /// created). 769 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 770 const char *GlobalName=nullptr, 771 unsigned Alignment=0); 772 773 /// Returns a pointer to a constant global variable for the given file-scope 774 /// compound literal expression. 775 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 776 777 /// \brief Returns a pointer to a global variable representing a temporary 778 /// with static or thread storage duration. 779 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, 780 const Expr *Inner); 781 782 /// \brief Retrieve the record type that describes the state of an 783 /// Objective-C fast enumeration loop (for..in). 784 QualType getObjCFastEnumerationStateType(); 785 786 /// Return the address of the constructor of the given type. 787 llvm::GlobalValue * 788 GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, CXXCtorType ctorType, 789 const CGFunctionInfo *fnInfo = nullptr, 790 bool DontDefer = false); 791 792 /// Return the address of the constructor of the given type. 793 llvm::GlobalValue * 794 GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 795 CXXDtorType dtorType, 796 const CGFunctionInfo *fnInfo = nullptr, 797 llvm::FunctionType *fnType = nullptr, 798 bool DontDefer = false); 799 800 /// Given a builtin id for a function like "__builtin_fabsf", return a 801 /// Function* for "fabsf". 802 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 803 unsigned BuiltinID); 804 805 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None); 806 807 /// Emit code for a single top level declaration. 808 void EmitTopLevelDecl(Decl *D); 809 810 /// Tell the consumer that this variable has been instantiated. 811 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD); 812 813 /// \brief If the declaration has internal linkage but is inside an 814 /// extern "C" linkage specification, prepare to emit an alias for it 815 /// to the expected name. 816 template<typename SomeDecl> 817 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV); 818 819 /// Add a global to a list to be added to the llvm.used metadata. 820 void addUsedGlobal(llvm::GlobalValue *GV); 821 822 /// Add a global to a list to be added to the llvm.compiler.used metadata. 823 void addCompilerUsedGlobal(llvm::GlobalValue *GV); 824 825 /// Add a destructor and object to add to the C++ global destructor function. 826 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) { 827 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object)); 828 } 829 830 /// Create a new runtime function with the specified type and name. 831 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty, 832 StringRef Name, 833 llvm::AttributeSet ExtraAttrs = 834 llvm::AttributeSet()); 835 /// Create a new runtime global variable with the specified type and name. 836 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 837 StringRef Name); 838 839 ///@name Custom Blocks Runtime Interfaces 840 ///@{ 841 842 llvm::Constant *getNSConcreteGlobalBlock(); 843 llvm::Constant *getNSConcreteStackBlock(); 844 llvm::Constant *getBlockObjectAssign(); 845 llvm::Constant *getBlockObjectDispose(); 846 847 ///@} 848 849 llvm::Constant *getLLVMLifetimeStartFn(); 850 llvm::Constant *getLLVMLifetimeEndFn(); 851 852 // Make sure that this type is translated. 853 void UpdateCompletedType(const TagDecl *TD); 854 855 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 856 857 /// Try to emit the initializer for the given declaration as a constant; 858 /// returns 0 if the expression cannot be emitted as a constant. 859 llvm::Constant *EmitConstantInit(const VarDecl &D, 860 CodeGenFunction *CGF = nullptr); 861 862 /// Try to emit the given expression as a constant; returns 0 if the 863 /// expression cannot be emitted as a constant. 864 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 865 CodeGenFunction *CGF = nullptr); 866 867 /// Emit the given constant value as a constant, in the type's scalar 868 /// representation. 869 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType, 870 CodeGenFunction *CGF = nullptr); 871 872 /// Emit the given constant value as a constant, in the type's memory 873 /// representation. 874 llvm::Constant *EmitConstantValueForMemory(const APValue &Value, 875 QualType DestType, 876 CodeGenFunction *CGF = nullptr); 877 878 /// Return the result of value-initializing the given type, i.e. a null 879 /// expression of the given type. This is usually, but not always, an LLVM 880 /// null constant. 881 llvm::Constant *EmitNullConstant(QualType T); 882 883 /// Return a null constant appropriate for zero-initializing a base class with 884 /// the given type. This is usually, but not always, an LLVM null constant. 885 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 886 887 /// Emit a general error that something can't be done. 888 void Error(SourceLocation loc, StringRef error); 889 890 /// Print out an error that codegen doesn't support the specified stmt yet. 891 void ErrorUnsupported(const Stmt *S, const char *Type); 892 893 /// Print out an error that codegen doesn't support the specified decl yet. 894 void ErrorUnsupported(const Decl *D, const char *Type); 895 896 /// Set the attributes on the LLVM function for the given decl and function 897 /// info. This applies attributes necessary for handling the ABI as well as 898 /// user specified attributes like section. 899 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 900 const CGFunctionInfo &FI); 901 902 /// Set the LLVM function attributes (sext, zext, etc). 903 void SetLLVMFunctionAttributes(const Decl *D, 904 const CGFunctionInfo &Info, 905 llvm::Function *F); 906 907 /// Set the LLVM function attributes which only apply to a function 908 /// definintion. 909 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 910 911 /// Return true iff the given type uses 'sret' when used as a return type. 912 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 913 914 /// Return true iff the given type uses an argument slot when 'sret' is used 915 /// as a return type. 916 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI); 917 918 /// Return true iff the given type uses 'fpret' when used as a return type. 919 bool ReturnTypeUsesFPRet(QualType ResultType); 920 921 /// Return true iff the given type uses 'fp2ret' when used as a return type. 922 bool ReturnTypeUsesFP2Ret(QualType ResultType); 923 924 /// Get the LLVM attributes and calling convention to use for a particular 925 /// function type. 926 /// 927 /// \param Info - The function type information. 928 /// \param TargetDecl - The decl these attributes are being constructed 929 /// for. If supplied the attributes applied to this decl may contribute to the 930 /// function attributes and calling convention. 931 /// \param PAL [out] - On return, the attribute list to use. 932 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 933 void ConstructAttributeList(const CGFunctionInfo &Info, 934 const Decl *TargetDecl, 935 AttributeListType &PAL, 936 unsigned &CallingConv, 937 bool AttrOnCallSite); 938 939 StringRef getMangledName(GlobalDecl GD); 940 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 941 const BlockDecl *BD); 942 943 void EmitTentativeDefinition(const VarDecl *D); 944 945 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired); 946 947 /// Emit the RTTI descriptors for the builtin types. 948 void EmitFundamentalRTTIDescriptors(); 949 950 /// \brief Appends Opts to the "Linker Options" metadata value. 951 void AppendLinkerOptions(StringRef Opts); 952 953 /// \brief Appends a detect mismatch command to the linker options. 954 void AddDetectMismatch(StringRef Name, StringRef Value); 955 956 /// \brief Appends a dependent lib to the "Linker Options" metadata value. 957 void AddDependentLib(StringRef Lib); 958 959 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); 960 961 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) { 962 F->setLinkage(getFunctionLinkage(GD)); 963 } 964 965 /// \brief Returns the appropriate linkage for the TypeInfo struct for a type. 966 llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(QualType Ty); 967 968 /// Return the appropriate linkage for the vtable, VTT, and type information 969 /// of the given class. 970 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 971 972 /// Return the store size, in character units, of the given LLVM type. 973 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 974 975 /// Returns LLVM linkage for a declarator. 976 llvm::GlobalValue::LinkageTypes 977 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, 978 bool IsConstantVariable); 979 980 /// Returns LLVM linkage for a declarator. 981 llvm::GlobalValue::LinkageTypes 982 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant); 983 984 /// Emit all the global annotations. 985 void EmitGlobalAnnotations(); 986 987 /// Emit an annotation string. 988 llvm::Constant *EmitAnnotationString(StringRef Str); 989 990 /// Emit the annotation's translation unit. 991 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 992 993 /// Emit the annotation line number. 994 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 995 996 /// Generate the llvm::ConstantStruct which contains the annotation 997 /// information for a given GlobalValue. The annotation struct is 998 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 999 /// GlobalValue being annotated. The second field is the constant string 1000 /// created from the AnnotateAttr's annotation. The third field is a constant 1001 /// string containing the name of the translation unit. The fourth field is 1002 /// the line number in the file of the annotated value declaration. 1003 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 1004 const AnnotateAttr *AA, 1005 SourceLocation L); 1006 1007 /// Add global annotations that are set on D, for the global GV. Those 1008 /// annotations are emitted during finalization of the LLVM code. 1009 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 1010 1011 const llvm::SpecialCaseList &getSanitizerBlacklist() const { 1012 return *SanitizerBlacklist; 1013 } 1014 1015 const SanitizerOptions &getSanOpts() const { return SanOpts; } 1016 1017 void addDeferredVTable(const CXXRecordDecl *RD) { 1018 DeferredVTables.push_back(RD); 1019 } 1020 1021 /// Emit code for a singal global function or var decl. Forward declarations 1022 /// are emitted lazily. 1023 void EmitGlobal(GlobalDecl D); 1024 1025 private: 1026 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 1027 1028 llvm::Constant * 1029 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D, 1030 bool ForVTable, bool DontDefer = false, 1031 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet()); 1032 1033 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 1034 llvm::PointerType *PTy, 1035 const VarDecl *D); 1036 1037 /// Set attributes which are common to any form of a global definition (alias, 1038 /// Objective-C method, function, global variable). 1039 /// 1040 /// NOTE: This should only be called for definitions. 1041 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 1042 1043 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO); 1044 1045 /// Set attributes for a global definition. 1046 void setFunctionDefinitionAttributes(const FunctionDecl *D, 1047 llvm::Function *F); 1048 1049 /// Set function attributes for a function declaration. 1050 void SetFunctionAttributes(GlobalDecl GD, 1051 llvm::Function *F, 1052 bool IsIncompleteFunction); 1053 1054 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr); 1055 1056 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1057 void EmitGlobalVarDefinition(const VarDecl *D); 1058 void EmitAliasDefinition(GlobalDecl GD); 1059 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 1060 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 1061 1062 // C++ related functions. 1063 1064 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target, 1065 bool InEveryTU); 1066 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 1067 1068 void EmitNamespace(const NamespaceDecl *D); 1069 void EmitLinkageSpec(const LinkageSpecDecl *D); 1070 void CompleteDIClassType(const CXXMethodDecl* D); 1071 1072 /// Emit a single constructor with the given type from a C++ constructor Decl. 1073 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 1074 1075 /// Emit a single destructor with the given type from a C++ destructor Decl. 1076 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 1077 1078 /// \brief Emit the function that initializes C++ thread_local variables. 1079 void EmitCXXThreadLocalInitFunc(); 1080 1081 /// Emit the function that initializes C++ globals. 1082 void EmitCXXGlobalInitFunc(); 1083 1084 /// Emit the function that destroys C++ globals. 1085 void EmitCXXGlobalDtorFunc(); 1086 1087 /// Emit the function that initializes the specified global (if PerformInit is 1088 /// true) and registers its destructor. 1089 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 1090 llvm::GlobalVariable *Addr, 1091 bool PerformInit); 1092 1093 // FIXME: Hardcoding priority here is gross. 1094 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535, 1095 llvm::Constant *AssociatedData = 0); 1096 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535); 1097 1098 /// Generates a global array of functions and priorities using the given list 1099 /// and name. This array will have appending linkage and is suitable for use 1100 /// as a LLVM constructor or destructor array. 1101 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 1102 1103 /// Emit the RTTI descriptors for the given type. 1104 void EmitFundamentalRTTIDescriptor(QualType Type); 1105 1106 /// Emit any needed decls for which code generation was deferred. 1107 void EmitDeferred(); 1108 1109 /// Call replaceAllUsesWith on all pairs in Replacements. 1110 void applyReplacements(); 1111 1112 void checkAliases(); 1113 1114 /// Emit any vtables which we deferred and still have a use for. 1115 void EmitDeferredVTables(); 1116 1117 /// Emit the llvm.used and llvm.compiler.used metadata. 1118 void emitLLVMUsed(); 1119 1120 /// \brief Emit the link options introduced by imported modules. 1121 void EmitModuleLinkOptions(); 1122 1123 /// \brief Emit aliases for internal-linkage declarations inside "C" language 1124 /// linkage specifications, giving them the "expected" name where possible. 1125 void EmitStaticExternCAliases(); 1126 1127 void EmitDeclMetadata(); 1128 1129 /// \brief Emit the Clang version as llvm.ident metadata. 1130 void EmitVersionIdentMetadata(); 1131 1132 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and 1133 /// .gcda files in a way that persists in .bc files. 1134 void EmitCoverageFile(); 1135 1136 /// Emits the initializer for a uuidof string. 1137 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType); 1138 1139 /// Determine if the given decl can be emitted lazily; this is only relevant 1140 /// for definitions. The given decl must be either a function or var decl. 1141 bool MayDeferGeneration(const ValueDecl *D); 1142 1143 /// Check whether we can use a "simpler", more core exceptions personality 1144 /// function. 1145 void SimplifyPersonality(); 1146 }; 1147 } // end namespace CodeGen 1148 } // end namespace clang 1149 1150 #endif 1151