clang 23.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"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/TargetParser/Triple.h"
40
41namespace clang {
42class ASTContext;
43class CodeGenOptions;
44class Decl;
45class GlobalDecl;
46class LangOptions;
47class TargetInfo;
48class VarDecl;
49
50namespace CIRGen {
51
52class CIRGenFunction;
53class CIRGenCXXABI;
54
55enum ForDefinition_t : bool { NotForDefinition = false, ForDefinition = true };
56
57/// This class organizes the cross-function state that is used while generating
58/// CIR code.
59class CIRGenModule : public CIRGenTypeCache {
60 CIRGenModule(CIRGenModule &) = delete;
61 CIRGenModule &operator=(CIRGenModule &) = delete;
62
63public:
64 CIRGenModule(mlir::MLIRContext &mlirContext, clang::ASTContext &astContext,
65 const clang::CodeGenOptions &cgo,
67
69
70private:
71 mutable std::unique_ptr<TargetCIRGenInfo> theTargetCIRGenInfo;
72
73 CIRGenBuilderTy builder;
74
75 /// Hold Clang AST information.
76 clang::ASTContext &astContext;
77
78 const clang::LangOptions &langOpts;
79
80 const clang::CodeGenOptions &codeGenOpts;
81
82 /// A "module" matches a c/cpp source file: containing a list of functions.
83 mlir::ModuleOp theModule;
84
86
87 const clang::TargetInfo &target;
88
89 std::unique_ptr<CIRGenCXXABI> abi;
90
91 CIRGenTypes genTypes;
92
93 /// Holds information about C++ vtables.
94 CIRGenVTables vtables;
95
96 /// Holds the CUDA runtime
97 std::unique_ptr<CIRGenCUDARuntime> cudaRuntime;
98
99 /// Holds the OpenMP runtime
100 std::unique_ptr<CIRGenOpenMPRuntime> openMPRuntime;
101
102 /// Per-function codegen information. Updated everytime emitCIR is called
103 /// for FunctionDecls's.
104 CIRGenFunction *curCGF = nullptr;
105
107
108 /// Accumulated record layout entries, materialized in release().
109 llvm::SmallVector<mlir::NamedAttribute> recordLayoutEntries;
110
111 llvm::DenseSet<clang::GlobalDecl> diagnosedConflictingDefinitions;
112
113 /// -------
114 /// Annotations
115 /// -------
116
117 /// We store each annotation as an attribute of GlobalOp and FuncOp rather
118 /// than collecting them into a single module-level list. The deferred map
119 /// lets us attach annotations at the end of codegen so the most up-to-date
120 /// ValueDecl (which carries all inherited annotations) is used.
121
122 /// Used for uniquing of annotation arguments.
123 llvm::DenseMap<unsigned, mlir::ArrayAttr> annotationArgs;
124
125 /// Store deferred function annotations so they can be emitted at the end
126 /// with the most up to date ValueDecl that will have all the inherited
127 /// annotations.
128 llvm::DenseMap<llvm::StringRef, const clang::ValueDecl *> deferredAnnotations;
129
130 /// A queue of (optional) vtables to consider emitting.
131 std::vector<const CXXRecordDecl *> deferredVTables;
132
133 /// A queue of (optional) vtables that may be emitted opportunistically.
134 std::vector<const CXXRecordDecl *> opportunisticVTables;
135
136 void createCUDARuntime();
137 void createOpenMPRuntime();
138
139 /// A helper for constructAttributeList that handles return attributes.
140 void constructFunctionReturnAttributes(const CIRGenFunctionInfo &info,
141 const Decl *targetDecl, bool isThunk,
142 mlir::NamedAttrList &retAttrs);
143 /// A helper for constructAttributeList that handles argument attributes.
144 void constructFunctionArgumentAttributes(
145 const CIRGenFunctionInfo &info, const clang::Decl *targetDecl,
146 bool isThunk, bool attrOnCallSite,
148 /// A helper function for constructAttributeList that determines whether a
149 /// return value might have been discarded.
150 bool mayDropFunctionReturn(const ASTContext &context, QualType retTy);
151 /// A helper function for constructAttributeList that determines whether
152 /// `noundef` on a return is possible.
153 bool hasStrictReturn(QualType retTy, const Decl *targetDecl);
154
155 llvm::DenseMap<const Expr *, mlir::Operation *>
156 materializedGlobalTemporaryMap;
157
158public:
159 mlir::ModuleOp getModule() const { return theModule; }
160 CIRGenBuilderTy &getBuilder() { return builder; }
161
162 /// Queue a record layout entry for materialization in release().
163 void addRecordLayout(mlir::StringAttr name, cir::RecordLayoutAttr attr) {
164 recordLayoutEntries.push_back(mlir::NamedAttribute(name, attr));
165 }
166 clang::ASTContext &getASTContext() const { return astContext; }
167 const clang::TargetInfo &getTarget() const { return target; }
168 const clang::CodeGenOptions &getCodeGenOpts() const { return codeGenOpts; }
169 clang::DiagnosticsEngine &getDiags() const { return diags; }
170 CIRGenTypes &getTypes() { return genTypes; }
171 const clang::LangOptions &getLangOpts() const { return langOpts; }
172
173 CIRGenCXXABI &getCXXABI() const { return *abi; }
174 mlir::MLIRContext &getMLIRContext() { return *builder.getContext(); }
175
177 // FIXME(cir): instead of creating a CIRDataLayout every time, set it as an
178 // attribute for the CIRModule class.
179 return cir::CIRDataLayout(theModule);
180 }
181
182 /// -------
183 /// Handling globals
184 /// -------
185
186 mlir::Operation *lastGlobalOp = nullptr;
187
188 /// Keep a map between lambda fields and names, this needs to be per module
189 /// since lambdas might get generated later as part of defered work, and since
190 /// the pointers are supposed to be uniqued, should be fine. Revisit this if
191 /// it ends up taking too much memory.
192 llvm::DenseMap<const clang::FieldDecl *, llvm::StringRef> lambdaFieldToName;
193 /// Map BlockAddrInfoAttr (function name, label name) to the corresponding CIR
194 /// LabelOp. This provides the main lookup table used to resolve block
195 /// addresses into their label operations.
196 llvm::DenseMap<cir::BlockAddrInfoAttr, cir::LabelOp> blockAddressInfoToLabel;
197 /// Map CIR BlockAddressOps directly to their resolved LabelOps.
198 /// Used once a block address has been successfully lowered to a label.
199 llvm::MapVector<cir::BlockAddressOp, cir::LabelOp> blockAddressToLabel;
200 /// Track CIR BlockAddressOps that cannot be resolved immediately
201 /// because their LabelOp has not yet been emitted. These entries
202 /// are solved later once the corresponding label is available.
203 llvm::DenseSet<cir::BlockAddressOp> unresolvedBlockAddressToLabel;
204 cir::LabelOp lookupBlockAddressInfo(cir::BlockAddrInfoAttr blockInfo);
205 void mapBlockAddress(cir::BlockAddrInfoAttr blockInfo, cir::LabelOp label);
206 void mapUnresolvedBlockAddress(cir::BlockAddressOp op);
207 void mapResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp);
208 void updateResolvedBlockAddress(cir::BlockAddressOp op,
209 cir::LabelOp newLabel);
210
211 /// Add a global value to the llvmUsed list.
212 void addUsedGlobal(cir::CIRGlobalValueInterface gv);
213
214 /// Add a global value to the llvmCompilerUsed list.
215 void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv);
216
217 /// Add a global to a list to be added to the llvm.compiler.used metadata.
218 void addUsedOrCompilerUsedGlobal(cir::CIRGlobalValueInterface gv);
219
220 /// Emit llvm.used and llvm.compiler.used globals.
221 void emitLLVMUsed();
222
223 /// Tell the consumer that this variable has been instantiated.
225
226 llvm::DenseMap<const Decl *, cir::GlobalOp> staticLocalDeclMap;
227 llvm::DenseMap<const VarDecl *, cir::GlobalOp> initializerConstants;
228
229 mlir::Operation *getGlobalValue(llvm::StringRef ref);
230
231 cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d) {
232 return staticLocalDeclMap[d];
233 }
234
235 void setStaticLocalDeclAddress(const VarDecl *d, cir::GlobalOp c) {
237 }
238
239 cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d,
240 cir::GlobalLinkageKind linkage);
241
242 Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr,
243 CharUnits align);
244
245 /// If the specified mangled name is not in the module, create and return an
246 /// mlir::GlobalOp value
247 cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty,
248 LangAS langAS, const VarDecl *d,
249 ForDefinition_t isForDefinition);
250
251 cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
252 ForDefinition_t isForDefinition);
253
254 static cir::GlobalOp
255 createGlobalOp(CIRGenModule &cgm, mlir::Location loc, llvm::StringRef name,
256 mlir::Type t, bool isConstant = false,
257 mlir::ptr::MemorySpaceAttrInterface addrSpace = {},
258 mlir::Operation *insertPoint = nullptr);
259
260 /// Add a global constructor or destructor to the module.
261 /// The priority is optional, if not specified, the default priority is used.
262 void addGlobalCtor(cir::FuncOp ctor,
263 std::optional<int> priority = std::nullopt);
264 void addGlobalDtor(cir::FuncOp dtor,
265 std::optional<int> priority = std::nullopt);
266
268 // In C23 (N3096) $6.7.10:
269 // """
270 // If any object is initialized with an empty initializer, then it is
271 // subject to default initialization:
272 // - if it is an aggregate, every member is initialized (recursively)
273 // according to these rules, and any padding is initialized to zero bits;
274 // - if it is a union, the first named member is initialized (recursively)
275 // according to these rules, and any padding is initialized to zero bits.
276 //
277 // If the aggregate or union contains elements or members that are
278 // aggregates or unions, these rules apply recursively to the subaggregates
279 // or contained unions.
280 //
281 // If there are fewer initializers in a brace-enclosed list than there are
282 // elements or members of an aggregate, or fewer characters in a string
283 // literal used to initialize an array of known size than there are elements
284 // in the array, the remainder of the aggregate is subject to default
285 // initialization.
286 // """
287 //
288 // The standard seems ambiguous in the following two areas:
289 // 1. For a union type with empty initializer, if the first named member is
290 // not the largest member, then the bytes comes after the first named member
291 // but before padding are left unspecified. An example is:
292 // union U { int a; long long b;};
293 // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left
294 // unspecified.
295 //
296 // 2. It only mentions padding for empty initializer, but doesn't mention
297 // padding for a non empty initialization list. And if the aggregation or
298 // union contains elements or members that are aggregates or unions, and
299 // some are non empty initializers, while others are empty initializers,
300 // the padding initialization is unclear. An example is:
301 // struct S1 { int a; long long b; };
302 // struct S2 { char c; struct S1 s1; };
303 // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a
304 // and s2.s1.b are unclear.
305 // struct S2 s2 = { 'c' };
306 //
307 // Here we choose to zero initiailize left bytes of a union type because
308 // projects like the Linux kernel are relying on this behavior. If we don't
309 // explicitly zero initialize them, the undef values can be optimized to
310 // return garbage data. We also choose to zero initialize paddings for
311 // aggregates and unions, no matter they are initialized by empty
312 // initializers or non empty initializers. This can provide a consistent
313 // behavior. So projects like the Linux kernel can rely on it.
314 return !getLangOpts().CPlusPlus;
315 }
316
317 llvm::StringMap<unsigned> cgGlobalNames;
318 std::string getUniqueGlobalName(const std::string &baseName);
319
320 /// Return the mlir::Value for the address of the given global variable.
321 /// If Ty is non-null and if the global doesn't exist, then it will be created
322 /// with the specified type instead of whatever the normal requested type
323 /// would be. If IsForDefinition is true, it is guaranteed that an actual
324 /// global with type Ty will be returned, not conversion of a variable with
325 /// the same mangled name but some other type.
326 mlir::Value
327 getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty = {},
328 ForDefinition_t isForDefinition = NotForDefinition);
329
330 /// Get or create a thunk function with the given name and type.
331 cir::FuncOp getAddrOfThunk(StringRef name, mlir::Type fnTy, GlobalDecl gd);
332
333 /// Return the mlir::GlobalViewAttr for the address of the given global.
334 cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d);
335
337 const CXXRecordDecl *derivedClass,
338 llvm::iterator_range<CastExpr::path_const_iterator> path);
339
340 /// Get the CIR attributes and calling convention to use for a particular
341 /// function type.
342 ///
343 /// \param name - The function name.
344 /// \param info - The function type information.
345 /// \param calleeInfo - The callee information these attributes are being
346 /// constructed for. If valid, the attributes applied to this decl may
347 /// contribute to the function attributes and calling convention.
348 /// \param attrs [out] - On return, the attribute list to use.
349 /// \param callingConv [out] - On return, the calling convention to use.
350 /// \param sideEffect [out] - On return, the side effect type of the
351 /// attributes.
352 /// \param attrOnCallSite - Whether or not the attributes are on a call site.
353 /// \param isThunk - Whether the function is a thunk.
355 llvm::StringRef name, const CIRGenFunctionInfo &info,
356 CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs,
358 mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv,
359 cir::SideEffect &sideEffect, bool attrOnCallSite, bool isThunk);
360 /// Helper function for constructAttributeList/others. Builds a set of
361 /// function attributes to add to a function based on language opts, codegen
362 /// opts, and some small properties.
363 void addDefaultFunctionAttributes(StringRef name, bool hasOptNoneAttr,
364 bool attrOnCallSite,
365 mlir::NamedAttrList &attrs);
366
367 /// Will return a global variable of the given type. If a variable with a
368 /// different type already exists then a new variable with the right type
369 /// will be created and all uses of the old variable will be replaced with a
370 /// bitcast to the new variable.
372 mlir::Location loc, llvm::StringRef name, mlir::Type ty,
373 cir::GlobalLinkageKind linkage, clang::CharUnits alignment);
374
375 void emitVTable(const CXXRecordDecl *rd);
376
377 /// Return the appropriate linkage for the vtable, VTT, and type information
378 /// of the given class.
379 cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd);
380
381 /// Get the address of the RTTI descriptor for the given type.
382 mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty,
383 bool forEH = false);
384
385 static mlir::SymbolTable::Visibility getMLIRVisibility(Visibility v) {
386 switch (v) {
388 return mlir::SymbolTable::Visibility::Public;
389 case HiddenVisibility:
390 return mlir::SymbolTable::Visibility::Private;
392 // The distinction between ProtectedVisibility and DefaultVisibility is
393 // that symbols with ProtectedVisibility, while visible to the dynamic
394 // linker like DefaultVisibility, are guaranteed to always dynamically
395 // resolve to a symbol in the current shared object. There is currently no
396 // equivalent MLIR visibility, so we fall back on the fact that the symbol
397 // is visible.
398 return mlir::SymbolTable::Visibility::Public;
399 }
400 llvm_unreachable("unknown visibility!");
401 }
402
403 llvm::DenseMap<mlir::Attribute, cir::GlobalOp> constantStringMap;
404
405 /// Return a constant array for the given string.
406 mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e);
407
408 /// Return a global symbol reference to a constant array for the given string
409 /// literal.
410 cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s,
411 llvm::StringRef name = ".str");
412
413 /// Return a global symbol reference to a constant array for the given string
414 /// literal.
415 cir::GlobalViewAttr
417 llvm::StringRef name = ".str");
418
419 /// Returns the address space for temporary allocations in the language. This
420 /// ensures that the allocated variable's address space matches the
421 /// expectations of the AST, rather than using the target's allocation address
422 /// space, which may lead to type mismatches in other parts of the IR.
424
425 /// Set attributes which are common to any form of a global definition (alias,
426 /// Objective-C method, function, global variable).
427 ///
428 /// NOTE: This should only be called for definitions.
429 void setCommonAttributes(GlobalDecl gd, mlir::Operation *op);
430
432
433 /// Helpers to convert the presumed location of Clang's SourceLocation to an
434 /// MLIR Location.
435 mlir::Location getLoc(clang::SourceLocation cLoc);
436 mlir::Location getLoc(clang::SourceRange cRange);
437
438 /// Return the best known alignment for an unknown pointer to a
439 /// particular class.
441
442 /// FIXME: this could likely be a common helper and not necessarily related
443 /// with codegen.
445 LValueBaseInfo *baseInfo = nullptr,
446 bool forPointeeType = false);
449 LValueBaseInfo *baseInfo = nullptr);
450
451 /// Returns the minimum object size for an object of the given class type
452 /// (or a class derived from it).
454
455 /// Returns the minimum object size for an object of the given type.
461
462 /// TODO: Add TBAAAccessInfo
464 const CXXRecordDecl *baseDecl,
465 CharUnits expectedTargetAlign);
466
467 /// Returns the assumed alignment of a virtual base of a class.
469 const CXXRecordDecl *derived,
470 const CXXRecordDecl *vbase);
471
472 cir::FuncOp
474 const CIRGenFunctionInfo *fnInfo = nullptr,
475 cir::FuncType fnType = nullptr, bool dontDefer = false,
476 ForDefinition_t isForDefinition = NotForDefinition) {
477 return getAddrAndTypeOfCXXStructor(gd, fnInfo, fnType, dontDefer,
478 isForDefinition)
479 .second;
480 }
481
482 std::pair<cir::FuncType, cir::FuncOp> getAddrAndTypeOfCXXStructor(
483 clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo = nullptr,
484 cir::FuncType fnType = nullptr, bool dontDefer = false,
485 ForDefinition_t isForDefinition = NotForDefinition);
486
487 /// List of global values which are required to be present in the object file;
488 /// This is used for forcing visibility of symbols which may otherwise be
489 /// optimized out.
490 std::vector<cir::CIRGlobalValueInterface> llvmUsed;
491 std::vector<cir::CIRGlobalValueInterface> llvmCompilerUsed;
492
493 mlir::Type getVTableComponentType();
494 CIRGenVTables &getVTables() { return vtables; }
495
497 return vtables.getItaniumVTableContext();
498 }
500 return vtables.getItaniumVTableContext();
501 }
502
503 /// This contains all the decls which have definitions but which are deferred
504 /// for emission and therefore should only be output if they are actually
505 /// used. If a decl is in this, then it is known to have not been referenced
506 /// yet.
507 std::map<llvm::StringRef, clang::GlobalDecl> deferredDecls;
508
509 // This is a list of deferred decls which we have seen that *are* actually
510 // referenced. These get code generated when the module is done.
511 std::vector<clang::GlobalDecl> deferredDeclsToEmit;
513 deferredDeclsToEmit.emplace_back(GD);
514 }
515
517
518 /// Determine whether the definition must be emitted; if this returns \c
519 /// false, the definition can be emitted lazily if it's used.
520 bool mustBeEmitted(const clang::ValueDecl *d);
521
522 /// Determine whether the definition can be emitted eagerly, or should be
523 /// delayed until the end of the translation unit. This is relevant for
524 /// definitions whose linkage can change, e.g. implicit function
525 /// instantiations which may later be explicitly instantiated.
527
528 bool verifyModule() const;
529
530 /// Return the address of the given function. If funcType is non-null, then
531 /// this function will use the specified type if it has to create it.
532 // TODO: this is a bit weird as `GetAddr` given we give back a FuncOp?
533 cir::FuncOp
534 getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType = nullptr,
535 bool forVTable = false, bool dontDefer = false,
536 ForDefinition_t isForDefinition = NotForDefinition);
537
538 mlir::Operation *
540 ForDefinition_t isForDefinition = NotForDefinition);
541
542 // Return whether RTTI information should be emitted for this target.
543 bool shouldEmitRTTI(bool forEH = false) {
544 return (forEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
545 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
546 getTriple().isNVPTX());
547 }
548
549 /// Emit type info if type of an expression is a variably modified
550 /// type. Also emit proper debug info for cast types.
552 CIRGenFunction *cgf = nullptr);
553
555 deferredVTables.push_back(rd);
556 }
557
558 /// Emit code for a single global function or variable declaration. Forward
559 /// declarations are emitted lazily.
561
562 void emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op,
563 GlobalDecl aliasGD, cir::FuncOp aliasee,
564 cir::GlobalLinkageKind linkage);
565
566 mlir::Type convertType(clang::QualType type);
567
568 /// Set the visibility for the given global.
569 void setGlobalVisibility(mlir::Operation *op, const NamedDecl *d) const;
570 void setDSOLocal(mlir::Operation *op) const;
571 void setDSOLocal(cir::CIRGlobalValueInterface gv) const;
572
573 /// Set visibility, dllimport/dllexport and dso_local.
574 /// This must be called after dllimport/dllexport is set.
575 void setGVProperties(mlir::Operation *op, const NamedDecl *d) const;
576 void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const;
577
578 /// Set TLS mode for the given operation based on the given variable
579 /// declaration.
580 void setTLSMode(mlir::Operation *op, const VarDecl &d);
581
582 /// Get TLS mode from CodeGenOptions.
583 cir::TLS_Model getDefaultCIRTLSModel() const;
584
585 /// Set function attributes for a function declaration.
586 void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f,
587 bool isIncompleteFunction, bool isThunk);
588
589 /// Set the CIR function attributes (Sext, zext, etc).
591 cir::FuncOp func, bool isThunk);
592
593 /// Set extra attributes (inline, etc.) for a function.
595 cir::FuncOp f);
596
598 mlir::Operation *op = nullptr);
599 void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op);
601 bool isTentative = false);
602
603 /// Helper function for the below two that will create the
604 /// constructor/destructor in specified regions, rather than in the GlobalOp.
605 void emitCXXSpecialVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
606 bool performInit, mlir::Region &ctorRegion,
607 mlir::Region &dtorRegion);
608 /// Emit the function that initializes the specified static-local variable.
609 void emitCXXStaticLocalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
610 bool performInit);
611 /// Emit the function that initializes the specified global
612 void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
613 bool performInit);
614
615 void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr,
616 bool performInit);
617
621 template <typename BeforeOpTy, typename DataClauseTy>
622 void emitGlobalOpenACCDeclareDataOperands(const Expr *varOperand,
623 DataClauseTy dataClause,
624 OpenACCModifierKind modifiers,
625 bool structured, bool implicit,
626 bool requiresDtor);
627 // Each of the acc.routine operations must have a unique name, so we just use
628 // an integer counter. This is how Flang does it, so it seems reasonable.
629 unsigned routineCounter = 0;
630 void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl,
631 cir::FuncOp func, SourceLocation pragmaLoc,
633
641
642 // C++ related functions.
643 void emitDeclContext(const DeclContext *dc);
644
645 /// Return the result of value-initializing the given type, i.e. a null
646 /// expression of the given type.
647 mlir::Value emitNullConstant(QualType t, mlir::Location loc);
648
649 mlir::TypedAttr emitNullConstantAttr(QualType t);
650
651 /// Return a null constant appropriate for zero-initializing a base class with
652 /// the given type. This is usually, but not always, an LLVM null constant.
653 mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record);
654
655 mlir::Value emitMemberPointerConstant(const UnaryOperator *e);
656 /// Returns a null attribute to represent either a null method or null data
657 /// member, depending on the type of mpt.
658 mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt);
659
660 llvm::StringRef getMangledName(clang::GlobalDecl gd);
661 // This function is to support the OpenACC 'bind' clause, which names an
662 // alternate name for the function to be called by. This function mangles
663 // `attachedFunction` as-if its name was actually `bindName` (that is, with
664 // the same signature). It has some additional complications, as the 'bind'
665 // target is always going to be a global function, so member functions need an
666 // explicit instead of implicit 'this' parameter, and thus gets mangled
667 // differently.
668 std::string getOpenACCBindMangledName(const IdentifierInfo *bindName,
669 const FunctionDecl *attachedFunction);
670
671 void emitTentativeDefinition(const VarDecl *d);
672
673 // Make sure that this type is translated.
674 void updateCompletedType(const clang::TagDecl *td);
675
676 // Produce code for this constructor/destructor. This method doesn't try to
677 // apply any ABI rules about which other constructors/destructors are needed
678 // or if they are alias to each other.
680
681 bool lookupRepresentativeDecl(llvm::StringRef mangledName,
682 clang::GlobalDecl &gd) const;
683
684 bool supportsCOMDAT() const;
685 void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op);
686
687 static void setInitializer(cir::GlobalOp &op, mlir::Attribute value);
688
689 // Whether a global variable should be emitted by CUDA/HIP host/device
690 // related attributes.
691 bool shouldEmitCUDAGlobalVar(const VarDecl *global) const;
692
693 /// Replace all uses of the old global with the new global, updating types
694 /// and references as needed. Erases the old global when done.
695 void replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV);
696
697 void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old,
698 cir::FuncOp newFn);
699
700 cir::FuncOp
701 getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType,
702 clang::GlobalDecl gd, bool forVTable,
703 bool dontDefer = false, bool isThunk = false,
704 ForDefinition_t isForDefinition = NotForDefinition,
705 mlir::NamedAttrList extraAttrs = {});
706
707 cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName,
708 mlir::Type funcType, clang::GlobalDecl gd,
709 bool forVTable,
710 mlir::NamedAttrList extraAttrs) {
711 return getOrCreateCIRFunction(mangledName, funcType, gd, forVTable,
712 /*dontDefer=*/false, /*isThunk=*/false,
713 NotForDefinition, extraAttrs);
714 }
715
716 cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name,
717 cir::FuncType funcType,
718 const clang::FunctionDecl *funcDecl);
719
720 /// Create a CIR function with builtin attribute set.
721 cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name,
722 cir::FuncType ty,
723 const clang::FunctionDecl *fd);
724
725 /// Mark the function as a special member (e.g. constructor, destructor)
726 void setCXXSpecialMemberAttr(cir::FuncOp funcOp,
727 const clang::FunctionDecl *funcDecl);
728
729 cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name,
730 mlir::NamedAttrList extraAttrs = {},
731 bool isLocal = false,
732 bool assumeConvergent = false);
733
734 static constexpr const char *builtinCoroId = "__builtin_coro_id";
735 static constexpr const char *builtinCoroAlloc = "__builtin_coro_alloc";
736 static constexpr const char *builtinCoroBegin = "__builtin_coro_begin";
737 static constexpr const char *builtinCoroEnd = "__builtin_coro_end";
738 static constexpr const char *builtinCoroFree = "__builtin_coro_free";
739
740 /// Given a builtin id for a function like "__builtin_fabsf", return a
741 /// Function* for "fabsf".
742 cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID);
743
745 assert(cudaRuntime != nullptr);
746 return *cudaRuntime;
747 }
748
750 assert(openMPRuntime != nullptr);
751 return *openMPRuntime;
752 }
753
754 mlir::IntegerAttr getSize(CharUnits size) {
755 return builder.getSizeFromCharUnits(size);
756 }
757
758 /// Emit any needed decls for which code generation was deferred.
759 void emitDeferred();
760
762 /// Emit any vtables which we deferred and still have a use for.
763 void emitDeferredVTables();
764
765 /// Try to emit external vtables as available_externally if they have emitted
766 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
767 /// is not allowed to create new references to things that need to be emitted
768 /// lazily.
770
771 /// Helper for `emitDeferred` to apply actual codegen.
772 void emitGlobalDecl(const clang::GlobalDecl &d);
773
774 const llvm::Triple &getTriple() const { return target.getTriple(); }
775
776 // Finalize CIR code generation.
777 void release();
778
779 /// Returns a pointer to a global variable representing a temporary with
780 /// static or thread storage duration.
781 mlir::Operation *getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte,
782 const Expr *init);
783
784 /// -------
785 /// Visibility and Linkage
786 /// -------
787
788 static mlir::SymbolTable::Visibility
789 getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK);
790 static cir::VisibilityKind getGlobalVisibilityKindFromClangVisibility(
791 clang::VisibilityAttr::VisibilityType visibility);
792 cir::VisibilityAttr getGlobalVisibilityAttrFromDecl(const Decl *decl);
793 cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd);
794 static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op);
795 cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd,
796 GVALinkage linkage);
797 void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f) {
798 cir::GlobalLinkageKind l = getFunctionLinkage(gd);
799 f.setLinkageAttr(cir::GlobalLinkageKindAttr::get(&getMLIRContext(), l));
800 mlir::SymbolTable::setSymbolVisibility(f,
802 }
803
804 cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd);
805
806 void addReplacement(llvm::StringRef name, mlir::Operation *op);
807
808 /// Helpers to emit "not yet implemented" error diagnostics
809 DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef);
810
811 template <typename T>
812 DiagnosticBuilder errorNYI(SourceLocation loc, llvm::StringRef feature,
813 const T &name) {
814 unsigned diagID =
815 diags.getCustomDiagID(DiagnosticsEngine::Error,
816 "ClangIR code gen Not Yet Implemented: %0: %1");
817 return diags.Report(loc, diagID) << feature << name;
818 }
819
820 DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature) {
821 // TODO: Convert the location to a SourceLocation
822 unsigned diagID = diags.getCustomDiagID(
823 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
824 return diags.Report(diagID) << feature;
825 }
826
827 DiagnosticBuilder errorNYI(llvm::StringRef feature) const {
828 // TODO: Make a default location? currSrcLoc?
829 unsigned diagID = diags.getCustomDiagID(
830 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
831 return diags.Report(diagID) << feature;
832 }
833
834 DiagnosticBuilder errorNYI(SourceRange, llvm::StringRef);
835
836 template <typename T>
837 DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature,
838 const T &name) {
839 return errorNYI(loc.getBegin(), feature, name) << loc;
840 }
841
842 /// Emit a general error that something can't be done.
843 void error(SourceLocation loc, llvm::StringRef error);
844
845 /// Print out an error that codegen doesn't support the specified stmt yet.
846 void errorUnsupported(const Stmt *s, llvm::StringRef type);
847
848 /// Print out an error that codegen doesn't support the specified decl yet.
849 void errorUnsupported(const Decl *d, llvm::StringRef type);
850
851 /// Emits AMDGPU specific Metadata.
852 void emitAMDGPUMetadata();
853
854 /// Add global annotations for a global value (GlobalOp or FuncOp).
855 void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv);
856
857private:
858 // An ordered map of canonical GlobalDecls to their mangled names.
859 llvm::MapVector<clang::GlobalDecl, llvm::StringRef> mangledDeclNames;
860 llvm::StringMap<clang::GlobalDecl, llvm::BumpPtrAllocator> manglings;
861
862 // FIXME: should we use llvm::TrackingVH<mlir::Operation> here?
863 llvm::MapVector<StringRef, mlir::Operation *> replacements;
864 /// Call replaceAllUsesWith on all pairs in replacements.
865 void applyReplacements();
866
867 void setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op);
868
869 /// Map source language used to a CIR attribute.
870 std::optional<cir::SourceLanguage> getCIRSourceLanguage() const;
871
872 /// Emit all the global annotations.
873 void emitGlobalAnnotations();
874
875 /// Build (or fetch from the dedup cache) the args ArrayAttr for an
876 /// annotation. Returns the empty ArrayAttr when the annotation has none.
877 mlir::ArrayAttr getOrCreateAnnotationArgs(const clang::AnnotateAttr *attr);
878
879 /// Create cir::AnnotationAttr for a single AnnotateAttr on a global.
880 cir::AnnotationAttr emitAnnotateAttr(const clang::AnnotateAttr *aa);
881
882 /// Return the AST address space of the underlying global variable for D, as
883 /// determined by its declaration. Normally this is the same as the address
884 /// space of D's type, but in CUDA, address spaces are associated with
885 /// declarations, not types. If D is nullptr, return the default address
886 /// space for global variable.
887 ///
888 /// For languages without explicit address spaces, if D has default address
889 /// space, target-specific global or constant address space may be returned.
890 LangAS getGlobalVarAddressSpace(const VarDecl *decl);
891};
892} // namespace CIRGen
893
894} // namespace clang
895
896#endif // LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H
Defines the SourceManager interface.
__device__ __2f16 float __ockl_bool s
__device__ __2f16 float c
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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
void updateResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp newLabel)
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 replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, cir::FuncOp newFn)
This function is called when we implement a function with no prototype, e.g.
static cir::GlobalOp createGlobalOp(CIRGenModule &cgm, mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
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)
void setGlobalVisibility(mlir::Operation *op, const NamedDecl *d) const
Set the visibility for the given global.
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
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
CIRGenCUDARuntime & getCUDARuntime()
llvm::DenseMap< cir::BlockAddrInfoAttr, cir::LabelOp > blockAddressInfoToLabel
Map BlockAddrInfoAttr (function name, label name) to the corresponding CIR LabelOp.
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.
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)
llvm::DenseMap< const VarDecl *, cir::GlobalOp > initializerConstants
void mapUnresolvedBlockAddress(cir::BlockAddressOp op)
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)
void addDefaultFunctionAttributes(StringRef name, bool hasOptNoneAttr, bool attrOnCallSite, mlir::NamedAttrList &attrs)
Helper function for constructAttributeList/others.
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.
llvm::DenseMap< const Decl *, cir::GlobalOp > staticLocalDeclMap
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.
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)
void mapResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp)
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.
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)
CharUnits getMinimumObjectSize(QualType ty)
Returns the minimum object size for an object of the given type.
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)
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.
void setTLSMode(mlir::Operation *op, const VarDecl &d)
Set TLS mode for the given operation based on the given variable declaration.
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 emitExplicitCastExprType(const ExplicitCastExpr *e, CIRGenFunction *cgf=nullptr)
Emit type info if type of an expression is a variably modified type.
const cir::CIRDataLayout getDataLayout() const
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.
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 constructAttributeList(llvm::StringRef name, const CIRGenFunctionInfo &info, CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs, llvm::MutableArrayRef< mlir::NamedAttrList > argAttrs, mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv, cir::SideEffect &sideEffect, bool attrOnCallSite, bool isThunk)
Get the CIR attributes and calling convention to use for a particular function type.
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)
static constexpr const char * builtinCoroAlloc
void emitVTablesOpportunistically()
Try to emit external vtables as available_externally if they have emitted all inlined virtual functio...
cir::TLS_Model getDefaultCIRTLSModel() const
Get TLS mode from CodeGenOptions.
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.
void addDeferredDeclToEmit(clang::GlobalDecl GD)
bool shouldEmitCUDAGlobalVar(const VarDecl *global) const
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)
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.
llvm::DenseSet< cir::BlockAddressOp > unresolvedBlockAddressToLabel
Track CIR BlockAddressOps that cannot be resolved immediately because their LabelOp has not yet been ...
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 replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV)
Replace all uses of the old global with the new global, updating types and references as needed.
static cir::VisibilityKind getGlobalVisibilityKindFromClangVisibility(clang::VisibilityAttr::VisibilityType visibility)
llvm::StringMap< unsigned > cgGlobalNames
void setCXXSpecialMemberAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl)
Mark the function as a special member (e.g. constructor, destructor)
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)
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()
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)
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.
llvm::MapVector< cir::BlockAddressOp, cir::LabelOp > blockAddressToLabel
Map CIR BlockAddressOps directly to their resolved LabelOps.
bool lookupRepresentativeDecl(llvm::StringRef mangledName, clang::GlobalDecl &gd) const
void emitDeclContext(const DeclContext *dc)
static constexpr const char * builtinCoroBegin
static constexpr const char * builtinCoroId
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)
static constexpr const char * builtinCoroFree
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
cir::LabelOp lookupBlockAddressInfo(cir::BlockAddrInfoAttr blockInfo)
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 mapBlockAddress(cir::BlockAddrInfoAttr blockInfo, cir::LabelOp label)
static constexpr const char * builtinCoroEnd
void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv)
Add global annotations for a global value (GlobalOp or FuncOp).
void setCIRFunctionAttributesForDefinition(const clang::FunctionDecl *fd, cir::FuncOp f)
Set extra attributes (inline, etc.) for a function.
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.
cir::VisibilityAttr getGlobalVisibilityAttrFromDecl(const Decl *decl)
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:50
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
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...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
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:780
A little helper class used to produce diagnostics.
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:3931
This represents one expression.
Definition Expr.h:112
Represents a function declaration or definition.
Definition Decl.h:2015
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
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:4920
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3708
This represents a decl that may have a name.
Definition Decl.h:274
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:937
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:86
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3732
Exposes information about the current target.
Definition TargetInfo.h:227
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:2247
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:926
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.
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
OpenACCModifierKind
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