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