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 "TrapReasonBuilder.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclOpenMP.h"
24#include "clang/AST/GlobalDecl.h"
25#include "clang/AST/Mangle.h"
26#include "clang/Basic/ABI.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/NoSanitizeList.h"
29#include "clang/Basic/ProfileList.h"
30#include "clang/Basic/StackExhaustionHandler.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/XRayLists.h"
33#include "clang/Lex/PreprocessorOptions.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/SetVector.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/StringMap.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/ValueHandle.h"
41#include "llvm/Support/Allocator.h"
42#include "llvm/Support/VirtualFileSystemFwd.h"
43#include "llvm/Transforms/Utils/SanitizerStats.h"
44#include <optional>
45
46namespace llvm {
47class Module;
48class Constant;
49class ConstantInt;
50class Function;
51class GlobalValue;
52class DataLayout;
53class FunctionType;
54class LLVMContext;
55class IndexedInstrProfReader;
56
57namespace abi {
58class ArgInfo;
59class IRTypeMapper;
60class TargetInfo;
61class TypeBuilder;
62} // namespace abi
63}
64
65namespace clang {
66class ASTContext;
67class AtomicType;
68class FunctionDecl;
69class IdentifierInfo;
70class ObjCImplementationDecl;
71class ObjCEncodeExpr;
72class BlockExpr;
73class CharUnits;
74class Decl;
75class Expr;
76class Stmt;
77class StringLiteral;
78class NamedDecl;
79class PointerAuthSchema;
80class ValueDecl;
81class VarDecl;
82class LangOptions;
83class CodeGenOptions;
84class HeaderSearchOptions;
85class DiagnosticsEngine;
86class AnnotateAttr;
87class CXXDestructorDecl;
88class Module;
89class CoverageSourceInfo;
90class InitSegAttr;
91
92namespace CodeGen {
93
94class CodeGenFunction;
95class CodeGenTBAA;
96class CGCXXABI;
97class CGDebugInfo;
98class CGObjCRuntime;
99class CGOpenCLRuntime;
100class CGOpenMPRuntime;
101class CGCUDARuntime;
102class CGHLSLRuntime;
103class CGFunctionInfo;
104class CoverageMappingModuleGen;
105class QualTypeMapper;
106class TargetCodeGenInfo;
107
108enum ForDefinition_t : bool {
109 NotForDefinition = false,
110 ForDefinition = true
111};
112
113/// The Counter with an optional additional Counter for
114/// branches. `Skipped` counter can be calculated with `Executed` and
115/// a common Counter (like `Parent`) as `(Parent-Executed)`.
116///
117/// In SingleByte mode, Counters are binary. Subtraction is not
118/// applicable (but addition is capable). In this case, both
119/// `Executed` and `Skipped` counters are required. `Skipped` is
120/// `None` by default. It is allocated in the coverage mapping.
121///
122/// There might be cases that `Parent` could be induced with
123/// `(Executed+Skipped)`. This is not always applicable.
124class CounterPair {
125public:
126 /// Optional value.
127 class ValueOpt {
128 private:
129 static constexpr uint32_t None = (1u << 31); /// None is allocated.
130 static constexpr uint32_t Mask = None - 1;
131
132 uint32_t Val;
133
134 public:
135 ValueOpt() : Val(None) {}
136
137 ValueOpt(unsigned InitVal) {
138 assert(!(InitVal & ~Mask));
139 Val = InitVal;
140 }
141
142 bool hasValue() const { return !(Val & None); }
143
144 operator uint32_t() const { return Val; }
145 };
146
147 ValueOpt Executed;
148 ValueOpt Skipped; /// May be None.
149
150 /// Initialized with Skipped=None.
151 CounterPair(unsigned Val) : Executed(Val) {}
152
153 // FIXME: Should work with {None, None}
154 CounterPair() : Executed(0) {}
155};
156
157struct OrderGlobalInitsOrStermFinalizers {
158 unsigned int priority;
159 unsigned int lex_order;
160 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
161 : priority(p), lex_order(l) {}
162
163 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
164 return priority == RHS.priority && lex_order == RHS.lex_order;
165 }
166
167 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
168 return std::tie(args: priority, args: lex_order) <
169 std::tie(args: RHS.priority, args: RHS.lex_order);
170 }
171};
172
173struct ObjCEntrypoints {
174 ObjCEntrypoints() { memset(s: this, c: 0, n: sizeof(*this)); }
175
176 /// void objc_alloc(id);
177 llvm::FunctionCallee objc_alloc;
178
179 /// void objc_allocWithZone(id);
180 llvm::FunctionCallee objc_allocWithZone;
181
182 /// void objc_alloc_init(id);
183 llvm::FunctionCallee objc_alloc_init;
184
185 /// void objc_autoreleasePoolPop(void*);
186 llvm::FunctionCallee objc_autoreleasePoolPop;
187
188 /// void objc_autoreleasePoolPop(void*);
189 /// Note this method is used when we are using exception handling
190 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
191
192 /// void *objc_autoreleasePoolPush(void);
193 llvm::Function *objc_autoreleasePoolPush;
194
195 /// id objc_autorelease(id);
196 llvm::Function *objc_autorelease;
197
198 /// id objc_autorelease(id);
199 /// Note this is the runtime method not the intrinsic.
200 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
201
202 /// id objc_autoreleaseReturnValue(id);
203 llvm::Function *objc_autoreleaseReturnValue;
204
205 /// void objc_copyWeak(id *dest, id *src);
206 llvm::Function *objc_copyWeak;
207
208 /// void objc_destroyWeak(id*);
209 llvm::Function *objc_destroyWeak;
210
211 /// id objc_initWeak(id*, id);
212 llvm::Function *objc_initWeak;
213
214 /// id objc_loadWeak(id*);
215 llvm::Function *objc_loadWeak;
216
217 /// id objc_loadWeakRetained(id*);
218 llvm::Function *objc_loadWeakRetained;
219
220 /// void objc_moveWeak(id *dest, id *src);
221 llvm::Function *objc_moveWeak;
222
223 /// id objc_retain(id);
224 llvm::Function *objc_retain;
225
226 /// id objc_retain(id);
227 /// Note this is the runtime method not the intrinsic.
228 llvm::FunctionCallee objc_retainRuntimeFunction;
229
230 /// id objc_retainAutorelease(id);
231 llvm::Function *objc_retainAutorelease;
232
233 /// id objc_retainAutoreleaseReturnValue(id);
234 llvm::Function *objc_retainAutoreleaseReturnValue;
235
236 /// id objc_retainAutoreleasedReturnValue(id);
237 llvm::Function *objc_retainAutoreleasedReturnValue;
238
239 /// id objc_retainBlock(id);
240 llvm::Function *objc_retainBlock;
241
242 /// void objc_release(id);
243 llvm::Function *objc_release;
244
245 /// void objc_release(id);
246 /// Note this is the runtime method not the intrinsic.
247 llvm::FunctionCallee objc_releaseRuntimeFunction;
248
249 /// void objc_storeStrong(id*, id);
250 llvm::Function *objc_storeStrong;
251
252 /// id objc_storeWeak(id*, id);
253 llvm::Function *objc_storeWeak;
254
255 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
256 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
257
258 /// A void(void) inline asm to use to mark that the return value of
259 /// a call will be immediately retain.
260 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
261
262 /// void clang.arc.use(...);
263 llvm::Function *clang_arc_use;
264
265 /// void clang.arc.noop.use(...);
266 llvm::Function *clang_arc_noop_use;
267};
268
269/// This class records statistics on instrumentation based profiling.
270class InstrProfStats {
271 uint32_t VisitedInMainFile = 0;
272 uint32_t MissingInMainFile = 0;
273 uint32_t Visited = 0;
274 uint32_t Missing = 0;
275 uint32_t Mismatched = 0;
276
277public:
278 InstrProfStats() = default;
279 /// Record that we've visited a function and whether or not that function was
280 /// in the main source file.
281 void addVisited(bool MainFile) {
282 if (MainFile)
283 ++VisitedInMainFile;
284 ++Visited;
285 }
286 /// Record that a function we've visited has no profile data.
287 void addMissing(bool MainFile) {
288 if (MainFile)
289 ++MissingInMainFile;
290 ++Missing;
291 }
292 /// Record that a function we've visited has mismatched profile data.
293 void addMismatched(bool MainFile) { ++Mismatched; }
294 /// Whether or not the stats we've gathered indicate any potential problems.
295 bool hasDiagnostics() { return Missing || Mismatched; }
296 /// Report potential problems we've found to \c Diags.
297 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
298};
299
300/// A pair of helper functions for a __block variable.
301class BlockByrefHelpers : public llvm::FoldingSetNode {
302 // MSVC requires this type to be complete in order to process this
303 // header.
304public:
305 llvm::Constant *CopyHelper;
306 llvm::Constant *DisposeHelper;
307
308 /// The alignment of the field. This is important because
309 /// different offsets to the field within the byref struct need to
310 /// have different helper functions.
311 CharUnits Alignment;
312
313 BlockByrefHelpers(CharUnits alignment)
314 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
315 BlockByrefHelpers(const BlockByrefHelpers &) = default;
316 virtual ~BlockByrefHelpers();
317
318 void Profile(llvm::FoldingSetNodeID &id) const {
319 id.AddInteger(I: Alignment.getQuantity());
320 profileImpl(id);
321 }
322 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
323
324 virtual bool needsCopy() const { return true; }
325 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
326
327 virtual bool needsDispose() const { return true; }
328 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
329};
330
331/// This class organizes the cross-function state that is used while generating
332/// LLVM code.
333class CodeGenModule : public CodeGenTypeCache {
334 CodeGenModule(const CodeGenModule &) = delete;
335 void operator=(const CodeGenModule &) = delete;
336
337public:
338 struct Structor {
339 Structor()
340 : Priority(0), LexOrder(~0u), Initializer(nullptr),
341 AssociatedData(nullptr) {}
342 Structor(int Priority, unsigned LexOrder, llvm::Constant *Initializer,
343 llvm::Constant *AssociatedData)
344 : Priority(Priority), LexOrder(LexOrder), Initializer(Initializer),
345 AssociatedData(AssociatedData) {}
346 int Priority;
347 unsigned LexOrder;
348 llvm::Constant *Initializer;
349 llvm::Constant *AssociatedData;
350 };
351
352 typedef std::vector<Structor> CtorList;
353
354private:
355 ASTContext &Context;
356 const LangOptions &LangOpts;
357 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS; // Only used for debug info.
358 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
359 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
360 const CodeGenOptions &CodeGenOpts;
361 unsigned NumAutoVarInit = 0;
362 llvm::Module &TheModule;
363 DiagnosticsEngine &Diags;
364 const TargetInfo &Target;
365 std::unique_ptr<CGCXXABI> ABI;
366 llvm::LLVMContext &VMContext;
367 std::string ModuleNameHash;
368 bool CXX20ModuleInits = false;
369 std::unique_ptr<CodeGenTBAA> TBAA;
370
371 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
372
373 /// Cached LLVMABI target lowering info, lazily constructed when the
374 /// experimental ABI lowering path is taken.
375 mutable std::unique_ptr<llvm::abi::TargetInfo> TheLLVMABITargetInfo;
376
377 /// Allocator and mappers used by the experimental LLVMABI-based lowering
378 /// path (gated on -fexperimental-abi-lowering). Constructed unconditionally
379 /// so the path can be entered without re-checking initialization, but the
380 /// caches stay empty when the flag is off.
381 llvm::BumpPtrAllocator AbiAlloc;
382 std::unique_ptr<QualTypeMapper> AbiMapper;
383 std::unique_ptr<llvm::abi::IRTypeMapper> AbiReverseMapper;
384
385 // This should not be moved earlier, since its initialization depends on some
386 // of the previous reference members being already initialized and also checks
387 // if TheTargetCodeGenInfo is NULL
388 std::unique_ptr<CodeGenTypes> Types;
389
390 /// Holds information about C++ vtables.
391 CodeGenVTables VTables;
392
393 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
394 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
395 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
396 std::unique_ptr<CGCUDARuntime> CUDARuntime;
397 std::unique_ptr<CGHLSLRuntime> HLSLRuntime;
398 std::unique_ptr<CGDebugInfo> DebugInfo;
399 std::unique_ptr<ObjCEntrypoints> ObjCData;
400 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
401 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
402 InstrProfStats PGOStats;
403 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
404 StackExhaustionHandler StackHandler;
405
406 // A set of references that have only been seen via a weakref so far. This is
407 // used to remove the weak of the reference if we ever see a direct reference
408 // or a definition.
409 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
410
411 /// This contains all the decls which have definitions but/ which are deferred
412 /// for emission and therefore should only be output if they are actually
413 /// used. If a decl is in this, then it is known to have not been referenced
414 /// yet.
415 llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
416
417 llvm::StringSet<llvm::BumpPtrAllocator> DeferredResolversToEmit;
418
419 /// This is a list of deferred decls which we have seen that *are* actually
420 /// referenced. These get code generated when the module is done.
421 std::vector<GlobalDecl> DeferredDeclsToEmit;
422 void addDeferredDeclToEmit(GlobalDecl GD) {
423 DeferredDeclsToEmit.emplace_back(args&: GD);
424 addEmittedDeferredDecl(GD);
425 }
426
427 /// Decls that were DeferredDecls and have now been emitted.
428 llvm::DenseMap<llvm::StringRef, GlobalDecl> EmittedDeferredDecls;
429
430 void addEmittedDeferredDecl(GlobalDecl GD) {
431 // Reemission is only needed in incremental mode.
432 if (!Context.getLangOpts().IncrementalExtensions)
433 return;
434
435 // Assume a linkage by default that does not need reemission.
436 auto L = llvm::GlobalValue::ExternalLinkage;
437 if (llvm::isa<FunctionDecl>(Val: GD.getDecl()))
438 L = getFunctionLinkage(GD);
439 else if (auto *VD = llvm::dyn_cast<VarDecl>(Val: GD.getDecl()))
440 L = getLLVMLinkageVarDefinition(VD);
441
442 if (llvm::GlobalValue::isInternalLinkage(Linkage: L) ||
443 llvm::GlobalValue::isLinkOnceLinkage(Linkage: L) ||
444 llvm::GlobalValue::isWeakLinkage(Linkage: L)) {
445 EmittedDeferredDecls[getMangledName(GD)] = GD;
446 }
447 }
448
449 /// List of alias we have emitted. Used to make sure that what they point to
450 /// is defined once we get to the end of the of the translation unit.
451 std::vector<GlobalDecl> Aliases;
452
453 /// List of multiversion functions to be emitted. This list is processed in
454 /// conjunction with other deferred symbols and is used to ensure that
455 /// multiversion function resolvers and ifuncs are defined and emitted.
456 std::vector<GlobalDecl> MultiVersionFuncs;
457
458 llvm::MapVector<StringRef, llvm::TrackingVH<llvm::Constant>> Replacements;
459
460 /// List of global values to be replaced with something else. Used when we
461 /// want to replace a GlobalValue but can't identify it by its mangled name
462 /// anymore (because the name is already taken).
463 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
464 GlobalValReplacements;
465
466 /// Variables for which we've emitted globals containing their constant
467 /// values along with the corresponding globals, for opportunistic reuse.
468 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
469
470 /// Set of global decls for which we already diagnosed mangled name conflict.
471 /// Required to not issue a warning (on a mangling conflict) multiple times
472 /// for the same decl.
473 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
474
475 /// A queue of (optional) vtables to consider emitting.
476 std::vector<const CXXRecordDecl*> DeferredVTables;
477
478 /// In incremental compilation, the set of vtable classes whose vtable
479 /// definitions were emitted into a previous PTU's module. Carried forward
480 /// by moveLazyEmissionStates() so later PTUs skip re-defining them.
481 llvm::SmallPtrSet<const CXXRecordDecl *, 8> EmittedVTables;
482
483 /// A queue of (optional) vtables that may be emitted opportunistically.
484 std::vector<const CXXRecordDecl *> OpportunisticVTables;
485
486 /// List of global values which are required to be present in the object file;
487 /// bitcast to i8*. This is used for forcing visibility of symbols which may
488 /// otherwise be optimized out.
489 std::vector<llvm::WeakTrackingVH> LLVMUsed;
490 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
491
492 /// Store the list of global constructors and their respective priorities to
493 /// be emitted when the translation unit is complete.
494 CtorList GlobalCtors;
495
496 /// Store the list of global destructors and their respective priorities to be
497 /// emitted when the translation unit is complete.
498 CtorList GlobalDtors;
499
500 /// An ordered map of canonical GlobalDecls to their mangled names.
501 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
502 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
503
504 /// Global annotations.
505 std::vector<llvm::Constant*> Annotations;
506
507 // Store deferred function annotations so they can be emitted at the end with
508 // most up to date ValueDecl that will have all the inherited annotations.
509 llvm::MapVector<StringRef, const ValueDecl *> DeferredAnnotations;
510
511 /// Map used to get unique annotation strings.
512 llvm::StringMap<llvm::Constant*> AnnotationStrings;
513
514 /// Used for uniquing of annotation arguments.
515 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
516
517 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
518
519 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
520 llvm::DenseMap<const UnnamedGlobalConstantDecl *, llvm::GlobalVariable *>
521 UnnamedGlobalConstantDeclMap;
522 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
523 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
524 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
525
526 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
527 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
528
529 /// Map used to get unique type descriptor constants for sanitizers.
530 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
531
532 /// Map used to track internal linkage functions declared within
533 /// extern "C" regions.
534 typedef llvm::MapVector<IdentifierInfo *,
535 llvm::GlobalValue *> StaticExternCMap;
536 StaticExternCMap StaticExternCValues;
537
538 /// thread_local variables defined or used in this TU.
539 std::vector<const VarDecl *> CXXThreadLocals;
540
541 /// thread_local variables with initializers that need to run
542 /// before any thread_local variable in this TU is odr-used.
543 std::vector<llvm::Function *> CXXThreadLocalInits;
544 std::vector<const VarDecl *> CXXThreadLocalInitVars;
545
546 /// Global variables with initializers that need to run before main.
547 std::vector<llvm::Function *> CXXGlobalInits;
548
549 /// When a C++ decl with an initializer is deferred, null is
550 /// appended to CXXGlobalInits, and the index of that null is placed
551 /// here so that the initializer will be performed in the correct
552 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
553 /// that we don't re-emit the initializer.
554 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
555
556 /// To remember which types did require a vector deleting destructor body.
557 /// This set basically contains classes that have virtual destructor and new[]
558 /// was emitted for the class.
559 llvm::SmallPtrSet<const CXXRecordDecl *, 16> RequireVectorDeletingDtor;
560
561 /// Pending MSVC __global_delete variants that may need forwarding bodies.
562 /// Maps each __global_delete wrapper alias to the corresponding global
563 /// ::operator delete FunctionDecl, in insertion order.
564 llvm::MapVector<llvm::GlobalAlias *, const FunctionDecl *>
565 PendingMSVCGlobalDeletes;
566
567 /// Whether this TU contains a direct use of global ::operator delete
568 /// (indicating that __global_delete forwarding bodies should be emitted).
569 bool HasDirectGlobalDelete = false;
570
571 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
572 GlobalInitData;
573
574 // When a tail call is performed on an "undefined" symbol, on PPC without pc
575 // relative feature, the tail call is not allowed. In "EmitCall" for such
576 // tail calls, the "undefined" symbols may be forward declarations, their
577 // definitions are provided in the module after the callsites. For such tail
578 // calls, diagnose message should not be emitted.
579 llvm::SmallSetVector<std::pair<const FunctionDecl *, SourceLocation>, 4>
580 MustTailCallUndefinedGlobals;
581
582 struct GlobalInitPriorityCmp {
583 bool operator()(const GlobalInitData &LHS,
584 const GlobalInitData &RHS) const {
585 return LHS.first.priority < RHS.first.priority;
586 }
587 };
588
589 /// Global variables with initializers whose order of initialization is set by
590 /// init_priority attribute.
591 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
592
593 /// Global destructor functions and arguments that need to run on termination.
594 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
595 /// functions, which also run on unloading a shared library.
596 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
597 llvm::Constant *>
598 CXXGlobalDtorsOrStermFinalizer_t;
599 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
600 CXXGlobalDtorsOrStermFinalizers;
601
602 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
603 StermFinalizerData;
604
605 struct StermFinalizerPriorityCmp {
606 bool operator()(const StermFinalizerData &LHS,
607 const StermFinalizerData &RHS) const {
608 return LHS.first.priority < RHS.first.priority;
609 }
610 };
611
612 /// Global variables with sterm finalizers whose order of initialization is
613 /// set by init_priority attribute.
614 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
615
616 /// The complete set of modules that has been imported.
617 llvm::SetVector<clang::Module *> ImportedModules;
618
619 /// The set of modules for which the module initializers
620 /// have been emitted.
621 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
622
623 /// A vector of metadata strings for linker options.
624 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
625
626 /// A vector of metadata strings for dependent libraries for ELF.
627 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
628
629 /// Global variable for copyright pragma comment (if present).
630 llvm::GlobalVariable *LoadTimeCommentGlobal = nullptr;
631
632 /// @name Cache for Objective-C runtime types
633 /// @{
634
635 /// Cached reference to the class for constant strings. This value has type
636 /// int * but is actually an Obj-C class pointer.
637 llvm::WeakTrackingVH CFConstantStringClassRef;
638
639 /// The type used to describe the state of a fast enumeration in
640 /// Objective-C's for..in loop.
641 QualType ObjCFastEnumerationStateType;
642
643 /// @}
644
645 /// Lazily create the Objective-C runtime
646 void createObjCRuntime();
647
648 void createOpenCLRuntime();
649 void createOpenMPRuntime();
650 void createCUDARuntime();
651 void createHLSLRuntime();
652
653 bool shouldEmitFunction(GlobalDecl GD);
654 // Whether a global variable should be emitted by CUDA/HIP host/device
655 // related attributes.
656 bool shouldEmitCUDAGlobalVar(const VarDecl *VD) const;
657 bool shouldOpportunisticallyEmitVTables();
658 /// Map used to be sure we don't emit the same CompoundLiteral twice.
659 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
660 EmittedCompoundLiterals;
661
662 /// Map of the global blocks we've emitted, so that we don't have to re-emit
663 /// them if the constexpr evaluator gets aggressive.
664 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
665
666 /// @name Cache for Blocks Runtime Globals
667 /// @{
668
669 llvm::Constant *NSConcreteGlobalBlock = nullptr;
670 llvm::Constant *NSConcreteStackBlock = nullptr;
671
672 llvm::FunctionCallee BlockObjectAssign = nullptr;
673 llvm::FunctionCallee BlockObjectDispose = nullptr;
674
675 llvm::Type *BlockDescriptorType = nullptr;
676 llvm::Type *GenericBlockLiteralType = nullptr;
677
678 struct {
679 int GlobalUniqueCount;
680 } Block;
681
682 GlobalDecl initializedGlobalDecl;
683
684 /// @}
685
686 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
687 llvm::Function *LifetimeStartFn = nullptr;
688
689 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
690 llvm::Function *LifetimeEndFn = nullptr;
691
692 /// void @llvm.fake.use(...)
693 llvm::Function *FakeUseFn = nullptr;
694
695 std::unique_ptr<SanitizerMetadata> SanitizerMD;
696
697 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
698
699 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
700
701 /// Mapping from canonical types to their metadata identifiers. We need to
702 /// maintain this mapping because identifiers may be formed from distinct
703 /// MDNodes.
704 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
705 MetadataTypeMap MetadataIdMap;
706 MetadataTypeMap VirtualMetadataIdMap;
707 MetadataTypeMap GeneralizedMetadataIdMap;
708 MetadataTypeMap CallGraphMetadataIdMap;
709
710 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
711 // when used with -fincremental-extensions.
712 std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *>
713 GlobalTopLevelStmtBlockInFlight;
714
715 llvm::DenseMap<GlobalDecl, uint16_t> PtrAuthDiscriminatorHashes;
716
717 llvm::DenseMap<const CXXRecordDecl *, std::optional<PointerAuthQualifier>>
718 VTablePtrAuthInfos;
719 std::optional<PointerAuthQualifier>
720 computeVTPointerAuthentication(const CXXRecordDecl *ThisClass,
721 bool IsVTTEntry);
722
723 AtomicOptions AtomicOpts;
724
725 // A set of functions which should be hot-patched; see
726 // -fms-hotpatch-functions-file (and -list). This will nearly always be empty.
727 // The list is sorted for binary-searching.
728 std::vector<std::string> MSHotPatchFunctions;
729
730public:
731 CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
732 const HeaderSearchOptions &headersearchopts,
733 const PreprocessorOptions &ppopts,
734 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
735 DiagnosticsEngine &Diags,
736 CoverageSourceInfo *CoverageInfo = nullptr);
737
738 ~CodeGenModule();
739
740 void clear();
741
742 /// Finalize LLVM code generation.
743 void Release();
744
745 /// Get the current Atomic options.
746 AtomicOptions getAtomicOpts() { return AtomicOpts; }
747
748 /// Set the current Atomic options.
749 void setAtomicOpts(AtomicOptions AO) { AtomicOpts = AO; }
750
751 /// Return true if we should emit location information for expressions.
752 bool getExpressionLocationsEnabled() const;
753
754 /// Return a reference to the configured Objective-C runtime.
755 CGObjCRuntime &getObjCRuntime() {
756 if (!ObjCRuntime) createObjCRuntime();
757 return *ObjCRuntime;
758 }
759
760 /// Return true iff an Objective-C runtime has been configured.
761 bool hasObjCRuntime() { return !!ObjCRuntime; }
762
763 /// Check if the precondition thunk optimization is enabled.
764 /// This checks runtime support and codegen options, but does NOT check
765 /// whether a specific method is eligible for thunks or inline preconditions.
766 ///
767 /// TODO: Add support for GNUStep as well, currently only supports NeXT
768 /// family.
769 bool isObjCDirectPreconditionThunkEnabled() const {
770 return getLangOpts().ObjCRuntime.allowsDirectDispatch() &&
771 getLangOpts().ObjCRuntime.isNeXTFamily() &&
772 getCodeGenOpts().ObjCDirectPreconditionThunk;
773 }
774
775 /// Check if a direct method should use precondition thunks at call sites.
776 /// Returns false if OMD is null, not a direct method, or variadic.
777 ///
778 /// Variadic methods use inline preconditions instead of thunks to avoid
779 /// musttail complexity across different architectures.
780 bool shouldHavePreconditionThunk(const ObjCMethodDecl *OMD) const {
781 return OMD && OMD->isDirectMethod() && !OMD->isVariadic() &&
782 isObjCDirectPreconditionThunkEnabled();
783 }
784
785 /// Check if a direct method should have inline precondition checks at call
786 /// sites.
787 /// Returns false if OMD is null, not a direct method, or not variadic.
788 ///
789 /// Variadic direct methods use inline preconditions rather than thunks
790 /// to avoid musttail complexity across different architectures.
791 bool shouldHavePreconditionInline(const ObjCMethodDecl *OMD) const {
792 return OMD && OMD->isDirectMethod() && OMD->isVariadic() &&
793 isObjCDirectPreconditionThunkEnabled();
794 }
795
796 const std::string &getModuleNameHash() const { return ModuleNameHash; }
797
798 /// Return a reference to the configured OpenCL runtime.
799 CGOpenCLRuntime &getOpenCLRuntime() {
800 assert(OpenCLRuntime != nullptr);
801 return *OpenCLRuntime;
802 }
803
804 /// Return a reference to the configured OpenMP runtime.
805 CGOpenMPRuntime &getOpenMPRuntime() {
806 assert(OpenMPRuntime != nullptr);
807 return *OpenMPRuntime;
808 }
809
810 /// Return a reference to the configured CUDA runtime.
811 CGCUDARuntime &getCUDARuntime() {
812 assert(CUDARuntime != nullptr);
813 return *CUDARuntime;
814 }
815
816 /// Return a reference to the configured HLSL runtime.
817 CGHLSLRuntime &getHLSLRuntime() {
818 assert(HLSLRuntime != nullptr);
819 return *HLSLRuntime;
820 }
821
822 ObjCEntrypoints &getObjCEntrypoints() const {
823 assert(ObjCData != nullptr);
824 return *ObjCData;
825 }
826
827 // Version checking functions, used to implement ObjC's @available:
828 // i32 @__isOSVersionAtLeast(i32, i32, i32)
829 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
830 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
831 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
832
833 InstrProfStats &getPGOStats() { return PGOStats; }
834 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
835
836 CoverageMappingModuleGen *getCoverageMapping() const {
837 return CoverageMapping.get();
838 }
839
840 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
841 return StaticLocalDeclMap[D];
842 }
843 void setStaticLocalDeclAddress(const VarDecl *D,
844 llvm::Constant *C) {
845 StaticLocalDeclMap[D] = C;
846 }
847
848 llvm::Constant *
849 getOrCreateStaticVarDecl(const VarDecl &D,
850 llvm::GlobalValue::LinkageTypes Linkage);
851
852 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
853 return StaticLocalDeclGuardMap[D];
854 }
855 void setStaticLocalDeclGuardAddress(const VarDecl *D,
856 llvm::GlobalVariable *C) {
857 StaticLocalDeclGuardMap[D] = C;
858 }
859
860 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
861 CharUnits Align);
862
863 bool lookupRepresentativeDecl(StringRef MangledName,
864 GlobalDecl &Result) const;
865
866 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
867 return AtomicSetterHelperFnMap[Ty];
868 }
869 void setAtomicSetterHelperFnMap(QualType Ty,
870 llvm::Constant *Fn) {
871 AtomicSetterHelperFnMap[Ty] = Fn;
872 }
873
874 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
875 return AtomicGetterHelperFnMap[Ty];
876 }
877 void setAtomicGetterHelperFnMap(QualType Ty,
878 llvm::Constant *Fn) {
879 AtomicGetterHelperFnMap[Ty] = Fn;
880 }
881
882 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
883 return TypeDescriptorMap[Ty];
884 }
885 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
886 TypeDescriptorMap[Ty] = C;
887 }
888
889 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
890
891 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
892 if (!NoObjCARCExceptionsMetadata)
893 NoObjCARCExceptionsMetadata = llvm::MDNode::get(Context&: getLLVMContext(), MDs: {});
894 return NoObjCARCExceptionsMetadata;
895 }
896
897 ASTContext &getContext() const { return Context; }
898 const LangOptions &getLangOpts() const { return LangOpts; }
899 const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const {
900 return FS;
901 }
902 const HeaderSearchOptions &getHeaderSearchOpts()
903 const { return HeaderSearchOpts; }
904 const PreprocessorOptions &getPreprocessorOpts()
905 const { return PreprocessorOpts; }
906 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
907 llvm::Module &getModule() const { return TheModule; }
908 DiagnosticsEngine &getDiags() const { return Diags; }
909 const llvm::DataLayout &getDataLayout() const {
910 return TheModule.getDataLayout();
911 }
912 const TargetInfo &getTarget() const { return Target; }
913 const llvm::Triple &getTriple() const { return Target.getTriple(); }
914 bool supportsCOMDAT() const;
915 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
916
917 const ABIInfo &getABIInfo();
918
919 /// Lazily build and return the LLVMABI library's TargetInfo for the current
920 /// target. Used by the experimental ABI lowering path
921 /// (-fexperimental-abi-lowering).
922 const llvm::abi::TargetInfo &getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB);
923
924 /// True when -fexperimental-abi-lowering is in effect AND the active target
925 /// has an LLVMABI implementation that supports the given LLVM calling
926 /// convention. Unsupported CCs fall back to the legacy ABIInfo path.
927 bool shouldUseLLVMABILowering(unsigned CallingConv) const;
928
929 /// Drive the experimental LLVMABI-based lowering path: map argument and
930 /// return types into the LLVMABI library, ask its target lowering to fill
931 /// in classification, and write the results back into FI.
932 void computeABIInfoUsingLib(CGFunctionInfo &FI);
933
934 CGCXXABI &getCXXABI() const { return *ABI; }
935 llvm::LLVMContext &getLLVMContext() { return VMContext; }
936
937 bool shouldUseTBAA() const { return TBAA != nullptr; }
938
939 const TargetCodeGenInfo &getTargetCodeGenInfo();
940
941 CodeGenTypes &getTypes() { return *Types; }
942
943 CodeGenVTables &getVTables() { return VTables; }
944
945 ItaniumVTableContext &getItaniumVTableContext() {
946 return VTables.getItaniumVTableContext();
947 }
948
949 const ItaniumVTableContext &getItaniumVTableContext() const {
950 return VTables.getItaniumVTableContext();
951 }
952
953 MicrosoftVTableContext &getMicrosoftVTableContext() {
954 return VTables.getMicrosoftVTableContext();
955 }
956
957 CtorList &getGlobalCtors() { return GlobalCtors; }
958 CtorList &getGlobalDtors() { return GlobalDtors; }
959
960 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
961 /// the given type.
962 llvm::MDNode *getTBAATypeInfo(QualType QTy);
963
964 /// getTBAAAccessInfo - Get TBAA information that describes an access to
965 /// an object of the given type.
966 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
967
968 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
969 /// access to a virtual table pointer.
970 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
971
972 llvm::MDNode *getTBAAStructInfo(QualType QTy);
973
974 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
975 /// type. Return null if the type is not suitable for use in TBAA access tags.
976 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
977
978 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
979 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
980
981 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
982 /// type casts.
983 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
984 TBAAAccessInfo TargetInfo);
985
986 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
987 /// purposes of conditional operator.
988 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
989 TBAAAccessInfo InfoB);
990
991 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
992 /// purposes of memory transfer calls.
993 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
994 TBAAAccessInfo SrcInfo);
995
996 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
997 /// base lvalue.
998 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
999 if (Base.getTBAAInfo().isMayAlias())
1000 return TBAAAccessInfo::getMayAliasInfo();
1001 return getTBAAAccessInfo(AccessType);
1002 }
1003
1004 bool isPaddedAtomicType(QualType type);
1005 bool isPaddedAtomicType(const AtomicType *type);
1006
1007 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
1008 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1009 TBAAAccessInfo TBAAInfo);
1010
1011 /// Adds !invariant.barrier !tag to instruction
1012 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
1013 const CXXRecordDecl *RD);
1014
1015 /// Emit the given number of characters as a value of type size_t.
1016 llvm::ConstantInt *getSize(CharUnits numChars);
1017
1018 /// Set the visibility for the given LLVM GlobalValue.
1019 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
1020
1021 void setDSOLocal(llvm::GlobalValue *GV) const;
1022
1023 bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const {
1024 return getLangOpts().hasDefaultVisibilityExportMapping() && D &&
1025 (D->getLinkageAndVisibility().getVisibility() ==
1026 DefaultVisibility) &&
1027 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
1028 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
1029 D->getLinkageAndVisibility().isVisibilityExplicit()));
1030 }
1031 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
1032 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
1033 /// Set visibility, dllimport/dllexport and dso_local.
1034 /// This must be called after dllimport/dllexport is set.
1035 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
1036 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
1037
1038 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
1039
1040 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
1041 /// variable declaration D.
1042 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
1043
1044 /// Get LLVM TLS mode from CodeGenOptions.
1045 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
1046
1047 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
1048 switch (V) {
1049 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
1050 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
1051 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
1052 }
1053 llvm_unreachable("unknown visibility!");
1054 }
1055
1056 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
1057 ForDefinition_t IsForDefinition
1058 = NotForDefinition);
1059
1060 /// Will return a global variable of the given type. If a variable with a
1061 /// different type already exists then a new variable with the right type
1062 /// will be created and all uses of the old variable will be replaced with a
1063 /// bitcast to the new variable.
1064 llvm::GlobalVariable *
1065 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
1066 llvm::GlobalValue::LinkageTypes Linkage,
1067 llvm::Align Alignment);
1068
1069 llvm::Function *CreateGlobalInitOrCleanUpFunction(
1070 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
1071 SourceLocation Loc = SourceLocation(), bool TLS = false,
1072 llvm::GlobalVariable::LinkageTypes Linkage =
1073 llvm::GlobalVariable::InternalLinkage);
1074
1075 /// Return the AST address space of the underlying global variable for D, as
1076 /// determined by its declaration. Normally this is the same as the address
1077 /// space of D's type, but in CUDA, address spaces are associated with
1078 /// declarations, not types. If D is nullptr, return the default address
1079 /// space for global variable.
1080 ///
1081 /// For languages without explicit address spaces, if D has default address
1082 /// space, target-specific global or constant address space may be returned.
1083 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
1084
1085 /// Return the AST address space of constant literal, which is used to emit
1086 /// the constant literal as global variable in LLVM IR.
1087 /// Note: This is not necessarily the address space of the constant literal
1088 /// in AST. For address space agnostic language, e.g. C++, constant literal
1089 /// in AST is always in default address space.
1090 LangAS GetGlobalConstantAddressSpace() const;
1091
1092 /// Return the llvm::Constant for the address of the given global variable.
1093 /// If Ty is non-null and if the global doesn't exist, then it will be created
1094 /// with the specified type instead of whatever the normal requested type
1095 /// would be. If IsForDefinition is true, it is guaranteed that an actual
1096 /// global with type Ty will be returned, not conversion of a variable with
1097 /// the same mangled name but some other type.
1098 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
1099 llvm::Type *Ty = nullptr,
1100 ForDefinition_t IsForDefinition
1101 = NotForDefinition);
1102
1103 /// Return the address of the given function. If Ty is non-null, then this
1104 /// function will use the specified type if it has to create it.
1105 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
1106 bool ForVTable = false,
1107 bool DontDefer = false,
1108 ForDefinition_t IsForDefinition
1109 = NotForDefinition);
1110
1111 // Return the function body address of the given function.
1112 llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
1113
1114 /// Return a function pointer for a reference to the given function.
1115 /// This correctly handles weak references, but does not apply a
1116 /// pointer signature.
1117 llvm::Constant *getRawFunctionPointer(GlobalDecl GD,
1118 llvm::Type *Ty = nullptr);
1119
1120 /// Return the ABI-correct function pointer value for a reference
1121 /// to the given function. This will apply a pointer signature if
1122 /// necessary, caching the result for the given function.
1123 llvm::Constant *getFunctionPointer(GlobalDecl GD, llvm::Type *Ty = nullptr);
1124
1125 /// Return the ABI-correct function pointer value for a reference
1126 /// to the given function. This will apply a pointer signature if
1127 /// necessary.
1128 llvm::Constant *getFunctionPointer(llvm::Constant *Pointer,
1129 QualType FunctionType);
1130
1131 llvm::Constant *getMemberFunctionPointer(const FunctionDecl *FD,
1132 llvm::Type *Ty = nullptr);
1133
1134 llvm::Constant *getMemberFunctionPointer(llvm::Constant *Pointer,
1135 QualType FT);
1136
1137 CGPointerAuthInfo getFunctionPointerAuthInfo(QualType T);
1138
1139 CGPointerAuthInfo getMemberFunctionPointerAuthInfo(QualType FT);
1140
1141 CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type);
1142
1143 CGPointerAuthInfo getPointerAuthInfoForType(QualType type);
1144
1145 bool shouldSignPointer(const PointerAuthSchema &Schema);
1146 llvm::Constant *getConstantSignedPointer(llvm::Constant *Pointer,
1147 const PointerAuthSchema &Schema,
1148 llvm::Constant *StorageAddress,
1149 GlobalDecl SchemaDecl,
1150 QualType SchemaType);
1151
1152 llvm::Constant *
1153 getConstantSignedPointer(llvm::Constant *Pointer, unsigned Key,
1154 llvm::Constant *StorageAddress,
1155 llvm::ConstantInt *OtherDiscriminator);
1156
1157 llvm::ConstantInt *
1158 getPointerAuthOtherDiscriminator(const PointerAuthSchema &Schema,
1159 GlobalDecl SchemaDecl, QualType SchemaType);
1160
1161 uint16_t getPointerAuthDeclDiscriminator(GlobalDecl GD);
1162
1163 std::optional<CGPointerAuthInfo> getVTablePointerAuthInfo(
1164 CodeGenFunction *Context, const CXXRecordDecl *Record,
1165 llvm::Value *StorageAddress, bool IsVTTEntry = false);
1166
1167 std::optional<PointerAuthQualifier>
1168 getVTablePointerAuthentication(const CXXRecordDecl *thisClass,
1169 bool IsVTTEntry = false);
1170
1171 CGPointerAuthInfo EmitPointerAuthInfo(const RecordDecl *RD);
1172
1173 // Return whether RTTI information should be emitted for this target.
1174 bool shouldEmitRTTI(bool ForEH = false) {
1175 return (ForEH || getLangOpts().RTTI) &&
1176 (!getLangOpts().isTargetDevice() || !getTriple().isGPU());
1177 }
1178
1179 /// Get the address of the RTTI descriptor for the given type.
1180 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
1181
1182 /// Get the address of a GUID.
1183 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
1184
1185 /// Get the address of a UnnamedGlobalConstant
1186 ConstantAddress
1187 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD);
1188
1189 /// Get the address of a template parameter object.
1190 ConstantAddress
1191 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
1192
1193 /// Get the address of the thunk for the given global decl.
1194 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
1195 GlobalDecl GD);
1196
1197 /// Get a reference to the target of VD.
1198 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
1199
1200 /// Returns the assumed alignment of an opaque pointer to the given class.
1201 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
1202
1203 /// Returns the minimum object size for an object of the given class type
1204 /// (or a class derived from it).
1205 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
1206
1207 /// Returns the minimum object size for an object of the given type.
1208 CharUnits getMinimumObjectSize(QualType Ty) {
1209 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
1210 return getMinimumClassObjectSize(CD: RD);
1211 return getContext().getTypeSizeInChars(T: Ty);
1212 }
1213
1214 /// Returns the assumed alignment of a virtual base of a class.
1215 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
1216 const CXXRecordDecl *Derived,
1217 const CXXRecordDecl *VBase);
1218
1219 /// Given a class pointer with an actual known alignment, and the
1220 /// expected alignment of an object at a dynamic offset w.r.t that
1221 /// pointer, return the alignment to assume at the offset.
1222 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
1223 const CXXRecordDecl *Class,
1224 CharUnits ExpectedTargetAlign);
1225
1226 CharUnits
1227 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
1228 CastExpr::path_const_iterator Start,
1229 CastExpr::path_const_iterator End);
1230
1231 /// Returns the offset from a derived class to a class. Returns null if the
1232 /// offset is 0.
1233 llvm::Constant *
1234 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
1235 CastExpr::path_const_iterator PathBegin,
1236 CastExpr::path_const_iterator PathEnd);
1237
1238 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
1239
1240 /// Fetches the global unique block count.
1241 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
1242
1243 /// Fetches the type of a generic block descriptor.
1244 llvm::Type *getBlockDescriptorType();
1245
1246 /// The type of a generic block literal.
1247 llvm::Type *getGenericBlockLiteralType();
1248
1249 /// Gets the address of a block which requires no captures.
1250 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
1251
1252 /// Returns the address of a block which requires no caputres, or null if
1253 /// we've yet to emit the block for BE.
1254 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
1255 return EmittedGlobalBlocks.lookup(Val: BE);
1256 }
1257
1258 /// Notes that BE's global block is available via Addr. Asserts that BE
1259 /// isn't already emitted.
1260 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
1261
1262 /// Return a pointer to a constant CFString object for the given string.
1263 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
1264
1265 /// Return a constant array for the given string.
1266 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
1267
1268 /// Return a pointer to a constant array for the given string literal.
1269 ConstantAddress
1270 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
1271 StringRef Name = ".str");
1272
1273 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1274 ConstantAddress
1275 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
1276
1277 /// Returns a pointer to a character array containing the literal and a
1278 /// terminating '\0' character. The result has pointer to array type.
1279 ///
1280 /// \param GlobalName If provided, the name to use for the global (if one is
1281 /// created).
1282 ConstantAddress GetAddrOfConstantCString(const std::string &Str,
1283 StringRef GlobalName = ".str");
1284
1285 /// Returns a pointer to a constant global variable for the given file-scope
1286 /// compound literal expression.
1287 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
1288
1289 /// If it's been emitted already, returns the GlobalVariable corresponding to
1290 /// a compound literal. Otherwise, returns null.
1291 llvm::GlobalVariable *
1292 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
1293
1294 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1295 /// emitted.
1296 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
1297 llvm::GlobalVariable *GV);
1298
1299 /// Returns a pointer to a global variable representing a temporary
1300 /// with static or thread storage duration.
1301 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
1302 const Expr *Inner);
1303
1304 /// Retrieve the record type that describes the state of an
1305 /// Objective-C fast enumeration loop (for..in).
1306 QualType getObjCFastEnumerationStateType();
1307
1308 // Produce code for this constructor/destructor. This method doesn't try
1309 // to apply any ABI rules about which other constructors/destructors
1310 // are needed or if they are alias to each other.
1311 llvm::Function *codegenCXXStructor(GlobalDecl GD);
1312
1313 /// Emit a trap stub body for functions in ASTContext::CUDADeviceInvalidFuncs.
1314 bool tryEmitCUDADeviceInvalidFunctionBody(GlobalDecl GD, llvm::Function *Fn);
1315
1316 /// Return the address of the constructor/destructor of the given type.
1317 llvm::Constant *
1318 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1319 llvm::FunctionType *FnType = nullptr,
1320 bool DontDefer = false,
1321 ForDefinition_t IsForDefinition = NotForDefinition) {
1322 return cast<llvm::Constant>(Val: getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1323 DontDefer,
1324 IsForDefinition)
1325 .getCallee());
1326 }
1327
1328 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1329 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1330 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1331 ForDefinition_t IsForDefinition = NotForDefinition);
1332
1333 /// Given a builtin id for a function like "__builtin_fabsf", return a
1334 /// Function* for "fabsf".
1335 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1336 unsigned BuiltinID);
1337
1338 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type *> Tys = {});
1339
1340 void AddCXXGlobalInit(llvm::Function *F) { CXXGlobalInits.push_back(x: F); }
1341
1342 /// Emit code for a single top level declaration.
1343 void EmitTopLevelDecl(Decl *D);
1344
1345 /// Stored a deferred empty coverage mapping for an unused
1346 /// and thus uninstrumented top level declaration.
1347 void AddDeferredUnusedCoverageMapping(Decl *D);
1348
1349 /// Remove the deferred empty coverage mapping as this
1350 /// declaration is actually instrumented.
1351 void ClearUnusedCoverageMapping(const Decl *D);
1352
1353 /// Emit all the deferred coverage mappings
1354 /// for the uninstrumented functions.
1355 void EmitDeferredUnusedCoverageMappings();
1356
1357 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1358 void EmitMainVoidAlias();
1359
1360 /// Tell the consumer that this variable has been instantiated.
1361 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1362
1363 /// If the declaration has internal linkage but is inside an
1364 /// extern "C" linkage specification, prepare to emit an alias for it
1365 /// to the expected name.
1366 template<typename SomeDecl>
1367 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1368
1369 /// Add a global to a list to be added to the llvm.used metadata.
1370 void addUsedGlobal(llvm::GlobalValue *GV);
1371
1372 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1373 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1374
1375 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1376 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1377
1378 /// Add a destructor and object to add to the C++ global destructor function.
1379 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1380 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1381 Args: DtorFn.getCallee(), Args&: Object);
1382 }
1383
1384 /// Add an sterm finalizer to the C++ global cleanup function.
1385 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1386 CXXGlobalDtorsOrStermFinalizers.emplace_back(Args: DtorFn.getFunctionType(),
1387 Args: DtorFn.getCallee(), Args: nullptr);
1388 }
1389
1390 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1391 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1392 int Priority) {
1393 AddGlobalDtor(Dtor: StermFinalizer, Priority);
1394 }
1395
1396 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1397 int Priority) {
1398 OrderGlobalInitsOrStermFinalizers Key(Priority,
1399 PrioritizedCXXStermFinalizers.size());
1400 PrioritizedCXXStermFinalizers.push_back(
1401 Elt: std::make_pair(x&: Key, y&: StermFinalizer));
1402 }
1403
1404 /// Create or return a runtime function declaration with the specified type
1405 /// and name. If \p AssumeConvergent is true, the call will have the
1406 /// convergent attribute added.
1407 ///
1408 /// For new code, please use the overload that takes a QualType; it sets
1409 /// function attributes more accurately.
1410 llvm::FunctionCallee
1411 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1412 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1413 bool Local = false, bool AssumeConvergent = false);
1414
1415 /// Create or return a runtime function declaration with the specified type
1416 /// and name. If \p AssumeConvergent is true, the call will have the
1417 /// convergent attribute added.
1418 llvm::FunctionCallee
1419 CreateRuntimeFunction(QualType ReturnTy, ArrayRef<QualType> ArgTys,
1420 StringRef Name,
1421 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1422 bool Local = false, bool AssumeConvergent = false);
1423
1424 /// Create a new runtime global variable with the specified type and name.
1425 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1426 StringRef Name);
1427
1428 ///@name Custom Blocks Runtime Interfaces
1429 ///@{
1430
1431 llvm::Constant *getNSConcreteGlobalBlock();
1432 llvm::Constant *getNSConcreteStackBlock();
1433 llvm::FunctionCallee getBlockObjectAssign();
1434 llvm::FunctionCallee getBlockObjectDispose();
1435
1436 ///@}
1437
1438 llvm::Function *getLLVMLifetimeStartFn();
1439 llvm::Function *getLLVMLifetimeEndFn();
1440 llvm::Function *getLLVMFakeUseFn();
1441
1442 // Make sure that this type is translated.
1443 void UpdateCompletedType(const TagDecl *TD);
1444
1445 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1446
1447 /// Emit type info if type of an expression is a variably modified
1448 /// type. Also emit proper debug info for cast types.
1449 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1450 CodeGenFunction *CGF = nullptr);
1451
1452 /// Return the result of value-initializing the given type, i.e. a null
1453 /// expression of the given type. This is usually, but not always, an LLVM
1454 /// null constant.
1455 llvm::Constant *EmitNullConstant(QualType T);
1456
1457 /// Return a null constant appropriate for zero-initializing a base class with
1458 /// the given type. This is usually, but not always, an LLVM null constant.
1459 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1460
1461 /// Emit a general error that something can't be done.
1462 void Error(SourceLocation loc, StringRef error);
1463
1464 /// Print out an error that codegen doesn't support the specified stmt yet.
1465 void ErrorUnsupported(const Stmt *S, const char *Type);
1466
1467 /// Print out an error that codegen doesn't support the specified stmt yet.
1468 void ErrorUnsupported(const Stmt *S, llvm::StringRef Type);
1469
1470 /// Print out an error that codegen doesn't support the specified decl yet.
1471 void ErrorUnsupported(const Decl *D, const char *Type);
1472
1473 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1474 /// guaranteed). Produces a warning if we're low on stack space and allocates
1475 /// more in that case. Use this in code that may recurse deeply to avoid stack
1476 /// overflow.
1477 void runWithSufficientStackSpace(SourceLocation Loc,
1478 llvm::function_ref<void()> Fn);
1479
1480 /// Set the attributes on the LLVM function for the given decl and function
1481 /// info. This applies attributes necessary for handling the ABI as well as
1482 /// user specified attributes like section.
1483 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1484 const CGFunctionInfo &FI);
1485
1486 /// Set the LLVM function attributes (sext, zext, etc).
1487 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1488 llvm::Function *F, bool IsThunk);
1489
1490 /// Set the LLVM function attributes which only apply to a function
1491 /// definition.
1492 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1493
1494 /// Set the LLVM function attributes that represent floating point
1495 /// environment.
1496 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1497
1498 /// Return true iff the given type uses 'sret' when used as a return type.
1499 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1500
1501 /// Return true iff the given type has `inreg` set.
1502 bool ReturnTypeHasInReg(const CGFunctionInfo &FI);
1503
1504 /// Return true iff the given type uses an argument slot when 'sret' is used
1505 /// as a return type.
1506 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1507
1508 /// Return true iff the given type uses 'fpret' when used as a return type.
1509 bool ReturnTypeUsesFPRet(QualType ResultType);
1510
1511 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1512 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1513
1514 /// Get the LLVM attributes and calling convention to use for a particular
1515 /// function type.
1516 ///
1517 /// \param Name - The function name.
1518 /// \param Info - The function type information.
1519 /// \param CalleeInfo - The callee information these attributes are being
1520 /// constructed for. If valid, the attributes applied to this decl may
1521 /// contribute to the function attributes and calling convention.
1522 /// \param Attrs [out] - On return, the attribute list to use.
1523 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1524 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1525 CGCalleeInfo CalleeInfo,
1526 llvm::AttributeList &Attrs, unsigned &CallingConv,
1527 bool AttrOnCallSite, bool IsThunk);
1528
1529 /// Adjust Memory attribute to ensure that the BE gets the right attribute
1530 // in order to generate the library call or the intrinsic for the function
1531 // name 'Name'.
1532 void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo,
1533 llvm::AttributeList &Attrs);
1534
1535 /// Like the overload taking a `Function &`, but intended specifically
1536 /// for frontends that want to build on Clang's target-configuration logic.
1537 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1538
1539 StringRef getMangledName(GlobalDecl GD);
1540 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1541 const GlobalDecl getMangledNameDecl(StringRef);
1542
1543 void EmitTentativeDefinition(const VarDecl *D);
1544
1545 void EmitExternalDeclaration(const DeclaratorDecl *D);
1546
1547 void EmitVTable(CXXRecordDecl *Class);
1548
1549 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1550
1551 /// Appends Opts to the "llvm.linker.options" metadata value.
1552 void AppendLinkerOptions(StringRef Opts);
1553
1554 /// Appends a detect mismatch command to the linker options.
1555 void AddDetectMismatch(StringRef Name, StringRef Value);
1556
1557 /// Appends a dependent lib to the appropriate metadata value.
1558 void AddDependentLib(StringRef Lib);
1559
1560 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1561
1562 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1563 F->setLinkage(getFunctionLinkage(GD));
1564 }
1565
1566 /// Return the appropriate linkage for the vtable, VTT, and type information
1567 /// of the given class.
1568 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1569
1570 /// Returns true if a vtable with the given linkage may be emitted with more
1571 /// than one address in the program, because the vtable is weak and the
1572 /// target's ABI allows weak vtables to be duplicated across images.
1573 bool mayVTableBeDuplicated(llvm::GlobalValue::LinkageTypes Linkage) const;
1574
1575 /// Return the store size, in character units, of the given LLVM type.
1576 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1577
1578 /// Returns LLVM linkage for a declarator.
1579 llvm::GlobalValue::LinkageTypes
1580 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage);
1581
1582 /// Returns LLVM linkage for a declarator.
1583 llvm::GlobalValue::LinkageTypes
1584 getLLVMLinkageVarDefinition(const VarDecl *VD);
1585
1586 /// Emit all the global annotations.
1587 void EmitGlobalAnnotations();
1588
1589 /// Emit an annotation string.
1590 llvm::Constant *EmitAnnotationString(StringRef Str);
1591
1592 /// Emit the annotation's translation unit.
1593 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1594
1595 /// Emit the annotation line number.
1596 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1597
1598 /// Emit additional args of the annotation.
1599 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1600
1601 /// Generate the llvm::ConstantStruct which contains the annotation
1602 /// information for a given GlobalValue. The annotation struct is
1603 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1604 /// GlobalValue being annotated. The second field is the constant string
1605 /// created from the AnnotateAttr's annotation. The third field is a constant
1606 /// string containing the name of the translation unit. The fourth field is
1607 /// the line number in the file of the annotated value declaration.
1608 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1609 const AnnotateAttr *AA,
1610 SourceLocation L);
1611
1612 /// Add global annotations that are set on D, for the global GV. Those
1613 /// annotations are emitted during finalization of the LLVM code.
1614 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1615
1616 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1617 SourceLocation Loc) const;
1618
1619 bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV,
1620 SourceLocation Loc, QualType Ty,
1621 StringRef Category = StringRef()) const;
1622
1623 /// Imbue XRay attributes to a function, applying the always/never attribute
1624 /// lists in the process. Returns true if we did imbue attributes this way,
1625 /// false otherwise.
1626 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1627 StringRef Category = StringRef()) const;
1628
1629 /// \returns true if \p Fn at \p Loc should be excluded from profile
1630 /// instrumentation by the SCL passed by \p -fprofile-list.
1631 ProfileList::ExclusionType
1632 isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const;
1633
1634 /// \returns true if \p Fn at \p Loc should be excluded from profile
1635 /// instrumentation.
1636 ProfileList::ExclusionType
1637 isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
1638 SourceLocation Loc) const;
1639
1640 SanitizerMetadata *getSanitizerMetadata() {
1641 return SanitizerMD.get();
1642 }
1643
1644 void addDeferredVTable(const CXXRecordDecl *RD) {
1645 DeferredVTables.push_back(x: RD);
1646 }
1647
1648 /// Emit code for a single global function or var decl. Forward declarations
1649 /// are emitted lazily.
1650 void EmitGlobal(GlobalDecl D);
1651
1652 /// Record that new[] was called for the class, transform vector deleting
1653 /// destructor definition in a form of alias to the actual definition.
1654 void requireVectorDestructorDefinition(const CXXRecordDecl *RD);
1655
1656 /// Record a pending __global_delete variant that may need a forwarding body.
1657 void addPendingGlobalDelete(llvm::GlobalAlias *GlobalDeleteAlias,
1658 const FunctionDecl *OperatorDeleteFD);
1659
1660 /// Get or create the MSVC-compatible __global_delete wrapper for the given
1661 /// global ::operator delete, registering it as a pending variant so a
1662 /// forwarding body can be emitted if this TU directly uses global
1663 /// ::operator delete.
1664 llvm::Constant *
1665 getOrCreateMSVCGlobalDeleteWrapper(const FunctionDecl *GlobOD);
1666
1667 /// Note that global ::operator delete is directly used in this TU.
1668 void noteDirectGlobalDelete();
1669
1670 /// Emit __global_delete forwarding bodies for any pending variants,
1671 /// if this TU directly uses global ::operator delete.
1672 void emitGlobalDeleteForwardingBodies();
1673
1674 /// Check that class need vector deleting destructor body.
1675 bool classNeedsVectorDestructor(const CXXRecordDecl *RD);
1676
1677 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1678 void EmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
1679
1680 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1681
1682 /// Set attributes which are common to any form of a global definition (alias,
1683 /// Objective-C method, function, global variable).
1684 ///
1685 /// NOTE: This should only be called for definitions.
1686 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1687
1688 void addReplacement(StringRef Name, llvm::Constant *C);
1689
1690 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1691
1692 /// Emit a code for threadprivate directive.
1693 /// \param D Threadprivate declaration.
1694 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1695
1696 /// Emit a code for declare reduction construct.
1697 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1698 CodeGenFunction *CGF = nullptr);
1699
1700 /// Emit a code for declare mapper construct.
1701 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1702 CodeGenFunction *CGF = nullptr);
1703
1704 // Emit code for the OpenACC Declare declaration.
1705 void EmitOpenACCDeclare(const OpenACCDeclareDecl *D,
1706 CodeGenFunction *CGF = nullptr);
1707 // Emit code for the OpenACC Routine declaration.
1708 void EmitOpenACCRoutine(const OpenACCRoutineDecl *D,
1709 CodeGenFunction *CGF = nullptr);
1710
1711 /// Emit a code for requires directive.
1712 /// \param D Requires declaration
1713 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1714
1715 /// Emit a code for the allocate directive.
1716 /// \param D The allocate declaration
1717 void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1718
1719 /// Return the alignment specified in an allocate directive, if present.
1720 std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD);
1721
1722 /// Returns whether the given record has hidden LTO visibility and therefore
1723 /// may participate in (single-module) CFI and whole-program vtable
1724 /// optimization.
1725 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1726
1727 /// Returns whether the given record has public LTO visibility (regardless of
1728 /// -lto-whole-program-visibility) and therefore may not participate in
1729 /// (single-module) CFI and whole-program vtable optimization.
1730 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD);
1731
1732 /// Returns the vcall visibility of the given type. This is the scope in which
1733 /// a virtual function call could be made which ends up being dispatched to a
1734 /// member function of this class. This scope can be wider than the visibility
1735 /// of the class itself when the class has a more-visible dynamic base class.
1736 /// The client should pass in an empty Visited set, which is used to prevent
1737 /// redundant recursive processing.
1738 llvm::GlobalObject::VCallVisibility
1739 GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1740 llvm::DenseSet<const CXXRecordDecl *> &Visited);
1741
1742 /// Emit type metadata for the given vtable using the given layout.
1743 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1744 llvm::GlobalVariable *VTable,
1745 const VTableLayout &VTLayout);
1746
1747 llvm::Type *getVTableComponentType() const;
1748
1749 /// Generate a cross-DSO type identifier for MD.
1750 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1751
1752 /// Generate a KCFI type identifier for T.
1753 llvm::ConstantInt *CreateKCFITypeId(QualType T, StringRef Salt);
1754
1755 /// Create a metadata identifier for the given function type.
1756 llvm::Metadata *CreateMetadataIdentifierForFnType(QualType T);
1757
1758 /// Create a metadata identifier for the given type. This may either be an
1759 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1760 /// internal identifiers).
1761 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1762
1763 /// Create a metadata identifier for the Call Graph Section.
1764 /// This is a generalized type identifier that is guaranteed to be an
1765 /// MDString.
1766 llvm::Metadata *CreateMetadataIdentifierForCallGraphType(QualType T);
1767
1768 /// Applies C default argument promotions to a parameter type for Call Graph
1769 /// Section type reconstruction.
1770 QualType GetCallGraphPromotedType(QualType Ty) const;
1771
1772 /// Reconstructs a FunctionProtoType for an unprototyped function type
1773 /// (FunctionNoProtoType) using the given parameter/argument types, applying
1774 /// default argument promotions to ensure call-site and definition-site type
1775 /// signatures match.
1776 QualType ReconstructCallGraphPrototype(const FunctionNoProtoType *FNPT,
1777 ArrayRef<QualType> ParamTypes) const;
1778
1779 /// Create a metadata identifier that is intended to be used to check virtual
1780 /// calls via a member function pointer.
1781 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1782
1783 /// Create a metadata identifier for the generalization of the given type.
1784 /// This may either be an MDString (for external identifiers) or a distinct
1785 /// unnamed MDNode (for internal identifiers).
1786 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1787
1788 /// Create and attach type metadata to the given function.
1789 void createFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1790 llvm::Function *F);
1791
1792 /// Create and attach callgraph metadata if the function is a potential
1793 /// indirect call target to support call graph section.
1794 void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F);
1795
1796 /// Create and attach callee_type metadata to the given call.
1797 void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB);
1798
1799 /// Set type metadata to the given function.
1800 void setKCFIType(const FunctionDecl *FD, llvm::Function *F);
1801
1802 /// Emit KCFI type identifier constants and remove unused identifiers.
1803 void finalizeKCFITypes();
1804
1805 /// Whether this function's return type has no side effects, and thus may
1806 /// be trivially discarded if it is unused.
1807 bool MayDropFunctionReturn(const ASTContext &Context,
1808 QualType ReturnType) const;
1809
1810 /// Returns whether this module needs the "all-vtables" type identifier.
1811 bool NeedAllVtablesTypeId() const;
1812
1813 /// Create and attach type metadata for the given vtable.
1814 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1815 const CXXRecordDecl *RD);
1816
1817 /// Return a vector of most-base classes for RD. This is used to implement
1818 /// control flow integrity checks for member function pointers.
1819 ///
1820 /// A most-base class of a class C is defined as a recursive base class of C,
1821 /// including C itself, that does not have any bases.
1822 SmallVector<const CXXRecordDecl *, 0>
1823 getMostBaseClasses(const CXXRecordDecl *RD);
1824
1825 /// Get the declaration of std::terminate for the platform.
1826 llvm::FunctionCallee getTerminateFn();
1827
1828 llvm::SanitizerStatReport &getSanStats();
1829
1830 llvm::Value *
1831 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1832
1833 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1834 /// information in the program executable. The argument information stored
1835 /// includes the argument name, its type, the address and access qualifiers
1836 /// used. This helper can be used to generate metadata for source code kernel
1837 /// function as well as generated implicitly kernels. If a kernel is generated
1838 /// implicitly null value has to be passed to the last two parameters,
1839 /// otherwise all parameters must have valid non-null values.
1840 /// \param FN is a pointer to IR function being generated.
1841 /// \param FD is a pointer to function declaration if any.
1842 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1843 void GenKernelArgMetadata(llvm::Function *FN,
1844 const FunctionDecl *FD = nullptr,
1845 CodeGenFunction *CGF = nullptr);
1846
1847 /// Get target specific null pointer.
1848 /// \param T is the LLVM type of the null pointer.
1849 /// \param QT is the clang QualType of the null pointer.
1850 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1851
1852 CharUnits getNaturalTypeAlignment(QualType T,
1853 LValueBaseInfo *BaseInfo = nullptr,
1854 TBAAAccessInfo *TBAAInfo = nullptr,
1855 bool forPointeeType = false);
1856 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1857 LValueBaseInfo *BaseInfo = nullptr,
1858 TBAAAccessInfo *TBAAInfo = nullptr);
1859 bool stopAutoInit();
1860
1861 /// Print the postfix for externalized static variable or kernels for single
1862 /// source offloading languages CUDA and HIP. The unique postfix is created
1863 /// using either the CUID argument, or the file's UniqueID and active macros.
1864 /// The fallback method without a CUID requires that the offloading toolchain
1865 /// does not define separate macros via the -cc1 options.
1866 void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
1867 const Decl *D) const;
1868
1869 /// Move some lazily-emitted states to the NewBuilder. This is especially
1870 /// essential for the incremental parsing environment like Clang Interpreter,
1871 /// because we'll lose all important information after each repl.
1872 void moveLazyEmissionStates(CodeGenModule *NewBuilder);
1873
1874 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1875 /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it,
1876 /// if a valid one was found.
1877 void handleCUDALaunchBoundsAttr(llvm::Function *F,
1878 const CUDALaunchBoundsAttr *A,
1879 int32_t *MaxThreadsVal = nullptr,
1880 int32_t *MinBlocksVal = nullptr,
1881 int32_t *MaxClusterRankVal = nullptr);
1882
1883 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1884 /// to \p F. Alternatively, the work group size can be taken from a \p
1885 /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is
1886 /// stored in it, if a valid one was found. If \p MaxThreadsVal is not
1887 /// nullptr, the max threads value is stored in it, if a valid one was found.
1888 void handleAMDGPUFlatWorkGroupSizeAttr(
1889 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A,
1890 const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr,
1891 int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr);
1892
1893 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1894 void handleAMDGPUWavesPerEUAttr(llvm::Function *F,
1895 const AMDGPUWavesPerEUAttr *A);
1896
1897 llvm::Constant *
1898 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1899 const VarDecl *D,
1900 ForDefinition_t IsForDefinition = NotForDefinition);
1901
1902 // FIXME: Hardcoding priority here is gross.
1903 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1904 unsigned LexOrder = ~0U,
1905 llvm::Constant *AssociatedData = nullptr);
1906 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1907 bool IsDtorAttrFunc = false);
1908
1909 // Return whether structured convergence intrinsics should be generated for
1910 // this target.
1911 bool shouldEmitConvergenceTokens() const {
1912 // TODO: this should probably become unconditional once the controlled
1913 // convergence becomes the norm.
1914 return getTriple().isSPIRVLogical() || getTriple().isDXIL();
1915 }
1916
1917 void addUndefinedGlobalForTailCall(
1918 std::pair<const FunctionDecl *, SourceLocation> Global) {
1919 MustTailCallUndefinedGlobals.insert(X: Global);
1920 }
1921
1922 bool shouldZeroInitPadding() const {
1923 // In C23 (N3096) $6.7.10:
1924 // """
1925 // If any object is initialized with an empty iniitializer, then it is
1926 // subject to default initialization:
1927 // - if it is an aggregate, every member is initialized (recursively)
1928 // according to these rules, and any padding is initialized to zero bits;
1929 // - if it is a union, the first named member is initialized (recursively)
1930 // according to these rules, and any padding is initialized to zero bits.
1931 //
1932 // If the aggregate or union contains elements or members that are
1933 // aggregates or unions, these rules apply recursively to the subaggregates
1934 // or contained unions.
1935 //
1936 // If there are fewer initializers in a brace-enclosed list than there are
1937 // elements or members of an aggregate, or fewer characters in a string
1938 // literal used to initialize an array of known size than there are elements
1939 // in the array, the remainder of the aggregate is subject to default
1940 // initialization.
1941 // """
1942 //
1943 // From my understanding, the standard is ambiguous in the following two
1944 // areas:
1945 // 1. For a union type with empty initializer, if the first named member is
1946 // not the largest member, then the bytes comes after the first named member
1947 // but before padding are left unspecified. An example is:
1948 // union U { int a; long long b;};
1949 // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left
1950 // unspecified.
1951 //
1952 // 2. It only mentions padding for empty initializer, but doesn't mention
1953 // padding for a non empty initialization list. And if the aggregation or
1954 // union contains elements or members that are aggregates or unions, and
1955 // some are non empty initializers, while others are empty initiailizers,
1956 // the padding initialization is unclear. An example is:
1957 // struct S1 { int a; long long b; };
1958 // struct S2 { char c; struct S1 s1; };
1959 // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a
1960 // and s2.s1.b are unclear.
1961 // struct S2 s2 = { 'c' };
1962 //
1963 // Here we choose to zero initiailize left bytes of a union type. Because
1964 // projects like the Linux kernel are relying on this behavior. If we don't
1965 // explicitly zero initialize them, the undef values can be optimized to
1966 // return gabage data. We also choose to zero initialize paddings for
1967 // aggregates and unions, no matter they are initialized by empty
1968 // initializers or non empty initializers. This can provide a consistent
1969 // behavior. So projects like the Linux kernel can rely on it.
1970 return !getLangOpts().CPlusPlus;
1971 }
1972
1973 // Helper to get the alignment for a variable.
1974 unsigned getVtableGlobalVarAlignment(const VarDecl *D = nullptr) {
1975 LangAS AS = GetGlobalVarAddressSpace(D);
1976 unsigned PAlign = Context.getLangOpts().RelativeCXXABIVTables
1977 ? 32
1978 : getTarget().getPointerAlign(AddrSpace: AS);
1979 return PAlign;
1980 }
1981
1982 /// Helper function to construct a TrapReasonBuilder
1983 TrapReasonBuilder BuildTrapReason(unsigned DiagID, TrapReason &TR) {
1984 return TrapReasonBuilder(&getDiags(), DiagID, TR);
1985 }
1986
1987 llvm::Constant *performAddrSpaceCast(llvm::Constant *Src,
1988 llvm::Type *DestTy) {
1989 // Since target may map different address spaces in AST to the same address
1990 // space, an address space conversion may end up as a bitcast.
1991 return llvm::ConstantExpr::getPointerCast(C: Src, Ty: DestTy);
1992 }
1993
1994 std::optional<llvm::Attribute::AttrKind>
1995 StackProtectorAttribute(const Decl *D) const;
1996
1997 std::string getPFPFieldName(const FieldDecl *FD);
1998 llvm::GlobalValue *getPFPDeactivationSymbol(const FieldDecl *FD);
1999
2000private:
2001 /// Translate an llvm::abi::ArgInfo (computed by the LLVMABI library) into
2002 /// the clang ABIArgInfo consumed by the rest of CodeGen. Used by the
2003 /// experimental ABI lowering path.
2004 ABIArgInfo convertABIArgInfo(const llvm::abi::ArgInfo &AbiInfo,
2005 QualType Type);
2006
2007 /// Process #pragma comment(copyright, ...).
2008 void ProcessPragmaCommentCopyright(StringRef Comment, bool isFromASTFile);
2009
2010 bool shouldDropDLLAttribute(const Decl *D, const llvm::GlobalValue *GV) const;
2011
2012 llvm::Constant *GetOrCreateLLVMFunction(
2013 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
2014 bool DontDefer = false, bool IsThunk = false,
2015 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
2016 ForDefinition_t IsForDefinition = NotForDefinition);
2017
2018 // Adds a declaration to the list of multi version functions if not present.
2019 void AddDeferredMultiVersionResolverToEmit(GlobalDecl GD);
2020
2021 // References to multiversion functions are resolved through an implicitly
2022 // defined resolver function. This function is responsible for creating
2023 // the resolver symbol for the provided declaration. The value returned
2024 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
2025 // that feature and for a regular function (llvm::GlobalValue) otherwise.
2026 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD);
2027
2028 // Set attributes to a resolver function generated by Clang.
2029 // GD is either the cpu_dispatch declaration or an arbitrarily chosen
2030 // function declaration that triggered the implicit generation of this
2031 // resolver function.
2032 //
2033 /// NOTE: This should only be called for definitions.
2034 void setMultiVersionResolverAttributes(llvm::Function *Resolver,
2035 GlobalDecl GD);
2036
2037 // In scenarios where a function is not known to be a multiversion function
2038 // until a later declaration, it is sometimes necessary to change the
2039 // previously created mangled name to align with requirements of whatever
2040 // multiversion function kind the function is now known to be. This function
2041 // is responsible for performing such mangled name updates.
2042 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
2043 StringRef &CurName);
2044
2045 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
2046 llvm::AttrBuilder &AttrBuilder,
2047 bool SetTargetFeatures = true);
2048 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
2049
2050 /// Set function attributes for a function declaration.
2051 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2052 bool IsIncompleteFunction, bool IsThunk);
2053
2054 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
2055
2056 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
2057 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
2058
2059 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
2060 void EmitAliasDefinition(GlobalDecl GD);
2061 void emitIFuncDefinition(GlobalDecl GD);
2062 void emitCPUDispatchDefinition(GlobalDecl GD);
2063 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
2064 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
2065
2066 // C++ related functions.
2067
2068 void EmitDeclContext(const DeclContext *DC);
2069 void EmitLinkageSpec(const LinkageSpecDecl *D);
2070 void EmitTopLevelStmt(const TopLevelStmtDecl *D);
2071
2072 /// Emit the function that initializes C++ thread_local variables.
2073 void EmitCXXThreadLocalInitFunc();
2074
2075 /// Emit the function that initializes global variables for a C++ Module.
2076 void EmitCXXModuleInitFunc(clang::Module *Primary);
2077
2078 /// Emit the function that initializes C++ globals.
2079 void EmitCXXGlobalInitFunc();
2080
2081 /// Emit the function that performs cleanup associated with C++ globals.
2082 void EmitCXXGlobalCleanUpFunc();
2083
2084 /// Emit the function that initializes the specified global (if PerformInit is
2085 /// true) and registers its destructor.
2086 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
2087 llvm::GlobalVariable *Addr,
2088 bool PerformInit);
2089
2090 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
2091 llvm::Function *InitFunc, InitSegAttr *ISA);
2092
2093 /// EmitCtorList - Generates a global array of functions and priorities using
2094 /// the given list and name. This array will have appending linkage and is
2095 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
2096 void EmitCtorList(CtorList &Fns, const char *GlobalName);
2097
2098 /// Emit any needed decls for which code generation was deferred.
2099 void EmitDeferred();
2100
2101 /// Try to emit external vtables as available_externally if they have emitted
2102 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
2103 /// is not allowed to create new references to things that need to be emitted
2104 /// lazily.
2105 void EmitVTablesOpportunistically();
2106
2107 /// Call replaceAllUsesWith on all pairs in Replacements.
2108 void applyReplacements();
2109
2110 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
2111 void applyGlobalValReplacements();
2112
2113 void checkAliases();
2114
2115 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
2116
2117 /// Register functions annotated with __attribute__((destructor)) using
2118 /// __cxa_atexit, if it is available, or atexit otherwise.
2119 void registerGlobalDtorsWithAtExit();
2120
2121 // When using sinit and sterm functions, unregister
2122 // __attribute__((destructor)) annotated functions which were previously
2123 // registered by the atexit subroutine using unatexit.
2124 void unregisterGlobalDtorsWithUnAtExit();
2125
2126 /// Emit deferred multiversion function resolvers and associated variants.
2127 void emitMultiVersionFunctions();
2128
2129 /// Emit any vtables which we deferred and still have a use for.
2130 void EmitDeferredVTables();
2131
2132 /// Emit a dummy function that reference a CoreFoundation symbol when
2133 /// @available is used on Darwin.
2134 void emitAtAvailableLinkGuard();
2135
2136 /// Emit the llvm.used and llvm.compiler.used metadata.
2137 void emitLLVMUsed();
2138
2139 /// For C++20 Itanium ABI, emit the initializers for the module.
2140 void EmitModuleInitializers(clang::Module *Primary);
2141
2142 /// Emit the link options introduced by imported modules.
2143 void EmitModuleLinkOptions();
2144
2145 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
2146 /// have a resolver name that matches 'Elem' to instead resolve to the name of
2147 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
2148 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
2149 /// may not reference aliases. Redirection is only performed if 'Elem' is only
2150 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
2151 /// redirection is successful, and 'false' is returned otherwise.
2152 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
2153 llvm::GlobalValue *CppFunc);
2154
2155 /// Emit aliases for internal-linkage declarations inside "C" language
2156 /// linkage specifications, giving them the "expected" name where possible.
2157 void EmitStaticExternCAliases();
2158
2159 void EmitDeclMetadata();
2160
2161 /// Emit the Clang version as llvm.ident metadata.
2162 void EmitVersionIdentMetadata();
2163
2164 /// Emit the Clang commandline as llvm.commandline metadata.
2165 void EmitCommandLineMetadata();
2166
2167 /// Emit the module flag metadata used to pass options controlling the
2168 /// the backend to LLVM.
2169 void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts);
2170
2171 /// Emits OpenCL specific Metadata e.g. OpenCL version.
2172 void EmitOpenCLMetadata();
2173
2174 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
2175 /// .gcda files in a way that persists in .bc files.
2176 void EmitCoverageFile();
2177
2178 /// Given a sycl_kernel_entry_point attributed function, emit the
2179 /// corresponding SYCL kernel caller offload entry point function.
2180 void EmitSYCLKernelCaller(const FunctionDecl *KernelEntryPointFn,
2181 ASTContext &Ctx);
2182
2183 /// Attach the "sycl-module-id" function attribute to \p Fn, to record the
2184 /// module ID for the translation unit. This attribute is applied to SYCL
2185 /// kernel entry point functions and functions declared with the
2186 /// sycl_external attribute to enable them to be identified as entry points
2187 /// by clang-sycl-linker during device-code splitting.
2188 void addSYCLModuleIdAttr(llvm::Function *Fn);
2189
2190 /// Embed the finalized SYCL device binary named by -foffload-include-binary
2191 /// into the host module.
2192 /// \return the function that registers the binary with the runtime, or null
2193 /// if the binary could not be read.
2194 llvm::Function *embedSYCLDeviceBinary();
2195
2196 /// Determine whether the definition must be emitted; if this returns \c
2197 /// false, the definition can be emitted lazily if it's used.
2198 bool MustBeEmitted(const ValueDecl *D);
2199
2200 /// Determine whether the definition can be emitted eagerly, or should be
2201 /// delayed until the end of the translation unit. This is relevant for
2202 /// definitions whose linkage can change, e.g. implicit function instantions
2203 /// which may later be explicitly instantiated.
2204 bool MayBeEmittedEagerly(const ValueDecl *D);
2205
2206 /// Check whether we can use a "simpler", more core exceptions personality
2207 /// function.
2208 void SimplifyPersonality();
2209
2210 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
2211 /// attributes which can be simply added to a function.
2212 void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
2213 bool AttrOnCallSite,
2214 llvm::AttrBuilder &FuncAttrs);
2215
2216 /// Helper function for ConstructAttributeList and
2217 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
2218 /// attributes to add to a function with the given properties.
2219 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
2220 bool AttrOnCallSite,
2221 llvm::AttrBuilder &FuncAttrs);
2222
2223 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
2224 StringRef Suffix,
2225 bool ForceString = false);
2226
2227 /// Emit deactivation symbols for any PFP fields whose offset is taken with
2228 /// offsetof.
2229 void emitPFPFieldsWithEvaluatedOffset();
2230};
2231
2232} // end namespace CodeGen
2233} // end namespace clang
2234
2235#endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
2236