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