Debian Codegraph @

clang/lib/CIR/CodeGen/CIRGenFunction.h

raw
1 //===----------------------------------------------------------------------===//
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 // Internal per-function state used for AST-to-ClangIR code gen
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef CLANG_LIB_CIR_CODEGEN_CIRGENFUNCTION_H
14 #define CLANG_LIB_CIR_CODEGEN_CIRGENFUNCTION_H
15
16 #include "CIRGenBuilder.h"
17 #include "CIRGenCall.h"
18 #include "CIRGenModule.h"
19 #include "CIRGenTypeCache.h"
20 #include "CIRGenValue.h"
21 #include "EHScopeStack.h"
22
23 #include "Address.h"
24
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/BaseSubobject.h"
27 #include "clang/AST/CharUnits.h"
28 #include "clang/AST/CurrentSourceLocExprScope.h"
29 #include "clang/AST/Decl.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/Stmt.h"
32 #include "clang/AST/Type.h"
33 #include "clang/Basic/OperatorKinds.h"
34 #include "clang/Basic/TargetBuiltins.h"
35 #include "clang/CIR/Dialect/IR/CIRDialect.h"
36 #include "clang/CIR/MissingFeatures.h"
37 #include "clang/CIR/TypeEvaluationKind.h"
38 #include "llvm/ADT/ScopedHashTable.h"
39
40 namespace {
41 class ScalarExprEmitter;
42 } // namespace
43
44 namespace mlir {
45 namespace acc {
46 class LoopOp;
47 } // namespace acc
48 } // namespace mlir
49
50 namespace clang::CIRGen {
51
52 struct CGCoroData;
53
54 class CIRGenFunction : public CIRGenTypeCache {
55 public:
56 CIRGenModule &cgm;
57
58 private:
59 friend class ::ScalarExprEmitter;
60 /// The builder is a helper class to create IR inside a function. The
61 /// builder is stateful, in particular it keeps an "insertion point": this
62 /// is where the next operations will be introduced.
63 CIRGenBuilderTy &builder;
64
65 /// A jump destination is an abstract label, branching to which may
66 /// require a jump out through normal cleanups.
67 struct JumpDest {
68 JumpDest() = default;
69 JumpDest(mlir::Block *block, EHScopeStack::stable_iterator depth = {},
70 unsigned index = 0)
71 : block(block) {}
72
73 bool isValid() const { return block != nullptr; }
74 mlir::Block *getBlock() const { return block; }
75 EHScopeStack::stable_iterator getScopeDepth() const { return scopeDepth; }
76 unsigned getDestIndex() const { return index; }
77
78 // This should be used cautiously.
79 void setScopeDepth(EHScopeStack::stable_iterator depth) {
80 scopeDepth = depth;
81 }
82
83 private:
84 mlir::Block *block = nullptr;
85 EHScopeStack::stable_iterator scopeDepth;
86 unsigned index;
87 };
88
89 public:
90 /// The GlobalDecl for the current function being compiled or the global
91 /// variable currently being initialized.
92 clang::GlobalDecl curGD;
93
94 /// Unified return block.
95 /// In CIR this is a function because each scope might have
96 /// its associated return block.
97 JumpDest returnBlock(mlir::Block *retBlock) {
98 return getJumpDestInCurrentScope(retBlock);
99 }
100
101 unsigned nextCleanupDestIndex = 1;
102
103 /// The compiler-generated variable that holds the return value.
104 std::optional<mlir::Value> fnRetAlloca;
105
106 // Holds coroutine data if the current function is a coroutine. We use a
107 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
108 // in this header.
109 struct CGCoroInfo {
110 std::unique_ptr<CGCoroData> data;
111 CGCoroInfo();
112 ~CGCoroInfo();
113 };
114 CGCoroInfo curCoro;
115
116 bool isCoroutine() const { return curCoro.data != nullptr; }
117
118 /// The temporary alloca to hold the return value. This is
119 /// invalid iff the function has no return value.
120 Address returnValue = Address::invalid();
121
122 /// Tracks function scope overall cleanup handling.
123 EHScopeStack ehStack;
124
125 GlobalDecl curSEHParent;
126
127 /// A mapping from NRVO variables to the flags used to indicate
128 /// when the NRVO has been applied to this variable.
129 llvm::DenseMap<const VarDecl *, mlir::Value> nrvoFlags;
130
131 llvm::DenseMap<const clang::ValueDecl *, clang::FieldDecl *>
132 lambdaCaptureFields;
133 clang::FieldDecl *lambdaThisCaptureField = nullptr;
134
135 /// CXXThisDecl - When generating code for a C++ member function,
136 /// this will hold the implicit 'this' declaration.
137 ImplicitParamDecl *cxxabiThisDecl = nullptr;
138 mlir::Value cxxabiThisValue = nullptr;
139 mlir::Value cxxThisValue = nullptr;
140 clang::CharUnits cxxThisAlignment;
141
142 /// When generating code for a constructor or destructor, this will hold the
143 /// implicit argument (e.g. VTT).
144 ImplicitParamDecl *cxxStructorImplicitParamDecl{};
145 mlir::Value cxxStructorImplicitParamValue{};
146
147 /// The value of 'this' to sue when evaluating CXXDefaultInitExprs within this
148 /// expression.
149 Address cxxDefaultInitExprThis = Address::invalid();
150
151 // Holds the Decl for the current outermost non-closure context
152 const clang::Decl *curFuncDecl = nullptr;
153 /// This is the inner-most code context, which includes blocks.
154 const clang::Decl *curCodeDecl = nullptr;
155
156 /// The current function or global initializer that is generated code for.
157 /// This is usually a cir::FuncOp, but it can also be a cir::GlobalOp for
158 /// global initializers.
159 mlir::Operation *curFn = nullptr;
160
161 /// Save Parameter Decl for coroutine.
162 llvm::SmallVector<const ParmVarDecl *> fnArgs;
163
164 using DeclMapTy = llvm::DenseMap<const clang::Decl *, Address>;
165 /// This keeps track of the CIR allocas or globals for local C
166 /// declarations.
167 DeclMapTy localDeclMap;
168
169 /// The type of the condition for the emitting switch statement.
170 llvm::SmallVector<mlir::Type, 2> condTypeStack;
171
172 clang::ASTContext &getContext() const { return cgm.getASTContext(); }
173
174 CIRGenBuilderTy &getBuilder() { return builder; }
175
176 CIRGenModule &getCIRGenModule() { return cgm; }
177 const CIRGenModule &getCIRGenModule() const { return cgm; }
178
179 mlir::Block *getCurFunctionEntryBlock() {
180 // We currently assume this isn't called for a global initializer.
181 auto fn = mlir::cast<cir::FuncOp>(curFn);
182 return &fn.getRegion().front();
183 }
184
185 /// Sanitizers enabled for this function.
186 clang::SanitizerSet sanOpts;
187
188 /// The symbol table maps a variable name to a value in the current scope.
189 /// Entering a function creates a new scope, and the function arguments are
190 /// added to the mapping. When the processing of a function is terminated,
191 /// the scope is destroyed and the mappings created in this scope are
192 /// dropped.
193 using SymTableTy = llvm::ScopedHashTable<const clang::Decl *, mlir::Value>;
194 SymTableTy symbolTable;
195
196 /// Whether a cir.stacksave operation has been added. Used to avoid
197 /// inserting cir.stacksave for multiple VLAs in the same scope.
198 bool didCallStackSave = false;
199
200 /// Whether or not a Microsoft-style asm block has been processed within
201 /// this fuction. These can potentially set the return value.
202 bool sawAsmBlock = false;
203
204 mlir::Type convertTypeForMem(QualType t);
205
206 mlir::Type convertType(clang::QualType t);
207 mlir::Type convertType(const TypeDecl *t) {
208 return convertType(getContext().getTypeDeclType(t));
209 }
210
211 /// Get integer from a mlir::Value that is an int constant or a constant op.
212 static int64_t getSExtIntValueFromConstOp(mlir::Value val) {
213 auto constOp = val.getDefiningOp<cir::ConstantOp>();
214 assert(constOp && "getSExtIntValueFromConstOp call with non ConstantOp");
215 return constOp.getIntValue().getSExtValue();
216 }
217
218 /// Get zero-extended integer from a mlir::Value that is an int constant or a
219 /// constant op.
220 static int64_t getZExtIntValueFromConstOp(mlir::Value val) {
221 auto constOp = val.getDefiningOp<cir::ConstantOp>();
222 assert(constOp && "getZExtIntValueFromConstOp call with non ConstantOp");
223 return constOp.getIntValue().getZExtValue();
224 }
225
226 /// Return the cir::TypeEvaluationKind of QualType \c type.
227 static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type);
228
229 static bool hasScalarEvaluationKind(clang::QualType type) {
230 return getEvaluationKind(type) == cir::TEK_Scalar;
231 }
232
233 static bool hasAggregateEvaluationKind(clang::QualType type) {
234 return getEvaluationKind(type) == cir::TEK_Aggregate;
235 }
236
237 CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder,
238 bool suppressNewContext = false);
239 ~CIRGenFunction();
240
241 CIRGenTypes &getTypes() const { return cgm.getTypes(); }
242
243 const TargetInfo &getTarget() const { return cgm.getTarget(); }
244 mlir::MLIRContext &getMLIRContext() { return cgm.getMLIRContext(); }
245
246 const TargetCIRGenInfo &getTargetHooks() const {
247 return cgm.getTargetCIRGenInfo();
248 }
249
250 // ---------------------
251 // Opaque value handling
252 // ---------------------
253
254 /// Keeps track of the current set of opaque value expressions.
255 llvm::DenseMap<const OpaqueValueExpr *, LValue> opaqueLValues;
256 llvm::DenseMap<const OpaqueValueExpr *, RValue> opaqueRValues;
257
258 // This keeps track of the associated size for each VLA type.
259 // We track this by the size expression rather than the type itself because
260 // in certain situations, like a const qualifier applied to an VLA typedef,
261 // multiple VLA types can share the same size expression.
262 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
263 // enter/leave scopes.
264 llvm::DenseMap<const Expr *, mlir::Value> vlaSizeMap;
265
266 public:
267 /// A non-RAII class containing all the information about a bound
268 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
269 /// this which makes individual mappings very simple; using this
270 /// class directly is useful when you have a variable number of
271 /// opaque values or don't want the RAII functionality for some
272 /// reason.
273 class OpaqueValueMappingData {
274 const OpaqueValueExpr *opaqueValue;
275 bool boundLValue;
276
277 OpaqueValueMappingData(const OpaqueValueExpr *ov, bool boundLValue)
278 : opaqueValue(ov), boundLValue(boundLValue) {}
279
280 public:
281 OpaqueValueMappingData() : opaqueValue(nullptr) {}
282
283 static bool shouldBindAsLValue(const Expr *expr) {
284 // gl-values should be bound as l-values for obvious reasons.
285 // Records should be bound as l-values because IR generation
286 // always keeps them in memory. Expressions of function type
287 // act exactly like l-values but are formally required to be
288 // r-values in C.
289 return expr->isGLValue() || expr->getType()->isFunctionType() ||
290 hasAggregateEvaluationKind(expr->getType());
291 }
292
293 static OpaqueValueMappingData
294 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const Expr *e) {
295 if (shouldBindAsLValue(ov))
296 return bind(cgf, ov, cgf.emitLValue(e));
297 return bind(cgf, ov, cgf.emitAnyExpr(e));
298 }
299
300 static OpaqueValueMappingData
301 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const LValue &lv) {
302 assert(shouldBindAsLValue(ov));
303 cgf.opaqueLValues.insert(std::make_pair(ov, lv));
304 return OpaqueValueMappingData(ov, true);
305 }
306
307 static OpaqueValueMappingData
308 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const RValue &rv) {
309 assert(!shouldBindAsLValue(ov));
310 cgf.opaqueRValues.insert(std::make_pair(ov, rv));
311
312 OpaqueValueMappingData data(ov, false);
313
314 // Work around an extremely aggressive peephole optimization in
315 // EmitScalarConversion which assumes that all other uses of a
316 // value are extant.
317 assert(!cir::MissingFeatures::peepholeProtection() && "NYI");
318 return data;
319 }
320
321 bool isValid() const { return opaqueValue != nullptr; }
322 void clear() { opaqueValue = nullptr; }
323
324 void unbind(CIRGenFunction &cgf) {
325 assert(opaqueValue && "no data to unbind!");
326
327 if (boundLValue) {
328 cgf.opaqueLValues.erase(opaqueValue);
329 } else {
330 cgf.opaqueRValues.erase(opaqueValue);
331 assert(!cir::MissingFeatures::peepholeProtection() && "NYI");
332 }
333 }
334 };
335
336 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
337 class OpaqueValueMapping {
338 CIRGenFunction &cgf;
339 OpaqueValueMappingData data;
340
341 public:
342 static bool shouldBindAsLValue(const Expr *expr) {
343 return OpaqueValueMappingData::shouldBindAsLValue(expr);
344 }
345
346 /// Build the opaque value mapping for the given conditional
347 /// operator if it's the GNU ?: extension. This is a common
348 /// enough pattern that the convenience operator is really
349 /// helpful.
350 ///
351 OpaqueValueMapping(CIRGenFunction &cgf,
352 const AbstractConditionalOperator *op)
353 : cgf(cgf) {
354 if (mlir::isa<ConditionalOperator>(op))
355 // Leave Data empty.
356 return;
357
358 const BinaryConditionalOperator *e =
359 mlir::cast<BinaryConditionalOperator>(op);
360 data = OpaqueValueMappingData::bind(cgf, e->getOpaqueValue(),
361 e->getCommon());
362 }
363
364 /// Build the opaque value mapping for an OpaqueValueExpr whose source
365 /// expression is set to the expression the OVE represents.
366 OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *ov)
367 : cgf(cgf) {
368 if (ov) {
369 assert(ov->getSourceExpr() && "wrong form of OpaqueValueMapping used "
370 "for OVE with no source expression");
371 data = OpaqueValueMappingData::bind(cgf, ov, ov->getSourceExpr());
372 }
373 }
374
375 OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *opaqueValue,
376 LValue lvalue)
377 : cgf(cgf),
378 data(OpaqueValueMappingData::bind(cgf, opaqueValue, lvalue)) {}
379
380 OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *opaqueValue,
381 RValue rvalue)
382 : cgf(cgf),
383 data(OpaqueValueMappingData::bind(cgf, opaqueValue, rvalue)) {}
384
385 void pop() {
386 data.unbind(cgf);
387 data.clear();
388 }
389
390 ~OpaqueValueMapping() {
391 if (data.isValid())
392 data.unbind(cgf);
393 }
394 };
395
396 private:
397 /// Declare a variable in the current scope, return success if the variable
398 /// wasn't declared yet.
399 void declare(mlir::Value addrVal, const clang::Decl *var, clang::QualType ty,
400 mlir::Location loc, clang::CharUnits alignment,
401 bool isParam = false);
402
403 public:
404 mlir::Value createDummyValue(mlir::Location loc, clang::QualType qt);
405
406 void emitNullInitialization(mlir::Location loc, Address destPtr, QualType ty);
407
408 private:
409 // Track current variable initialization (if there's one)
410 const clang::VarDecl *currVarDecl = nullptr;
411 class VarDeclContext {
412 CIRGenFunction &p;
413 const clang::VarDecl *oldVal = nullptr;
414
415 public:
416 VarDeclContext(CIRGenFunction &p, const VarDecl *value) : p(p) {
417 if (p.currVarDecl)
418 oldVal = p.currVarDecl;
419 p.currVarDecl = value;
420 }
421
422 /// Can be used to restore the state early, before the dtor
423 /// is run.
424 void restore() { p.currVarDecl = oldVal; }
425 ~VarDeclContext() { restore(); }
426 };
427
428 public:
429 /// Use to track source locations across nested visitor traversals.
430 /// Always use a `SourceLocRAIIObject` to change currSrcLoc.
431 std::optional<mlir::Location> currSrcLoc;
432 class SourceLocRAIIObject {
433 CIRGenFunction &cgf;
434 std::optional<mlir::Location> oldLoc;
435
436 public:
437 SourceLocRAIIObject(CIRGenFunction &cgf, mlir::Location value) : cgf(cgf) {
438 if (cgf.currSrcLoc)
439 oldLoc = cgf.currSrcLoc;
440 cgf.currSrcLoc = value;
441 }
442
443 /// Can be used to restore the state early, before the dtor
444 /// is run.
445 void restore() { cgf.currSrcLoc = oldLoc; }
446 ~SourceLocRAIIObject() { restore(); }
447 };
448
449 using SymTableScopeTy =
450 llvm::ScopedHashTableScope<const clang::Decl *, mlir::Value>;
451
452 /// Hold counters for incrementally naming temporaries
453 unsigned counterRefTmp = 0;
454 unsigned counterAggTmp = 0;
455 std::string getCounterRefTmpAsString();
456 std::string getCounterAggTmpAsString();
457
458 /// Helpers to convert Clang's SourceLocation to a MLIR Location.
459 mlir::Location getLoc(clang::SourceLocation srcLoc);
460 mlir::Location getLoc(clang::SourceRange srcLoc);
461 mlir::Location getLoc(mlir::Location lhs, mlir::Location rhs);
462
463 const clang::LangOptions &getLangOpts() const { return cgm.getLangOpts(); }
464
465 /// True if an insertion point is defined. If not, this indicates that the
466 /// current code being emitted is unreachable.
467 /// FIXME(cir): we need to inspect this and perhaps use a cleaner mechanism
468 /// since we don't yet force null insertion point to designate behavior (like
469 /// LLVM's codegen does) and we probably shouldn't.
470 bool haveInsertPoint() const {
471 return builder.getInsertionBlock() != nullptr;
472 }
473
474 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
475 // an ObjCMethodDecl.
476 struct PrototypeWrapper {
477 llvm::PointerUnion<const clang::FunctionProtoType *,
478 const clang::ObjCMethodDecl *>
479 p;
480
481 PrototypeWrapper(const clang::FunctionProtoType *ft) : p(ft) {}
482 PrototypeWrapper(const clang::ObjCMethodDecl *md) : p(md) {}
483 };
484
485 bool isLValueSuitableForInlineAtomic(LValue lv);
486
487 /// An abstract representation of regular/ObjC call/message targets.
488 class AbstractCallee {
489 /// The function declaration of the callee.
490 [[maybe_unused]] const clang::Decl *calleeDecl;
491
492 public:
493 AbstractCallee() : calleeDecl(nullptr) {}
494 AbstractCallee(const clang::FunctionDecl *fd) : calleeDecl(fd) {}
495
496 bool hasFunctionDecl() const {
497 return llvm::isa_and_nonnull<clang::FunctionDecl>(calleeDecl);
498 }
499
500 unsigned getNumParams() const {
501 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
502 return fd->getNumParams();
503 return llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_size();
504 }
505
506 const clang::ParmVarDecl *getParamDecl(unsigned I) const {
507 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
508 return fd->getParamDecl(I);
509 return *(llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_begin() +
510 I);
511 }
512 };
513
514 struct VlaSizePair {
515 mlir::Value numElts;
516 QualType type;
517
518 VlaSizePair(mlir::Value num, QualType ty) : numElts(num), type(ty) {}
519 };
520
521 /// Return the number of elements for a single dimension
522 /// for the given array type.
523 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
524
525 /// Returns an MLIR::Value+QualType pair that corresponds to the size,
526 /// in non-variably-sized elements, of a variable length array type,
527 /// plus that largest non-variably-sized element type. Assumes that
528 /// the type has already been emitted with emitVariablyModifiedType.
529 VlaSizePair getVLASize(const VariableArrayType *type);
530 VlaSizePair getVLASize(QualType type);
531
532 Address getAsNaturalAddressOf(Address addr, QualType pointeeTy);
533
534 mlir::Value getAsNaturalPointerTo(Address addr, QualType pointeeType) {
535 return getAsNaturalAddressOf(addr, pointeeType).getBasePointer();
536 }
537
538 void finishFunction(SourceLocation endLoc);
539
540 /// Determine whether the given initializer is trivial in the sense
541 /// that it requires no code to be generated.
542 bool isTrivialInitializer(const Expr *init);
543
544 /// If the specified expression does not fold to a constant, or if it does but
545 /// contains a label, return false. If it constant folds return true and set
546 /// the boolean result in Result.
547 bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool,
548 bool allowLabels = false);
549 bool constantFoldsToSimpleInteger(const clang::Expr *cond,
550 llvm::APSInt &resultInt,
551 bool allowLabels = false);
552
553 /// Return true if the statement contains a label in it. If
554 /// this statement is not executed normally, it not containing a label means
555 /// that we can just remove the code.
556 bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts = false);
557
558 Address emitExtVectorElementLValue(LValue lv, mlir::Location loc);
559
560 class ConstantEmission {
561 // Cannot use mlir::TypedAttr directly here because of bit availability.
562 llvm::PointerIntPair<mlir::Attribute, 1, bool> valueAndIsReference;
563 ConstantEmission(mlir::TypedAttr c, bool isReference)
564 : valueAndIsReference(c, isReference) {}
565
566 public:
567 ConstantEmission() {}
568 static ConstantEmission forReference(mlir::TypedAttr c) {
569 return ConstantEmission(c, true);
570 }
571 static ConstantEmission forValue(mlir::TypedAttr c) {
572 return ConstantEmission(c, false);
573 }
574
575 explicit operator bool() const {
576 return valueAndIsReference.getOpaqueValue() != nullptr;
577 }
578
579 bool isReference() const { return valueAndIsReference.getInt(); }
580 LValue getReferenceLValue(CIRGenFunction &cgf, Expr *refExpr) const {
581 assert(isReference());
582 cgf.cgm.errorNYI(refExpr->getSourceRange(),
583 "ConstantEmission::getReferenceLValue");
584 return {};
585 }
586
587 mlir::TypedAttr getValue() const {
588 assert(!isReference());
589 return mlir::cast<mlir::TypedAttr>(valueAndIsReference.getPointer());
590 }
591 };
592
593 ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr);
594 ConstantEmission tryEmitAsConstant(const MemberExpr *me);
595
596 struct AutoVarEmission {
597 const clang::VarDecl *variable;
598 /// The address of the alloca for languages with explicit address space
599 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
600 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
601 /// as a global constant.
602 Address addr;
603
604 /// True if the variable is of aggregate type and has a constant
605 /// initializer.
606 bool isConstantAggregate = false;
607
608 /// True if the variable is a __block variable that is captured by an
609 /// escaping block.
610 bool isEscapingByRef = false;
611
612 /// True if the variable was emitted as an offload recipe, and thus doesn't
613 /// have the same sort of alloca initialization.
614 bool emittedAsOffload = false;
615
616 mlir::Value nrvoFlag{};
617
618 struct Invalid {};
619 AutoVarEmission(Invalid) : variable(nullptr), addr(Address::invalid()) {}
620
621 AutoVarEmission(const clang::VarDecl &variable)
622 : variable(&variable), addr(Address::invalid()) {}
623
624 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
625
626 bool wasEmittedAsGlobal() const { return !addr.isValid(); }
627
628 bool wasEmittedAsOffloadClause() const { return emittedAsOffload; }
629
630 /// Returns the raw, allocated address, which is not necessarily
631 /// the address of the object itself. It is casted to default
632 /// address space for address space agnostic languages.
633 Address getAllocatedAddress() const { return addr; }
634
635 // Changes the stored address for the emission. This function should only
636 // be used in extreme cases, and isn't required to model normal AST
637 // initialization/variables.
638 void setAllocatedAddress(Address a) { addr = a; }
639
640 /// Returns the address of the object within this declaration.
641 /// Note that this does not chase the forwarding pointer for
642 /// __block decls.
643 Address getObjectAddress(CIRGenFunction &cgf) const {
644 if (!isEscapingByRef)
645 return addr;
646
647 assert(!cir::MissingFeatures::opAllocaEscapeByReference());
648 return Address::invalid();
649 }
650 };
651
652 /// The given basic block lies in the current EH scope, but may be a
653 /// target of a potentially scope-crossing jump; get a stable handle
654 /// to which we can perform this jump later.
655 /// CIRGen: this mostly tracks state for figuring out the proper scope
656 /// information, no actual branches are emitted.
657 JumpDest getJumpDestInCurrentScope(mlir::Block *target) {
658 return JumpDest(target, ehStack.getInnermostNormalCleanup(),
659 nextCleanupDestIndex++);
660 }
661 /// IndirectBranch - The first time an indirect goto is seen we create a block
662 /// reserved for the indirect branch. Unlike before,the actual 'indirectbr'
663 /// is emitted at the end of the function, once all block destinations have
664 /// been resolved.
665 mlir::Block *indirectGotoBlock = nullptr;
666
667 void resolveBlockAddresses();
668 void finishIndirectBranch();
669
670 /// Perform the usual unary conversions on the specified expression and
671 /// compare the result against zero, returning an Int1Ty value.
672 mlir::Value evaluateExprAsBool(const clang::Expr *e);
673
674 cir::GlobalOp addInitializerToStaticVarDecl(const VarDecl &d,
675 cir::GlobalOp gv,
676 cir::GetGlobalOp gvAddr);
677
678 /// Enter the cleanups necessary to complete the given phase of destruction
679 /// for a destructor. The end result should call destructors on members and
680 /// base classes in reverse order of their construction.
681 void enterDtorCleanups(const CXXDestructorDecl *dtor, CXXDtorType type);
682
683 /// Determines whether an EH cleanup is required to destroy a type
684 /// with the given destruction kind.
685 /// TODO(cir): could be shared with Clang LLVM codegen
686 bool needsEHCleanup(QualType::DestructionKind kind) {
687 switch (kind) {
688 case QualType::DK_none:
689 return false;
690 case QualType::DK_cxx_destructor:
691 case QualType::DK_objc_weak_lifetime:
692 case QualType::DK_nontrivial_c_struct:
693 return getLangOpts().Exceptions;
694 case QualType::DK_objc_strong_lifetime:
695 return getLangOpts().Exceptions &&
696 cgm.getCodeGenOpts().ObjCAutoRefCountExceptions;
697 }
698 llvm_unreachable("bad destruction kind");
699 }
700
701 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
702 return needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup;
703 }
704
705 void pushStackRestore(CleanupKind kind, Address spMem);
706
707 /// Set the address of a local variable.
708 void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr) {
709 assert(!localDeclMap.count(vd) && "Decl already exists in LocalDeclMap!");
710 localDeclMap.insert({vd, addr});
711
712 // Add to the symbol table if not there already.
713 if (symbolTable.count(vd))
714 return;
715 symbolTable.insert(vd, addr.getPointer());
716 }
717
718 // Replaces the address of the local variable, if it exists. Else does the
719 // same thing as setAddrOfLocalVar.
720 void replaceAddrOfLocalVar(const clang::VarDecl *vd, Address addr) {
721 localDeclMap.insert_or_assign(vd, addr);
722 }
723
724 // A class to allow reverting changes to a var-decl's registration to the
725 // localDeclMap. This is used in cases where things are being inserted into
726 // the variable list but don't follow normal lookup/search rules, like in
727 // OpenACC recipe generation.
728 class DeclMapRevertingRAII {
729 CIRGenFunction &cgf;
730 const VarDecl *vd;
731 bool shouldDelete = false;
732 Address oldAddr = Address::invalid();
733
734 public:
735 DeclMapRevertingRAII(CIRGenFunction &cgf, const VarDecl *vd)
736 : cgf(cgf), vd(vd) {
737 auto mapItr = cgf.localDeclMap.find(vd);
738
739 if (mapItr != cgf.localDeclMap.end())
740 oldAddr = mapItr->second;
741 else
742 shouldDelete = true;
743 }
744
745 ~DeclMapRevertingRAII() {
746 if (shouldDelete)
747 cgf.localDeclMap.erase(vd);
748 else
749 cgf.localDeclMap.insert_or_assign(vd, oldAddr);
750 }
751 };
752
753 bool shouldNullCheckClassCastValue(const CastExpr *ce);
754
755 RValue convertTempToRValue(Address addr, clang::QualType type,
756 clang::SourceLocation loc);
757
758 static bool
759 isConstructorDelegationValid(const clang::CXXConstructorDecl *ctor);
760
761 struct VPtr {
762 clang::BaseSubobject base;
763 const clang::CXXRecordDecl *nearestVBase;
764 clang::CharUnits offsetFromNearestVBase;
765 const clang::CXXRecordDecl *vtableClass;
766 };
767
768 using VisitedVirtualBasesSetTy =
769 llvm::SmallPtrSet<const clang::CXXRecordDecl *, 4>;
770
771 using VPtrsVector = llvm::SmallVector<VPtr, 4>;
772 VPtrsVector getVTablePointers(const clang::CXXRecordDecl *vtableClass);
773 void getVTablePointers(clang::BaseSubobject base,
774 const clang::CXXRecordDecl *nearestVBase,
775 clang::CharUnits offsetFromNearestVBase,
776 bool baseIsNonVirtualPrimaryBase,
777 const clang::CXXRecordDecl *vtableClass,
778 VisitedVirtualBasesSetTy &vbases, VPtrsVector &vptrs);
779 /// Return the Value of the vtable pointer member pointed to by thisAddr.
780 mlir::Value getVTablePtr(mlir::Location loc, Address thisAddr,
781 const clang::CXXRecordDecl *vtableClass);
782
783 /// Returns whether we should perform a type checked load when loading a
784 /// virtual function for virtual calls to members of RD. This is generally
785 /// true when both vcall CFI and whole-program-vtables are enabled.
786 bool shouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *rd);
787
788 /// Source location information about the default argument or member
789 /// initializer expression we're evaluating, if any.
790 clang::CurrentSourceLocExprScope curSourceLocExprScope;
791 using SourceLocExprScopeGuard =
792 clang::CurrentSourceLocExprScope::SourceLocExprScopeGuard;
793
794 /// A scope within which we are constructing the fields of an object which
795 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use if
796 /// we need to evaluate the CXXDefaultInitExpr within the evaluation.
797 class FieldConstructionScope {
798 public:
799 FieldConstructionScope(CIRGenFunction &cgf, Address thisAddr)
800 : cgf(cgf), oldCXXDefaultInitExprThis(cgf.cxxDefaultInitExprThis) {
801 cgf.cxxDefaultInitExprThis = thisAddr;
802 }
803 ~FieldConstructionScope() {
804 cgf.cxxDefaultInitExprThis = oldCXXDefaultInitExprThis;
805 }
806
807 private:
808 CIRGenFunction &cgf;
809 Address oldCXXDefaultInitExprThis;
810 };
811
812 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
813 /// is overridden to be the object under construction.
814 class CXXDefaultInitExprScope {
815 public:
816 CXXDefaultInitExprScope(CIRGenFunction &cgf, const CXXDefaultInitExpr *e)
817 : cgf{cgf}, oldCXXThisValue(cgf.cxxThisValue),
818 oldCXXThisAlignment(cgf.cxxThisAlignment),
819 sourceLocScope(e, cgf.curSourceLocExprScope) {
820 cgf.cxxThisValue = cgf.cxxDefaultInitExprThis.getPointer();
821 cgf.cxxThisAlignment = cgf.cxxDefaultInitExprThis.getAlignment();
822 }
823 ~CXXDefaultInitExprScope() {
824 cgf.cxxThisValue = oldCXXThisValue;
825 cgf.cxxThisAlignment = oldCXXThisAlignment;
826 }
827
828 public:
829 CIRGenFunction &cgf;
830 mlir::Value oldCXXThisValue;
831 clang::CharUnits oldCXXThisAlignment;
832 SourceLocExprScopeGuard sourceLocScope;
833 };
834
835 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
836 CXXDefaultArgExprScope(CIRGenFunction &cfg, const CXXDefaultArgExpr *e)
837 : SourceLocExprScopeGuard(e, cfg.curSourceLocExprScope) {}
838 };
839
840 LValue makeNaturalAlignPointeeAddrLValue(mlir::Value v, clang::QualType t);
841 LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty);
842
843 /// Construct an address with the natural alignment of T. If a pointer to T
844 /// is expected to be signed, the pointer passed to this function must have
845 /// been signed, and the returned Address will have the pointer authentication
846 /// information needed to authenticate the signed pointer.
847 Address makeNaturalAddressForPointer(mlir::Value ptr, QualType t,
848 CharUnits alignment,
849 bool forPointeeType = false,
850 LValueBaseInfo *baseInfo = nullptr) {
851 if (alignment.isZero())
852 alignment = cgm.getNaturalTypeAlignment(t, baseInfo);
853 return Address(ptr, convertTypeForMem(t), alignment);
854 }
855
856 Address getAddressOfBaseClass(
857 Address value, const CXXRecordDecl *derived,
858 llvm::iterator_range<CastExpr::path_const_iterator> path,
859 bool nullCheckValue, SourceLocation loc);
860
861 Address getAddressOfDerivedClass(
862 mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived,
863 llvm::iterator_range<CastExpr::path_const_iterator> path,
864 bool nullCheckValue);
865
866 /// Return the VTT parameter that should be passed to a base
867 /// constructor/destructor with virtual bases.
868 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
869 /// to ItaniumCXXABI.cpp together with all the references to VTT.
870 mlir::Value getVTTParameter(GlobalDecl gd, bool forVirtualBase,
871 bool delegating);
872
873 LValue makeAddrLValue(Address addr, QualType ty,
874 AlignmentSource source = AlignmentSource::Type) {
875 return makeAddrLValue(addr, ty, LValueBaseInfo(source));
876 }
877
878 LValue makeAddrLValue(Address addr, QualType ty, LValueBaseInfo baseInfo) {
879 return LValue::makeAddr(addr, ty, baseInfo);
880 }
881
882 void initializeVTablePointers(mlir::Location loc,
883 const clang::CXXRecordDecl *rd);
884 void initializeVTablePointer(mlir::Location loc, const VPtr &vptr);
885
886 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *fd);
887
888 /// Return the address of a local variable.
889 Address getAddrOfLocalVar(const clang::VarDecl *vd) {
890 auto it = localDeclMap.find(vd);
891 assert(it != localDeclMap.end() &&
892 "Invalid argument to getAddrOfLocalVar(), no decl!");
893 return it->second;
894 }
895
896 Address getAddrOfBitFieldStorage(LValue base, const clang::FieldDecl *field,
897 mlir::Type fieldType, unsigned index);
898
899 /// Given an opaque value expression, return its LValue mapping if it exists,
900 /// otherwise create one.
901 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
902
903 /// Given an opaque value expression, return its RValue mapping if it exists,
904 /// otherwise create one.
905 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
906
907 /// Load the value for 'this'. This function is only valid while generating
908 /// code for an C++ member function.
909 /// FIXME(cir): this should return a mlir::Value!
910 mlir::Value loadCXXThis() {
911 assert(cxxThisValue && "no 'this' value for this function");
912 return cxxThisValue;
913 }
914 Address loadCXXThisAddress();
915
916 /// Load the VTT parameter to base constructors/destructors have virtual
917 /// bases. FIXME: Every place that calls LoadCXXVTT is something that needs to
918 /// be abstracted properly.
919 mlir::Value loadCXXVTT() {
920 assert(cxxStructorImplicitParamValue && "no VTT value for this function");
921 return cxxStructorImplicitParamValue;
922 }
923
924 /// Convert the given pointer to a complete class to the given direct base.
925 Address getAddressOfDirectBaseInCompleteClass(mlir::Location loc,
926 Address value,
927 const CXXRecordDecl *derived,
928 const CXXRecordDecl *base,
929 bool baseIsVirtual);
930
931 /// Determine whether a return value slot may overlap some other object.
932 AggValueSlot::Overlap_t getOverlapForReturnValue() {
933 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
934 // class subobjects. These cases may need to be revisited depending on the
935 // resolution of the relevant core issue.
936 return AggValueSlot::DoesNotOverlap;
937 }
938
939 /// Determine whether a base class initialization may overlap some other
940 /// object.
941 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *rd,
942 const CXXRecordDecl *baseRD,
943 bool isVirtual);
944
945 /// Get an appropriate 'undef' rvalue for the given type.
946 /// TODO: What's the equivalent for MLIR? Currently we're only using this for
947 /// void types so it just returns RValue::get(nullptr) but it'll need
948 /// addressed later.
949 RValue getUndefRValue(clang::QualType ty);
950
951 cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
952 cir::FuncType funcType);
953
954 clang::QualType buildFunctionArgList(clang::GlobalDecl gd,
955 FunctionArgList &args);
956
957 /// Emit the function prologue: declare function arguments in the symbol
958 /// table.
959 void emitFunctionProlog(const FunctionArgList &args, mlir::Block *entryBB,
960 const FunctionDecl *fd, SourceLocation bodyBeginLoc);
961
962 /// Emit code for the start of a function.
963 /// \param loc The location to be associated with the function.
964 /// \param startLoc The location of the function body.
965 void startFunction(clang::GlobalDecl gd, clang::QualType returnType,
966 cir::FuncOp fn, cir::FuncType funcType,
967 FunctionArgList args, clang::SourceLocation loc,
968 clang::SourceLocation startLoc);
969
970 /// returns true if aggregate type has a volatile member.
971 bool hasVolatileMember(QualType t) {
972 if (const auto *rd = t->getAsRecordDecl())
973 return rd->hasVolatileMember();
974 return false;
975 }
976
977 void populateUnwindResumeBlock(bool isCleanup, cir::TryOp tryOp);
978 void populateEHCatchRegions(EHScopeStack::stable_iterator scope,
979 cir::TryOp tryOp);
980
981 /// The cleanup depth enclosing all the cleanups associated with the
982 /// parameters.
983 EHScopeStack::stable_iterator prologueCleanupDepth;
984
985 bool isCatchOrCleanupRequired();
986 void populateCatchHandlersIfRequired(cir::TryOp tryOp);
987
988 /// Takes the old cleanup stack size and emits the cleanup blocks
989 /// that have been added.
990 void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth);
991 void popCleanupBlock();
992
993 /// Push a cleanup to be run at the end of the current full-expression. Safe
994 /// against the possibility that we're currently inside a
995 /// conditionally-evaluated expression.
996 template <class T, class... As>
997 void pushFullExprCleanup(CleanupKind kind, As... a) {
998 // If we're not in a conditional branch, or if none of the
999 // arguments requires saving, then use the unconditional cleanup.
1000 if (!isInConditionalBranch())
1001 return ehStack.pushCleanup<T>(kind, a...);
1002
1003 cgm.errorNYI("pushFullExprCleanup in conditional branch");
1004 }
1005
1006 /// Enters a new scope for capturing cleanups, all of which
1007 /// will be executed once the scope is exited.
1008 class RunCleanupsScope {
1009 EHScopeStack::stable_iterator cleanupStackDepth, oldCleanupStackDepth;
1010
1011 protected:
1012 bool performCleanup;
1013 bool oldDidCallStackSave;
1014
1015 private:
1016 RunCleanupsScope(const RunCleanupsScope &) = delete;
1017 void operator=(const RunCleanupsScope &) = delete;
1018
1019 protected:
1020 CIRGenFunction &cgf;
1021
1022 public:
1023 /// Enter a new cleanup scope.
1024 explicit RunCleanupsScope(CIRGenFunction &cgf)
1025 : performCleanup(true), cgf(cgf) {
1026 cleanupStackDepth = cgf.ehStack.stable_begin();
1027 oldDidCallStackSave = cgf.didCallStackSave;
1028 cgf.didCallStackSave = false;
1029 oldCleanupStackDepth = cgf.currentCleanupStackDepth;
1030 cgf.currentCleanupStackDepth = cleanupStackDepth;
1031 }
1032
1033 /// Exit this cleanup scope, emitting any accumulated cleanups.
1034 ~RunCleanupsScope() {
1035 if (performCleanup)
1036 forceCleanup();
1037 }
1038
1039 /// Force the emission of cleanups now, instead of waiting
1040 /// until this object is destroyed.
1041 void forceCleanup() {
1042 assert(performCleanup && "Already forced cleanup");
1043 {
1044 mlir::OpBuilder::InsertionGuard guard(cgf.getBuilder());
1045 cgf.didCallStackSave = oldDidCallStackSave;
1046 cgf.popCleanupBlocks(cleanupStackDepth);
1047 performCleanup = false;
1048 cgf.currentCleanupStackDepth = oldCleanupStackDepth;
1049 }
1050 }
1051 };
1052
1053 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
1054 EHScopeStack::stable_iterator currentCleanupStackDepth = ehStack.stable_end();
1055
1056 public:
1057 /// Represents a scope, including function bodies, compound statements, and
1058 /// the substatements of if/while/do/for/switch/try statements. This class
1059 /// handles any automatic cleanup, along with the return value.
1060 struct LexicalScope : public RunCleanupsScope {
1061 private:
1062 // Block containing cleanup code for things initialized in this
1063 // lexical context (scope).
1064 mlir::Block *cleanupBlock = nullptr;
1065
1066 // Points to the scope entry block. This is useful, for instance, for
1067 // helping to insert allocas before finalizing any recursive CodeGen from
1068 // switches.
1069 mlir::Block *entryBlock;
1070
1071 LexicalScope *parentScope = nullptr;
1072
1073 // Holds the actual value for ScopeKind::Try
1074 cir::TryOp tryOp = nullptr;
1075
1076 // On a coroutine body, the OnFallthrough sub stmt holds the handler
1077 // (CoreturnStmt) for control flow falling off the body. Keep track
1078 // of emitted co_return in this scope and allow OnFallthrough to be
1079 // skipeed.
1080 bool hasCoreturnStmt = false;
1081
1082 // Only Regular is used at the moment. Support for other kinds will be
1083 // added as the relevant statements/expressions are upstreamed.
1084 enum Kind {
1085 Regular, // cir.if, cir.scope, if_regions
1086 Ternary, // cir.ternary
1087 Switch, // cir.switch
1088 Try, // cir.try
1089 GlobalInit // cir.global initialization code
1090 };
1091 Kind scopeKind = Kind::Regular;
1092
1093 // The scope return value.
1094 mlir::Value retVal = nullptr;
1095
1096 mlir::Location beginLoc;
1097 mlir::Location endLoc;
1098
1099 public:
1100 unsigned depth = 0;
1101
1102 LexicalScope(CIRGenFunction &cgf, mlir::Location loc, mlir::Block *eb)
1103 : RunCleanupsScope(cgf), entryBlock(eb), parentScope(cgf.curLexScope),
1104 beginLoc(loc), endLoc(loc) {
1105
1106 assert(entryBlock && "LexicalScope requires an entry block");
1107 cgf.curLexScope = this;
1108 if (parentScope)
1109 ++depth;
1110
1111 if (const auto fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(loc)) {
1112 assert(fusedLoc.getLocations().size() == 2 && "too many locations");
1113 beginLoc = fusedLoc.getLocations()[0];
1114 endLoc = fusedLoc.getLocations()[1];
1115 }
1116 }
1117
1118 void setRetVal(mlir::Value v) { retVal = v; }
1119
1120 void cleanup();
1121 void restore() { cgf.curLexScope = parentScope; }
1122
1123 ~LexicalScope() {
1124 assert(!cir::MissingFeatures::generateDebugInfo());
1125 cleanup();
1126 restore();
1127 }
1128
1129 // ---
1130 // Coroutine tracking
1131 // ---
1132 bool hasCoreturn() const { return hasCoreturnStmt; }
1133 void setCoreturn() { hasCoreturnStmt = true; }
1134
1135 // ---
1136 // Kind
1137 // ---
1138 bool isGlobalInit() { return scopeKind == Kind::GlobalInit; }
1139 bool isRegular() { return scopeKind == Kind::Regular; }
1140 bool isSwitch() { return scopeKind == Kind::Switch; }
1141 bool isTernary() { return scopeKind == Kind::Ternary; }
1142 bool isTry() { return scopeKind == Kind::Try; }
1143 cir::TryOp getClosestTryParent();
1144 void setAsGlobalInit() { scopeKind = Kind::GlobalInit; }
1145 void setAsSwitch() { scopeKind = Kind::Switch; }
1146 void setAsTernary() { scopeKind = Kind::Ternary; }
1147 void setAsTry(cir::TryOp op) {
1148 scopeKind = Kind::Try;
1149 tryOp = op;
1150 }
1151
1152 // Lazy create cleanup block or return what's available.
1153 mlir::Block *getOrCreateCleanupBlock(mlir::OpBuilder &builder) {
1154 if (cleanupBlock)
1155 return cleanupBlock;
1156 cleanupBlock = createCleanupBlock(builder);
1157 return cleanupBlock;
1158 }
1159
1160 cir::TryOp getTry() {
1161 assert(isTry());
1162 return tryOp;
1163 }
1164
1165 mlir::Block *getCleanupBlock(mlir::OpBuilder &builder) {
1166 return cleanupBlock;
1167 }
1168
1169 mlir::Block *createCleanupBlock(mlir::OpBuilder &builder) {
1170 // Create the cleanup block but dont hook it up around just yet.
1171 mlir::OpBuilder::InsertionGuard guard(builder);
1172 mlir::Region *r = builder.getBlock() ? builder.getBlock()->getParent()
1173 : &cgf.curFn->getRegion(0);
1174 cleanupBlock = builder.createBlock(r);
1175 return cleanupBlock;
1176 }
1177
1178 // ---
1179 // Return handling.
1180 // ---
1181
1182 private:
1183 // On switches we need one return block per region, since cases don't
1184 // have their own scopes but are distinct regions nonetheless.
1185
1186 // TODO: This implementation should change once we have support for early
1187 // exits in MLIR structured control flow (llvm-project#161575)
1188 llvm::SmallVector<mlir::Block *> retBlocks;
1189 llvm::DenseMap<mlir::Block *, mlir::Location> retLocs;
1190 llvm::DenseMap<cir::CaseOp, unsigned> retBlockInCaseIndex;
1191 std::optional<unsigned> normalRetBlockIndex;
1192
1193 // There's usually only one ret block per scope, but this needs to be
1194 // get or create because of potential unreachable return statements, note
1195 // that for those, all source location maps to the first one found.
1196 mlir::Block *createRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1197 assert((isa_and_nonnull<cir::CaseOp>(
1198 cgf.builder.getBlock()->getParentOp()) ||
1199 retBlocks.size() == 0) &&
1200 "only switches can hold more than one ret block");
1201
1202 // Create the return block but don't hook it up just yet.
1203 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
1204 auto *b = cgf.builder.createBlock(cgf.builder.getBlock()->getParent());
1205 retBlocks.push_back(b);
1206 updateRetLoc(b, loc);
1207 return b;
1208 }
1209
1210 cir::ReturnOp emitReturn(mlir::Location loc);
1211 void emitImplicitReturn();
1212
1213 public:
1214 llvm::ArrayRef<mlir::Block *> getRetBlocks() { return retBlocks; }
1215 mlir::Location getRetLoc(mlir::Block *b) { return retLocs.at(b); }
1216 void updateRetLoc(mlir::Block *b, mlir::Location loc) {
1217 retLocs.insert_or_assign(b, loc);
1218 }
1219
1220 mlir::Block *getOrCreateRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1221 // Check if we're inside a case region
1222 if (auto caseOp = mlir::dyn_cast_if_present<cir::CaseOp>(
1223 cgf.builder.getBlock()->getParentOp())) {
1224 auto iter = retBlockInCaseIndex.find(caseOp);
1225 if (iter != retBlockInCaseIndex.end()) {
1226 // Reuse existing return block
1227 mlir::Block *ret = retBlocks[iter->second];
1228 updateRetLoc(ret, loc);
1229 return ret;
1230 }
1231 // Create new return block
1232 mlir::Block *ret = createRetBlock(cgf, loc);
1233 retBlockInCaseIndex[caseOp] = retBlocks.size() - 1;
1234 return ret;
1235 }
1236
1237 if (normalRetBlockIndex) {
1238 mlir::Block *ret = retBlocks[*normalRetBlockIndex];
1239 updateRetLoc(ret, loc);
1240 return ret;
1241 }
1242
1243 mlir::Block *ret = createRetBlock(cgf, loc);
1244 normalRetBlockIndex = retBlocks.size() - 1;
1245 return ret;
1246 }
1247
1248 mlir::Block *getEntryBlock() { return entryBlock; }
1249 };
1250
1251 LexicalScope *curLexScope = nullptr;
1252
1253 typedef void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty);
1254
1255 static Destroyer destroyCXXObject;
1256
1257 void pushDestroy(QualType::DestructionKind dtorKind, Address addr,
1258 QualType type);
1259
1260 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1261 Destroyer *destroyer);
1262
1263 Destroyer *getDestroyer(clang::QualType::DestructionKind kind);
1264
1265 /// ----------------------
1266 /// CIR emit functions
1267 /// ----------------------
1268 public:
1269 bool getAArch64SVEProcessedOperands(unsigned builtinID, const CallExpr *expr,
1270 SmallVectorImpl<mlir::Value> &ops,
1271 clang::SVETypeFlags typeFlags);
1272 std::optional<mlir::Value>
1273 emitAArch64BuiltinExpr(unsigned builtinID, const CallExpr *expr,
1274 ReturnValueSlot returnValue,
1275 llvm::Triple::ArchType arch);
1276 std::optional<mlir::Value> emitAArch64SMEBuiltinExpr(unsigned builtinID,
1277 const CallExpr *expr);
1278 std::optional<mlir::Value> emitAArch64SVEBuiltinExpr(unsigned builtinID,
1279 const CallExpr *expr);
1280
1281 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty,
1282 SourceLocation loc,
1283 SourceLocation assumptionLoc,
1284 int64_t alignment,
1285 mlir::Value offsetValue = nullptr);
1286
1287 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, const Expr *expr,
1288 SourceLocation assumptionLoc,
1289 int64_t alignment,
1290 mlir::Value offsetValue = nullptr);
1291
1292 private:
1293 void emitAndUpdateRetAlloca(clang::QualType type, mlir::Location loc,
1294 clang::CharUnits alignment);
1295
1296 CIRGenCallee emitDirectCallee(const GlobalDecl &gd);
1297
1298 public:
1299 Address emitAddrOfFieldStorage(Address base, const FieldDecl *field,
1300 llvm::StringRef fieldName,
1301 unsigned fieldIndex);
1302
1303 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1304 mlir::Location loc, clang::CharUnits alignment,
1305 bool insertIntoFnEntryBlock,
1306 mlir::Value arraySize = nullptr);
1307 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1308 mlir::Location loc, clang::CharUnits alignment,
1309 mlir::OpBuilder::InsertPoint ip,
1310 mlir::Value arraySize = nullptr);
1311
1312 void emitAggregateStore(mlir::Value value, Address dest);
1313
1314 void emitAggExpr(const clang::Expr *e, AggValueSlot slot);
1315
1316 enum ExprValueKind { EVK_RValue, EVK_NonRValue };
1317
1318 LValue emitAggExprToLValue(const Expr *e);
1319
1320 /// Emit an aggregate copy.
1321 ///
1322 /// \param isVolatile \c true iff either the source or the destination is
1323 /// volatile.
1324 /// \param MayOverlap Whether the tail padding of the destination might be
1325 /// occupied by some other object. More efficient code can often be
1326 /// generated if not.
1327 void emitAggregateCopy(LValue dest, LValue src, QualType eltTy,
1328 AggValueSlot::Overlap_t mayOverlap,
1329 bool isVolatile = false);
1330
1331 /// Emit code to compute the specified expression which can have any type. The
1332 /// result is returned as an RValue struct. If this is an aggregate
1333 /// expression, the aggloc/agglocvolatile arguments indicate where the result
1334 /// should be returned.
1335 RValue emitAnyExpr(const clang::Expr *e,
1336 AggValueSlot aggSlot = AggValueSlot::ignored(),
1337 bool ignoreResult = false);
1338
1339 /// Emits the code necessary to evaluate an arbitrary expression into the
1340 /// given memory location.
1341 void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals,
1342 bool isInitializer);
1343
1344 /// Similarly to emitAnyExpr(), however, the result will always be accessible
1345 /// even if no aggregate location is provided.
1346 RValue emitAnyExprToTemp(const clang::Expr *e);
1347
1348 void emitAnyExprToExn(const Expr *e, Address addr);
1349
1350 void emitArrayDestroy(mlir::Value begin, mlir::Value numElements,
1351 QualType elementType, CharUnits elementAlign,
1352 Destroyer *destroyer);
1353
1354 mlir::Value emitArrayLength(const clang::ArrayType *arrayType,
1355 QualType &baseType, Address &addr);
1356 LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e);
1357
1358 LValue emitExtVectorElementExpr(const ExtVectorElementExpr *e);
1359
1360 Address emitArrayToPointerDecay(const Expr *e,
1361 LValueBaseInfo *baseInfo = nullptr);
1362
1363 mlir::LogicalResult emitAsmStmt(const clang::AsmStmt &s);
1364
1365 RValue emitAtomicExpr(AtomicExpr *e);
1366 void emitAtomicInit(Expr *init, LValue dest);
1367 void emitAtomicStore(RValue rvalue, LValue dest, bool isInit);
1368 void emitAtomicStore(RValue rvalue, LValue dest, cir::MemOrder order,
1369 bool isVolatile, bool isInit);
1370 void emitAtomicExprWithMemOrder(
1371 const Expr *memOrder, bool isStore, bool isLoad, bool isFence,
1372 llvm::function_ref<void(cir::MemOrder)> emitAtomicOp);
1373
1374 AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d,
1375 mlir::OpBuilder::InsertPoint ip = {});
1376
1377 /// Emit code and set up symbol table for a variable declaration with auto,
1378 /// register, or no storage class specifier. These turn into simple stack
1379 /// objects, globals depending on target.
1380 void emitAutoVarDecl(const clang::VarDecl &d);
1381
1382 void emitAutoVarCleanups(const AutoVarEmission &emission);
1383 /// Emit the initializer for an allocated variable. If this call is not
1384 /// associated with the call to emitAutoVarAlloca (as the address of the
1385 /// emission is not directly an alloca), the allocatedSeparately parameter can
1386 /// be used to suppress the assertions. However, this should only be used in
1387 /// extreme cases, as it doesn't properly reflect the language/AST.
1388 void emitAutoVarInit(const AutoVarEmission &emission);
1389 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1390 clang::QualType::DestructionKind dtorKind);
1391
1392 void maybeEmitDeferredVarDeclInit(const VarDecl *vd);
1393
1394 void emitBaseInitializer(mlir::Location loc, const CXXRecordDecl *classDecl,
1395 CXXCtorInitializer *baseInit);
1396
1397 LValue emitBinaryOperatorLValue(const BinaryOperator *e);
1398
1399 cir::BrOp emitBranchThroughCleanup(mlir::Location loc, JumpDest dest);
1400
1401 mlir::LogicalResult emitBreakStmt(const clang::BreakStmt &s);
1402
1403 RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID,
1404 const clang::CallExpr *e, ReturnValueSlot returnValue);
1405
1406 /// Returns a Value corresponding to the size of the given expression by
1407 /// emitting a `cir.objsize` operation.
1408 ///
1409 /// \param e The expression whose object size to compute
1410 /// \param type Determines the semantics of the object size computation.
1411 /// The type parameter is a 2-bit value where:
1412 /// bit 0 (type & 1): 0 = whole object, 1 = closest subobject
1413 /// bit 1 (type & 2): 0 = maximum size, 2 = minimum size
1414 /// \param resType The result type for the size value
1415 /// \param emittedE Optional pre-emitted pointer value. If non-null, we'll
1416 /// call `cir.objsize` on this value rather than emitting e.
1417 /// \param isDynamic If true, allows runtime evaluation via dynamic mode
1418 mlir::Value emitBuiltinObjectSize(const clang::Expr *e, unsigned type,
1419 cir::IntType resType, mlir::Value emittedE,
1420 bool isDynamic);
1421
1422 mlir::Value evaluateOrEmitBuiltinObjectSize(const clang::Expr *e,
1423 unsigned type,
1424 cir::IntType resType,
1425 mlir::Value emittedE,
1426 bool isDynamic);
1427
1428 int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts);
1429
1430 void instantiateIndirectGotoBlock();
1431
1432 RValue emitCall(const CIRGenFunctionInfo &funcInfo,
1433 const CIRGenCallee &callee, ReturnValueSlot returnValue,
1434 const CallArgList &args, cir::CIRCallOpInterface *callOp,
1435 mlir::Location loc);
1436 RValue emitCall(const CIRGenFunctionInfo &funcInfo,
1437 const CIRGenCallee &callee, ReturnValueSlot returnValue,
1438 const CallArgList &args,
1439 cir::CIRCallOpInterface *callOrTryCall = nullptr) {
1440 assert(currSrcLoc && "source location must have been set");
1441 return emitCall(funcInfo, callee, returnValue, args, callOrTryCall,
1442 *currSrcLoc);
1443 }
1444
1445 RValue emitCall(clang::QualType calleeTy, const CIRGenCallee &callee,
1446 const clang::CallExpr *e, ReturnValueSlot returnValue);
1447 void emitCallArg(CallArgList &args, const clang::Expr *e,
1448 clang::QualType argType);
1449 void emitCallArgs(
1450 CallArgList &args, PrototypeWrapper prototype,
1451 llvm::iterator_range<clang::CallExpr::const_arg_iterator> argRange,
1452 AbstractCallee callee = AbstractCallee(), unsigned paramsToSkip = 0);
1453 RValue emitCallExpr(const clang::CallExpr *e,
1454 ReturnValueSlot returnValue = ReturnValueSlot());
1455 LValue emitCallExprLValue(const clang::CallExpr *e);
1456 CIRGenCallee emitCallee(const clang::Expr *e);
1457
1458 template <typename T>
1459 mlir::LogicalResult emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
1460 mlir::ArrayAttr value,
1461 cir::CaseOpKind kind,
1462 bool buildingTopLevelCase);
1463
1464 mlir::LogicalResult emitCaseStmt(const clang::CaseStmt &s,
1465 mlir::Type condType,
1466 bool buildingTopLevelCase);
1467
1468 LValue emitCastLValue(const CastExpr *e);
1469
1470 /// Emits an argument for a call to a `__builtin_assume`. If the builtin
1471 /// sanitizer is enabled, a runtime check is also emitted.
1472 mlir::Value emitCheckedArgForAssume(const Expr *e);
1473
1474 /// Emit a conversion from the specified complex type to the specified
1475 /// destination type, where the destination type is an LLVM scalar type.
1476 mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy,
1477 QualType dstTy, SourceLocation loc);
1478
1479 LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e);
1480 LValue emitCompoundLiteralLValue(const CompoundLiteralExpr *e);
1481
1482 void emitConstructorBody(FunctionArgList &args);
1483
1484 mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s);
1485 cir::CallOp emitCoroEndBuiltinCall(mlir::Location loc, mlir::Value nullPtr);
1486 cir::CallOp emitCoroIDBuiltinCall(mlir::Location loc, mlir::Value nullPtr);
1487 cir::CallOp emitCoroAllocBuiltinCall(mlir::Location loc);
1488 cir::CallOp emitCoroBeginBuiltinCall(mlir::Location loc,
1489 mlir::Value coroframeAddr);
1490 RValue emitCoroutineFrame();
1491
1492 void emitDestroy(Address addr, QualType type, Destroyer *destroyer);
1493
1494 void emitDestructorBody(FunctionArgList &args);
1495
1496 mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s);
1497
1498 mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s);
1499
1500 void emitCXXConstructExpr(const clang::CXXConstructExpr *e,
1501 AggValueSlot dest);
1502
1503 void emitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1504 const clang::ArrayType *arrayType,
1505 Address arrayBegin, const CXXConstructExpr *e,
1506 bool newPointerIsChecked,
1507 bool zeroInitialize = false);
1508 void emitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1509 mlir::Value numElements, Address arrayBase,
1510 const CXXConstructExpr *e,
1511 bool newPointerIsChecked,
1512 bool zeroInitialize);
1513 void emitCXXConstructorCall(const clang::CXXConstructorDecl *d,
1514 clang::CXXCtorType type, bool forVirtualBase,
1515 bool delegating, AggValueSlot thisAVS,
1516 const clang::CXXConstructExpr *e);
1517
1518 void emitCXXConstructorCall(const clang::CXXConstructorDecl *d,
1519 clang::CXXCtorType type, bool forVirtualBase,
1520 bool delegating, Address thisAddr,
1521 CallArgList &args, clang::SourceLocation loc);
1522
1523 void emitCXXDeleteExpr(const CXXDeleteExpr *e);
1524
1525 void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type,
1526 bool forVirtualBase, bool delegating,
1527 Address thisAddr, QualType thisTy);
1528
1529 RValue emitCXXDestructorCall(GlobalDecl dtor, const CIRGenCallee &callee,
1530 mlir::Value thisVal, QualType thisTy,
1531 mlir::Value implicitParam,
1532 QualType implicitParamTy, const CallExpr *e);
1533
1534 mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s,
1535 llvm::ArrayRef<const Attr *> attrs);
1536
1537 RValue emitCXXMemberCallExpr(const clang::CXXMemberCallExpr *e,
1538 ReturnValueSlot returnValue);
1539
1540 Address emitCXXMemberDataPointerAddress(
1541 const Expr *e, Address base, mlir::Value memberPtr,
1542 const MemberPointerType *memberPtrType, LValueBaseInfo *baseInfo);
1543
1544 RValue emitCXXMemberOrOperatorCall(
1545 const clang::CXXMethodDecl *md, const CIRGenCallee &callee,
1546 ReturnValueSlot returnValue, mlir::Value thisPtr,
1547 mlir::Value implicitParam, clang::QualType implicitParamTy,
1548 const clang::CallExpr *ce, CallArgList *rtlArgs);
1549
1550 RValue emitCXXMemberOrOperatorMemberCallExpr(
1551 const clang::CallExpr *ce, const clang::CXXMethodDecl *md,
1552 ReturnValueSlot returnValue, bool hasQualifier,
1553 clang::NestedNameSpecifier qualifier, bool isArrow,
1554 const clang::Expr *base);
1555
1556 mlir::Value emitCXXNewExpr(const CXXNewExpr *e);
1557
1558 void emitNewArrayInitializer(const CXXNewExpr *e, QualType elementType,
1559 mlir::Type elementTy, Address beginPtr,
1560 mlir::Value numElements,
1561 mlir::Value allocSizeWithoutCookie);
1562
1563 RValue emitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *e,
1564 const CXXMethodDecl *md,
1565 ReturnValueSlot returnValue);
1566
1567 RValue emitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *expr);
1568
1569 RValue emitNewOrDeleteBuiltinCall(const FunctionProtoType *type,
1570 const CallExpr *callExpr,
1571 OverloadedOperatorKind op);
1572
1573 void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType,
1574 Address ptr);
1575
1576 void emitCXXThrowExpr(const CXXThrowExpr *e);
1577
1578 mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s);
1579
1580 mlir::LogicalResult emitCXXTryStmtUnderScope(const clang::CXXTryStmt &s);
1581
1582 void enterCXXTryStmt(const CXXTryStmt &s, cir::TryOp tryOp,
1583 bool isFnTryBlock = false);
1584
1585 void exitCXXTryStmt(const CXXTryStmt &s, bool isFnTryBlock = false);
1586
1587 void emitCtorPrologue(const clang::CXXConstructorDecl *ctor,
1588 clang::CXXCtorType ctorType, FunctionArgList &args);
1589
1590 // It's important not to confuse this and emitDelegateCXXConstructorCall.
1591 // Delegating constructors are the C++11 feature. The constructor delegate
1592 // optimization is used to reduce duplication in the base and complete
1593 // constructors where they are substantially the same.
1594 void emitDelegatingCXXConstructorCall(const CXXConstructorDecl *ctor,
1595 const FunctionArgList &args);
1596
1597 void emitDeleteCall(const FunctionDecl *deleteFD, mlir::Value ptr,
1598 QualType deleteTy);
1599
1600 mlir::LogicalResult emitDoStmt(const clang::DoStmt &s);
1601
1602 mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce);
1603
1604 /// Emit an expression as an initializer for an object (variable, field, etc.)
1605 /// at the given location. The expression is not necessarily the normal
1606 /// initializer for the object, and the address is not necessarily
1607 /// its normal location.
1608 ///
1609 /// \param init the initializing expression
1610 /// \param d the object to act as if we're initializing
1611 /// \param lvalue the lvalue to initialize
1612 /// \param capturedByInit true if \p d is a __block variable whose address is
1613 /// potentially changed by the initializer
1614 void emitExprAsInit(const clang::Expr *init, const clang::ValueDecl *d,
1615 LValue lvalue, bool capturedByInit = false);
1616
1617 mlir::LogicalResult emitFunctionBody(const clang::Stmt *body);
1618
1619 mlir::LogicalResult emitGotoStmt(const clang::GotoStmt &s);
1620
1621 mlir::LogicalResult emitIndirectGotoStmt(const IndirectGotoStmt &s);
1622
1623 void emitImplicitAssignmentOperatorBody(FunctionArgList &args);
1624
1625 void emitInitializerForField(clang::FieldDecl *field, LValue lhs,
1626 clang::Expr *init);
1627
1628 LValue emitPredefinedLValue(const PredefinedExpr *e);
1629
1630 mlir::Value emitPromotedComplexExpr(const Expr *e, QualType promotionType);
1631
1632 mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType);
1633
1634 mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType);
1635
1636 void emitReturnOfRValue(mlir::Location loc, RValue rv, QualType ty);
1637
1638 mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee,
1639 llvm::ArrayRef<mlir::Value> args = {});
1640
1641 void emitInvariantStart(CharUnits size, mlir::Value addr, mlir::Location loc);
1642
1643 /// Emit the computation of the specified expression of scalar type.
1644 mlir::Value emitScalarExpr(const clang::Expr *e,
1645 bool ignoreResultAssign = false);
1646
1647 mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv,
1648 cir::UnaryOpKind kind, bool isPre);
1649
1650 /// Build a debug stoppoint if we are emitting debug info.
1651 void emitStopPoint(const Stmt *s);
1652
1653 // Build CIR for a statement. useCurrentScope should be true if no
1654 // new scopes need be created when finding a compound statement.
1655 mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope,
1656 llvm::ArrayRef<const Attr *> attrs = {});
1657
1658 mlir::LogicalResult emitSimpleStmt(const clang::Stmt *s,
1659 bool useCurrentScope);
1660
1661 mlir::LogicalResult emitForStmt(const clang::ForStmt &s);
1662
1663 void emitForwardingCallToLambda(const CXXMethodDecl *lambdaCallOperator,
1664 CallArgList &callArgs);
1665
1666 RValue emitCoawaitExpr(const CoawaitExpr &e,
1667 AggValueSlot aggSlot = AggValueSlot::ignored(),
1668 bool ignoreResult = false);
1669 /// Emit the computation of the specified expression of complex type,
1670 /// returning the result.
1671 mlir::Value emitComplexExpr(const Expr *e);
1672
1673 void emitComplexExprIntoLValue(const Expr *e, LValue dest, bool isInit);
1674
1675 mlir::Value emitComplexPrePostIncDec(const UnaryOperator *e, LValue lv,
1676 cir::UnaryOpKind op, bool isPre);
1677
1678 LValue emitComplexAssignmentLValue(const BinaryOperator *e);
1679 LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e);
1680 LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e,
1681 mlir::Value &result);
1682
1683 mlir::LogicalResult
1684 emitCompoundStmt(const clang::CompoundStmt &s, Address *lastValue = nullptr,
1685 AggValueSlot slot = AggValueSlot::ignored());
1686
1687 mlir::LogicalResult
1688 emitCompoundStmtWithoutScope(const clang::CompoundStmt &s,
1689 Address *lastValue = nullptr,
1690 AggValueSlot slot = AggValueSlot::ignored());
1691
1692 void emitDecl(const clang::Decl &d, bool evaluateConditionDecl = false);
1693 mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s);
1694 LValue emitDeclRefLValue(const clang::DeclRefExpr *e);
1695
1696 mlir::LogicalResult emitDefaultStmt(const clang::DefaultStmt &s,
1697 mlir::Type condType,
1698 bool buildingTopLevelCase);
1699
1700 void emitDelegateCXXConstructorCall(const clang::CXXConstructorDecl *ctor,
1701 clang::CXXCtorType ctorType,
1702 const FunctionArgList &args,
1703 clang::SourceLocation loc);
1704
1705 /// We are performing a delegate call; that is, the current function is
1706 /// delegating to another one. Produce a r-value suitable for passing the
1707 /// given parameter.
1708 void emitDelegateCallArg(CallArgList &args, const clang::VarDecl *param,
1709 clang::SourceLocation loc);
1710
1711 /// Emit an `if` on a boolean condition to the specified blocks.
1712 /// FIXME: Based on the condition, this might try to simplify the codegen of
1713 /// the conditional based on the branch.
1714 /// In the future, we may apply code generation simplifications here,
1715 /// similar to those used in classic LLVM codegen
1716 /// See `EmitBranchOnBoolExpr` for inspiration.
1717 mlir::LogicalResult emitIfOnBoolExpr(const clang::Expr *cond,
1718 const clang::Stmt *thenS,
1719 const clang::Stmt *elseS);
1720 cir::IfOp emitIfOnBoolExpr(const clang::Expr *cond,
1721 BuilderCallbackRef thenBuilder,
1722 mlir::Location thenLoc,
1723 BuilderCallbackRef elseBuilder,
1724 std::optional<mlir::Location> elseLoc = {});
1725
1726 mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond);
1727
1728 LValue emitPointerToDataMemberBinaryExpr(const BinaryOperator *e);
1729
1730 mlir::LogicalResult emitLabel(const clang::LabelDecl &d);
1731 mlir::LogicalResult emitLabelStmt(const clang::LabelStmt &s);
1732
1733 void emitLambdaDelegatingInvokeBody(const CXXMethodDecl *md);
1734 void emitLambdaStaticInvokeBody(const CXXMethodDecl *md);
1735
1736 void populateCatchHandlers(cir::TryOp tryOp);
1737
1738 mlir::LogicalResult emitIfStmt(const clang::IfStmt &s);
1739
1740 /// Emit code to compute the specified expression,
1741 /// ignoring the result.
1742 void emitIgnoredExpr(const clang::Expr *e);
1743
1744 RValue emitLoadOfBitfieldLValue(LValue lv, SourceLocation loc);
1745
1746 /// Load a complex number from the specified l-value.
1747 mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc);
1748
1749 RValue emitLoadOfExtVectorElementLValue(LValue lv);
1750
1751 /// Given an expression that represents a value lvalue, this method emits
1752 /// the address of the lvalue, then loads the result as an rvalue,
1753 /// returning the rvalue.
1754 RValue emitLoadOfLValue(LValue lv, SourceLocation loc);
1755
1756 Address emitLoadOfReference(LValue refLVal, mlir::Location loc,
1757 LValueBaseInfo *pointeeBaseInfo);
1758 LValue emitLoadOfReferenceLValue(Address refAddr, mlir::Location loc,
1759 QualType refTy, AlignmentSource source);
1760
1761 /// EmitLoadOfScalar - Load a scalar value from an address, taking
1762 /// care to appropriately convert from the memory representation to
1763 /// the LLVM value representation. The l-value must be a simple
1764 /// l-value.
1765 mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc);
1766 mlir::Value emitLoadOfScalar(Address addr, bool isVolatile, QualType ty,
1767 SourceLocation loc, LValueBaseInfo baseInfo);
1768
1769 /// Emit code to compute a designator that specifies the location
1770 /// of the expression.
1771 /// FIXME: document this function better.
1772 LValue emitLValue(const clang::Expr *e);
1773 LValue emitLValueForBitField(LValue base, const FieldDecl *field);
1774 LValue emitLValueForField(LValue base, const clang::FieldDecl *field);
1775
1776 LValue emitLValueForLambdaField(const FieldDecl *field);
1777 LValue emitLValueForLambdaField(const FieldDecl *field,
1778 mlir::Value thisValue);
1779
1780 /// Like emitLValueForField, excpet that if the Field is a reference, this
1781 /// will return the address of the reference and not the address of the value
1782 /// stored in the reference.
1783 LValue emitLValueForFieldInitialization(LValue base,
1784 const clang::FieldDecl *field,
1785 llvm::StringRef fieldName);
1786
1787 LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e);
1788
1789 LValue emitMemberExpr(const MemberExpr *e);
1790
1791 LValue emitOpaqueValueLValue(const OpaqueValueExpr *e);
1792
1793 LValue emitConditionalOperatorLValue(const AbstractConditionalOperator *expr);
1794
1795 /// Given an expression with a pointer type, emit the value and compute our
1796 /// best estimate of the alignment of the pointee.
1797 ///
1798 /// One reasonable way to use this information is when there's a language
1799 /// guarantee that the pointer must be aligned to some stricter value, and
1800 /// we're simply trying to ensure that sufficiently obvious uses of under-
1801 /// aligned objects don't get miscompiled; for example, a placement new
1802 /// into the address of a local variable. In such a case, it's quite
1803 /// reasonable to just ignore the returned alignment when it isn't from an
1804 /// explicit source.
1805 Address emitPointerWithAlignment(const clang::Expr *expr,
1806 LValueBaseInfo *baseInfo = nullptr);
1807
1808 /// Emits a reference binding to the passed in expression.
1809 RValue emitReferenceBindingToExpr(const Expr *e);
1810
1811 mlir::LogicalResult emitReturnStmt(const clang::ReturnStmt &s);
1812
1813 RValue emitRotate(const CallExpr *e, bool isRotateLeft);
1814
1815 mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e);
1816
1817 /// Emit a conversion from the specified type to the specified destination
1818 /// type, both of which are CIR scalar types.
1819 mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType,
1820 clang::QualType dstType,
1821 clang::SourceLocation loc);
1822
1823 void emitScalarInit(const clang::Expr *init, mlir::Location loc,
1824 LValue lvalue, bool capturedByInit = false);
1825
1826 mlir::Value emitScalarOrConstFoldImmArg(unsigned iceArguments, unsigned idx,
1827 const Expr *argExpr);
1828
1829 void emitStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage);
1830
1831 void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest,
1832 bool isInit);
1833
1834 void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile,
1835 clang::QualType ty, LValueBaseInfo baseInfo,
1836 bool isInit = false, bool isNontemporal = false);
1837 void emitStoreOfScalar(mlir::Value value, LValue lvalue, bool isInit);
1838
1839 /// Store the specified rvalue into the specified
1840 /// lvalue, where both are guaranteed to the have the same type, and that type
1841 /// is 'Ty'.
1842 void emitStoreThroughLValue(RValue src, LValue dst, bool isInit = false);
1843
1844 mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult);
1845
1846 LValue emitStringLiteralLValue(const StringLiteral *e,
1847 llvm::StringRef name = ".str");
1848
1849 mlir::LogicalResult emitSwitchBody(const clang::Stmt *s);
1850 mlir::LogicalResult emitSwitchCase(const clang::SwitchCase &s,
1851 bool buildingTopLevelCase);
1852 mlir::LogicalResult emitSwitchStmt(const clang::SwitchStmt &s);
1853
1854 std::optional<mlir::Value>
1855 emitTargetBuiltinExpr(unsigned builtinID, const clang::CallExpr *e,
1856 ReturnValueSlot &returnValue);
1857
1858 /// Given a value and its clang type, returns the value casted to its memory
1859 /// representation.
1860 /// Note: CIR defers most of the special casting to the final lowering passes
1861 /// to conserve the high level information.
1862 mlir::Value emitToMemory(mlir::Value value, clang::QualType ty);
1863
1864 /// Emit a trap instruction, which is used to abort the program in an abnormal
1865 /// way, usually for debugging purposes.
1866 /// \p createNewBlock indicates whether to create a new block for the IR
1867 /// builder. Since the `cir.trap` operation is a terminator, operations that
1868 /// follow a trap cannot be emitted after `cir.trap` in the same block. To
1869 /// ensure these operations get emitted successfully, you need to create a new
1870 /// dummy block and set the insertion point there before continuing from the
1871 /// trap operation.
1872 void emitTrap(mlir::Location loc, bool createNewBlock);
1873
1874 LValue emitUnaryOpLValue(const clang::UnaryOperator *e);
1875
1876 mlir::Value emitUnPromotedValue(mlir::Value result, QualType unPromotionType);
1877
1878 /// Emit a reached-unreachable diagnostic if \p loc is valid and runtime
1879 /// checking is enabled. Otherwise, just emit an unreachable instruction.
1880 /// \p createNewBlock indicates whether to create a new block for the IR
1881 /// builder. Since the `cir.unreachable` operation is a terminator, operations
1882 /// that follow an unreachable point cannot be emitted after `cir.unreachable`
1883 /// in the same block. To ensure these operations get emitted successfully,
1884 /// you need to create a dummy block and set the insertion point there before
1885 /// continuing from the unreachable point.
1886 void emitUnreachable(clang::SourceLocation loc, bool createNewBlock);
1887
1888 /// This method handles emission of any variable declaration
1889 /// inside a function, including static vars etc.
1890 void emitVarDecl(const clang::VarDecl &d);
1891
1892 void emitVariablyModifiedType(QualType ty);
1893
1894 mlir::LogicalResult emitWhileStmt(const clang::WhileStmt &s);
1895
1896 std::optional<mlir::Value> emitX86BuiltinExpr(unsigned builtinID,
1897 const CallExpr *expr);
1898
1899 /// Given an assignment `*lhs = rhs`, emit a test that checks if \p rhs is
1900 /// nonnull, if 1\p LHS is marked _Nonnull.
1901 void emitNullabilityCheck(LValue lhs, mlir::Value rhs,
1902 clang::SourceLocation loc);
1903
1904 /// An object to manage conditionally-evaluated expressions.
1905 class ConditionalEvaluation {
1906 CIRGenFunction &cgf;
1907 mlir::OpBuilder::InsertPoint insertPt;
1908
1909 public:
1910 ConditionalEvaluation(CIRGenFunction &cgf)
1911 : cgf(cgf), insertPt(cgf.builder.saveInsertionPoint()) {}
1912 ConditionalEvaluation(CIRGenFunction &cgf, mlir::OpBuilder::InsertPoint ip)
1913 : cgf(cgf), insertPt(ip) {}
1914
1915 void beginEvaluation() {
1916 assert(cgf.outermostConditional != this);
1917 if (!cgf.outermostConditional)
1918 cgf.outermostConditional = this;
1919 }
1920
1921 void endEvaluation() {
1922 assert(cgf.outermostConditional != nullptr);
1923 if (cgf.outermostConditional == this)
1924 cgf.outermostConditional = nullptr;
1925 }
1926
1927 /// Returns the insertion point which will be executed prior to each
1928 /// evaluation of the conditional code. In LLVM OG, this method
1929 /// is called getStartingBlock.
1930 mlir::OpBuilder::InsertPoint getInsertPoint() const { return insertPt; }
1931 };
1932
1933 struct ConditionalInfo {
1934 std::optional<LValue> lhs{}, rhs{};
1935 mlir::Value result{};
1936 };
1937
1938 // Return true if we're currently emitting one branch or the other of a
1939 // conditional expression.
1940 bool isInConditionalBranch() const { return outermostConditional != nullptr; }
1941
1942 void setBeforeOutermostConditional(mlir::Value value, Address addr) {
1943 assert(isInConditionalBranch());
1944 {
1945 mlir::OpBuilder::InsertionGuard guard(builder);
1946 builder.restoreInsertionPoint(outermostConditional->getInsertPoint());
1947 builder.createStore(
1948 value.getLoc(), value, addr, /*isVolatile=*/false,
1949 mlir::IntegerAttr::get(
1950 mlir::IntegerType::get(value.getContext(), 64),
1951 (uint64_t)addr.getAlignment().getAsAlign().value()));
1952 }
1953 }
1954
1955 // Points to the outermost active conditional control. This is used so that
1956 // we know if a temporary should be destroyed conditionally.
1957 ConditionalEvaluation *outermostConditional = nullptr;
1958
1959 /// An RAII object to record that we're evaluating a statement
1960 /// expression.
1961 class StmtExprEvaluation {
1962 CIRGenFunction &cgf;
1963
1964 /// We have to save the outermost conditional: cleanups in a
1965 /// statement expression aren't conditional just because the
1966 /// StmtExpr is.
1967 ConditionalEvaluation *savedOutermostConditional;
1968
1969 public:
1970 StmtExprEvaluation(CIRGenFunction &cgf)
1971 : cgf(cgf), savedOutermostConditional(cgf.outermostConditional) {
1972 cgf.outermostConditional = nullptr;
1973 }
1974
1975 ~StmtExprEvaluation() {
1976 cgf.outermostConditional = savedOutermostConditional;
1977 }
1978 };
1979
1980 template <typename FuncTy>
1981 ConditionalInfo emitConditionalBlocks(const AbstractConditionalOperator *e,
1982 const FuncTy &branchGenFunc);
1983
1984 mlir::Value emitTernaryOnBoolExpr(const clang::Expr *cond, mlir::Location loc,
1985 const clang::Stmt *thenS,
1986 const clang::Stmt *elseS);
1987
1988 /// Build a "reference" to a va_list; this is either the address or the value
1989 /// of the expression, depending on how va_list is defined.
1990 Address emitVAListRef(const Expr *e);
1991
1992 /// Emits the start of a CIR variable-argument operation (`cir.va_start`)
1993 ///
1994 /// \param vaList A reference to the \c va_list as emitted by either
1995 /// \c emitVAListRef or \c emitMSVAListRef.
1996 ///
1997 /// \param count The number of arguments in \c vaList
1998 void emitVAStart(mlir::Value vaList, mlir::Value count);
1999
2000 /// Emits the end of a CIR variable-argument operation (`cir.va_start`)
2001 ///
2002 /// \param vaList A reference to the \c va_list as emitted by either
2003 /// \c emitVAListRef or \c emitMSVAListRef.
2004 void emitVAEnd(mlir::Value vaList);
2005
2006 /// Generate code to get an argument from the passed in pointer
2007 /// and update it accordingly.
2008 ///
2009 /// \param ve The \c VAArgExpr for which to generate code.
2010 ///
2011 /// \param vaListAddr Receives a reference to the \c va_list as emitted by
2012 /// either \c emitVAListRef or \c emitMSVAListRef.
2013 ///
2014 /// \returns SSA value with the argument.
2015 mlir::Value emitVAArg(VAArgExpr *ve);
2016
2017 /// ----------------------
2018 /// CIR build helpers
2019 /// -----------------
2020 public:
2021 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2022 const Twine &name = "tmp",
2023 mlir::Value arraySize = nullptr,
2024 bool insertIntoFnEntryBlock = false);
2025 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2026 const Twine &name = "tmp",
2027 mlir::OpBuilder::InsertPoint ip = {},
2028 mlir::Value arraySize = nullptr);
2029 Address createTempAlloca(mlir::Type ty, CharUnits align, mlir::Location loc,
2030 const Twine &name = "tmp",
2031 mlir::Value arraySize = nullptr,
2032 Address *alloca = nullptr,
2033 mlir::OpBuilder::InsertPoint ip = {});
2034 Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align,
2035 mlir::Location loc,
2036 const Twine &name = "tmp",
2037 mlir::Value arraySize = nullptr,
2038 mlir::OpBuilder::InsertPoint ip = {});
2039
2040 /// Create a temporary memory object of the given type, with
2041 /// appropriate alignmen and cast it to the default address space. Returns
2042 /// the original alloca instruction by \p Alloca if it is not nullptr.
2043 Address createMemTemp(QualType t, mlir::Location loc,
2044 const Twine &name = "tmp", Address *alloca = nullptr,
2045 mlir::OpBuilder::InsertPoint ip = {});
2046 Address createMemTemp(QualType t, CharUnits align, mlir::Location loc,
2047 const Twine &name = "tmp", Address *alloca = nullptr,
2048 mlir::OpBuilder::InsertPoint ip = {});
2049
2050 //===--------------------------------------------------------------------===//
2051 // OpenMP Emission
2052 //===--------------------------------------------------------------------===//
2053 public:
2054 mlir::LogicalResult emitOMPScopeDirective(const OMPScopeDirective &s);
2055 mlir::LogicalResult emitOMPErrorDirective(const OMPErrorDirective &s);
2056 mlir::LogicalResult emitOMPParallelDirective(const OMPParallelDirective &s);
2057 mlir::LogicalResult emitOMPTaskwaitDirective(const OMPTaskwaitDirective &s);
2058 mlir::LogicalResult emitOMPTaskyieldDirective(const OMPTaskyieldDirective &s);
2059 mlir::LogicalResult emitOMPBarrierDirective(const OMPBarrierDirective &s);
2060 mlir::LogicalResult emitOMPMetaDirective(const OMPMetaDirective &s);
2061 mlir::LogicalResult emitOMPCanonicalLoop(const OMPCanonicalLoop &s);
2062 mlir::LogicalResult emitOMPSimdDirective(const OMPSimdDirective &s);
2063 mlir::LogicalResult emitOMPTileDirective(const OMPTileDirective &s);
2064 mlir::LogicalResult emitOMPUnrollDirective(const OMPUnrollDirective &s);
2065 mlir::LogicalResult emitOMPFuseDirective(const OMPFuseDirective &s);
2066 mlir::LogicalResult emitOMPForDirective(const OMPForDirective &s);
2067 mlir::LogicalResult emitOMPForSimdDirective(const OMPForSimdDirective &s);
2068 mlir::LogicalResult emitOMPSectionsDirective(const OMPSectionsDirective &s);
2069 mlir::LogicalResult emitOMPSectionDirective(const OMPSectionDirective &s);
2070 mlir::LogicalResult emitOMPSingleDirective(const OMPSingleDirective &s);
2071 mlir::LogicalResult emitOMPMasterDirective(const OMPMasterDirective &s);
2072 mlir::LogicalResult emitOMPCriticalDirective(const OMPCriticalDirective &s);
2073 mlir::LogicalResult
2074 emitOMPParallelForDirective(const OMPParallelForDirective &s);
2075 mlir::LogicalResult
2076 emitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &s);
2077 mlir::LogicalResult
2078 emitOMPParallelMasterDirective(const OMPParallelMasterDirective &s);
2079 mlir::LogicalResult
2080 emitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &s);
2081 mlir::LogicalResult emitOMPTaskDirective(const OMPTaskDirective &s);
2082 mlir::LogicalResult emitOMPTaskgroupDirective(const OMPTaskgroupDirective &s);
2083 mlir::LogicalResult emitOMPFlushDirective(const OMPFlushDirective &s);
2084 mlir::LogicalResult emitOMPDepobjDirective(const OMPDepobjDirective &s);
2085 mlir::LogicalResult emitOMPScanDirective(const OMPScanDirective &s);
2086 mlir::LogicalResult emitOMPOrderedDirective(const OMPOrderedDirective &s);
2087 mlir::LogicalResult emitOMPAtomicDirective(const OMPAtomicDirective &s);
2088 mlir::LogicalResult emitOMPTargetDirective(const OMPTargetDirective &s);
2089 mlir::LogicalResult emitOMPTeamsDirective(const OMPTeamsDirective &s);
2090 mlir::LogicalResult
2091 emitOMPCancellationPointDirective(const OMPCancellationPointDirective &s);
2092 mlir::LogicalResult emitOMPCancelDirective(const OMPCancelDirective &s);
2093 mlir::LogicalResult
2094 emitOMPTargetDataDirective(const OMPTargetDataDirective &s);
2095 mlir::LogicalResult
2096 emitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &s);
2097 mlir::LogicalResult
2098 emitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &s);
2099 mlir::LogicalResult
2100 emitOMPTargetParallelDirective(const OMPTargetParallelDirective &s);
2101 mlir::LogicalResult
2102 emitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &s);
2103 mlir::LogicalResult emitOMPTaskLoopDirective(const OMPTaskLoopDirective &s);
2104 mlir::LogicalResult
2105 emitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &s);
2106 mlir::LogicalResult
2107 emitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &s);
2108 mlir::LogicalResult
2109 emitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &s);
2110 mlir::LogicalResult
2111 emitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &s);
2112 mlir::LogicalResult
2113 emitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &s);
2114 mlir::LogicalResult
2115 emitOMPParallelGenericLoopDirective(const OMPParallelGenericLoopDirective &s);
2116 mlir::LogicalResult
2117 emitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &s);
2118 mlir::LogicalResult emitOMPParallelMaskedTaskLoopDirective(
2119 const OMPParallelMaskedTaskLoopDirective &s);
2120 mlir::LogicalResult emitOMPParallelMaskedTaskLoopSimdDirective(
2121 const OMPParallelMaskedTaskLoopSimdDirective &s);
2122 mlir::LogicalResult emitOMPParallelMasterTaskLoopDirective(
2123 const OMPParallelMasterTaskLoopDirective &s);
2124 mlir::LogicalResult emitOMPParallelMasterTaskLoopSimdDirective(
2125 const OMPParallelMasterTaskLoopSimdDirective &s);
2126 mlir::LogicalResult
2127 emitOMPDistributeDirective(const OMPDistributeDirective &s);
2128 mlir::LogicalResult emitOMPDistributeParallelForDirective(
2129 const OMPDistributeParallelForDirective &s);
2130 mlir::LogicalResult emitOMPDistributeParallelForSimdDirective(
2131 const OMPDistributeParallelForSimdDirective &s);
2132 mlir::LogicalResult
2133 emitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &s);
2134 mlir::LogicalResult emitOMPTargetParallelGenericLoopDirective(
2135 const OMPTargetParallelGenericLoopDirective &s);
2136 mlir::LogicalResult emitOMPTargetParallelForSimdDirective(
2137 const OMPTargetParallelForSimdDirective &s);
2138 mlir::LogicalResult
2139 emitOMPTargetSimdDirective(const OMPTargetSimdDirective &s);
2140 mlir::LogicalResult emitOMPTargetTeamsGenericLoopDirective(
2141 const OMPTargetTeamsGenericLoopDirective &s);
2142 mlir::LogicalResult
2143 emitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &s);
2144 mlir::LogicalResult
2145 emitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &s);
2146 mlir::LogicalResult
2147 emitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &s);
2148 mlir::LogicalResult emitOMPTeamsDistributeParallelForSimdDirective(
2149 const OMPTeamsDistributeParallelForSimdDirective &s);
2150 mlir::LogicalResult emitOMPTeamsDistributeParallelForDirective(
2151 const OMPTeamsDistributeParallelForDirective &s);
2152 mlir::LogicalResult
2153 emitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &s);
2154 mlir::LogicalResult
2155 emitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &s);
2156 mlir::LogicalResult emitOMPTargetTeamsDistributeDirective(
2157 const OMPTargetTeamsDistributeDirective &s);
2158 mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForDirective(
2159 const OMPTargetTeamsDistributeParallelForDirective &s);
2160 mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForSimdDirective(
2161 const OMPTargetTeamsDistributeParallelForSimdDirective &s);
2162 mlir::LogicalResult emitOMPTargetTeamsDistributeSimdDirective(
2163 const OMPTargetTeamsDistributeSimdDirective &s);
2164 mlir::LogicalResult emitOMPInteropDirective(const OMPInteropDirective &s);
2165 mlir::LogicalResult emitOMPDispatchDirective(const OMPDispatchDirective &s);
2166 mlir::LogicalResult
2167 emitOMPGenericLoopDirective(const OMPGenericLoopDirective &s);
2168 mlir::LogicalResult emitOMPReverseDirective(const OMPReverseDirective &s);
2169 mlir::LogicalResult
2170 emitOMPInterchangeDirective(const OMPInterchangeDirective &s);
2171 mlir::LogicalResult emitOMPAssumeDirective(const OMPAssumeDirective &s);
2172 mlir::LogicalResult emitOMPMaskedDirective(const OMPMaskedDirective &s);
2173 mlir::LogicalResult emitOMPStripeDirective(const OMPStripeDirective &s);
2174
2175 void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl &d);
2176 void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl &d);
2177 void emitOMPCapturedExpr(const OMPCapturedExprDecl &d);
2178 void emitOMPAllocateDecl(const OMPAllocateDecl &d);
2179 void emitOMPDeclareReduction(const OMPDeclareReductionDecl &d);
2180 void emitOMPDeclareMapper(const OMPDeclareMapperDecl &d);
2181 void emitOMPRequiresDecl(const OMPRequiresDecl &d);
2182
2183 private:
2184 template <typename Op>
2185 void emitOpenMPClauses(Op &op, ArrayRef<const OMPClause *> clauses);
2186
2187 //===--------------------------------------------------------------------===//
2188 // OpenACC Emission
2189 //===--------------------------------------------------------------------===//
2190 private:
2191 template <typename Op>
2192 Op emitOpenACCOp(mlir::Location start, OpenACCDirectiveKind dirKind,
2193 llvm::ArrayRef<const OpenACCClause *> clauses);
2194 // Function to do the basic implementation of an operation with an Associated
2195 // Statement. Models AssociatedStmtConstruct.
2196 template <typename Op, typename TermOp>
2197 mlir::LogicalResult
2198 emitOpenACCOpAssociatedStmt(mlir::Location start, mlir::Location end,
2199 OpenACCDirectiveKind dirKind,
2200 llvm::ArrayRef<const OpenACCClause *> clauses,
2201 const Stmt *associatedStmt);
2202
2203 template <typename Op, typename TermOp>
2204 mlir::LogicalResult emitOpenACCOpCombinedConstruct(
2205 mlir::Location start, mlir::Location end, OpenACCDirectiveKind dirKind,
2206 llvm::ArrayRef<const OpenACCClause *> clauses, const Stmt *loopStmt);
2207
2208 template <typename Op>
2209 void emitOpenACCClauses(Op &op, OpenACCDirectiveKind dirKind,
2210 ArrayRef<const OpenACCClause *> clauses);
2211 // The second template argument doesn't need to be a template, since it should
2212 // always be an mlir::acc::LoopOp, but as this is a template anyway, we make
2213 // it a template argument as this way we can avoid including the OpenACC MLIR
2214 // headers here. We will count on linker failures/explicit instantiation to
2215 // ensure we don't mess this up, but it is only called from 1 place, and
2216 // instantiated 3x.
2217 template <typename ComputeOp, typename LoopOp>
2218 void emitOpenACCClauses(ComputeOp &op, LoopOp &loopOp,
2219 OpenACCDirectiveKind dirKind,
2220 ArrayRef<const OpenACCClause *> clauses);
2221
2222 // The OpenACC LoopOp requires that we have auto, seq, or independent on all
2223 // LoopOp operations for the 'none' device type case. This function checks if
2224 // the LoopOp has one, else it updates it to have one.
2225 void updateLoopOpParallelism(mlir::acc::LoopOp &op, bool isOrphan,
2226 OpenACCDirectiveKind dk);
2227
2228 // The OpenACC 'cache' construct actually applies to the 'loop' if present. So
2229 // keep track of the 'loop' so that we can add the cache vars to it correctly.
2230 mlir::acc::LoopOp *activeLoopOp = nullptr;
2231
2232 struct ActiveOpenACCLoopRAII {
2233 CIRGenFunction &cgf;
2234 mlir::acc::LoopOp *oldLoopOp;
2235
2236 ActiveOpenACCLoopRAII(CIRGenFunction &cgf, mlir::acc::LoopOp *newOp)
2237 : cgf(cgf), oldLoopOp(cgf.activeLoopOp) {
2238 cgf.activeLoopOp = newOp;
2239 }
2240 ~ActiveOpenACCLoopRAII() { cgf.activeLoopOp = oldLoopOp; }
2241 };
2242
2243 // Keep track of the last place we inserted a 'recipe' so that we can insert
2244 // the next one in lexical order.
2245 mlir::OpBuilder::InsertPoint lastRecipeLocation;
2246
2247 public:
2248 // Helper type used to store the list of important information for a 'data'
2249 // clause variable, or a 'cache' variable reference.
2250 struct OpenACCDataOperandInfo {
2251 mlir::Location beginLoc;
2252 mlir::Value varValue;
2253 std::string name;
2254 // The type of the original variable reference: that is, after 'bounds' have
2255 // removed pointers/array types/etc. So in the case of int arr[5], and a
2256 // private(arr[1]), 'origType' is 'int', but 'baseType' is 'int[5]'.
2257 QualType origType;
2258 QualType baseType;
2259 llvm::SmallVector<mlir::Value> bounds;
2260 // The list of types that we found when going through the bounds, which we
2261 // can use to properly set the alloca section.
2262 llvm::SmallVector<QualType> boundTypes;
2263 };
2264
2265 // Gets the collection of info required to lower and OpenACC clause or cache
2266 // construct variable reference.
2267 OpenACCDataOperandInfo getOpenACCDataOperandInfo(const Expr *e);
2268 // Helper function to emit the integer expressions as required by an OpenACC
2269 // clause/construct.
2270 mlir::Value emitOpenACCIntExpr(const Expr *intExpr);
2271 // Helper function to emit an integer constant as an mlir int type, used for
2272 // constants in OpenACC constructs/clauses.
2273 mlir::Value createOpenACCConstantInt(mlir::Location loc, unsigned width,
2274 int64_t value);
2275
2276 mlir::LogicalResult
2277 emitOpenACCComputeConstruct(const OpenACCComputeConstruct &s);
2278 mlir::LogicalResult emitOpenACCLoopConstruct(const OpenACCLoopConstruct &s);
2279 mlir::LogicalResult
2280 emitOpenACCCombinedConstruct(const OpenACCCombinedConstruct &s);
2281 mlir::LogicalResult emitOpenACCDataConstruct(const OpenACCDataConstruct &s);
2282 mlir::LogicalResult
2283 emitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct &s);
2284 mlir::LogicalResult
2285 emitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &s);
2286 mlir::LogicalResult
2287 emitOpenACCHostDataConstruct(const OpenACCHostDataConstruct &s);
2288 mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s);
2289 mlir::LogicalResult emitOpenACCInitConstruct(const OpenACCInitConstruct &s);
2290 mlir::LogicalResult
2291 emitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &s);
2292 mlir::LogicalResult emitOpenACCSetConstruct(const OpenACCSetConstruct &s);
2293 mlir::LogicalResult
2294 emitOpenACCUpdateConstruct(const OpenACCUpdateConstruct &s);
2295 mlir::LogicalResult
2296 emitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &s);
2297 mlir::LogicalResult emitOpenACCCacheConstruct(const OpenACCCacheConstruct &s);
2298
2299 void emitOpenACCDeclare(const OpenACCDeclareDecl &d);
2300 void emitOpenACCRoutine(const OpenACCRoutineDecl &d);
2301
2302 /// Create a temporary memory object for the given aggregate type.
2303 AggValueSlot createAggTemp(QualType ty, mlir::Location loc,
2304 const Twine &name = "tmp",
2305 Address *alloca = nullptr) {
2306 assert(!cir::MissingFeatures::aggValueSlot());
2307 return AggValueSlot::forAddr(
2308 createMemTemp(ty, loc, name, alloca), ty.getQualifiers(),
2309 AggValueSlot::IsNotDestructed, AggValueSlot::IsNotAliased,
2310 AggValueSlot::DoesNotOverlap);
2311 }
2312
2313 private:
2314 QualType getVarArgType(const Expr *arg);
2315 };
2316
2317 } // namespace clang::CIRGen
2318
2319 #endif