clang 24.0.0git
CIRGenModule.h
Go to the documentation of this file.
1//===--- CIRGenModule.h - Per-Module state for CIR gen ----------*- 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 CIR translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H
14#define LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H
15
16#include "CIRGenBuilder.h"
17#include "CIRGenCUDARuntime.h"
18#include "CIRGenCall.h"
19#include "CIRGenOpenMPRuntime.h"
20#include "CIRGenTypeCache.h"
21#include "CIRGenTypes.h"
22#include "CIRGenVTables.h"
23#include "CIRGenValue.h"
24
25#include "clang/AST/CharUnits.h"
28
29#include "TargetInfo.h"
30#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
31#include "mlir/IR/Builders.h"
32#include "mlir/IR/BuiltinOps.h"
33#include "mlir/IR/MLIRContext.h"
34#include "clang/AST/Decl.h"
39#include "llvm/ADT/SetVector.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/StringMap.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/TargetParser/Triple.h"
44
45namespace clang {
46class ASTContext;
47class CodeGenOptions;
48class Decl;
49class GlobalDecl;
50class LangOptions;
54class TargetInfo;
55class VarDecl;
56
57namespace CIRGen {
58
59class CIRGenFunction;
60class CIRGenCXXABI;
61
62enum ForDefinition_t : bool { NotForDefinition = false, ForDefinition = true };
63
64/// This class organizes the cross-function state that is used while generating
65/// CIR code.
66class CIRGenModule : public CIRGenTypeCache {
67 CIRGenModule(CIRGenModule &) = delete;
68 CIRGenModule &operator=(CIRGenModule &) = delete;
69
70public:
71 CIRGenModule(mlir::MLIRContext &mlirContext, clang::ASTContext &astContext,
72 const clang::CodeGenOptions &cgo,
74
76
77private:
78 mutable std::unique_ptr<TargetCIRGenInfo> theTargetCIRGenInfo;
79
80 CIRGenBuilderTy builder;
81
82 /// Hold Clang AST information.
83 clang::ASTContext &astContext;
84
85 const clang::LangOptions &langOpts;
86
87 /// Seeded from langOpts and then pushed and popped by clang::atomic.
88 clang::AtomicOptions atomicOpts;
89
90 const clang::CodeGenOptions &codeGenOpts;
91
92 /// A "module" matches a c/cpp source file: containing a list of functions.
93 mlir::ModuleOp theModule;
94
95 /// Cached data layout for the module. Built lazily: the layout spec is
96 /// attached after construction, in CIRGenerator::Initialize.
97 mutable std::optional<cir::CIRDataLayout> dataLayout;
98
100
101 const clang::TargetInfo &target;
102
103 std::unique_ptr<CIRGenCXXABI> abi;
104
105 CIRGenTypes genTypes;
106
107 /// Holds information about C++ vtables.
108 CIRGenVTables vtables;
109
110 /// Holds the CUDA runtime
111 std::unique_ptr<CIRGenCUDARuntime> cudaRuntime;
112
113 /// Holds the OpenMP runtime
114 std::unique_ptr<CIRGenOpenMPRuntime> openMPRuntime;
115
116 /// Per-function codegen information. Updated everytime emitCIR is called
117 /// for FunctionDecls's.
118 CIRGenFunction *curCGF = nullptr;
119
121
122 /// Accumulated record layout entries, materialized in release().
123 llvm::SmallVector<mlir::NamedAttribute> recordLayoutEntries;
124
125 /// Whether C++20 named modules get their own module initializer function,
126 /// which requires the Itanium mangling of the initializer name.
127 bool cxx20ModuleInits = false;
128
129 /// The complete set of modules that have been imported.
130 llvm::SetVector<clang::Module *> importedModules;
131
132 /// The location of the first import declaration of each imported module.
133 llvm::DenseMap<clang::Module *, clang::SourceLocation> moduleImportLocs;
134
135 /// The set of modules for which the module initializers have been emitted.
136 llvm::SmallPtrSet<clang::Module *, 16> emittedModuleInitializers;
137
138 /// The Itanium-mangled name of the initializer function of a C++20 named
139 /// module.
140 std::string getModuleInitializerName(clang::Module *mod);
141
142 llvm::DenseSet<clang::GlobalDecl> diagnosedConflictingDefinitions;
143
144 /// -------
145 /// Annotations
146 /// -------
147
148 /// We store each annotation as an attribute of GlobalOp and FuncOp rather
149 /// than collecting them into a single module-level list. The deferred map
150 /// lets us attach annotations at the end of codegen so the most up-to-date
151 /// ValueDecl (which carries all inherited annotations) is used.
152
153 /// Used for uniquing of annotation arguments.
154 llvm::DenseMap<unsigned, mlir::ArrayAttr> annotationArgs;
155
156 /// Store deferred function annotations so they can be emitted at the end
157 /// with the most up to date ValueDecl that will have all the inherited
158 /// annotations.
159 llvm::DenseMap<llvm::StringRef, const clang::ValueDecl *> deferredAnnotations;
160
161 /// A queue of (optional) vtables to consider emitting.
162 std::vector<const CXXRecordDecl *> deferredVTables;
163
164 /// A queue of (optional) vtables that may be emitted opportunistically.
165 std::vector<const CXXRecordDecl *> opportunisticVTables;
166
167 void createCUDARuntime();
168 void createOpenMPRuntime();
169 void setOpenCLVersionAttr(llvm::StringRef attrName, unsigned version);
170
171 /// A helper for constructAttributeList that handles return attributes.
172 void constructFunctionReturnAttributes(const CIRGenFunctionInfo &info,
173 const Decl *targetDecl, bool isThunk,
174 mlir::NamedAttrList &retAttrs);
175 /// A helper for constructAttributeList that handles argument attributes.
176 void constructFunctionArgumentAttributes(
177 const CIRGenFunctionInfo &info, const clang::Decl *targetDecl,
178 bool isThunk, bool attrOnCallSite,
180 /// A helper function for constructAttributeList that determines whether a
181 /// return value might have been discarded.
182 bool mayDropFunctionReturn(const ASTContext &context, QualType retTy);
183 /// A helper function for constructAttributeList that determines whether
184 /// `noundef` on a return is possible.
185 bool hasStrictReturn(QualType retTy, const Decl *targetDecl);
186
187 llvm::DenseMap<const Expr *, mlir::Operation *>
188 materializedGlobalTemporaryMap;
189
190public:
191 mlir::ModuleOp getModule() const { return theModule; }
192 CIRGenBuilderTy &getBuilder() { return builder; }
193
194 /// Queue a record layout entry for materialization in release().
195 void addRecordLayout(mlir::StringAttr name, cir::RecordLayoutAttr attr) {
196 recordLayoutEntries.push_back(mlir::NamedAttribute(name, attr));
197 }
198 clang::ASTContext &getASTContext() const { return astContext; }
199 const clang::TargetInfo &getTarget() const { return target; }
200 const clang::CodeGenOptions &getCodeGenOpts() const { return codeGenOpts; }
201 clang::DiagnosticsEngine &getDiags() const { return diags; }
202 CIRGenTypes &getTypes() { return genTypes; }
203 const clang::LangOptions &getLangOpts() const { return langOpts; }
204
205 /// The atomic options in effect at the point currently being emitted.
206 /// clang::atomic adjusts these for the extent of the statement it is attached
207 /// to, so they are module state rather than a fixed language option.
208 clang::AtomicOptions getAtomicOpts() const { return atomicOpts; }
209 void setAtomicOpts(clang::AtomicOptions opts) { atomicOpts = opts; }
210
211 CIRGenCXXABI &getCXXABI() const { return *abi; }
212 mlir::MLIRContext &getMLIRContext() { return *builder.getContext(); }
213
215 if (!dataLayout)
216 dataLayout.emplace(theModule);
217 return *dataLayout;
218 }
219
220 /// -------
221 /// Handling globals
222 /// -------
223
224 mlir::Operation *lastGlobalOp = nullptr;
225
226 /// Keep a map between lambda fields and names, this needs to be per module
227 /// since lambdas might get generated later as part of defered work, and since
228 /// the pointers are supposed to be uniqued, should be fine. Revisit this if
229 /// it ends up taking too much memory.
230 llvm::DenseMap<const clang::FieldDecl *, llvm::StringRef> lambdaFieldToName;
231
232 /// Add a global value to the llvmUsed list.
233 void addUsedGlobal(cir::CIRGlobalValueInterface gv);
234
235 /// Add a global value to the llvmCompilerUsed list.
236 void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv);
237
238 /// Add a global to a list to be added to the llvm.compiler.used metadata.
239 void addUsedOrCompilerUsedGlobal(cir::CIRGlobalValueInterface gv);
240
241 /// Emit llvm.used and llvm.compiler.used globals.
242 void emitLLVMUsed();
243
244 /// Tell the consumer that this variable has been instantiated.
246
247 llvm::DenseMap<const Decl *, cir::GlobalOp> staticLocalDeclMap;
248 llvm::DenseMap<const VarDecl *, cir::GlobalOp> initializerConstants;
249
250 /// Cache for O(1) symbol lookups by name, replacing the O(N) linear scan
251 /// in SymbolTable::lookupSymbolIn that getGlobalValue used previously.
252 llvm::StringMap<mlir::Operation *> symbolLookupCache;
253
254 mlir::Operation *getGlobalValue(llvm::StringRef ref);
255
256 /// O(1) lookup of a FuncOp by name in the symbol cache.
257 /// Returns nullptr if the name is not found or is not a FuncOp.
258 cir::FuncOp lookupFuncOp(llvm::StringRef name) {
259 auto *op = getGlobalValue(name);
260 return op ? mlir::dyn_cast<cir::FuncOp>(op) : cir::FuncOp{};
261 }
262
263 void insertGlobalSymbol(mlir::Operation *op) {
264 if (auto sym = mlir::dyn_cast<mlir::SymbolOpInterface>(op))
265 symbolLookupCache[sym.getName()] = op;
266 }
267 void eraseGlobalSymbol(mlir::Operation *op) {
268 if (auto sym = mlir::dyn_cast<mlir::SymbolOpInterface>(op)) {
269 auto it = symbolLookupCache.find(sym.getName());
270 if (it != symbolLookupCache.end() && it->second == op)
271 symbolLookupCache.erase(it);
272 }
273 }
274
275 cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d) {
276 return staticLocalDeclMap[d];
277 }
278
279 void setStaticLocalDeclAddress(const VarDecl *d, cir::GlobalOp c) {
280 staticLocalDeclMap[d] = c;
281 }
282
283 cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d,
284 cir::GlobalLinkageKind linkage);
285
286 Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr,
287 CharUnits align);
288
289 /// If the specified mangled name is not in the module, create and return an
290 /// mlir::GlobalOp value
291 cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty,
292 LangAS langAS, const VarDecl *d,
293 ForDefinition_t isForDefinition);
294
295 cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
296 ForDefinition_t isForDefinition);
297
298 cir::GlobalOp
299 createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t,
300 bool isConstant = false,
301 mlir::ptr::MemorySpaceAttrInterface addrSpace = {},
302 mlir::Operation *insertPoint = nullptr);
303
304 /// Add a global constructor or destructor to the module.
305 /// The priority is optional, if not specified, the default priority is used.
306 void addGlobalCtor(cir::FuncOp ctor,
307 std::optional<int> priority = std::nullopt);
308 void addGlobalDtor(cir::FuncOp dtor,
309 std::optional<int> priority = std::nullopt);
310
312 // In C23 (N3096) $6.7.10:
313 // """
314 // If any object is initialized with an empty initializer, then it is
315 // subject to default initialization:
316 // - if it is an aggregate, every member is initialized (recursively)
317 // according to these rules, and any padding is initialized to zero bits;
318 // - if it is a union, the first named member is initialized (recursively)
319 // according to these rules, and any padding is initialized to zero bits.
320 //
321 // If the aggregate or union contains elements or members that are
322 // aggregates or unions, these rules apply recursively to the subaggregates
323 // or contained unions.
324 //
325 // If there are fewer initializers in a brace-enclosed list than there are
326 // elements or members of an aggregate, or fewer characters in a string
327 // literal used to initialize an array of known size than there are elements
328 // in the array, the remainder of the aggregate is subject to default
329 // initialization.
330 // """
331 //
332 // The standard seems ambiguous in the following two areas:
333 // 1. For a union type with empty initializer, if the first named member is
334 // not the largest member, then the bytes comes after the first named member
335 // but before padding are left unspecified. An example is:
336 // union U { int a; long long b;};
337 // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left
338 // unspecified.
339 //
340 // 2. It only mentions padding for empty initializer, but doesn't mention
341 // padding for a non empty initialization list. And if the aggregation or
342 // union contains elements or members that are aggregates or unions, and
343 // some are non empty initializers, while others are empty initializers,
344 // the padding initialization is unclear. An example is:
345 // struct S1 { int a; long long b; };
346 // struct S2 { char c; struct S1 s1; };
347 // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a
348 // and s2.s1.b are unclear.
349 // struct S2 s2 = { 'c' };
350 //
351 // Here we choose to zero initiailize left bytes of a union type because
352 // projects like the Linux kernel are relying on this behavior. If we don't
353 // explicitly zero initialize them, the undef values can be optimized to
354 // return garbage data. We also choose to zero initialize paddings for
355 // aggregates and unions, no matter they are initialized by empty
356 // initializers or non empty initializers. This can provide a consistent
357 // behavior. So projects like the Linux kernel can rely on it.
358 return !getLangOpts().CPlusPlus;
359 }
360
361 llvm::StringMap<unsigned> cgGlobalNames;
362 std::string getUniqueGlobalName(const std::string &baseName);
363
364 /// Return the mlir::Value for the address of the given global variable.
365 /// If Ty is non-null and if the global doesn't exist, then it will be created
366 /// with the specified type instead of whatever the normal requested type
367 /// would be. If IsForDefinition is true, it is guaranteed that an actual
368 /// global with type Ty will be returned, not conversion of a variable with
369 /// the same mangled name but some other type.
370 mlir::Value
371 getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty = {},
372 ForDefinition_t isForDefinition = NotForDefinition);
373
374 /// Cast \p addr, the address of the global \p vd, to the address space of
375 /// the declared type of \p vd if they differ.
376 mlir::Value castGlobalToDeclAddrSpace(mlir::Value addr, const VarDecl &vd);
377
378 /// Get or create a thunk function with the given name and type.
379 cir::FuncOp getAddrOfThunk(StringRef name, mlir::Type fnTy, GlobalDecl gd);
380
381 /// Return the mlir::GlobalViewAttr for the address of the given global.
382 cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d);
383
384 /// Get the GlobalOp of a template parameter object.
385 cir::GlobalOp
387 // Get the GlobalOp of a source_location object.
388 cir::GlobalOp
390
392 const CXXRecordDecl *derivedClass,
393 llvm::iterator_range<CastExpr::path_const_iterator> path);
394
395 /// Get the CIR attributes and calling convention to use for a particular
396 /// function type.
397 ///
398 /// \param name - The function name.
399 /// \param info - The function type information.
400 /// \param calleeInfo - The callee information these attributes are being
401 /// constructed for. If valid, the attributes applied to this decl may
402 /// contribute to the function attributes and calling convention.
403 /// \param attrs [out] - On return, the attribute list to use.
404 /// \param callingConv [out] - On return, the calling convention to use.
405 /// \param attrOnCallSite - Whether or not the attributes are on a call site.
406 /// \param isThunk - Whether the function is a thunk.
408 llvm::StringRef name, const CIRGenFunctionInfo &info,
409 CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs,
411 mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv,
412 bool attrOnCallSite, bool isThunk);
413 /// Helper function for constructAttributeList/others. Builds a set of
414 /// function attributes to add to a function based on language opts, codegen
415 /// opts, and some small properties.
416 void addDefaultFunctionAttributes(StringRef name, bool hasOptNoneAttr,
417 bool attrOnCallSite,
418 mlir::NamedAttrList &attrs);
419
420 /// Returns the frame pointer kind to record on functions and on the module,
421 /// or std::nullopt when \p kind is CodeGenOptions::FramePointerKind::None,
422 /// the default, which is left implicit.
423 static std::optional<cir::FramePointerKind>
425
426 /// Will return a global variable of the given type. If a variable with a
427 /// different type already exists then a new variable with the right type
428 /// will be created and all uses of the old variable will be replaced with a
429 /// bitcast to the new variable.
431 mlir::Location loc, llvm::StringRef name, mlir::Type ty,
432 cir::GlobalLinkageKind linkage, clang::CharUnits alignment);
433
434 void emitVTable(const CXXRecordDecl *rd);
435
436 /// Return the appropriate linkage for the vtable, VTT, and type information
437 /// of the given class.
438 cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd);
439
440 /// Get the address of the RTTI descriptor for the given type.
441 mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty,
442 bool forEH = false);
443
444 static mlir::SymbolTable::Visibility getMLIRVisibility(Visibility v) {
445 switch (v) {
447 return mlir::SymbolTable::Visibility::Public;
448 case HiddenVisibility:
449 return mlir::SymbolTable::Visibility::Private;
451 // The distinction between ProtectedVisibility and DefaultVisibility is
452 // that symbols with ProtectedVisibility, while visible to the dynamic
453 // linker like DefaultVisibility, are guaranteed to always dynamically
454 // resolve to a symbol in the current shared object. There is currently no
455 // equivalent MLIR visibility, so we fall back on the fact that the symbol
456 // is visible.
457 return mlir::SymbolTable::Visibility::Public;
458 }
459 llvm_unreachable("unknown visibility!");
460 }
461
462 static cir::VisibilityKind getCIRVisibilityKind(Visibility v) {
463 switch (v) {
465 return cir::VisibilityKind::Default;
466 case HiddenVisibility:
467 return cir::VisibilityKind::Hidden;
469 return cir::VisibilityKind::Protected;
470 }
471
472 llvm_unreachable("unknown visibility!");
473 }
474
475 llvm::DenseMap<mlir::Attribute, cir::GlobalOp> constantStringMap;
476 llvm::DenseMap<const UnnamedGlobalConstantDecl *, cir::GlobalOp>
478 llvm::DenseMap<const CompoundLiteralExpr *, cir::GlobalOp>
480
481 cir::GlobalOp
486 cir::GlobalOp gv) {
487 [[maybe_unused]] bool ok = emittedCompoundLiterals.insert({e, gv}).second;
488 assert(ok && "compound literal global already emitted");
489 }
490
491 /// Return a constant array for the given string.
492 mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e);
493
494 /// Return a global symbol reference to a constant array for the given string
495 /// literal.
496 cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s,
497 llvm::StringRef name = ".str");
498
499 /// Return a global symbol reference to a constant array for the given string
500 /// literal.
501 cir::GlobalViewAttr
503 llvm::StringRef name = ".str");
504
505 /// Create a private constant global holding the null-terminated string
506 /// \p str, mirroring llvm::IRBuilder::CreateGlobalString.
507 cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str,
508 llvm::StringRef name);
509
510 /// Returns the address space for temporary allocations in the language. This
511 /// ensures that the allocated variable's address space matches the
512 /// expectations of the AST, rather than using the target's allocation address
513 /// space, which may lead to type mismatches in other parts of the IR.
515
516 /// Return the CIR address space attribute for a global in \p as, honoring
517 /// the target address space map where the LangAS fold would lose it.
518 mlir::ptr::MemorySpaceAttrInterface getGlobalCIRAddressSpace(LangAS as);
519
520 /// Set attributes which are common to any form of a global definition (alias,
521 /// Objective-C method, function, global variable).
522 ///
523 /// NOTE: This should only be called for definitions.
524 void setCommonAttributes(GlobalDecl gd, mlir::Operation *op);
525
527
528 /// Helpers to convert the presumed location of Clang's SourceLocation to an
529 /// MLIR Location.
530 mlir::Location getLoc(clang::SourceLocation cLoc);
531 mlir::Location getLoc(clang::SourceRange cRange);
532
533 /// Return the best known alignment for an unknown pointer to a
534 /// particular class.
536
537 /// FIXME: this could likely be a common helper and not necessarily related
538 /// with codegen.
540 LValueBaseInfo *baseInfo = nullptr,
541 bool forPointeeType = false);
544 LValueBaseInfo *baseInfo = nullptr);
545
546 /// Returns the minimum object size for an object of the given class type
547 /// (or a class derived from it).
549
550 /// Returns the minimum object size for an object of the given type.
556
557 /// TODO: Add TBAAAccessInfo
559 const CXXRecordDecl *baseDecl,
560 CharUnits expectedTargetAlign);
561
562 /// Returns the assumed alignment of a virtual base of a class.
564 const CXXRecordDecl *derived,
565 const CXXRecordDecl *vbase);
566
567 cir::FuncOp
569 const CIRGenFunctionInfo *fnInfo = nullptr,
570 cir::FuncType fnType = nullptr, bool dontDefer = false,
571 ForDefinition_t isForDefinition = NotForDefinition) {
572 return getAddrAndTypeOfCXXStructor(gd, fnInfo, fnType, dontDefer,
573 isForDefinition)
574 .second;
575 }
576
577 std::pair<cir::FuncType, cir::FuncOp> getAddrAndTypeOfCXXStructor(
578 clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo = nullptr,
579 cir::FuncType fnType = nullptr, bool dontDefer = false,
580 ForDefinition_t isForDefinition = NotForDefinition);
581
582 /// List of global values which are required to be present in the object file;
583 /// This is used for forcing visibility of symbols which may otherwise be
584 /// optimized out.
585 std::vector<cir::CIRGlobalValueInterface> llvmUsed;
586 std::vector<cir::CIRGlobalValueInterface> llvmCompilerUsed;
587
588 mlir::Type getVTableComponentType();
589 CIRGenVTables &getVTables() { return vtables; }
590
592 return vtables.getItaniumVTableContext();
593 }
595 return vtables.getItaniumVTableContext();
596 }
597
598 /// This contains all the decls which have definitions but which are deferred
599 /// for emission and therefore should only be output if they are actually
600 /// used. If a decl is in this, then it is known to have not been referenced
601 /// yet.
602 std::map<llvm::StringRef, clang::GlobalDecl> deferredDecls;
603
604 // This is a list of deferred decls which we have seen that *are* actually
605 // referenced. These get code generated when the module is done.
606 std::vector<clang::GlobalDecl> deferredDeclsToEmit;
608 deferredDeclsToEmit.emplace_back(GD);
609 }
610
612
613 /// Determine whether the definition must be emitted; if this returns \c
614 /// false, the definition can be emitted lazily if it's used.
615 bool mustBeEmitted(const clang::ValueDecl *d);
616
617 /// Check if `fd` ends up calling itself directly through asm label or
618 /// builtin-pointer-to-self trickery (e.g., glibc's `extern inline` libc
619 /// wrappers that call `__builtin_strrchr`, which the codegen lowers to a
620 /// call on the same asm-named symbol). Emitting an
621 /// `available_externally` body for such a function feeds the LLVM
622 /// Decide whether to emit the body of `gd` to CIR. Returns false for
623 /// available_externally functions that are trivially recursive (PR9614).
624 /// Mirrors classic CodeGen's `CodeGenModule::shouldEmitFunction`.
626
627 /// Determine whether the definition can be emitted eagerly, or should be
628 /// delayed until the end of the translation unit. This is relevant for
629 /// definitions whose linkage can change, e.g. implicit function
630 /// instantiations which may later be explicitly instantiated.
632
633 bool verifyModule() const;
634
635 /// Return the address of the given function. If funcType is non-null, then
636 /// this function will use the specified type if it has to create it.
637 // TODO: this is a bit weird as `GetAddr` given we give back a FuncOp?
638 cir::FuncOp
639 getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType = nullptr,
640 bool forVTable = false, bool dontDefer = false,
641 ForDefinition_t isForDefinition = NotForDefinition);
642
643 mlir::Operation *
645 ForDefinition_t isForDefinition = NotForDefinition);
646
647 // Return whether RTTI information should be emitted for this target.
648 bool shouldEmitRTTI(bool forEH = false) {
649 return (forEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
650 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
651 getTriple().isNVPTX());
652 }
653
654 /// Emit type info if type of an expression is a variably modified
655 /// type. Also emit proper debug info for cast types.
657 CIRGenFunction *cgf = nullptr);
658
660 deferredVTables.push_back(rd);
661 }
662
663 /// Emit code for a single global function or variable declaration. Forward
664 /// declarations are emitted lazily.
666
667 void emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op,
668 GlobalDecl aliasGD, cir::FuncOp aliasee,
669 cir::GlobalLinkageKind linkage);
670
671 /// Emit a definition for an `__attribute__((alias))` declaration.
673
674 mlir::Type convertType(clang::QualType type);
675
676 /// Set the visibility for the given global.
677 void setGlobalVisibility(cir::CIRGlobalValueInterface gv,
678 const NamedDecl *d) const;
679 void setDSOLocal(mlir::Operation *op) const;
680 void setDSOLocal(cir::CIRGlobalValueInterface gv) const;
681
682 /// Set visibility, dllimport/dllexport and dso_local.
683 /// This must be called after dllimport/dllexport is set.
684 void setGVProperties(mlir::Operation *op, const NamedDecl *d) const;
685 void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const;
686
687 /// Set TLS mode for the given operation based on the given variable
688 /// declaration. If `isExtendingDecl` is true, then the operation is a
689 /// temporary whose lifetime is extended by the variable declared by `d`.
690 void setTLSMode(mlir::Operation *op, const VarDecl &d,
691 bool isExtendingDecl = false);
692
693 /// Get TLS mode from CodeGenOptions.
694 cir::TLSModel getDefaultCIRTLSModel() const;
695
696 /// Set function attributes for a function declaration.
697 void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f,
698 bool isIncompleteFunction, bool isThunk);
699
700 /// Set the CIR function attributes (Sext, zext, etc).
702 cir::FuncOp func, bool isThunk);
703
704 /// Set extra attributes (inline, etc.) for a function.
706 cir::FuncOp f);
707
708 /// Generate OpenCL kernel argument metadata for a kernel function.
709 void emitOpenCLKernelArgMetadata(cir::FuncOp func,
710 const clang::FunctionDecl *fd);
711
713 mlir::Operation *op = nullptr);
714 void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op);
715
716 /// Emit the SYCL kernel caller offload entry point function generated for a
717 /// function declared with the sycl_kernel_entry_point attribute.
718 void emitSYCLKernelCaller(const clang::FunctionDecl *kernelEntryPointFn,
719 clang::ASTContext &ctx);
720
721 void addSYCLModuleIdAttr(cir::FuncOp fn);
723 bool isTentative = false);
724
725 /// Helper function for the below two that will create the
726 /// constructor/destructor in specified regions, rather than in the GlobalOp.
727 void emitCXXSpecialVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
728 bool performInit, mlir::Region &ctorRegion,
729 mlir::Region &dtorRegion);
730 /// Emit the function that initializes the specified static-local variable.
731 void emitCXXStaticLocalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
732 bool performInit);
733 /// Emit the function that initializes the specified global
734 void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
735 bool performInit);
736
737 void setGlobalTlsReferences(const VarDecl &vd, cir::GlobalOp globalOp);
738 void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr,
739 bool performInit);
740
744 template <typename BeforeOpTy, typename DataClauseTy>
745 void emitGlobalOpenACCDeclareDataOperands(const Expr *varOperand,
746 DataClauseTy dataClause,
747 OpenACCModifierKind modifiers,
748 bool structured, bool implicit,
749 bool requiresDtor);
750 // Each of the acc.routine operations must have a unique name, so we just use
751 // an integer counter. This is how Flang does it, so it seems reasonable.
752 unsigned routineCounter = 0;
753 void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl,
754 cir::FuncOp func, SourceLocation pragmaLoc,
756
764
765 // C++ related functions.
766 void emitDeclContext(const DeclContext *dc);
767
768 /// Return the result of value-initializing the given type, i.e. a null
769 /// expression of the given type.
770 mlir::Value emitNullConstant(QualType t, mlir::Location loc);
771
772 mlir::TypedAttr emitNullConstantAttr(QualType t);
773
774 /// Get target specific null pointer.
775 mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt,
776 mlir::Location loc);
777
778 /// Return a null constant appropriate for zero-initializing a base class with
779 /// the given type. This is usually, but not always, an LLVM null constant.
780 mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record);
781
782 mlir::Value emitMemberPointerConstant(const UnaryOperator *e);
783 /// Returns a null attribute to represent either a null method or null data
784 /// member, depending on the type of mpt.
785 mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt);
786
787 /// Build a GEP-style field-index path from \p destClass to \p decl.
788 /// \p decl may be a FieldDecl, or an IndirectFieldDecl(in the case of an
789 /// anonymous struct/union).
790 /// Returns std::nullopt and emits errorNYI for virtual-base paths.
791 std::optional<llvm::SmallVector<int32_t>>
792 buildMemberPath(const CXXRecordDecl *destClass, const ValueDecl *decl);
793
794 /// Returns true if \p field is a potentially-overlapping field with no CIR
795 /// field index (e.g. a [[no_unique_address]] member that is empty for both
796 /// layout and the ABI). Such fields have no entry in the CIR record, so a
797 /// pointer-to-data-member to them is represented by an explicit byte offset
798 /// (#cir.data_member_offset) rather than a field-index path.
799 bool isEmptyFieldForMemberPointer(const FieldDecl *field);
800
801 llvm::StringRef getMangledName(clang::GlobalDecl gd);
802 // This function is to support the OpenACC 'bind' clause, which names an
803 // alternate name for the function to be called by. This function mangles
804 // `attachedFunction` as-if its name was actually `bindName` (that is, with
805 // the same signature). It has some additional complications, as the 'bind'
806 // target is always going to be a global function, so member functions need an
807 // explicit instead of implicit 'this' parameter, and thus gets mangled
808 // differently.
809 std::string getOpenACCBindMangledName(const IdentifierInfo *bindName,
810 const FunctionDecl *attachedFunction);
811
812 void emitTentativeDefinition(const VarDecl *d);
813
814 // Make sure that this type is translated.
815 void updateCompletedType(const clang::TagDecl *td);
816
817 // Produce code for this constructor/destructor. This method doesn't try to
818 // apply any ABI rules about which other constructors/destructors are needed
819 // or if they are alias to each other.
821
822 bool lookupRepresentativeDecl(llvm::StringRef mangledName,
823 clang::GlobalDecl &gd) const;
824
825 bool supportsCOMDAT() const;
826 void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op);
827
828 static void setInitializer(cir::GlobalOp &op, mlir::Attribute value);
829
830 /// Print the postfix for externalized static variable or kernels for single
831 /// source offloading languages CUDA and HIP. The unique postfix is created
832 /// using either the CUID argument, or the file's UniqueID and active macros.
833 /// The fallback method without a CUID requires that the offloading toolchain
834 /// does not define separate macros via the -cc1 options.
835 void printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d);
836
837 /// Replace all uses of the old global with the new global, updating types
838 /// and references as needed. Erases the old global when done.
839 void replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV);
840
841 void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old,
842 cir::FuncOp newFn);
843
844 cir::FuncOp
845 getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType,
846 clang::GlobalDecl gd, bool forVTable,
847 bool dontDefer = false, bool isThunk = false,
848 ForDefinition_t isForDefinition = NotForDefinition,
849 mlir::NamedAttrList extraAttrs = {});
850
851 cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName,
852 mlir::Type funcType, clang::GlobalDecl gd,
853 bool forVTable,
854 mlir::NamedAttrList extraAttrs) {
855 return getOrCreateCIRFunction(mangledName, funcType, gd, forVTable,
856 /*dontDefer=*/false, /*isThunk=*/false,
857 NotForDefinition, extraAttrs);
858 }
859
860 cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name,
861 cir::FuncType funcType,
862 const clang::FunctionDecl *funcDecl);
863
864 /// Create a CIR function with builtin attribute set.
865 cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name,
866 cir::FuncType ty,
867 const clang::FunctionDecl *fd);
868
869 /// Record the func_info tag for a function, either a C++ special member
870 /// form (constructor, destructor, assignment) or a known standard library
871 /// entity that passes can recognize without the AST.
872 void setFuncInfoAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl);
873
874 cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name,
875 mlir::NamedAttrList extraAttrs = {},
876 bool isLocal = false,
877 bool assumeConvergent = false);
878
879 /// Given a builtin id for a function like "__builtin_fabsf", return a
880 /// Function* for "fabsf".
881 cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID);
882
884 assert(cudaRuntime != nullptr);
885 return *cudaRuntime;
886 }
887
889 assert(openMPRuntime != nullptr);
890 return *openMPRuntime;
891 }
892
895
896 mlir::IntegerAttr getSize(CharUnits size) {
897 return builder.getSizeFromCharUnits(size);
898 }
899
900 /// Emit any needed decls for which code generation was deferred.
901 void emitDeferred();
902
904 /// Emit any vtables which we deferred and still have a use for.
905 void emitDeferredVTables();
906
907 /// Try to emit external vtables as available_externally if they have emitted
908 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
909 /// is not allowed to create new references to things that need to be emitted
910 /// lazily.
912
913 /// Helper for `emitDeferred` to apply actual codegen.
914 void emitGlobalDecl(const clang::GlobalDecl &d);
915
916 const llvm::Triple &getTriple() const { return target.getTriple(); }
917
918 // Finalize CIR code generation.
919 void release();
920
921 /// Returns a pointer to a global variable representing a temporary with
922 /// static or thread storage duration.
923 mlir::Operation *getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte,
924 const Expr *init);
925
926 /// -------
927 /// Visibility and Linkage
928 /// -------
929
930 static mlir::SymbolTable::Visibility
931 getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK);
932 cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd);
933 static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op);
934 cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd,
935 GVALinkage linkage);
936 void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f) {
937 cir::GlobalLinkageKind l = getFunctionLinkage(gd);
938 f.setLinkageAttr(cir::GlobalLinkageKindAttr::get(&getMLIRContext(), l));
939 mlir::SymbolTable::setSymbolVisibility(f,
941 }
942
943 cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd);
944
945 void addReplacement(llvm::StringRef name, mlir::Operation *op);
946
947 /// Helpers to emit "not yet implemented" error diagnostics
948 DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef);
949
950 template <typename T>
951 DiagnosticBuilder errorNYI(SourceLocation loc, llvm::StringRef feature,
952 const T &name) {
953 unsigned diagID =
954 diags.getCustomDiagID(DiagnosticsEngine::Error,
955 "ClangIR code gen Not Yet Implemented: %0: %1");
956 return diags.Report(loc, diagID) << feature << name;
957 }
958
959 DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature) {
960 // TODO: Convert the location to a SourceLocation
961 unsigned diagID = diags.getCustomDiagID(
962 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
963 return diags.Report(diagID) << feature;
964 }
965
966 DiagnosticBuilder errorNYI(llvm::StringRef feature) const {
967 // TODO: Make a default location? currSrcLoc?
968 unsigned diagID = diags.getCustomDiagID(
969 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
970 return diags.Report(diagID) << feature;
971 }
972
973 DiagnosticBuilder errorNYI(SourceRange, llvm::StringRef);
974
975 template <typename T>
976 DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature,
977 const T &name) {
978 return errorNYI(loc.getBegin(), feature, name) << loc;
979 }
980
981 /// Emit a general error that something can't be done.
982 void error(SourceLocation loc, llvm::StringRef error);
983
984 /// Print out an error that codegen doesn't support the specified stmt yet.
985 void errorUnsupported(const Stmt *s, llvm::StringRef type);
986
987 /// Print out an error that codegen doesn't support the specified decl yet.
988 void errorUnsupported(const Decl *d, llvm::StringRef type);
989
990 /// Emits AMDGPU specific Metadata.
991 void emitAMDGPUMetadata();
992
993 /// Add global annotations for a global value (GlobalOp or FuncOp).
994 void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv);
995
996private:
997 /// Search \p currentClass and its non-virtual base subobjects for \p field,
998 /// appending CIR field indices along the path from \p currentClass.
999 bool findFieldMemberPath(const CXXRecordDecl *currentClass,
1000 const FieldDecl *field,
1002
1003 // An ordered map of canonical GlobalDecls to their mangled names.
1004 llvm::MapVector<clang::GlobalDecl, llvm::StringRef> mangledDeclNames;
1005 llvm::StringMap<clang::GlobalDecl, llvm::BumpPtrAllocator> manglings;
1006
1007 // FIXME: should we use llvm::TrackingVH<mlir::Operation> here?
1008 llvm::MapVector<StringRef, mlir::Operation *> replacements;
1009 /// Call replaceAllUsesWith on all pairs in replacements.
1010 void applyReplacements();
1011
1012 bool getCPUAndFeaturesAttributes(GlobalDecl gd,
1013 llvm::StringMap<std::string> &attrs,
1014 bool setTargetFeatures = true);
1015 void setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op);
1016
1017 /// Map source language used to a CIR attribute.
1018 std::optional<cir::SourceLanguage> getCIRSourceLanguage() const;
1019
1020 /// Emit all the global annotations.
1021 void emitGlobalAnnotations();
1022
1023 /// Build (or fetch from the dedup cache) the args ArrayAttr for an
1024 /// annotation. Returns the empty ArrayAttr when the annotation has none.
1025 mlir::ArrayAttr getOrCreateAnnotationArgs(const clang::AnnotateAttr *attr);
1026
1027 /// Create cir::AnnotationAttr for a single AnnotateAttr on a global.
1028 cir::AnnotationAttr emitAnnotateAttr(const clang::AnnotateAttr *aa);
1029
1030 /// Return the AST address space of the underlying global variable for D, as
1031 /// determined by its declaration. Normally this is the same as the address
1032 /// space of D's type, but in CUDA, address spaces are associated with
1033 /// declarations, not types. If D is nullptr, return the default address
1034 /// space for global variable.
1035 ///
1036 /// For languages without explicit address spaces, if D has default address
1037 /// space, target-specific global or constant address space may be returned.
1038 LangAS getGlobalVarAddressSpace(const VarDecl *decl);
1039};
1040} // namespace CIRGen
1041
1042} // namespace clang
1043
1044#endif // LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H
Defines some OpenACC-specific enums and functions.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Implements C++ ABI-specific code generation functions.
Abstract information about a function or function prototype.
Definition CIRGenCall.h:27
cir::GlobalOp getAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *gcd)
mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt, mlir::Location loc)
Get target specific null pointer.
void setGlobalVisibility(cir::CIRGlobalValueInterface gv, const NamedDecl *d) const
Set the visibility for the given global.
void addUsedOrCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global to a list to be added to the llvm.compiler.used metadata.
void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, bool performInit)
Emit the function that initializes the specified global.
void setFuncInfoAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl)
Record the func_info tag for a function, either a C++ special member form (constructor,...
void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, cir::FuncOp newFn)
This function is called when we implement a function with no prototype, e.g.
bool shouldEmitFunction(clang::GlobalDecl gd)
Check if fd ends up calling itself directly through asm label or builtin-pointer-to-self trickery (e....
llvm::StringRef getMangledName(clang::GlobalDecl gd)
cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *derivedClass, llvm::iterator_range< CastExpr::path_const_iterator > path)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
void emitDeferred()
Emit any needed decls for which code generation was deferred.
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd)
clang::ASTContext & getASTContext() const
bool isPaddedAtomicType(QualType type)
void insertGlobalSymbol(mlir::Operation *op)
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
CIRGenCUDARuntime & getCUDARuntime()
void emitTopLevelDecl(clang::Decl *decl)
CharUnits getDynamicOffsetAlignment(CharUnits actualBaseAlign, const CXXRecordDecl *baseDecl, CharUnits expectedTargetAlign)
TODO: Add TBAAAccessInfo.
void emitGlobalOpenACCDeclareDataOperands(const Expr *varOperand, DataClauseTy dataClause, OpenACCModifierKind modifiers, bool structured, bool implicit, bool requiresDtor)
void emitOMPDeclareMapper(const OMPDeclareMapperDecl *d)
void addReplacement(llvm::StringRef name, mlir::Operation *op)
mlir::Type convertType(clang::QualType type)
bool shouldEmitRTTI(bool forEH=false)
cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s, llvm::StringRef name=".str")
Return a global symbol reference to a constant array for the given string literal.
void addSYCLModuleIdAttr(cir::FuncOp fn)
std::vector< cir::CIRGlobalValueInterface > llvmUsed
List of global values which are required to be present in the object file; This is used for forcing v...
void emitOMPCapturedExpr(const OMPCapturedExprDecl *d)
clang::AtomicOptions getAtomicOpts() const
The atomic options in effect at the point currently being emitted.
llvm::DenseMap< const VarDecl *, cir::GlobalOp > initializerConstants
llvm::DenseMap< const CompoundLiteralExpr *, cir::GlobalOp > emittedCompoundLiterals
std::optional< llvm::SmallVector< int32_t > > buildMemberPath(const CXXRecordDecl *destClass, const ValueDecl *decl)
Build a GEP-style field-index path from destClass to decl.
bool mustBeEmitted(const clang::ValueDecl *d)
Determine whether the definition must be emitted; if this returns false, the definition can be emitte...
void emitGlobalOpenACCDeclareDecl(const clang::OpenACCDeclareDecl *cd)
mlir::IntegerAttr getSize(CharUnits size)
cir::TLSModel getDefaultCIRTLSModel() const
Get TLS mode from CodeGenOptions.
void addDefaultFunctionAttributes(StringRef name, bool hasOptNoneAttr, bool attrOnCallSite, mlir::NamedAttrList &attrs)
Helper function for constructAttributeList/others.
void setGlobalTlsReferences(const VarDecl &vd, cir::GlobalOp globalOp)
void emitOpenCLKernelArgMetadata(cir::FuncOp func, const clang::FunctionDecl *fd)
Generate OpenCL kernel argument metadata for a kernel function.
DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature, const T &name)
CIRGenBuilderTy & getBuilder()
void setDSOLocal(mlir::Operation *op) const
void emitCXXStaticLocalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, bool performInit)
Emit the function that initializes the specified static-local variable.
std::string getUniqueGlobalName(const std::string &baseName)
std::pair< cir::FuncType, cir::FuncOp > getAddrAndTypeOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
ItaniumVTableContext & getItaniumVTableContext()
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty, LangAS langAS, const VarDecl *d, ForDefinition_t isForDefinition)
If the specified mangled name is not in the module, create and return an mlir::GlobalOp value.
cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name, cir::FuncType ty, const clang::FunctionDecl *fd)
Create a CIR function with builtin attribute set.
cir::GlobalOp getAddrOfTemplateParamObject(const TemplateParamObjectDecl *tpo)
Get the GlobalOp of a template parameter object.
llvm::DenseMap< const Decl *, cir::GlobalOp > staticLocalDeclMap
cir::FuncOp lookupFuncOp(llvm::StringRef name)
O(1) lookup of a FuncOp by name in the symbol cache.
void emitGlobalOpenACCRoutineDecl(const clang::OpenACCRoutineDecl *cd)
clang::CharUnits getClassPointerAlignment(const clang::CXXRecordDecl *rd)
Return the best known alignment for an unknown pointer to a particular class.
void handleCXXStaticMemberVarInstantiation(VarDecl *vd)
Tell the consumer that this variable has been instantiated.
llvm::DenseMap< const UnnamedGlobalConstantDecl *, cir::GlobalOp > unnamedGlobalConstantDeclMap
std::vector< cir::CIRGlobalValueInterface > llvmCompilerUsed
CharUnits getMinimumClassObjectSize(const CXXRecordDecl *cd)
Returns the minimum object size for an object of the given class type (or a class derived from it).
void emitOMPRequiresDecl(const OMPRequiresDecl *d)
void emitGlobalDefinition(clang::GlobalDecl gd, mlir::Operation *op=nullptr)
clang::DiagnosticsEngine & getDiags() const
CharUnits getVBaseAlignment(CharUnits derivedAlign, const CXXRecordDecl *derived, const CXXRecordDecl *vbase)
Returns the assumed alignment of a virtual base of a class.
cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd, GVALinkage linkage)
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str, llvm::StringRef name)
Create a private constant global holding the null-terminated string str, mirroring llvm::IRBuilder::C...
void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f, bool isIncompleteFunction, bool isThunk)
Set function attributes for a function declaration.
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
const ItaniumVTableContext & getItaniumVTableContext() const
const clang::TargetInfo & getTarget() const
mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record)
Return a null constant appropriate for zero-initializing a base class with the given type.
void setCIRFunctionAttributes(GlobalDecl gd, const CIRGenFunctionInfo &info, cir::FuncOp func, bool isThunk)
Set the CIR function attributes (Sext, zext, etc).
cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID)
Given a builtin id for a function like "__builtin_fabsf", return a Function* for "fabsf".
const llvm::Triple & getTriple() const
static mlir::SymbolTable::Visibility getMLIRVisibility(Visibility v)
void emitTentativeDefinition(const VarDecl *d)
const cir::CIRDataLayout & getDataLayout() const
CharUnits getMinimumObjectSize(QualType ty)
Returns the minimum object size for an object of the given type.
void emitAliasDefinition(GlobalDecl gd)
Emit a definition for an __attribute__((alias)) declaration.
void addUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmUsed list.
cir::GlobalOp createOrReplaceCXXRuntimeVariable(mlir::Location loc, llvm::StringRef name, mlir::Type ty, cir::GlobalLinkageKind linkage, clang::CharUnits alignment)
Will return a global variable of the given type.
void emitOMPAllocateDecl(const OMPAllocateDecl *d)
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
void emitGlobalDecl(const clang::GlobalDecl &d)
Helper for emitDeferred to apply actual codegen.
void emitGlobalVarDefinition(const clang::VarDecl *vd, bool isTentative=false)
static std::optional< cir::FramePointerKind > getFramePointerKind(CodeGenOptions::FramePointerKind kind)
Returns the frame pointer kind to record on functions and on the module, or std::nullopt when kind is...
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
cir::FuncOp getAddrOfThunk(StringRef name, mlir::Type fnTy, GlobalDecl gd)
Get or create a thunk function with the given name and type.
DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature)
void addRecordLayout(mlir::StringAttr name, cir::RecordLayoutAttr attr)
Queue a record layout entry for materialization in release().
cir::FuncOp getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType=nullptr, bool forVTable=false, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
Return the address of the given function.
mlir::TypedAttr emitNullConstantAttr(QualType t)
void emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op, GlobalDecl aliasGD, cir::FuncOp aliasee, cir::GlobalLinkageKind linkage)
void emitLLVMUsed()
Emit llvm.used and llvm.compiler.used globals.
mlir::Value emitMemberPointerConstant(const UnaryOperator *e)
void emitGlobalOpenACCDecl(const clang::OpenACCConstructDecl *cd)
void setTLSMode(mlir::Operation *op, const VarDecl &d, bool isExtendingDecl=false)
Set TLS mode for the given operation based on the given variable declaration.
void emitExplicitCastExprType(const ExplicitCastExpr *e, CIRGenFunction *cgf=nullptr)
Emit type info if type of an expression is a variably modified type.
void eraseGlobalSymbol(mlir::Operation *op)
mlir::Operation * getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte, const Expr *init)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
std::map< llvm::StringRef, clang::GlobalDecl > deferredDecls
This contains all the decls which have definitions but which are deferred for emission and therefore ...
void errorUnsupported(const Stmt *s, llvm::StringRef type)
Print out an error that codegen doesn't support the specified stmt yet.
mlir::Value getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty={}, ForDefinition_t isForDefinition=NotForDefinition)
Return the mlir::Value for the address of the given global variable.
llvm::StringMap< mlir::Operation * > symbolLookupCache
Cache for O(1) symbol lookups by name, replacing the O(N) linear scan in SymbolTable::lookupSymbolIn ...
static void setInitializer(cir::GlobalOp &op, mlir::Attribute value)
cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d)
Return the mlir::GlobalViewAttr for the address of the given global.
void addGlobalCtor(cir::FuncOp ctor, std::optional< int > priority=std::nullopt)
Add a global constructor or destructor to the module.
cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd)
void updateCompletedType(const clang::TagDecl *td)
const clang::CodeGenOptions & getCodeGenOpts() const
void emitDeferredVTables()
Emit any vtables which we deferred and still have a use for.
const clang::LangOptions & getLangOpts() const
void printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d)
Print the postfix for externalized static variable or kernels for single source offloading languages ...
cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType, clang::GlobalDecl gd, bool forVTable, bool dontDefer=false, bool isThunk=false, ForDefinition_t isForDefinition=NotForDefinition, mlir::NamedAttrList extraAttrs={})
void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl, cir::FuncOp func, SourceLocation pragmaLoc, ArrayRef< const OpenACCClause * > clauses)
void emitVTablesOpportunistically()
Try to emit external vtables as available_externally if they have emitted all inlined virtual functio...
cir::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
void addGlobalDtor(cir::FuncOp dtor, std::optional< int > priority=std::nullopt)
Add a function to the list that will be called when the module is unloaded.
mlir::Value castGlobalToDeclAddrSpace(mlir::Value addr, const VarDecl &vd)
Cast addr, the address of the global vd, to the address space of the declared type of vd if they diff...
void addDeferredDeclToEmit(clang::GlobalDecl GD)
void setAtomicOpts(clang::AtomicOptions opts)
cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name, cir::FuncType funcType, const clang::FunctionDecl *funcDecl)
const TargetCIRGenInfo & getTargetCIRGenInfo()
void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr, bool performInit)
static cir::VisibilityKind getCIRVisibilityKind(Visibility v)
void addDeferredVTable(const CXXRecordDecl *rd)
void setStaticLocalDeclAddress(const VarDecl *d, cir::GlobalOp c)
void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const
LangAS getLangTempAllocaAddressSpace() const
Returns the address space for temporary allocations in the language.
cir::FuncOp codegenCXXStructor(clang::GlobalDecl gd)
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
llvm::DenseMap< mlir::Attribute, cir::GlobalOp > constantStringMap
mlir::Operation * lastGlobalOp
void setCIRFunctionAttributesForDefinition(const clang::Decl *decl, cir::FuncOp f)
Set extra attributes (inline, etc.) for a function.
void replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV)
Replace all uses of the old global with the new global, updating types and references as needed.
llvm::StringMap< unsigned > cgGlobalNames
mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt)
Returns a null attribute to represent either a null method or null data member, depending on the type...
mlir::Operation * getGlobalValue(llvm::StringRef ref)
cir::GlobalOp getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *e)
mlir::Value emitNullConstant(QualType t, mlir::Location loc)
Return the result of value-initializing the given type, i.e.
void emitOMPDeclareReduction(const OMPDeclareReductionDecl *d)
mlir::ModuleOp getModule() const
void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmCompilerUsed list.
clang::CharUnits getNaturalTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo=nullptr, bool forPointeeType=false)
FIXME: this could likely be a common helper and not necessarily related with codegen.
mlir::MLIRContext & getMLIRContext()
void emitSYCLKernelCaller(const clang::FunctionDecl *kernelEntryPointFn, clang::ASTContext &ctx)
Emit the SYCL kernel caller offload entry point function generated for a function declared with the s...
mlir::Operation * getAddrOfGlobal(clang::GlobalDecl gd, ForDefinition_t isForDefinition=NotForDefinition)
DiagnosticBuilder errorNYI(llvm::StringRef feature) const
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d)
bool isEmptyFieldForMemberPointer(const FieldDecl *field)
Returns true if field is a potentially-overlapping field with no CIR field index (e....
CIRGenCXXABI & getCXXABI() const
cir::GlobalViewAttr getAddrOfConstantStringFromLiteral(const StringLiteral *s, llvm::StringRef name=".str")
Return a global symbol reference to a constant array for the given string literal.
void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *e, cir::GlobalOp gv)
bool lookupRepresentativeDecl(llvm::StringRef mangledName, clang::GlobalDecl &gd) const
void emitDeclContext(const DeclContext *dc)
mlir::ptr::MemorySpaceAttrInterface getGlobalCIRAddressSpace(LangAS as)
Return the CIR address space attribute for a global in as, honoring the target address space map wher...
cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType, clang::GlobalDecl gd, bool forVTable, mlir::NamedAttrList extraAttrs)
clang::CharUnits getNaturalPointeeTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo=nullptr)
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
bool mayBeEmittedEagerly(const clang::ValueDecl *d)
Determine whether the definition can be emitted eagerly, or should be delayed until the end of the tr...
llvm::DenseMap< const clang::FieldDecl *, llvm::StringRef > lambdaFieldToName
Keep a map between lambda fields and names, this needs to be per module since lambdas might get gener...
DiagnosticBuilder errorNYI(SourceLocation loc, llvm::StringRef feature, const T &name)
void constructAttributeList(llvm::StringRef name, const CIRGenFunctionInfo &info, CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs, llvm::MutableArrayRef< mlir::NamedAttrList > argAttrs, mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv, bool attrOnCallSite, bool isThunk)
Get the CIR attributes and calling convention to use for a particular function type.
void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv)
Add global annotations for a global value (GlobalOp or FuncOp).
std::string getOpenACCBindMangledName(const IdentifierInfo *bindName, const FunctionDecl *attachedFunction)
void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op)
CIRGenVTables & getVTables()
void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f)
std::vector< clang::GlobalDecl > deferredDeclsToEmit
void emitVTable(const CXXRecordDecl *rd)
This is a callback from Sema to tell us that a particular vtable is required to be emitted in this tr...
void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *d)
CIRGenOpenMPRuntime & getOpenMPRuntime()
void emitAMDGPUMetadata()
Emits AMDGPU specific Metadata.
void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl *d)
cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr, CharUnits align)
void emitCXXSpecialVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, bool performInit, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
Helper function for the below two that will create the constructor/destructor in specified regions,...
mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e)
Return a constant array for the given string.
void setCommonAttributes(GlobalDecl gd, mlir::Operation *op)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
This class organizes the cross-module state that is used while lowering AST types to CIR types.
Definition CIRGenTypes.h:51
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
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...
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3653
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:781
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3976
This represents one expression.
Definition Expr.h:113
Represents a member of a struct/union/class.
Definition Decl.h:3299
Represents a function declaration or definition.
Definition Decl.h:2059
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
This represents a decl that may have a name.
Definition Decl.h:275
This represents 'pragma omp allocate ...' directive.
Definition DeclOpenMP.h:536
Pseudo declaration for capturing expressions.
Definition DeclOpenMP.h:445
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 groupprivate ...' directive.
Definition DeclOpenMP.h:173
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
This represents 'pragma omp threadprivate ...' directive.
Definition DeclOpenMP.h:110
A (possibly-)qualified type.
Definition TypeBase.h:938
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1823
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3856
Exposes information about the current target.
Definition TargetInfo.h:228
A template parameter object.
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:2292
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
Represents a variable declaration or definition.
Definition Decl.h:933
Defines the clang::TargetInfo interface.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Top level wrappers for InstallAPI frontend operations.
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
OpenACCModifierKind
const FunctionProtoType * T
LangAS
Defines the address space values used by the address space qualifier of QualType.
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