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

source code of clang/lib/CodeGen/CodeGenModule.h