1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is the internal per-translation-unit state used for llvm translation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 15 16 #include "CGVTables.h" 17 #include "CodeGenTypeCache.h" 18 #include "CodeGenTypes.h" 19 #include "SanitizerMetadata.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclOpenMP.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 "clang/Basic/SanitizerBlacklist.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Basic/XRayLists.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 OpenMPIRBuilder; 49 class IndexedInstrProfReader; 50 } 51 52 namespace clang { 53 class ASTContext; 54 class AtomicType; 55 class FunctionDecl; 56 class IdentifierInfo; 57 class ObjCMethodDecl; 58 class ObjCImplementationDecl; 59 class ObjCCategoryImplDecl; 60 class ObjCProtocolDecl; 61 class ObjCEncodeExpr; 62 class BlockExpr; 63 class CharUnits; 64 class Decl; 65 class Expr; 66 class Stmt; 67 class InitListExpr; 68 class StringLiteral; 69 class NamedDecl; 70 class ValueDecl; 71 class VarDecl; 72 class LangOptions; 73 class CodeGenOptions; 74 class HeaderSearchOptions; 75 class PreprocessorOptions; 76 class DiagnosticsEngine; 77 class AnnotateAttr; 78 class CXXDestructorDecl; 79 class Module; 80 class CoverageSourceInfo; 81 class TargetAttr; 82 class InitSegAttr; 83 struct ParsedTargetAttr; 84 85 namespace CodeGen { 86 87 class CallArgList; 88 class CodeGenFunction; 89 class CodeGenTBAA; 90 class CGCXXABI; 91 class CGDebugInfo; 92 class CGObjCRuntime; 93 class CGOpenCLRuntime; 94 class CGOpenMPRuntime; 95 class CGCUDARuntime; 96 class BlockFieldFlags; 97 class FunctionArgList; 98 class CoverageMappingModuleGen; 99 class TargetCodeGenInfo; 100 101 enum ForDefinition_t : bool { 102 NotForDefinition = false, 103 ForDefinition = true 104 }; 105 106 struct OrderGlobalInits { 107 unsigned int priority; 108 unsigned int lex_order; 109 OrderGlobalInits(unsigned int p, unsigned int l) 110 : priority(p), lex_order(l) {} 111 112 bool operator==(const OrderGlobalInits &RHS) const { 113 return priority == RHS.priority && lex_order == RHS.lex_order; 114 } 115 116 bool operator<(const OrderGlobalInits &RHS) const { 117 return std::tie(priority, lex_order) < 118 std::tie(RHS.priority, RHS.lex_order); 119 } 120 }; 121 122 struct ObjCEntrypoints { 123 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); } 124 125 /// void objc_alloc(id); 126 llvm::FunctionCallee objc_alloc; 127 128 /// void objc_allocWithZone(id); 129 llvm::FunctionCallee objc_allocWithZone; 130 131 /// void objc_alloc_init(id); 132 llvm::FunctionCallee objc_alloc_init; 133 134 /// void objc_autoreleasePoolPop(void*); 135 llvm::FunctionCallee objc_autoreleasePoolPop; 136 137 /// void objc_autoreleasePoolPop(void*); 138 /// Note this method is used when we are using exception handling 139 llvm::FunctionCallee objc_autoreleasePoolPopInvoke; 140 141 /// void *objc_autoreleasePoolPush(void); 142 llvm::Function *objc_autoreleasePoolPush; 143 144 /// id objc_autorelease(id); 145 llvm::Function *objc_autorelease; 146 147 /// id objc_autorelease(id); 148 /// Note this is the runtime method not the intrinsic. 149 llvm::FunctionCallee objc_autoreleaseRuntimeFunction; 150 151 /// id objc_autoreleaseReturnValue(id); 152 llvm::Function *objc_autoreleaseReturnValue; 153 154 /// void objc_copyWeak(id *dest, id *src); 155 llvm::Function *objc_copyWeak; 156 157 /// void objc_destroyWeak(id*); 158 llvm::Function *objc_destroyWeak; 159 160 /// id objc_initWeak(id*, id); 161 llvm::Function *objc_initWeak; 162 163 /// id objc_loadWeak(id*); 164 llvm::Function *objc_loadWeak; 165 166 /// id objc_loadWeakRetained(id*); 167 llvm::Function *objc_loadWeakRetained; 168 169 /// void objc_moveWeak(id *dest, id *src); 170 llvm::Function *objc_moveWeak; 171 172 /// id objc_retain(id); 173 llvm::Function *objc_retain; 174 175 /// id objc_retain(id); 176 /// Note this is the runtime method not the intrinsic. 177 llvm::FunctionCallee objc_retainRuntimeFunction; 178 179 /// id objc_retainAutorelease(id); 180 llvm::Function *objc_retainAutorelease; 181 182 /// id objc_retainAutoreleaseReturnValue(id); 183 llvm::Function *objc_retainAutoreleaseReturnValue; 184 185 /// id objc_retainAutoreleasedReturnValue(id); 186 llvm::Function *objc_retainAutoreleasedReturnValue; 187 188 /// id objc_retainBlock(id); 189 llvm::Function *objc_retainBlock; 190 191 /// void objc_release(id); 192 llvm::Function *objc_release; 193 194 /// void objc_release(id); 195 /// Note this is the runtime method not the intrinsic. 196 llvm::FunctionCallee objc_releaseRuntimeFunction; 197 198 /// void objc_storeStrong(id*, id); 199 llvm::Function *objc_storeStrong; 200 201 /// id objc_storeWeak(id*, id); 202 llvm::Function *objc_storeWeak; 203 204 /// id objc_unsafeClaimAutoreleasedReturnValue(id); 205 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue; 206 207 /// A void(void) inline asm to use to mark that the return value of 208 /// a call will be immediately retain. 209 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 210 211 /// void clang.arc.use(...); 212 llvm::Function *clang_arc_use; 213 }; 214 215 /// This class records statistics on instrumentation based profiling. 216 class InstrProfStats { 217 uint32_t VisitedInMainFile; 218 uint32_t MissingInMainFile; 219 uint32_t Visited; 220 uint32_t Missing; 221 uint32_t Mismatched; 222 223 public: 224 InstrProfStats() 225 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0), 226 Mismatched(0) {} 227 /// Record that we've visited a function and whether or not that function was 228 /// in the main source file. 229 void addVisited(bool MainFile) { 230 if (MainFile) 231 ++VisitedInMainFile; 232 ++Visited; 233 } 234 /// Record that a function we've visited has no profile data. 235 void addMissing(bool MainFile) { 236 if (MainFile) 237 ++MissingInMainFile; 238 ++Missing; 239 } 240 /// Record that a function we've visited has mismatched profile data. 241 void addMismatched(bool MainFile) { ++Mismatched; } 242 /// Whether or not the stats we've gathered indicate any potential problems. 243 bool hasDiagnostics() { return Missing || Mismatched; } 244 /// Report potential problems we've found to \c Diags. 245 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile); 246 }; 247 248 /// A pair of helper functions for a __block variable. 249 class BlockByrefHelpers : public llvm::FoldingSetNode { 250 // MSVC requires this type to be complete in order to process this 251 // header. 252 public: 253 llvm::Constant *CopyHelper; 254 llvm::Constant *DisposeHelper; 255 256 /// The alignment of the field. This is important because 257 /// different offsets to the field within the byref struct need to 258 /// have different helper functions. 259 CharUnits Alignment; 260 261 BlockByrefHelpers(CharUnits alignment) 262 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {} 263 BlockByrefHelpers(const BlockByrefHelpers &) = default; 264 virtual ~BlockByrefHelpers(); 265 266 void Profile(llvm::FoldingSetNodeID &id) const { 267 id.AddInteger(Alignment.getQuantity()); 268 profileImpl(id); 269 } 270 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 271 272 virtual bool needsCopy() const { return true; } 273 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0; 274 275 virtual bool needsDispose() const { return true; } 276 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0; 277 }; 278 279 /// This class organizes the cross-function state that is used while generating 280 /// LLVM code. 281 class CodeGenModule : public CodeGenTypeCache { 282 CodeGenModule(const CodeGenModule &) = delete; 283 void operator=(const CodeGenModule &) = delete; 284 285 public: 286 struct Structor { 287 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {} 288 Structor(int Priority, llvm::Constant *Initializer, 289 llvm::Constant *AssociatedData) 290 : Priority(Priority), Initializer(Initializer), 291 AssociatedData(AssociatedData) {} 292 int Priority; 293 llvm::Constant *Initializer; 294 llvm::Constant *AssociatedData; 295 }; 296 297 typedef std::vector<Structor> CtorList; 298 299 private: 300 ASTContext &Context; 301 const LangOptions &LangOpts; 302 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info. 303 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info. 304 const CodeGenOptions &CodeGenOpts; 305 unsigned NumAutoVarInit = 0; 306 llvm::Module &TheModule; 307 DiagnosticsEngine &Diags; 308 const TargetInfo &Target; 309 std::unique_ptr<CGCXXABI> ABI; 310 llvm::LLVMContext &VMContext; 311 312 std::unique_ptr<CodeGenTBAA> TBAA; 313 314 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo; 315 316 // This should not be moved earlier, since its initialization depends on some 317 // of the previous reference members being already initialized and also checks 318 // if TheTargetCodeGenInfo is NULL 319 CodeGenTypes Types; 320 321 /// Holds information about C++ vtables. 322 CodeGenVTables VTables; 323 324 std::unique_ptr<CGObjCRuntime> ObjCRuntime; 325 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime; 326 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime; 327 std::unique_ptr<llvm::OpenMPIRBuilder> OMPBuilder; 328 std::unique_ptr<CGCUDARuntime> CUDARuntime; 329 std::unique_ptr<CGDebugInfo> DebugInfo; 330 std::unique_ptr<ObjCEntrypoints> ObjCData; 331 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr; 332 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader; 333 InstrProfStats PGOStats; 334 std::unique_ptr<llvm::SanitizerStatReport> SanStats; 335 336 // A set of references that have only been seen via a weakref so far. This is 337 // used to remove the weak of the reference if we ever see a direct reference 338 // or a definition. 339 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 340 341 /// This contains all the decls which have definitions but/ which are deferred 342 /// for emission and therefore should only be output if they are actually 343 /// used. If a decl is in this, then it is known to have not been referenced 344 /// yet. 345 std::map<StringRef, GlobalDecl> DeferredDecls; 346 347 /// This is a list of deferred decls which we have seen that *are* actually 348 /// referenced. These get code generated when the module is done. 349 std::vector<GlobalDecl> DeferredDeclsToEmit; 350 void addDeferredDeclToEmit(GlobalDecl GD) { 351 DeferredDeclsToEmit.emplace_back(GD); 352 } 353 354 /// List of alias we have emitted. Used to make sure that what they point to 355 /// is defined once we get to the end of the of the translation unit. 356 std::vector<GlobalDecl> Aliases; 357 358 /// List of multiversion functions that have to be emitted. Used to make sure 359 /// we properly emit the iFunc. 360 std::vector<GlobalDecl> MultiVersionFuncs; 361 362 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy; 363 ReplacementsTy Replacements; 364 365 /// List of global values to be replaced with something else. Used when we 366 /// want to replace a GlobalValue but can't identify it by its mangled name 367 /// anymore (because the name is already taken). 368 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8> 369 GlobalValReplacements; 370 371 /// Variables for which we've emitted globals containing their constant 372 /// values along with the corresponding globals, for opportunistic reuse. 373 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants; 374 375 /// Set of global decls for which we already diagnosed mangled name conflict. 376 /// Required to not issue a warning (on a mangling conflict) multiple times 377 /// for the same decl. 378 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions; 379 380 /// A queue of (optional) vtables to consider emitting. 381 std::vector<const CXXRecordDecl*> DeferredVTables; 382 383 /// A queue of (optional) vtables that may be emitted opportunistically. 384 std::vector<const CXXRecordDecl *> OpportunisticVTables; 385 386 /// List of global values which are required to be present in the object file; 387 /// bitcast to i8*. This is used for forcing visibility of symbols which may 388 /// otherwise be optimized out. 389 std::vector<llvm::WeakTrackingVH> LLVMUsed; 390 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed; 391 392 /// Store the list of global constructors and their respective priorities to 393 /// be emitted when the translation unit is complete. 394 CtorList GlobalCtors; 395 396 /// Store the list of global destructors and their respective priorities to be 397 /// emitted when the translation unit is complete. 398 CtorList GlobalDtors; 399 400 /// A unique trailing identifier as a part of sinit/sterm function when 401 /// UseSinitAndSterm of CXXABI is set as true. 402 std::string GlobalUniqueModuleId; 403 404 /// An ordered map of canonical GlobalDecls to their mangled names. 405 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames; 406 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings; 407 408 // An ordered map of canonical GlobalDecls paired with the cpu-index for 409 // cpu-specific name manglings. 410 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef> 411 CPUSpecificMangledDeclNames; 412 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator> 413 CPUSpecificManglings; 414 415 /// Global annotations. 416 std::vector<llvm::Constant*> Annotations; 417 418 /// Map used to get unique annotation strings. 419 llvm::StringMap<llvm::Constant*> AnnotationStrings; 420 421 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap; 422 423 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap; 424 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap; 425 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap; 426 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap; 427 428 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 429 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 430 431 /// Map used to get unique type descriptor constants for sanitizers. 432 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap; 433 434 /// Map used to track internal linkage functions declared within 435 /// extern "C" regions. 436 typedef llvm::MapVector<IdentifierInfo *, 437 llvm::GlobalValue *> StaticExternCMap; 438 StaticExternCMap StaticExternCValues; 439 440 /// thread_local variables defined or used in this TU. 441 std::vector<const VarDecl *> CXXThreadLocals; 442 443 /// thread_local variables with initializers that need to run 444 /// before any thread_local variable in this TU is odr-used. 445 std::vector<llvm::Function *> CXXThreadLocalInits; 446 std::vector<const VarDecl *> CXXThreadLocalInitVars; 447 448 /// Global variables with initializers that need to run before main. 449 std::vector<llvm::Function *> CXXGlobalInits; 450 451 /// When a C++ decl with an initializer is deferred, null is 452 /// appended to CXXGlobalInits, and the index of that null is placed 453 /// here so that the initializer will be performed in the correct 454 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure 455 /// that we don't re-emit the initializer. 456 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 457 458 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData; 459 460 struct GlobalInitPriorityCmp { 461 bool operator()(const GlobalInitData &LHS, 462 const GlobalInitData &RHS) const { 463 return LHS.first.priority < RHS.first.priority; 464 } 465 }; 466 467 /// Global variables with initializers whose order of initialization is set by 468 /// init_priority attribute. 469 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits; 470 471 /// Global destructor functions and arguments that need to run on termination. 472 /// When UseSinitAndSterm is set, it instead contains sterm finalizer 473 /// functions, which also run on unloading a shared library. 474 std::vector< 475 std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>> 476 CXXGlobalDtorsOrStermFinalizers; 477 478 /// The complete set of modules that has been imported. 479 llvm::SetVector<clang::Module *> ImportedModules; 480 481 /// The set of modules for which the module initializers 482 /// have been emitted. 483 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers; 484 485 /// A vector of metadata strings for linker options. 486 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata; 487 488 /// A vector of metadata strings for dependent libraries for ELF. 489 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries; 490 491 /// @name Cache for Objective-C runtime types 492 /// @{ 493 494 /// Cached reference to the class for constant strings. This value has type 495 /// int * but is actually an Obj-C class pointer. 496 llvm::WeakTrackingVH CFConstantStringClassRef; 497 498 /// The type used to describe the state of a fast enumeration in 499 /// Objective-C's for..in loop. 500 QualType ObjCFastEnumerationStateType; 501 502 /// @} 503 504 /// Lazily create the Objective-C runtime 505 void createObjCRuntime(); 506 507 void createOpenCLRuntime(); 508 void createOpenMPRuntime(); 509 void createCUDARuntime(); 510 511 bool isTriviallyRecursive(const FunctionDecl *F); 512 bool shouldEmitFunction(GlobalDecl GD); 513 bool shouldOpportunisticallyEmitVTables(); 514 /// Map used to be sure we don't emit the same CompoundLiteral twice. 515 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *> 516 EmittedCompoundLiterals; 517 518 /// Map of the global blocks we've emitted, so that we don't have to re-emit 519 /// them if the constexpr evaluator gets aggressive. 520 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks; 521 522 /// @name Cache for Blocks Runtime Globals 523 /// @{ 524 525 llvm::Constant *NSConcreteGlobalBlock = nullptr; 526 llvm::Constant *NSConcreteStackBlock = nullptr; 527 528 llvm::FunctionCallee BlockObjectAssign = nullptr; 529 llvm::FunctionCallee BlockObjectDispose = nullptr; 530 531 llvm::Type *BlockDescriptorType = nullptr; 532 llvm::Type *GenericBlockLiteralType = nullptr; 533 534 struct { 535 int GlobalUniqueCount; 536 } Block; 537 538 GlobalDecl initializedGlobalDecl; 539 540 /// @} 541 542 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>) 543 llvm::Function *LifetimeStartFn = nullptr; 544 545 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>) 546 llvm::Function *LifetimeEndFn = nullptr; 547 548 std::unique_ptr<SanitizerMetadata> SanitizerMD; 549 550 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls; 551 552 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping; 553 554 /// Mapping from canonical types to their metadata identifiers. We need to 555 /// maintain this mapping because identifiers may be formed from distinct 556 /// MDNodes. 557 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap; 558 MetadataTypeMap MetadataIdMap; 559 MetadataTypeMap VirtualMetadataIdMap; 560 MetadataTypeMap GeneralizedMetadataIdMap; 561 562 public: 563 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts, 564 const PreprocessorOptions &ppopts, 565 const CodeGenOptions &CodeGenOpts, llvm::Module &M, 566 DiagnosticsEngine &Diags, 567 CoverageSourceInfo *CoverageInfo = nullptr); 568 569 ~CodeGenModule(); 570 571 void clear(); 572 573 /// Finalize LLVM code generation. 574 void Release(); 575 576 /// Return true if we should emit location information for expressions. 577 bool getExpressionLocationsEnabled() const; 578 579 /// Return a reference to the configured Objective-C runtime. 580 CGObjCRuntime &getObjCRuntime() { 581 if (!ObjCRuntime) createObjCRuntime(); 582 return *ObjCRuntime; 583 } 584 585 /// Return true iff an Objective-C runtime has been configured. 586 bool hasObjCRuntime() { return !!ObjCRuntime; } 587 588 /// Return a reference to the configured OpenCL runtime. 589 CGOpenCLRuntime &getOpenCLRuntime() { 590 assert(OpenCLRuntime != nullptr); 591 return *OpenCLRuntime; 592 } 593 594 /// Return a reference to the configured OpenMP runtime. 595 CGOpenMPRuntime &getOpenMPRuntime() { 596 assert(OpenMPRuntime != nullptr); 597 return *OpenMPRuntime; 598 } 599 600 /// Return a pointer to the configured OpenMPIRBuilder, if any. 601 llvm::OpenMPIRBuilder *getOpenMPIRBuilder() { return OMPBuilder.get(); } 602 603 /// Return a reference to the configured CUDA runtime. 604 CGCUDARuntime &getCUDARuntime() { 605 assert(CUDARuntime != nullptr); 606 return *CUDARuntime; 607 } 608 609 ObjCEntrypoints &getObjCEntrypoints() const { 610 assert(ObjCData != nullptr); 611 return *ObjCData; 612 } 613 614 // Version checking function, used to implement ObjC's @available: 615 // i32 @__isOSVersionAtLeast(i32, i32, i32) 616 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr; 617 618 InstrProfStats &getPGOStats() { return PGOStats; } 619 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); } 620 621 CoverageMappingModuleGen *getCoverageMapping() const { 622 return CoverageMapping.get(); 623 } 624 625 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { 626 return StaticLocalDeclMap[D]; 627 } 628 void setStaticLocalDeclAddress(const VarDecl *D, 629 llvm::Constant *C) { 630 StaticLocalDeclMap[D] = C; 631 } 632 633 llvm::Constant * 634 getOrCreateStaticVarDecl(const VarDecl &D, 635 llvm::GlobalValue::LinkageTypes Linkage); 636 637 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { 638 return StaticLocalDeclGuardMap[D]; 639 } 640 void setStaticLocalDeclGuardAddress(const VarDecl *D, 641 llvm::GlobalVariable *C) { 642 StaticLocalDeclGuardMap[D] = C; 643 } 644 645 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, 646 CharUnits Align); 647 648 bool lookupRepresentativeDecl(StringRef MangledName, 649 GlobalDecl &Result) const; 650 651 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 652 return AtomicSetterHelperFnMap[Ty]; 653 } 654 void setAtomicSetterHelperFnMap(QualType Ty, 655 llvm::Constant *Fn) { 656 AtomicSetterHelperFnMap[Ty] = Fn; 657 } 658 659 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 660 return AtomicGetterHelperFnMap[Ty]; 661 } 662 void setAtomicGetterHelperFnMap(QualType Ty, 663 llvm::Constant *Fn) { 664 AtomicGetterHelperFnMap[Ty] = Fn; 665 } 666 667 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) { 668 return TypeDescriptorMap[Ty]; 669 } 670 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) { 671 TypeDescriptorMap[Ty] = C; 672 } 673 674 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); } 675 676 llvm::MDNode *getNoObjCARCExceptionsMetadata() { 677 if (!NoObjCARCExceptionsMetadata) 678 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None); 679 return NoObjCARCExceptionsMetadata; 680 } 681 682 ASTContext &getContext() const { return Context; } 683 const LangOptions &getLangOpts() const { return LangOpts; } 684 const HeaderSearchOptions &getHeaderSearchOpts() 685 const { return HeaderSearchOpts; } 686 const PreprocessorOptions &getPreprocessorOpts() 687 const { return PreprocessorOpts; } 688 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 689 llvm::Module &getModule() const { return TheModule; } 690 DiagnosticsEngine &getDiags() const { return Diags; } 691 const llvm::DataLayout &getDataLayout() const { 692 return TheModule.getDataLayout(); 693 } 694 const TargetInfo &getTarget() const { return Target; } 695 const llvm::Triple &getTriple() const { return Target.getTriple(); } 696 bool supportsCOMDAT() const; 697 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO); 698 699 CGCXXABI &getCXXABI() const { return *ABI; } 700 llvm::LLVMContext &getLLVMContext() { return VMContext; } 701 702 bool shouldUseTBAA() const { return TBAA != nullptr; } 703 704 const TargetCodeGenInfo &getTargetCodeGenInfo(); 705 706 CodeGenTypes &getTypes() { return Types; } 707 708 CodeGenVTables &getVTables() { return VTables; } 709 710 ItaniumVTableContext &getItaniumVTableContext() { 711 return VTables.getItaniumVTableContext(); 712 } 713 714 MicrosoftVTableContext &getMicrosoftVTableContext() { 715 return VTables.getMicrosoftVTableContext(); 716 } 717 718 CtorList &getGlobalCtors() { return GlobalCtors; } 719 CtorList &getGlobalDtors() { return GlobalDtors; } 720 721 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of 722 /// the given type. 723 llvm::MDNode *getTBAATypeInfo(QualType QTy); 724 725 /// getTBAAAccessInfo - Get TBAA information that describes an access to 726 /// an object of the given type. 727 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType); 728 729 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an 730 /// access to a virtual table pointer. 731 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType); 732 733 llvm::MDNode *getTBAAStructInfo(QualType QTy); 734 735 /// getTBAABaseTypeInfo - Get metadata that describes the given base access 736 /// type. Return null if the type is not suitable for use in TBAA access tags. 737 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy); 738 739 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access. 740 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info); 741 742 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of 743 /// type casts. 744 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 745 TBAAAccessInfo TargetInfo); 746 747 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the 748 /// purposes of conditional operator. 749 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 750 TBAAAccessInfo InfoB); 751 752 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the 753 /// purposes of memory transfer calls. 754 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 755 TBAAAccessInfo SrcInfo); 756 757 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given 758 /// base lvalue. 759 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) { 760 if (Base.getTBAAInfo().isMayAlias()) 761 return TBAAAccessInfo::getMayAliasInfo(); 762 return getTBAAAccessInfo(AccessType); 763 } 764 765 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor); 766 767 bool isPaddedAtomicType(QualType type); 768 bool isPaddedAtomicType(const AtomicType *type); 769 770 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag. 771 void DecorateInstructionWithTBAA(llvm::Instruction *Inst, 772 TBAAAccessInfo TBAAInfo); 773 774 /// Adds !invariant.barrier !tag to instruction 775 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, 776 const CXXRecordDecl *RD); 777 778 /// Emit the given number of characters as a value of type size_t. 779 llvm::ConstantInt *getSize(CharUnits numChars); 780 781 /// Set the visibility for the given LLVM GlobalValue. 782 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 783 784 void setDSOLocal(llvm::GlobalValue *GV) const; 785 786 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const; 787 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const; 788 /// Set visibility, dllimport/dllexport and dso_local. 789 /// This must be called after dllimport/dllexport is set. 790 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const; 791 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const; 792 793 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const; 794 795 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local 796 /// variable declaration D. 797 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const; 798 799 /// Get LLVM TLS mode from CodeGenOptions. 800 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const; 801 802 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 803 switch (V) { 804 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 805 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 806 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 807 } 808 llvm_unreachable("unknown visibility!"); 809 } 810 811 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, 812 ForDefinition_t IsForDefinition 813 = NotForDefinition); 814 815 /// Will return a global variable of the given type. If a variable with a 816 /// different type already exists then a new variable with the right type 817 /// will be created and all uses of the old variable will be replaced with a 818 /// bitcast to the new variable. 819 llvm::GlobalVariable * 820 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 821 llvm::GlobalValue::LinkageTypes Linkage, 822 unsigned Alignment); 823 824 llvm::Function *CreateGlobalInitOrCleanUpFunction( 825 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, 826 SourceLocation Loc = SourceLocation(), bool TLS = false, 827 bool IsExternalLinkage = false); 828 829 /// Return the AST address space of the underlying global variable for D, as 830 /// determined by its declaration. Normally this is the same as the address 831 /// space of D's type, but in CUDA, address spaces are associated with 832 /// declarations, not types. If D is nullptr, return the default address 833 /// space for global variable. 834 /// 835 /// For languages without explicit address spaces, if D has default address 836 /// space, target-specific global or constant address space may be returned. 837 LangAS GetGlobalVarAddressSpace(const VarDecl *D); 838 839 /// Return the llvm::Constant for the address of the given global variable. 840 /// If Ty is non-null and if the global doesn't exist, then it will be created 841 /// with the specified type instead of whatever the normal requested type 842 /// would be. If IsForDefinition is true, it is guaranteed that an actual 843 /// global with type Ty will be returned, not conversion of a variable with 844 /// the same mangled name but some other type. 845 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 846 llvm::Type *Ty = nullptr, 847 ForDefinition_t IsForDefinition 848 = NotForDefinition); 849 850 /// Return the AST address space of string literal, which is used to emit 851 /// the string literal as global variable in LLVM IR. 852 /// Note: This is not necessarily the address space of the string literal 853 /// in AST. For address space agnostic language, e.g. C++, string literal 854 /// in AST is always in default address space. 855 LangAS getStringLiteralAddressSpace() const; 856 857 /// Return the address of the given function. If Ty is non-null, then this 858 /// function will use the specified type if it has to create it. 859 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr, 860 bool ForVTable = false, 861 bool DontDefer = false, 862 ForDefinition_t IsForDefinition 863 = NotForDefinition); 864 865 /// Get the address of the RTTI descriptor for the given type. 866 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 867 868 /// Get the address of a GUID. 869 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD); 870 871 /// Get the address of the thunk for the given global decl. 872 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, 873 GlobalDecl GD); 874 875 /// Get a reference to the target of VD. 876 ConstantAddress GetWeakRefReference(const ValueDecl *VD); 877 878 /// Returns the assumed alignment of an opaque pointer to the given class. 879 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD); 880 881 /// Returns the minimum object size for an object of the given class type 882 /// (or a class derived from it). 883 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD); 884 885 /// Returns the minimum object size for an object of the given type. 886 CharUnits getMinimumObjectSize(QualType Ty) { 887 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) 888 return getMinimumClassObjectSize(RD); 889 return getContext().getTypeSizeInChars(Ty); 890 } 891 892 /// Returns the assumed alignment of a virtual base of a class. 893 CharUnits getVBaseAlignment(CharUnits DerivedAlign, 894 const CXXRecordDecl *Derived, 895 const CXXRecordDecl *VBase); 896 897 /// Given a class pointer with an actual known alignment, and the 898 /// expected alignment of an object at a dynamic offset w.r.t that 899 /// pointer, return the alignment to assume at the offset. 900 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, 901 const CXXRecordDecl *Class, 902 CharUnits ExpectedTargetAlign); 903 904 CharUnits 905 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, 906 CastExpr::path_const_iterator Start, 907 CastExpr::path_const_iterator End); 908 909 /// Returns the offset from a derived class to a class. Returns null if the 910 /// offset is 0. 911 llvm::Constant * 912 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 913 CastExpr::path_const_iterator PathBegin, 914 CastExpr::path_const_iterator PathEnd); 915 916 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache; 917 918 /// Fetches the global unique block count. 919 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 920 921 /// Fetches the type of a generic block descriptor. 922 llvm::Type *getBlockDescriptorType(); 923 924 /// The type of a generic block literal. 925 llvm::Type *getGenericBlockLiteralType(); 926 927 /// Gets the address of a block which requires no captures. 928 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name); 929 930 /// Returns the address of a block which requires no caputres, or null if 931 /// we've yet to emit the block for BE. 932 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) { 933 return EmittedGlobalBlocks.lookup(BE); 934 } 935 936 /// Notes that BE's global block is available via Addr. Asserts that BE 937 /// isn't already emitted. 938 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); 939 940 /// Return a pointer to a constant CFString object for the given string. 941 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); 942 943 /// Return a pointer to a constant NSString object for the given string. Or a 944 /// user defined String object as defined via 945 /// -fconstant-string-class=class_name option. 946 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal); 947 948 /// Return a constant array for the given string. 949 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 950 951 /// Return a pointer to a constant array for the given string literal. 952 ConstantAddress 953 GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 954 StringRef Name = ".str"); 955 956 /// Return a pointer to a constant array for the given ObjCEncodeExpr node. 957 ConstantAddress 958 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 959 960 /// Returns a pointer to a character array containing the literal and a 961 /// terminating '\0' character. The result has pointer to array type. 962 /// 963 /// \param GlobalName If provided, the name to use for the global (if one is 964 /// created). 965 ConstantAddress 966 GetAddrOfConstantCString(const std::string &Str, 967 const char *GlobalName = nullptr); 968 969 /// Returns a pointer to a constant global variable for the given file-scope 970 /// compound literal expression. 971 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 972 973 /// If it's been emitted already, returns the GlobalVariable corresponding to 974 /// a compound literal. Otherwise, returns null. 975 llvm::GlobalVariable * 976 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E); 977 978 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already 979 /// emitted. 980 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, 981 llvm::GlobalVariable *GV); 982 983 /// Returns a pointer to a global variable representing a temporary 984 /// with static or thread storage duration. 985 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, 986 const Expr *Inner); 987 988 /// Retrieve the record type that describes the state of an 989 /// Objective-C fast enumeration loop (for..in). 990 QualType getObjCFastEnumerationStateType(); 991 992 // Produce code for this constructor/destructor. This method doesn't try 993 // to apply any ABI rules about which other constructors/destructors 994 // are needed or if they are alias to each other. 995 llvm::Function *codegenCXXStructor(GlobalDecl GD); 996 997 /// Return the address of the constructor/destructor of the given type. 998 llvm::Constant * 999 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1000 llvm::FunctionType *FnType = nullptr, 1001 bool DontDefer = false, 1002 ForDefinition_t IsForDefinition = NotForDefinition) { 1003 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType, 1004 DontDefer, 1005 IsForDefinition) 1006 .getCallee()); 1007 } 1008 1009 llvm::FunctionCallee getAddrAndTypeOfCXXStructor( 1010 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr, 1011 llvm::FunctionType *FnType = nullptr, bool DontDefer = false, 1012 ForDefinition_t IsForDefinition = NotForDefinition); 1013 1014 /// Given a builtin id for a function like "__builtin_fabsf", return a 1015 /// Function* for "fabsf". 1016 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD, 1017 unsigned BuiltinID); 1018 1019 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None); 1020 1021 /// Emit code for a single top level declaration. 1022 void EmitTopLevelDecl(Decl *D); 1023 1024 /// Stored a deferred empty coverage mapping for an unused 1025 /// and thus uninstrumented top level declaration. 1026 void AddDeferredUnusedCoverageMapping(Decl *D); 1027 1028 /// Remove the deferred empty coverage mapping as this 1029 /// declaration is actually instrumented. 1030 void ClearUnusedCoverageMapping(const Decl *D); 1031 1032 /// Emit all the deferred coverage mappings 1033 /// for the uninstrumented functions. 1034 void EmitDeferredUnusedCoverageMappings(); 1035 1036 /// Emit an alias for "main" if it has no arguments (needed for wasm). 1037 void EmitMainVoidAlias(); 1038 1039 /// Tell the consumer that this variable has been instantiated. 1040 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD); 1041 1042 /// If the declaration has internal linkage but is inside an 1043 /// extern "C" linkage specification, prepare to emit an alias for it 1044 /// to the expected name. 1045 template<typename SomeDecl> 1046 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV); 1047 1048 /// Add a global to a list to be added to the llvm.used metadata. 1049 void addUsedGlobal(llvm::GlobalValue *GV); 1050 1051 /// Add a global to a list to be added to the llvm.compiler.used metadata. 1052 void addCompilerUsedGlobal(llvm::GlobalValue *GV); 1053 1054 /// Add a destructor and object to add to the C++ global destructor function. 1055 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) { 1056 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1057 DtorFn.getCallee(), Object); 1058 } 1059 1060 /// Add an sterm finalizer to the C++ global cleanup function. 1061 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) { 1062 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(), 1063 DtorFn.getCallee(), nullptr); 1064 } 1065 1066 /// Create or return a runtime function declaration with the specified type 1067 /// and name. If \p AssumeConvergent is true, the call will have the 1068 /// convergent attribute added. 1069 llvm::FunctionCallee 1070 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, 1071 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1072 bool Local = false, bool AssumeConvergent = false); 1073 1074 /// Create or return a runtime function declaration with the specified type 1075 /// and name. This will automatically add the convergent attribute to the 1076 /// function declaration. 1077 llvm::FunctionCallee CreateConvergentRuntimeFunction( 1078 llvm::FunctionType *Ty, StringRef Name, 1079 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1080 bool Local = false) { 1081 return CreateRuntimeFunction(Ty, Name, ExtraAttrs, Local, true); 1082 } 1083 1084 /// Create a new runtime global variable with the specified type and name. 1085 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 1086 StringRef Name); 1087 1088 ///@name Custom Blocks Runtime Interfaces 1089 ///@{ 1090 1091 llvm::Constant *getNSConcreteGlobalBlock(); 1092 llvm::Constant *getNSConcreteStackBlock(); 1093 llvm::FunctionCallee getBlockObjectAssign(); 1094 llvm::FunctionCallee getBlockObjectDispose(); 1095 1096 ///@} 1097 1098 llvm::Function *getLLVMLifetimeStartFn(); 1099 llvm::Function *getLLVMLifetimeEndFn(); 1100 1101 // Make sure that this type is translated. 1102 void UpdateCompletedType(const TagDecl *TD); 1103 1104 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 1105 1106 /// Emit type info if type of an expression is a variably modified 1107 /// type. Also emit proper debug info for cast types. 1108 void EmitExplicitCastExprType(const ExplicitCastExpr *E, 1109 CodeGenFunction *CGF = nullptr); 1110 1111 /// Return the result of value-initializing the given type, i.e. a null 1112 /// expression of the given type. This is usually, but not always, an LLVM 1113 /// null constant. 1114 llvm::Constant *EmitNullConstant(QualType T); 1115 1116 /// Return a null constant appropriate for zero-initializing a base class with 1117 /// the given type. This is usually, but not always, an LLVM null constant. 1118 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 1119 1120 /// Emit a general error that something can't be done. 1121 void Error(SourceLocation loc, StringRef error); 1122 1123 /// Print out an error that codegen doesn't support the specified stmt yet. 1124 void ErrorUnsupported(const Stmt *S, const char *Type); 1125 1126 /// Print out an error that codegen doesn't support the specified decl yet. 1127 void ErrorUnsupported(const Decl *D, const char *Type); 1128 1129 /// Set the attributes on the LLVM function for the given decl and function 1130 /// info. This applies attributes necessary for handling the ABI as well as 1131 /// user specified attributes like section. 1132 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1133 const CGFunctionInfo &FI); 1134 1135 /// Set the LLVM function attributes (sext, zext, etc). 1136 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, 1137 llvm::Function *F); 1138 1139 /// Set the LLVM function attributes which only apply to a function 1140 /// definition. 1141 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 1142 1143 /// Return true iff the given type uses 'sret' when used as a return type. 1144 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 1145 1146 /// Return true iff the given type uses an argument slot when 'sret' is used 1147 /// as a return type. 1148 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI); 1149 1150 /// Return true iff the given type uses 'fpret' when used as a return type. 1151 bool ReturnTypeUsesFPRet(QualType ResultType); 1152 1153 /// Return true iff the given type uses 'fp2ret' when used as a return type. 1154 bool ReturnTypeUsesFP2Ret(QualType ResultType); 1155 1156 /// Get the LLVM attributes and calling convention to use for a particular 1157 /// function type. 1158 /// 1159 /// \param Name - The function name. 1160 /// \param Info - The function type information. 1161 /// \param CalleeInfo - The callee information these attributes are being 1162 /// constructed for. If valid, the attributes applied to this decl may 1163 /// contribute to the function attributes and calling convention. 1164 /// \param Attrs [out] - On return, the attribute list to use. 1165 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 1166 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, 1167 CGCalleeInfo CalleeInfo, 1168 llvm::AttributeList &Attrs, unsigned &CallingConv, 1169 bool AttrOnCallSite); 1170 1171 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as 1172 /// though we had emitted it ourselves. We remove any attributes on F that 1173 /// conflict with the attributes we add here. 1174 /// 1175 /// This is useful for adding attrs to bitcode modules that you want to link 1176 /// with but don't control, such as CUDA's libdevice. When linking with such 1177 /// a bitcode library, you might want to set e.g. its functions' 1178 /// "unsafe-fp-math" attribute to match the attr of the functions you're 1179 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of 1180 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM 1181 /// will propagate unsafe-fp-math=false up to every transitive caller of a 1182 /// function in the bitcode library! 1183 /// 1184 /// With the exception of fast-math attrs, this will only make the attributes 1185 /// on the function more conservative. But it's unsafe to call this on a 1186 /// function which relies on particular fast-math attributes for correctness. 1187 /// It's up to you to ensure that this is safe. 1188 void addDefaultFunctionDefinitionAttributes(llvm::Function &F); 1189 1190 /// Like the overload taking a `Function &`, but intended specifically 1191 /// for frontends that want to build on Clang's target-configuration logic. 1192 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs); 1193 1194 StringRef getMangledName(GlobalDecl GD); 1195 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD); 1196 1197 void EmitTentativeDefinition(const VarDecl *D); 1198 1199 void EmitExternalDeclaration(const VarDecl *D); 1200 1201 void EmitVTable(CXXRecordDecl *Class); 1202 1203 void RefreshTypeCacheForClass(const CXXRecordDecl *Class); 1204 1205 /// Appends Opts to the "llvm.linker.options" metadata value. 1206 void AppendLinkerOptions(StringRef Opts); 1207 1208 /// Appends a detect mismatch command to the linker options. 1209 void AddDetectMismatch(StringRef Name, StringRef Value); 1210 1211 /// Appends a dependent lib to the appropriate metadata value. 1212 void AddDependentLib(StringRef Lib); 1213 1214 1215 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); 1216 1217 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) { 1218 F->setLinkage(getFunctionLinkage(GD)); 1219 } 1220 1221 /// Return the appropriate linkage for the vtable, VTT, and type information 1222 /// of the given class. 1223 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 1224 1225 /// Return the store size, in character units, of the given LLVM type. 1226 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 1227 1228 /// Returns LLVM linkage for a declarator. 1229 llvm::GlobalValue::LinkageTypes 1230 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, 1231 bool IsConstantVariable); 1232 1233 /// Returns LLVM linkage for a declarator. 1234 llvm::GlobalValue::LinkageTypes 1235 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant); 1236 1237 /// Emit all the global annotations. 1238 void EmitGlobalAnnotations(); 1239 1240 /// Emit an annotation string. 1241 llvm::Constant *EmitAnnotationString(StringRef Str); 1242 1243 /// Emit the annotation's translation unit. 1244 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 1245 1246 /// Emit the annotation line number. 1247 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 1248 1249 /// Generate the llvm::ConstantStruct which contains the annotation 1250 /// information for a given GlobalValue. The annotation struct is 1251 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 1252 /// GlobalValue being annotated. The second field is the constant string 1253 /// created from the AnnotateAttr's annotation. The third field is a constant 1254 /// string containing the name of the translation unit. The fourth field is 1255 /// the line number in the file of the annotated value declaration. 1256 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 1257 const AnnotateAttr *AA, 1258 SourceLocation L); 1259 1260 /// Add global annotations that are set on D, for the global GV. Those 1261 /// annotations are emitted during finalization of the LLVM code. 1262 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 1263 1264 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn, 1265 SourceLocation Loc) const; 1266 1267 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc, 1268 QualType Ty, 1269 StringRef Category = StringRef()) const; 1270 1271 /// Imbue XRay attributes to a function, applying the always/never attribute 1272 /// lists in the process. Returns true if we did imbue attributes this way, 1273 /// false otherwise. 1274 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1275 StringRef Category = StringRef()) const; 1276 1277 SanitizerMetadata *getSanitizerMetadata() { 1278 return SanitizerMD.get(); 1279 } 1280 1281 void addDeferredVTable(const CXXRecordDecl *RD) { 1282 DeferredVTables.push_back(RD); 1283 } 1284 1285 /// Emit code for a single global function or var decl. Forward declarations 1286 /// are emitted lazily. 1287 void EmitGlobal(GlobalDecl D); 1288 1289 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 1290 1291 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 1292 1293 /// Set attributes which are common to any form of a global definition (alias, 1294 /// Objective-C method, function, global variable). 1295 /// 1296 /// NOTE: This should only be called for definitions. 1297 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV); 1298 1299 void addReplacement(StringRef Name, llvm::Constant *C); 1300 1301 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C); 1302 1303 /// Emit a code for threadprivate directive. 1304 /// \param D Threadprivate declaration. 1305 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D); 1306 1307 /// Emit a code for declare reduction construct. 1308 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 1309 CodeGenFunction *CGF = nullptr); 1310 1311 /// Emit a code for declare mapper construct. 1312 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 1313 CodeGenFunction *CGF = nullptr); 1314 1315 /// Emit a code for requires directive. 1316 /// \param D Requires declaration 1317 void EmitOMPRequiresDecl(const OMPRequiresDecl *D); 1318 1319 /// Returns whether the given record has hidden LTO visibility and therefore 1320 /// may participate in (single-module) CFI and whole-program vtable 1321 /// optimization. 1322 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD); 1323 1324 /// Returns whether the given record has public std LTO visibility 1325 /// and therefore may not participate in (single-module) CFI and whole-program 1326 /// vtable optimization. 1327 bool HasLTOVisibilityPublicStd(const CXXRecordDecl *RD); 1328 1329 /// Returns the vcall visibility of the given type. This is the scope in which 1330 /// a virtual function call could be made which ends up being dispatched to a 1331 /// member function of this class. This scope can be wider than the visibility 1332 /// of the class itself when the class has a more-visible dynamic base class. 1333 llvm::GlobalObject::VCallVisibility 1334 GetVCallVisibilityLevel(const CXXRecordDecl *RD); 1335 1336 /// Emit type metadata for the given vtable using the given layout. 1337 void EmitVTableTypeMetadata(const CXXRecordDecl *RD, 1338 llvm::GlobalVariable *VTable, 1339 const VTableLayout &VTLayout); 1340 1341 /// Generate a cross-DSO type identifier for MD. 1342 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD); 1343 1344 /// Create a metadata identifier for the given type. This may either be an 1345 /// MDString (for external identifiers) or a distinct unnamed MDNode (for 1346 /// internal identifiers). 1347 llvm::Metadata *CreateMetadataIdentifierForType(QualType T); 1348 1349 /// Create a metadata identifier that is intended to be used to check virtual 1350 /// calls via a member function pointer. 1351 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T); 1352 1353 /// Create a metadata identifier for the generalization of the given type. 1354 /// This may either be an MDString (for external identifiers) or a distinct 1355 /// unnamed MDNode (for internal identifiers). 1356 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T); 1357 1358 /// Create and attach type metadata to the given function. 1359 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1360 llvm::Function *F); 1361 1362 /// Returns whether this module needs the "all-vtables" type identifier. 1363 bool NeedAllVtablesTypeId() const; 1364 1365 /// Create and attach type metadata for the given vtable. 1366 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, 1367 const CXXRecordDecl *RD); 1368 1369 /// Return a vector of most-base classes for RD. This is used to implement 1370 /// control flow integrity checks for member function pointers. 1371 /// 1372 /// A most-base class of a class C is defined as a recursive base class of C, 1373 /// including C itself, that does not have any bases. 1374 std::vector<const CXXRecordDecl *> 1375 getMostBaseClasses(const CXXRecordDecl *RD); 1376 1377 /// Get the declaration of std::terminate for the platform. 1378 llvm::FunctionCallee getTerminateFn(); 1379 1380 llvm::SanitizerStatReport &getSanStats(); 1381 1382 llvm::Value * 1383 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF); 1384 1385 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 1386 /// information in the program executable. The argument information stored 1387 /// includes the argument name, its type, the address and access qualifiers 1388 /// used. This helper can be used to generate metadata for source code kernel 1389 /// function as well as generated implicitly kernels. If a kernel is generated 1390 /// implicitly null value has to be passed to the last two parameters, 1391 /// otherwise all parameters must have valid non-null values. 1392 /// \param FN is a pointer to IR function being generated. 1393 /// \param FD is a pointer to function declaration if any. 1394 /// \param CGF is a pointer to CodeGenFunction that generates this function. 1395 void GenOpenCLArgMetadata(llvm::Function *FN, 1396 const FunctionDecl *FD = nullptr, 1397 CodeGenFunction *CGF = nullptr); 1398 1399 /// Get target specific null pointer. 1400 /// \param T is the LLVM type of the null pointer. 1401 /// \param QT is the clang QualType of the null pointer. 1402 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT); 1403 1404 CharUnits getNaturalTypeAlignment(QualType T, 1405 LValueBaseInfo *BaseInfo = nullptr, 1406 TBAAAccessInfo *TBAAInfo = nullptr, 1407 bool forPointeeType = false); 1408 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1409 LValueBaseInfo *BaseInfo = nullptr, 1410 TBAAAccessInfo *TBAAInfo = nullptr); 1411 bool stopAutoInit(); 1412 1413 private: 1414 llvm::Constant *GetOrCreateLLVMFunction( 1415 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable, 1416 bool DontDefer = false, bool IsThunk = false, 1417 llvm::AttributeList ExtraAttrs = llvm::AttributeList(), 1418 ForDefinition_t IsForDefinition = NotForDefinition); 1419 1420 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD, 1421 llvm::Type *DeclTy, 1422 const FunctionDecl *FD); 1423 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD); 1424 1425 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 1426 llvm::PointerType *PTy, 1427 const VarDecl *D, 1428 ForDefinition_t IsForDefinition 1429 = NotForDefinition); 1430 1431 bool GetCPUAndFeaturesAttributes(GlobalDecl GD, 1432 llvm::AttrBuilder &AttrBuilder); 1433 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO); 1434 1435 /// Set function attributes for a function declaration. 1436 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1437 bool IsIncompleteFunction, bool IsThunk); 1438 1439 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr); 1440 1441 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1442 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV); 1443 1444 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false); 1445 void EmitExternalVarDeclaration(const VarDecl *D); 1446 void EmitAliasDefinition(GlobalDecl GD); 1447 void emitIFuncDefinition(GlobalDecl GD); 1448 void emitCPUDispatchDefinition(GlobalDecl GD); 1449 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 1450 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 1451 1452 // C++ related functions. 1453 1454 void EmitDeclContext(const DeclContext *DC); 1455 void EmitLinkageSpec(const LinkageSpecDecl *D); 1456 1457 /// Emit the function that initializes C++ thread_local variables. 1458 void EmitCXXThreadLocalInitFunc(); 1459 1460 /// Emit the function that initializes C++ globals. 1461 void EmitCXXGlobalInitFunc(); 1462 1463 /// Emit the function that performs cleanup associated with C++ globals. 1464 void EmitCXXGlobalCleanUpFunc(); 1465 1466 /// Emit the function that initializes the specified global (if PerformInit is 1467 /// true) and registers its destructor. 1468 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 1469 llvm::GlobalVariable *Addr, 1470 bool PerformInit); 1471 1472 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr, 1473 llvm::Function *InitFunc, InitSegAttr *ISA); 1474 1475 // FIXME: Hardcoding priority here is gross. 1476 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535, 1477 llvm::Constant *AssociatedData = nullptr); 1478 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535); 1479 1480 /// EmitCtorList - Generates a global array of functions and priorities using 1481 /// the given list and name. This array will have appending linkage and is 1482 /// suitable for use as a LLVM constructor or destructor array. Clears Fns. 1483 void EmitCtorList(CtorList &Fns, const char *GlobalName); 1484 1485 /// Emit any needed decls for which code generation was deferred. 1486 void EmitDeferred(); 1487 1488 /// Try to emit external vtables as available_externally if they have emitted 1489 /// all inlined virtual functions. It runs after EmitDeferred() and therefore 1490 /// is not allowed to create new references to things that need to be emitted 1491 /// lazily. 1492 void EmitVTablesOpportunistically(); 1493 1494 /// Call replaceAllUsesWith on all pairs in Replacements. 1495 void applyReplacements(); 1496 1497 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements. 1498 void applyGlobalValReplacements(); 1499 1500 void checkAliases(); 1501 1502 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit; 1503 1504 /// Register functions annotated with __attribute__((destructor)) using 1505 /// __cxa_atexit, if it is available, or atexit otherwise. 1506 void registerGlobalDtorsWithAtExit(); 1507 1508 void emitMultiVersionFunctions(); 1509 1510 /// Emit any vtables which we deferred and still have a use for. 1511 void EmitDeferredVTables(); 1512 1513 /// Emit a dummy function that reference a CoreFoundation symbol when 1514 /// @available is used on Darwin. 1515 void emitAtAvailableLinkGuard(); 1516 1517 /// Emit the llvm.used and llvm.compiler.used metadata. 1518 void emitLLVMUsed(); 1519 1520 /// Emit the link options introduced by imported modules. 1521 void EmitModuleLinkOptions(); 1522 1523 /// Emit aliases for internal-linkage declarations inside "C" language 1524 /// linkage specifications, giving them the "expected" name where possible. 1525 void EmitStaticExternCAliases(); 1526 1527 void EmitDeclMetadata(); 1528 1529 /// Emit the Clang version as llvm.ident metadata. 1530 void EmitVersionIdentMetadata(); 1531 1532 /// Emit the Clang commandline as llvm.commandline metadata. 1533 void EmitCommandLineMetadata(); 1534 1535 /// Emit the module flag metadata used to pass options controlling the 1536 /// the backend to LLVM. 1537 void EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts); 1538 1539 /// Emits OpenCL specific Metadata e.g. OpenCL version. 1540 void EmitOpenCLMetadata(); 1541 1542 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and 1543 /// .gcda files in a way that persists in .bc files. 1544 void EmitCoverageFile(); 1545 1546 /// Determine whether the definition must be emitted; if this returns \c 1547 /// false, the definition can be emitted lazily if it's used. 1548 bool MustBeEmitted(const ValueDecl *D); 1549 1550 /// Determine whether the definition can be emitted eagerly, or should be 1551 /// delayed until the end of the translation unit. This is relevant for 1552 /// definitions whose linkage can change, e.g. implicit function instantions 1553 /// which may later be explicitly instantiated. 1554 bool MayBeEmittedEagerly(const ValueDecl *D); 1555 1556 /// Check whether we can use a "simpler", more core exceptions personality 1557 /// function. 1558 void SimplifyPersonality(); 1559 1560 /// Helper function for ConstructAttributeList and 1561 /// addDefaultFunctionDefinitionAttributes. Builds a set of function 1562 /// attributes to add to a function with the given properties. 1563 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone, 1564 bool AttrOnCallSite, 1565 llvm::AttrBuilder &FuncAttrs); 1566 1567 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 1568 StringRef Suffix); 1569 }; 1570 1571 } // end namespace CodeGen 1572 } // end namespace clang 1573 1574 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H 1575