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