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