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