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