clang 23.0.0git
CIRGenDecl.cpp
Go to the documentation of this file.
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// This contains code to emit Decl nodes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenCleanup.h"
15#include "CIRGenFunction.h"
16#include "mlir/IR/Location.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Attrs.inc"
19#include "clang/AST/Decl.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/Basic/Cuda.h"
26
27using namespace clang;
28using namespace clang::CIRGen;
29
32 mlir::OpBuilder::InsertPoint ip) {
33 QualType ty = d.getType();
35 cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: address space");
36
37 mlir::Location loc = getLoc(d.getSourceRange());
38 bool nrvo =
39 getContext().getLangOpts().ElideConstructors && d.isNRVOVariable();
40
42 emission.isEscapingByRef = d.isEscapingByref();
43 if (emission.isEscapingByRef)
44 cgm.errorNYI(d.getSourceRange(),
45 "emitAutoVarAlloca: decl escaping by reference");
46
47 CharUnits alignment = getContext().getDeclAlign(&d);
48
49 // If the type is variably-modified, emit all the VLA sizes for it.
50 if (ty->isVariablyModifiedType())
52
54
55 Address address = Address::invalid();
56 if (ty->isConstantSizeType()) {
57 // If this value is an array, struct, or vector with a statically
58 // determinable constant initializer, there are optimizations we can do.
59 //
60 // TODO: We should constant-evaluate the initializer of any variable,
61 // as long as it is initialized by a constant expression. Currently,
62 // isConstantInitializer produces wrong answers for structs with
63 // reference or bitfield members, and a few other cases, and checking
64 // for POD-ness protects us from some of these.
65 if (d.getInit() &&
66 (ty->isArrayType() || ty->isRecordType() || ty->isVectorType()) &&
67 (d.isConstexpr() ||
68 ((ty.isPODType(getContext()) ||
69 getContext().getBaseElementType(ty)->isObjCObjectPointerType()) &&
71
72 // If the variable's a const type, and it's neither an NRVO
73 // candidate nor a __block variable and has no mutable members,
74 // emit it as a global instead.
75 // Exception is if a variable is located in non-constant address space
76 // in OpenCL.
77 // TODO(cir): perhaps we don't need this at all at CIR since this can
78 // be done as part of lowering down to LLVM.
79 bool needsDtor =
81 if ((!getContext().getLangOpts().OpenCL ||
83 (cgm.getCodeGenOpts().MergeAllConstants && !nrvo &&
84 !d.isEscapingByref() &&
85 ty.isConstantStorage(getContext(), true, !needsDtor))) {
86 cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: type constant");
87 }
88 // Otherwise, tell the initialization code that we're in this case.
89 emission.isConstantAggregate = true;
90 }
91
92 // A normal fixed sized variable becomes an alloca in the entry block,
93 // unless:
94 // - it's an NRVO variable.
95 // - we are compiling OpenMP and it's an OpenMP local variable.
96 if (nrvo) {
97 // The named return value optimization: allocate this variable in the
98 // return slot, so that we can elide the copy when returning this
99 // variable (C++0x [class.copy]p34).
100 address = returnValue;
101
102 if (const RecordDecl *rd = ty->getAsRecordDecl()) {
103 if (const auto *cxxrd = dyn_cast<CXXRecordDecl>(rd);
104 (cxxrd && !cxxrd->hasTrivialDestructor()) ||
105 rd->isNonTrivialToPrimitiveDestroy()) {
106 // In LLVM: Create a flag that is used to indicate when the NRVO was
107 // applied to this variable. Set it to zero to indicate that NRVO was
108 // not applied. For now, use the same approach for CIRGen until we can
109 // be sure it's worth doing something more aggressive.
110 cir::ConstantOp falseNVRO = builder.getFalse(loc);
111 Address nrvoFlag = createTempAlloca(falseNVRO.getType(),
112 CharUnits::One(), loc, "nrvo",
113 /*arraySize=*/nullptr);
114 assert(builder.getInsertionBlock());
115 builder.createStore(loc, falseNVRO, nrvoFlag);
116
117 // Record the NRVO flag for this variable.
118 nrvoFlags[&d] = nrvoFlag.getPointer();
119 emission.nrvoFlag = nrvoFlag.getPointer();
120 }
121 }
122 } else {
123 // A normal fixed sized variable becomes an alloca in the entry block,
124 mlir::Type allocaTy = convertTypeForMem(ty);
125 // Create the temp alloca and declare variable using it.
126 address = createTempAlloca(allocaTy, alignment, loc, d.getName(),
127 /*arraySize=*/nullptr, /*alloca=*/nullptr, ip);
128 declare(address.getPointer(), &d, ty, getLoc(d.getSourceRange()),
129 alignment);
130 }
131 } else {
132 // Non-constant size type
134 if (!didCallStackSave) {
135 // Save the stack.
136 cir::PointerType defaultTy = allocaInt8PtrTy;
138 cgm.getDataLayout().getAlignment(defaultTy, false));
139 Address stack = createTempAlloca(defaultTy, align, loc, "saved_stack");
140
141 mlir::Value v = builder.createStackSave(loc, defaultTy);
142 assert(v.getType() == allocaInt8PtrTy);
143 builder.createStore(loc, v, stack);
144
145 didCallStackSave = true;
146
147 // Push a cleanup block and restore the stack there.
148 // FIXME: in general circumstances, this should be an EH cleanup.
150 }
151
152 VlaSizePair vlaSize = getVLASize(ty);
153 mlir::Type memTy = convertTypeForMem(vlaSize.type);
154
155 // Allocate memory for the array.
156 address =
157 createTempAlloca(memTy, alignment, loc, d.getName(), vlaSize.numElts,
158 /*alloca=*/nullptr, builder.saveInsertionPoint());
159
160 // If we have debug info enabled, properly describe the VLA dimensions for
161 // this type by registering the vla size expression for each of the
162 // dimensions.
164 }
165
166 emission.addr = address;
167 setAddrOfLocalVar(&d, address);
168
169 return emission;
170}
171
172/// Determine whether the given initializer is trivial in the sense
173/// that it requires no code to be generated.
175 if (!init)
176 return true;
177
178 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(init))
179 if (CXXConstructorDecl *constructor = construct->getConstructor())
180 if (constructor->isTrivial() && constructor->isDefaultConstructor() &&
181 !construct->requiresZeroInitialization())
182 return true;
183
184 return false;
185}
186
187static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d,
188 Address addr, bool isVolatile,
189 CIRGenBuilderTy &builder,
190 mlir::TypedAttr constant) {
191 mlir::Type ty = constant.getType();
192 cir::CIRDataLayout layout{cgm.getModule()};
193 uint64_t constantSize = layout.getTypeAllocSize(ty);
194 if (!constantSize)
195 return;
198
199 if (addr.getElementType() != ty)
200 addr = addr.withElementType(builder, ty);
201
202 // If the address is an alloca, set the init attribute.
203 // The address is usually and alloca, but there is at least one case where
204 // emitAutoVarInit is called from the OpenACC codegen with an address that
205 // is not an alloca.
206 auto allocaOp = addr.getDefiningOp<cir::AllocaOp>();
207 if (allocaOp)
208 allocaOp.setInitAttr(mlir::UnitAttr::get(&cgm.getMLIRContext()));
209
210 // There are cases where OpenACC codegen calls emitAutoVarInit with a
211 // temporary decl that doesn't have a source range set.
212 mlir::Location loc = builder.getUnknownLoc();
213 if (d.getSourceRange().isValid())
214 loc = cgm.getLoc(d.getSourceRange());
215
216 // Emit cir.const + cir.store, preserving source-level semantics. For
217 // aggregate types (arrays, records), LoweringPrepare implements the OG
218 // optimization tiers (shouldCreateMemCpyFromGlobal, shouldUseBZeroPlusStores,
219 // shouldUseMemSetToInitialize, shouldSplitConstantStore) by transforming
220 // into cir.global + cir.get_global + cir.copy when appropriate.
221 builder.createStore(loc, builder.getConstant(loc, constant), addr);
222}
223
225 const CIRGenFunction::AutoVarEmission &emission) {
226 assert(emission.variable && "emission was not valid!");
227
228 // If this was emitted as a global constant, we're done.
229 if (emission.wasEmittedAsGlobal())
230 return;
231
232 const VarDecl &d = *emission.variable;
233
234 QualType type = d.getType();
235
236 // If this local has an initializer, emit it now.
237 const Expr *init = d.getInit();
238
239 // Initialize the variable here if it doesn't have a initializer and it is a
240 // C struct that is non-trivial to initialize or an array containing such a
241 // struct.
242 if (!init && type.isNonTrivialToPrimitiveDefaultInitialize() ==
244 cgm.errorNYI(d.getSourceRange(),
245 "emitAutoVarInit: non-trivial to default initialize");
246 return;
247 }
248
249 const Address addr = emission.addr;
250
251 // Check whether this is a byref variable that's potentially
252 // captured and moved by its own initializer. If so, we'll need to
253 // emit the initializer first, then copy into the variable.
255
256 // Note: constexpr already initializes everything correctly.
257 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
258 (d.isConstexpr()
260 : (d.getAttr<UninitializedAttr>()
262 : getContext().getLangOpts().getTrivialAutoVarInit()));
263
264 auto initializeWhatIsTechnicallyUninitialized = [&](Address addr) {
265 if (trivialAutoVarInit ==
267 return;
268
269 cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: trivial initialization");
270 };
271
272 if (isTrivialInitializer(init)) {
273 initializeWhatIsTechnicallyUninitialized(addr);
274 return;
275 }
276
277 mlir::Attribute constant;
278 if (emission.isConstantAggregate ||
280 // FIXME: Differently from LLVM we try not to emit / lower too much
281 // here for CIR since we are interested in seeing the ctor in some
282 // analysis later on. So CIR's implementation of ConstantEmitter will
283 // frequently return an empty Attribute, to signal we want to codegen
284 // some trivial ctor calls and whatnots.
286 if (constant && !mlir::isa<cir::ZeroAttr>(constant) &&
287 (trivialAutoVarInit !=
289 cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: constant aggregate");
290 return;
291 }
292 }
293
294 // NOTE(cir): In case we have a constant initializer, we can just emit a
295 // store. But, in CIR, we wish to retain any ctor calls, so if it is a
296 // CXX temporary object creation, we ensure the ctor call is used deferring
297 // its removal/optimization to the CIR lowering.
298 if (!constant || isa<CXXTemporaryObjectExpr>(init)) {
299 initializeWhatIsTechnicallyUninitialized(addr);
301 emitExprAsInit(init, &d, lv);
302
303 if (!emission.wasEmittedAsOffloadClause()) {
304 // In case lv has uses it means we indeed initialized something
305 // out of it while trying to build the expression, mark it as such.
306 mlir::Value val = lv.getAddress().getPointer();
307 assert(val && "Should have an address");
308 auto allocaOp = val.getDefiningOp<cir::AllocaOp>();
309 assert(allocaOp && "Address should come straight out of the alloca");
310
311 if (!allocaOp.use_empty())
312 allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext()));
313 }
314
315 return;
316 }
317
318 // FIXME(cir): migrate most of this file to use mlir::TypedAttr directly.
319 auto typedConstant = mlir::dyn_cast<mlir::TypedAttr>(constant);
320 assert(typedConstant && "expected typed attribute");
321 if (!emission.isConstantAggregate) {
322 // For simple scalar/complex initialization, store the value directly.
323 LValue lv = makeAddrLValue(addr, type);
324 assert(init && "expected initializer");
325 mlir::Location initLoc = getLoc(init->getSourceRange());
326 // lv.setNonGC(true);
328 RValue::get(builder.getConstant(initLoc, typedConstant)), lv);
329 }
330
331 emitStoresForConstant(cgm, d, addr, type.isVolatileQualified(), builder,
332 typedConstant);
333}
334
336 const CIRGenFunction::AutoVarEmission &emission) {
337 const VarDecl &d = *emission.variable;
338
339 // Check the type for a cleanup.
341 emitAutoVarTypeCleanup(emission, dtorKind);
342
344
345 // Handle the cleanup attribute.
346 if (d.hasAttr<CleanupAttr>())
347 cgm.errorNYI(d.getSourceRange(), "emitAutoVarCleanups: CleanupAttr");
348}
349
350/// Emit code and set up symbol table for a variable declaration with auto,
351/// register, or no storage class specifier. These turn into simple stack
352/// objects, globals depending on target.
358
360 // If the declaration has external storage, don't emit it now, allow it to be
361 // emitted lazily on its first use.
362 if (d.hasExternalStorage())
363 return;
364
365 if (d.getStorageDuration() != SD_Automatic) {
366 // Static sampler variables translated to function calls.
367 if (d.getType()->isSamplerT()) {
368 // Nothing needs to be done here, but let's flag it as an error until we
369 // have a test. It requires OpenCL support.
370 cgm.errorNYI(d.getSourceRange(), "emitVarDecl: static sampler type");
371 return;
372 }
373
374 cir::GlobalLinkageKind linkage =
375 cgm.getCIRLinkageVarDefinition(&d, /*IsConstant=*/false);
376
377 // FIXME: We need to force the emission/use of a guard variable for
378 // some variables even if we can constant-evaluate them because
379 // we can't guarantee every translation unit will constant-evaluate them.
380
381 return emitStaticVarDecl(d, linkage);
382 }
383
385 cgm.errorNYI(d.getSourceRange(), "emitVarDecl: openCL address space");
386
387 assert(d.hasLocalStorage());
388
389 CIRGenFunction::VarDeclContext varDeclCtx{*this, &d};
390 return emitAutoVarDecl(d);
391}
392
393static std::string getStaticDeclName(CIRGenModule &cgm, const VarDecl &d) {
394 if (cgm.getLangOpts().CPlusPlus)
395 return cgm.getMangledName(&d).str();
396
397 // If this isn't C++, we don't need a mangled name, just a pretty one.
398 assert(!d.isExternallyVisible() && "name shouldn't matter");
399 std::string contextName;
400 const DeclContext *dc = d.getDeclContext();
401 if (auto *cd = dyn_cast<CapturedDecl>(dc))
402 dc = cast<DeclContext>(cd->getNonClosureContext());
403 if (const auto *fd = dyn_cast<FunctionDecl>(dc))
404 contextName = std::string(cgm.getMangledName(fd));
405 else if (isa<BlockDecl>(dc))
406 cgm.errorNYI(d.getSourceRange(),
407 "getStaticDeclName: block decl context for static var");
408 else if (isa<ObjCMethodDecl>(dc))
409 cgm.errorNYI(d.getSourceRange(),
410 "getStaticDeclName: ObjC decl context for static var");
411 else
412 cgm.errorNYI(d.getSourceRange(),
413 "getStaticDeclName: Unknown context for static var decl");
414
415 contextName += "." + d.getNameAsString();
416 return contextName;
417}
418
419// TODO(cir): LLVM uses a Constant base class. Maybe CIR could leverage an
420// interface for all constants?
421cir::GlobalOp
423 cir::GlobalLinkageKind linkage) {
424 // In general, we don't always emit static var decls once before we reference
425 // them. It is possible to reference them before emitting the function that
426 // contains them, and it is possible to emit the containing function multiple
427 // times.
428 if (cir::GlobalOp existingGV = getStaticLocalDeclAddress(&d))
429 return existingGV;
430
431 QualType ty = d.getType();
432 assert(ty->isConstantSizeType() && "VLAs can't be static");
433
434 // Use the label if the variable is renamed with the asm-label extension.
435 if (d.hasAttr<AsmLabelAttr>())
436 errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: asm label");
437
438 std::string name = getStaticDeclName(*this, d);
439
440 mlir::Type lty = getTypes().convertTypeForMem(ty);
442
443 // OpenCL variables in local address space and CUDA shared
444 // variables cannot have an initializer.
445 mlir::Attribute init = nullptr;
447 d.hasAttr<CUDASharedAttr>() || d.hasAttr<LoaderUninitializedAttr>())
448 init = cir::UndefAttr::get(lty);
449 else
450 init = builder.getZeroInitAttr(convertType(ty));
451
452 cir::GlobalOp gv = builder.createVersionedGlobal(
453 getModule(), getLoc(d.getLocation()), name, lty, false, linkage);
454 // TODO(cir): infer visibility from linkage in global op builder.
455 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage));
456 gv.setInitialValueAttr(init);
457 gv.setAlignment(getASTContext().getDeclAlign(&d).getAsAlign().value());
458
459 if (supportsCOMDAT() && gv.isWeakForLinker())
460 gv.setComdat(true);
461
462 if (d.getTLSKind())
463 errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: TLS");
464
465 setGVProperties(gv, &d);
466
467 // OG checks if the expected address space, denoted by the type, is the
468 // same as the actual address space indicated by attributes. If they aren't
469 // the same, an addrspacecast is emitted when this variable is accessed.
470 // In CIR however, cir.get_global already carries that information in
471 // !cir.ptr type - if this global is in OpenCL local address space, then its
472 // type would be !cir.ptr<..., addrspace(offload_local)>. Therefore we don't
473 // need an explicit address space cast in CIR: they will get emitted when
474 // lowering to LLVM IR.
475
476 // Ensure that the static local gets initialized by making sure the parent
477 // function gets emitted eventually.
478 const Decl *dc = cast<Decl>(d.getDeclContext());
479
480 // We can't name blocks or captured statements directly, so try to emit their
481 // parents.
482 if (isa<BlockDecl>(dc) || isa<CapturedDecl>(dc)) {
483 dc = dc->getNonClosureContext();
484 // FIXME: Ensure that global blocks get emitted.
485 if (!dc)
486 errorNYI(d.getSourceRange(), "non-closure context");
487 }
488
489 GlobalDecl gd;
491 errorNYI(d.getSourceRange(), "C++ constructors static var context");
492 else if (isa<CXXDestructorDecl>(dc))
493 errorNYI(d.getSourceRange(), "C++ destructors static var context");
494 else if (const auto *fd = dyn_cast<FunctionDecl>(dc))
495 gd = GlobalDecl(fd);
496 else {
497 // Don't do anything for Obj-C method decls or global closures. We should
498 // never defer them.
499 assert(isa<ObjCMethodDecl>(dc) && "unexpected parent code decl");
500 }
502 // Disable emission of the parent function for the OpenMP device codegen.
503 errorNYI(d.getSourceRange(), "OpenMP");
504 }
505
506 return gv;
507}
508
510 mlir::Attribute constAttr,
511 CharUnits align) {
512 auto functionName = [&](const DeclContext *dc) -> std::string {
513 if (const auto *fd = dyn_cast<FunctionDecl>(dc)) {
514 if (const auto *cc = dyn_cast<CXXConstructorDecl>(fd))
515 return cc->getNameAsString();
516 if (const auto *cd = dyn_cast<CXXDestructorDecl>(fd))
517 return cd->getNameAsString();
518 return std::string(getMangledName(fd));
519 } else if (const auto *om = dyn_cast<ObjCMethodDecl>(dc)) {
520 return om->getNameAsString();
521 } else if (isa<BlockDecl>(dc)) {
522 return "<block>";
523 } else if (isa<CapturedDecl>(dc)) {
524 return "<captured>";
525 } else {
526 llvm_unreachable("expected a function or method");
527 }
528 };
529
530 // Form a simple per-variable cache of these values in case we find we
531 // want to reuse them.
532 cir::GlobalOp &cacheEntry = initializerConstants[&d];
533 if (!cacheEntry || cacheEntry.getInitialValue() != constAttr) {
534 auto ty = mlir::cast<mlir::TypedAttr>(constAttr).getType();
535 bool isConstant = true;
536
537 std::string name;
538 if (d.hasGlobalStorage())
539 name = getMangledName(&d).str() + ".const";
540 else if (const DeclContext *dc = d.getParentFunctionOrMethod())
541 name = ("__const." + functionName(dc) + "." + d.getName()).str();
542 else
543 llvm_unreachable("local variable has no parent function or method");
544
546 cir::GlobalOp gv = builder.createVersionedGlobal(
547 getModule(), getLoc(d.getLocation()), name, ty, isConstant,
548 cir::GlobalLinkageKind::PrivateLinkage);
549 // TODO(cir): infer visibility from linkage in global op builder.
550 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(
551 cir::GlobalLinkageKind::PrivateLinkage));
552 gv.setInitialValueAttr(constAttr);
553 gv.setAlignment(align.getAsAlign().value());
554 // TODO(cir): Set unnamed address attribute when available in CIR
555
556 cacheEntry = gv;
557 } else if (cacheEntry.getAlignment() < align.getQuantity()) {
558 cacheEntry.setAlignment(align.getAsAlign().value());
559 }
560
561 // Create a GetGlobalOp to get a pointer to the global
563 mlir::Type eltTy = mlir::cast<mlir::TypedAttr>(constAttr).getType();
564 auto ptrTy = builder.getPointerTo(cacheEntry.getSymType());
565 mlir::Value globalPtr = cir::GetGlobalOp::create(
566 builder, getLoc(d.getLocation()), ptrTy, cacheEntry.getSymName());
567 return Address(globalPtr, eltTy, align);
568}
569
570/// Add the initializer for 'd' to the global variable that has already been
571/// created for it. If the initializer has a different type than gv does, this
572/// may free gv and return a different one. Otherwise it just returns gv.
574 const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr) {
575 ConstantEmitter emitter(*this);
576 mlir::TypedAttr init = mlir::dyn_cast_if_present<mlir::TypedAttr>(
577 emitter.tryEmitForInitializer(d));
578
579 // If constant emission failed, then this should be a C++ static
580 // initializer.
581 if (!init) {
582 if (!getLangOpts().CPlusPlus) {
583 cgm.errorNYI(d.getInit()->getSourceRange(),
584 "constant l-value expression");
585 } else if (d.hasFlexibleArrayInit(getContext())) {
586 cgm.errorNYI(d.getInit()->getSourceRange(), "flexible array initializer");
587 } else {
588 // Since we have a static initializer, this global variable can't
589 // be constant.
590 gv.setConstant(false);
591 emitCXXGuardedInit(d, gv, /*performInit*/ true);
592 gvAddr.setStaticLocal(true);
593 }
594 return gv;
595 }
596
597 // TODO(cir): There should be debug code here to assert that the decl size
598 // matches the CIR data layout type alloc size, but the code for calculating
599 // the type alloc size is not implemented yet.
601
602 // The initializer may differ in type from the global. Rewrite
603 // the global to match the initializer. (We have to do this
604 // because some types, like unions, can't be completely represented
605 // in the LLVM type system.)
606 if (gv.getSymType() != init.getType()) {
607 gv.setSymType(init.getType());
608
609 // Normally this should be done with a call to cgm.replaceGlobal(oldGV, gv),
610 // but since at this point the current block hasn't been really attached,
611 // there's no visibility into the GetGlobalOp corresponding to this Global.
612 // Given those constraints, thread in the GetGlobalOp and update it
613 // directly.
615 gvAddr.getAddr().setType(builder.getPointerTo(init.getType()));
616 }
617
618 bool needsDtor =
620
621 gv.setConstant(d.getType().isConstantStorage(
622 getContext(), /*ExcludeCtor=*/true, !needsDtor));
623 gv.setInitialValueAttr(init);
624
625 emitter.finalize(gv);
626
627 if (needsDtor) {
628 // We have a constant initializer, but a nontrivial destructor. We still
629 // need to perform a guarded "initialization" in order to register the
630 // destructor.
631 cgm.errorNYI(d.getSourceRange(), "C++ guarded init");
632 }
633
634 return gv;
635}
636
638 cir::GlobalLinkageKind linkage) {
639 // Check to see if we already have a global variable for this
640 // declaration. This can happen when double-emitting function
641 // bodies, e.g. with complete and base constructors.
642 cir::GlobalOp globalOp = cgm.getOrCreateStaticVarDecl(d, linkage);
643 // TODO(cir): we should have a way to represent global ops as values without
644 // having to emit a get global op. Sometimes these emissions are not used.
645 mlir::Value addr = builder.createGetGlobal(globalOp);
646 auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>();
647 assert(getAddrOp && "expected cir::GetGlobalOp");
648
649 CharUnits alignment = getContext().getDeclAlign(&d);
650
651 // Store into LocalDeclMap before generating initializer to handle
652 // circular references.
653 mlir::Type elemTy = convertTypeForMem(d.getType());
654 setAddrOfLocalVar(&d, Address(addr, elemTy, alignment));
655
656 // We can't have a VLA here, but we can have a pointer to a VLA,
657 // even though that doesn't really make any sense.
658 // Make sure to evaluate VLA bounds now so that we have them for later.
659 if (d.getType()->isVariablyModifiedType()) {
660 cgm.errorNYI(d.getSourceRange(),
661 "emitStaticVarDecl: variably modified type");
662 }
663
664 // Save the type in case adding the initializer forces a type change.
665 mlir::Type expectedType = addr.getType();
666
667 cir::GlobalOp var = globalOp;
668
670
671 // If this value has an initializer, emit it.
672 if (d.getInit())
673 var = addInitializerToStaticVarDecl(d, var, getAddrOp);
674
675 var.setAlignment(alignment.getAsAlign().value());
676
677 // There are a lot of attributes that need to be handled here. Until
678 // we start to support them, we just report an error if there are any.
679 if (d.hasAttr<AnnotateAttr>())
680 cgm.errorNYI(d.getSourceRange(), "emitStaticVarDecl: Global annotations");
681 if (d.getAttr<PragmaClangBSSSectionAttr>())
682 cgm.errorNYI(d.getSourceRange(),
683 "emitStaticVarDecl: CIR global BSS section attribute");
684 if (d.getAttr<PragmaClangDataSectionAttr>())
685 cgm.errorNYI(d.getSourceRange(),
686 "emitStaticVarDecl: CIR global Data section attribute");
687 if (d.getAttr<PragmaClangRodataSectionAttr>())
688 cgm.errorNYI(d.getSourceRange(),
689 "emitStaticVarDecl: CIR global Rodata section attribute");
690 if (d.getAttr<PragmaClangRelroSectionAttr>())
691 cgm.errorNYI(d.getSourceRange(),
692 "emitStaticVarDecl: CIR global Relro section attribute");
693
694 if (d.getAttr<SectionAttr>())
695 cgm.errorNYI(d.getSourceRange(),
696 "emitStaticVarDecl: CIR global object file section attribute");
697
698 if (cgm.getCodeGenOpts().KeepPersistentStorageVariables)
699 cgm.errorNYI(d.getSourceRange(), "static var keep persistent storage");
700
701 // From traditional codegen:
702 // We may have to cast the constant because of the initializer
703 // mismatch above.
704 //
705 // FIXME: It is really dangerous to store this in the map; if anyone
706 // RAUW's the GV uses of this constant will be invalid.
707 mlir::Value castedAddr =
708 builder.createBitcast(getAddrOp.getAddr(), expectedType);
709 localDeclMap.find(&d)->second = Address(castedAddr, elemTy, alignment);
710 cgm.setStaticLocalDeclAddress(&d, var);
711
714}
715
716void CIRGenFunction::emitScalarInit(const Expr *init, mlir::Location loc,
717 LValue lvalue, bool capturedByInit) {
719
720 SourceLocRAIIObject locRAII{*this, loc};
721 mlir::Value value = emitScalarExpr(init);
722 if (capturedByInit) {
723 cgm.errorNYI(init->getSourceRange(), "emitScalarInit: captured by init");
724 return;
725 }
727 emitStoreThroughLValue(RValue::get(value), lvalue, true);
728}
729
731 LValue lvalue, bool capturedByInit) {
732 SourceLocRAIIObject loc{*this, getLoc(init->getSourceRange())};
733 if (capturedByInit) {
734 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
735 return;
736 }
737
738 QualType type = d->getType();
739
740 if (type->isReferenceType()) {
741 RValue rvalue = emitReferenceBindingToExpr(init);
742 if (capturedByInit)
743 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
744 emitStoreThroughLValue(rvalue, lvalue);
745 return;
746 }
748 case cir::TEK_Scalar:
749 emitScalarInit(init, getLoc(d->getSourceRange()), lvalue);
750 return;
751 case cir::TEK_Complex: {
752 mlir::Value complex = emitComplexExpr(init);
753 if (capturedByInit)
754 cgm.errorNYI(init->getSourceRange(),
755 "emitExprAsInit: complex type captured by init");
756 mlir::Location loc = getLoc(init->getExprLoc());
757 emitStoreOfComplex(loc, complex, lvalue,
758 /*isInit*/ true);
759 return;
760 }
762 // The overlap flag here should be calculated.
764 emitAggExpr(init,
768 return;
769 }
770 llvm_unreachable("bad evaluation kind");
771}
772
773void CIRGenFunction::emitDecl(const Decl &d, bool evaluateConditionDecl) {
774 switch (d.getKind()) {
775 case Decl::BuiltinTemplate:
776 case Decl::TranslationUnit:
777 case Decl::ExternCContext:
778 case Decl::Namespace:
779 case Decl::UnresolvedUsingTypename:
780 case Decl::ClassTemplateSpecialization:
781 case Decl::ClassTemplatePartialSpecialization:
782 case Decl::VarTemplateSpecialization:
783 case Decl::VarTemplatePartialSpecialization:
784 case Decl::TemplateTypeParm:
785 case Decl::UnresolvedUsingValue:
786 case Decl::NonTypeTemplateParm:
787 case Decl::CXXDeductionGuide:
788 case Decl::CXXMethod:
789 case Decl::CXXConstructor:
790 case Decl::CXXDestructor:
791 case Decl::CXXConversion:
792 case Decl::Field:
793 case Decl::MSProperty:
794 case Decl::IndirectField:
795 case Decl::ObjCIvar:
796 case Decl::ObjCAtDefsField:
797 case Decl::ParmVar:
798 case Decl::ImplicitParam:
799 case Decl::ClassTemplate:
800 case Decl::VarTemplate:
801 case Decl::FunctionTemplate:
802 case Decl::TypeAliasTemplate:
803 case Decl::TemplateTemplateParm:
804 case Decl::ObjCMethod:
805 case Decl::ObjCCategory:
806 case Decl::ObjCProtocol:
807 case Decl::ObjCInterface:
808 case Decl::ObjCCategoryImpl:
809 case Decl::ObjCImplementation:
810 case Decl::ObjCProperty:
811 case Decl::ObjCCompatibleAlias:
812 case Decl::PragmaComment:
813 case Decl::PragmaDetectMismatch:
814 case Decl::AccessSpec:
815 case Decl::LinkageSpec:
816 case Decl::Export:
817 case Decl::ObjCPropertyImpl:
818 case Decl::FileScopeAsm:
819 case Decl::Friend:
820 case Decl::FriendTemplate:
821 case Decl::Block:
822 case Decl::OutlinedFunction:
823 case Decl::Captured:
824 case Decl::UsingShadow:
825 case Decl::ConstructorUsingShadow:
826 case Decl::ObjCTypeParam:
827 case Decl::Binding:
828 case Decl::UnresolvedUsingIfExists:
829 case Decl::HLSLBuffer:
830 case Decl::HLSLRootSignature:
831 llvm_unreachable("Declaration should not be in declstmts!");
832
833 case Decl::Function: // void X();
834 case Decl::EnumConstant: // enum ? { X = ? }
835 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
836 case Decl::Label: // __label__ x;
837 case Decl::Import:
838 case Decl::MSGuid: // __declspec(uuid("..."))
839 case Decl::TemplateParamObject:
840 case Decl::Empty:
841 case Decl::Concept:
842 case Decl::LifetimeExtendedTemporary:
843 case Decl::RequiresExprBody:
844 case Decl::UnnamedGlobalConstant:
845 // None of these decls require codegen support.
846 return;
847
848 case Decl::Enum: // enum X;
849 case Decl::Record: // struct/union/class X;
850 case Decl::CXXRecord: // struct/union/class X; [C++]
851 case Decl::NamespaceAlias:
852 case Decl::Using: // using X; [C++]
853 case Decl::UsingEnum: // using enum X; [C++]
854 case Decl::UsingDirective: // using namespace X; [C++]
856 return;
857 case Decl::Var:
858 case Decl::Decomposition: {
859 const VarDecl &vd = cast<VarDecl>(d);
860 assert(vd.isLocalVarDecl() &&
861 "Should not see file-scope variables inside a function!");
862 emitVarDecl(vd);
863 if (evaluateConditionDecl)
865 return;
866 }
867 case Decl::OpenACCDeclare:
869 return;
870 case Decl::OpenACCRoutine:
872 return;
873 case Decl::OMPThreadPrivate:
875 return;
876 case Decl::OMPGroupPrivate:
878 return;
879 case Decl::OMPAllocate:
881 return;
882 case Decl::OMPCapturedExpr:
884 return;
885 case Decl::OMPRequires:
887 return;
888 case Decl::OMPDeclareMapper:
890 return;
891 case Decl::OMPDeclareReduction:
893 return;
894 case Decl::Typedef: // typedef int X;
895 case Decl::TypeAlias: { // using X = int; [C++0x]
896 QualType ty = cast<TypedefNameDecl>(d).getUnderlyingType();
898 if (ty->isVariablyModifiedType())
899 cgm.errorNYI(d.getSourceRange(), "emitDecl: variably modified type");
900 return;
901 }
902 case Decl::ImplicitConceptSpecialization:
903 case Decl::TopLevelStmt:
904 case Decl::UsingPack:
905 cgm.errorNYI(d.getSourceRange(),
906 std::string("emitDecl: unhandled decl type: ") +
907 d.getDeclKindName());
908 }
909}
910
912 SourceLocation loc) {
913 if (!sanOpts.has(SanitizerKind::NullabilityAssign))
914 return;
915
917}
918
919namespace {
920struct DestroyObject final : EHScopeStack::Cleanup {
921 DestroyObject(Address addr, QualType type,
922 CIRGenFunction::Destroyer *destroyer)
923 : addr(addr), type(type), destroyer(destroyer) {
925 }
926
927 Address addr;
929 CIRGenFunction::Destroyer *destroyer;
930
931 void emit(CIRGenFunction &cgf, Flags flags) override {
933 cgf.emitDestroy(addr, type, destroyer);
934 }
935};
936
937template <class Derived> struct DestroyNRVOVariable : EHScopeStack::Cleanup {
938 DestroyNRVOVariable(Address addr, QualType type, mlir::Value nrvoFlag)
939 : nrvoFlag(nrvoFlag), addr(addr), ty(type) {}
940
941 mlir::Value nrvoFlag;
942 Address addr;
943 QualType ty;
944
945 void emit(CIRGenFunction &cgf, Flags flags) override {
946 // Along the exceptions path we always execute the dtor.
947 bool nrvo = flags.isForNormalCleanup() && nrvoFlag;
948
949 CIRGenBuilderTy &builder = cgf.getBuilder();
950 mlir::OpBuilder::InsertionGuard guard(builder);
951 if (nrvo) {
952 // If we exited via NRVO, we skip the destructor call.
953 mlir::Location loc = addr.getPointer().getLoc();
954 mlir::Value didNRVO = builder.createFlagLoad(loc, nrvoFlag);
955 mlir::Value notNRVO = builder.createNot(didNRVO);
956 cir::IfOp::create(builder, loc, notNRVO, /*withElseRegion=*/false,
957 [&](mlir::OpBuilder &b, mlir::Location) {
958 static_cast<Derived *>(this)->emitDestructorCall(cgf);
959 builder.createYield(loc);
960 });
961 } else {
962 static_cast<Derived *>(this)->emitDestructorCall(cgf);
963 }
964 }
965
966 virtual ~DestroyNRVOVariable() = default;
967};
968
969struct DestroyNRVOVariableCXX final
970 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
971 DestroyNRVOVariableCXX(Address addr, QualType type,
972 const CXXDestructorDecl *dtor, mlir::Value nrvoFlag)
973 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, nrvoFlag),
974 dtor(dtor) {}
975
976 const CXXDestructorDecl *dtor;
977
978 void emitDestructorCall(CIRGenFunction &cgf) {
980 /*forVirtualBase=*/false,
981 /*delegating=*/false, addr, ty);
982 }
983};
984
985struct CallStackRestore final : EHScopeStack::Cleanup {
986 Address stack;
987 CallStackRestore(Address stack) : stack(stack) {}
988 void emit(CIRGenFunction &cgf, Flags flags) override {
989 mlir::Location loc = stack.getPointer().getLoc();
990 mlir::Value v = cgf.getBuilder().createLoad(loc, stack);
991 cgf.getBuilder().createStackRestore(loc, v);
992 }
993};
994
995/// A cleanup which performs a partial array destroy where the end pointer is
996/// irregularly determined and must be loaded from a local.
997struct IrregularPartialArrayDestroy final : EHScopeStack::Cleanup {
998 mlir::Value arrayBegin;
999 Address arrayEndPointer;
1000 QualType elementType;
1001 CharUnits elementAlign;
1002 CIRGenFunction::Destroyer *destroyer;
1003
1004 IrregularPartialArrayDestroy(mlir::Value arrayBegin, Address arrayEndPointer,
1005 QualType elementType, CharUnits elementAlign,
1006 CIRGenFunction::Destroyer *destroyer)
1007 : arrayBegin(arrayBegin), arrayEndPointer(arrayEndPointer),
1008 elementType(elementType), elementAlign(elementAlign),
1009 destroyer(destroyer) {}
1010
1011 void emit(CIRGenFunction &cgf, Flags flags) override {
1012 CIRGenBuilderTy &builder = cgf.getBuilder();
1013 mlir::Location loc = arrayBegin.getLoc();
1014
1015 mlir::Value arrayEnd = builder.createLoad(loc, arrayEndPointer);
1016
1017 // The cleanup is destroying elements in reverse from arrayEnd back to
1018 // arrayBegin, but only if arrayEnd != arrayBegin (i.e. something was
1019 // constructed).
1020 mlir::Type cirElementType = cgf.convertTypeForMem(elementType);
1021 cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType);
1022
1023 mlir::Value ne = cir::CmpOp::create(builder, loc, cir::CmpOpKind::ne,
1024 arrayEnd, arrayBegin);
1025 cir::IfOp::create(
1026 builder, loc, ne, /*withElseRegion=*/false,
1027 [&](mlir::OpBuilder &b, mlir::Location loc) {
1028 Address iterAddr = cgf.createTempAlloca(
1029 ptrToElmType, cgf.getPointerAlign(), loc, "__array_idx");
1030 builder.createStore(loc, arrayEnd, iterAddr);
1031 builder.createDoWhile(
1032 loc,
1033 /*condBuilder=*/
1034 [&](mlir::OpBuilder &b, mlir::Location loc) {
1035 mlir::Value cur = builder.createLoad(loc, iterAddr);
1036 mlir::Value cmp = cir::CmpOp::create(
1037 builder, loc, cir::CmpOpKind::ne, cur, arrayBegin);
1038 builder.createCondition(cmp);
1039 },
1040 /*bodyBuilder=*/
1041 [&](mlir::OpBuilder &b, mlir::Location loc) {
1042 mlir::Value cur = builder.createLoad(loc, iterAddr);
1043 cir::ConstantOp negOne = builder.getConstInt(
1044 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), -1);
1045 mlir::Value prev = cir::PtrStrideOp::create(
1046 builder, loc, ptrToElmType, cur, negOne);
1047 builder.createStore(loc, prev, iterAddr);
1048 Address elemAddr = Address(prev, cirElementType, elementAlign);
1049 destroyer(cgf, elemAddr, elementType);
1050 builder.createYield(loc);
1051 });
1052 builder.createYield(loc);
1053 });
1054 }
1055};
1056} // namespace
1057
1058/// Push an EH cleanup to destroy already-constructed elements of the given
1059/// array. The cleanup may be popped with deactivateCleanupBlock or
1060/// popCleanupBlock.
1061///
1062/// \param elementType - the immediate element type of the array;
1063/// possibly still an array type
1065 Address arrayEndPointer,
1066 QualType elementType,
1067 CharUnits elementAlign,
1068 Destroyer *destroyer) {
1069 ehStack.pushCleanup<IrregularPartialArrayDestroy>(
1070 EHCleanup, arrayBegin, arrayEndPointer, elementType, elementAlign,
1071 destroyer);
1072}
1073
1074/// pushEHDestroyIfNeeded - Push the standard destructor for the given type as
1075/// an EH-only cleanup. If EH cleanup is not needed, just return.
1077 Address addr, QualType type) {
1078 if (!needsEHCleanup(dtorKind))
1079 return;
1080
1082 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind));
1083}
1084
1085/// Push the standard destructor for the given type as
1086/// at least a normal cleanup.
1088 Address addr, QualType type) {
1089 assert(dtorKind && "cannot push destructor for trivial type");
1090
1091 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1092 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind));
1093}
1094
1096 QualType type, Destroyer *destroyer) {
1097 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1098}
1099
1102 assert(dtorKind && "cannot push destructor for trivial type");
1103
1104 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1106 cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup);
1107}
1108
1110 CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
1111 bool useEHCleanupForArray) {
1114 destroyer);
1115}
1116
1118 Address addr, QualType type,
1119 Destroyer *destroyer,
1120 bool useEHCleanupForArray) {
1121 if (isInConditionalBranch()) {
1122 cgm.errorNYI("conditional lifetime-extended destroy");
1123 return;
1124 }
1125
1126 // Add the cleanup to the EHStack. After the full-expr, this would be
1127 // deactivated before being popped from the stack.
1128 pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
1129 useEHCleanupForArray);
1130
1132
1133 pushCleanupAfterFullExpr(cleanupKind, addr, type, destroyer);
1134}
1135
1137 const PendingCleanupEntry &entry) {
1138 ehStack.pushCleanup<DestroyObject>(entry.kind, entry.addr, entry.type,
1139 entry.destroyer);
1140
1141 if (entry.activeFlag.isValid()) {
1142 EHCleanupScope &scope = cast<EHCleanupScope>(*ehStack.begin());
1143 scope.setActiveFlag(entry.activeFlag);
1144 if (scope.isNormalCleanup())
1146 if (scope.isEHCleanup())
1147 scope.setTestFlagInEHCleanup();
1148 }
1149}
1150
1151/// Destroys all the elements of the given array, beginning from last to first.
1152///
1153/// \param begin - a type* denoting the first element of the array
1154/// \param numElements - the number of elements in the array
1155/// \param elementType - the element type of the array
1156/// \param destroyer - the function to call to destroy elements
1158 mlir::Value numElements,
1159 QualType elementType,
1160 CharUnits elementAlign,
1161 Destroyer *destroyer) {
1162 assert(!elementType->isArrayType());
1163
1164 // Differently from LLVM traditional codegen, use a higher level
1165 // representation instead of lowering directly to a loop.
1166 mlir::Type cirElementType = convertTypeForMem(elementType);
1167 cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType);
1168
1169 auto regionBuilder = [&](mlir::OpBuilder &b, mlir::Location loc) {
1170 mlir::BlockArgument arg =
1171 b.getInsertionBlock()->addArgument(ptrToElmType, loc);
1172 Address curAddr = Address(arg, cirElementType, elementAlign);
1174
1175 // Perform the actual destruction there.
1176 destroyer(*this, curAddr, elementType);
1177
1178 cir::YieldOp::create(b, loc);
1179 };
1180
1181 // For a constant array size, use the static form of ArrayDtor.
1182 if (auto constantCount = numElements.getDefiningOp<cir::ConstantOp>()) {
1183 uint64_t size = 0;
1184 if (auto constIntAttr = constantCount.getValueAttr<cir::IntAttr>())
1185 size = constIntAttr.getUInt();
1186 auto arrayTy = cir::ArrayType::get(cirElementType, size);
1187 mlir::Value arrayOp = builder.createPtrBitcast(begin, arrayTy);
1188 cir::ArrayDtor::create(builder, *currSrcLoc, arrayOp, regionBuilder);
1189 return;
1190 }
1191
1192 // For a dynamic array size (VLA), use the dynamic form of ArrayDtor.
1193 mlir::Value elemBegin = builder.createPtrBitcast(begin, cirElementType);
1194 cir::ArrayDtor::create(builder, *currSrcLoc, elemBegin, numElements,
1195 regionBuilder);
1196}
1197
1198/// Immediately perform the destruction of the given object.
1199///
1200/// \param addr - the address of the object; a type*
1201/// \param type - the type of the object; if an array type, all
1202/// objects are destroyed in reverse order
1203/// \param destroyer - the function to call to destroy individual
1204/// elements
1206 Destroyer *destroyer) {
1208 if (!arrayType)
1209 return destroyer(*this, addr, type);
1210
1211 mlir::Value length = emitArrayLength(arrayType, type, addr);
1212
1213 CharUnits elementAlign = addr.getAlignment().alignmentOfArrayElement(
1214 getContext().getTypeSizeInChars(type));
1215
1216 // If the array length is constant, we can check for zero at compile time.
1217 auto constantCount = length.getDefiningOp<cir::ConstantOp>();
1218 if (constantCount) {
1219 auto constIntAttr = mlir::dyn_cast<cir::IntAttr>(constantCount.getValue());
1220 if (constIntAttr && constIntAttr.getUInt() == 0)
1221 return;
1222 }
1223
1224 mlir::Value begin = addr.getPointer();
1226 emitArrayDestroy(begin, length, type, elementAlign, destroyer);
1227
1228 // If the array destroy didn't use the length op, we can erase it.
1229 if (constantCount && constantCount.use_empty())
1230 constantCount.erase();
1231}
1232
1235 switch (kind) {
1236 case QualType::DK_none:
1237 llvm_unreachable("no destroyer for trivial dtor");
1239 return destroyCXXObject;
1243 cgm.errorNYI("getDestroyer: other destruction kind");
1244 return nullptr;
1245 }
1246 llvm_unreachable("Unknown DestructionKind");
1247}
1248
1250 ehStack.pushCleanup<CallStackRestore>(kind, spMem);
1251}
1252
1253/// Enter a destroy cleanup for the given local variable.
1255 const CIRGenFunction::AutoVarEmission &emission,
1256 QualType::DestructionKind dtorKind) {
1257 assert(dtorKind != QualType::DK_none);
1258
1259 // Note that for __block variables, we want to destroy the
1260 // original stack object, not the possibly forwarded object.
1261 Address addr = emission.getObjectAddress(*this);
1262
1263 const VarDecl *var = emission.variable;
1264 QualType type = var->getType();
1265
1266 CleanupKind cleanupKind = NormalAndEHCleanup;
1267 CIRGenFunction::Destroyer *destroyer = nullptr;
1268
1269 switch (dtorKind) {
1270 case QualType::DK_none:
1271 llvm_unreachable("no cleanup for trivially-destructible variable");
1272
1274 // If there's an NRVO flag on the emission, we need a different
1275 // cleanup.
1276 if (emission.nrvoFlag) {
1277 assert(!type->isArrayType());
1278 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1279 ehStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1280 emission.nrvoFlag);
1281 return;
1282 }
1283 // Otherwise, this is handled below.
1284 break;
1285
1289 cgm.errorNYI(var->getSourceRange(),
1290 "emitAutoVarTypeCleanup: other dtor kind");
1291 return;
1292 }
1293
1294 // If we haven't chosen a more specific destroyer, use the default.
1295 if (!destroyer)
1296 destroyer = getDestroyer(dtorKind);
1297
1299 ehStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1300}
1301
1303 if (auto *dd = dyn_cast_if_present<DecompositionDecl>(vd)) {
1304 for (auto *b : dd->flat_bindings())
1305 if (auto *hd = b->getHoldingVar())
1306 emitVarDecl(*hd);
1307 }
1308}
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d, Address addr, bool isVolatile, CIRGenBuilderTy &builder, mlir::TypedAttr constant)
static std::string getStaticDeclName(CIRGenModule &cgm, const VarDecl &d)
This file defines OpenACC nodes for declarative directives.
Defines the clang::Expr interface and subclasses for C++ expressions.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__device__ __2f16 b
cir::ConditionOp createCondition(mlir::Value condition)
Create a loop condition.
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
cir::PointerType getPointerTo(mlir::Type ty)
cir::DoWhileOp createDoWhile(mlir::Location loc, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> condBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> bodyBuilder)
Create a do-while operation.
mlir::Value createNot(mlir::Location loc, mlir::Value value)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
llvm::TypeSize getTypeAllocSize(mlir::Type ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
mlir::Value getPointer() const
Definition Address.h:96
mlir::Type getElementType() const
Definition Address.h:123
static Address invalid()
Definition Address.h:74
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:136
bool isValid() const
Definition Address.h:75
mlir::Operation * getDefiningOp() const
Get the operation which defines this address.
Definition Address.h:139
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
cir::StackRestoreOp createStackRestore(mlir::Location loc, mlir::Value v)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false)
void emitOpenACCRoutine(const OpenACCRoutineDecl &d)
cir::GlobalOp addInitializerToStaticVarDecl(const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr)
Add the initializer for 'd' to the global variable that has already been created for it.
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d, mlir::OpBuilder::InsertPoint ip={})
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, clang::QualType::DestructionKind dtorKind)
Enter a destroy cleanup for the given local variable.
void emitVariablyModifiedType(QualType ty)
const clang::LangOptions & getLangOpts() const
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
void emitOMPRequiresDecl(const OMPRequiresDecl &d)
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
void emitStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
bool isTrivialInitializer(const Expr *init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
void emitOpenACCDeclare(const OpenACCDeclareDecl &d)
void pushIrregularPartialArrayCleanup(mlir::Value arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlign, Destroyer *destroyer)
Push an EH cleanup to destroy already-constructed elements of the given array.
void pushCleanupAndDeferDeactivation(CleanupKind kind, As... a)
Push a cleanup and record it for deferred deactivation.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitOMPDeclareReduction(const OMPDeclareReductionDecl &d)
void emitExprAsInit(const clang::Expr *init, const clang::ValueDecl *d, LValue lvalue, bool capturedByInit=false)
Emit an expression as an initializer for an object (variable, field, etc.) at the given location.
void emitCXXGuardedInit(const VarDecl &varDecl, cir::GlobalOp globalOp, bool performInit)
Emit a guarded initializer for a static local variable or a static data member of a class template in...
mlir::Value emitArrayLength(const clang::ArrayType *arrayType, QualType &baseType, Address &addr)
Computes the length of an array in elements, as well as the base element type and a properly-typed fi...
RValue emitReferenceBindingToExpr(const Expr *e)
Emits a reference binding to the passed in expression.
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
CleanupKind getCleanupKind(QualType::DestructionKind kind)
void emitOMPAllocateDecl(const OMPAllocateDecl &d)
void emitOMPDeclareMapper(const OMPDeclareMapperDecl &d)
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
mlir::Type convertTypeForMem(QualType t)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
void emitVarDecl(const clang::VarDecl &d)
This method handles emission of any variable declaration inside a function, including static vars etc...
Address returnValue
The temporary alloca to hold the return value.
void emitArrayDestroy(mlir::Value begin, mlir::Value numElements, QualType elementType, CharUnits elementAlign, Destroyer *destroyer)
Destroys all the elements of the given array, beginning from last to first.
void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void emitScalarInit(const clang::Expr *init, mlir::Location loc, LValue lvalue, bool capturedByInit=false)
void emitAutoVarInit(const AutoVarEmission &emission)
Emit the initializer for an allocated variable.
void maybeEmitDeferredVarDeclInit(const VarDecl *vd)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
void pushStackRestore(CleanupKind kind, Address spMem)
void emitAutoVarDecl(const clang::VarDecl &d)
Emit code and set up symbol table for a variable declaration with auto, register, or no storage class...
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CIRGenBuilderTy & getBuilder()
bool didCallStackSave
Whether a cir.stacksave operation has been added.
void emitDecl(const clang::Decl &d, bool evaluateConditionDecl=false)
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
llvm::DenseMap< const VarDecl *, mlir::Value > nrvoFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
mlir::MLIRContext & getMLIRContext()
Destroyer * getDestroyer(clang::QualType::DestructionKind kind)
void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty)
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
void pushEHDestroyIfNeeded(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushEHDestroyIfNeeded - Push the standard destructor for the given type as an EH-only cleanup.
void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl &d)
void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl &d)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
void pushFullExprCleanup(CleanupKind kind, As... a)
Push a cleanup to be run at the end of the current full-expression.
std::optional< mlir::Location > currSrcLoc
Use to track source locations across nested visitor traversals.
clang::ASTContext & getContext() const
void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
Set the address of a local variable.
void pushCleanupAfterFullExpr(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer)
Queue a cleanup to be pushed after finishing the current full-expression.
void emitNullabilityCheck(LValue lhs, mlir::Value rhs, clang::SourceLocation loc)
Given an assignment *lhs = rhs, emit a test that checks if rhs is nonnull, if 1LHS is marked _Nonnull...
void emitOMPCapturedExpr(const OMPCapturedExprDecl &d)
void emitStoreThroughLValue(RValue src, LValue dst, bool isInit=false)
Store the specified rvalue into the specified lvalue, where both are guaranteed to the have the same ...
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
void emitAutoVarCleanups(const AutoVarEmission &emission)
This class organizes the cross-function state that is used while generating CIR code.
llvm::StringRef getMangledName(clang::GlobalDecl gd)
cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
mlir::Type convertType(clang::QualType type)
llvm::DenseMap< const VarDecl *, cir::GlobalOp > initializerConstants
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
const clang::LangOptions & getLangOpts() const
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
mlir::ModuleOp getModule() const
mlir::MLIRContext & getMLIRContext()
cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d)
Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr, CharUnits align)
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
mlir::Attribute tryEmitForInitializer(const VarDecl &d)
Try to emit the initializer of the given declaration as an abstract constant.
mlir::Attribute tryEmitAbstractForInitializer(const VarDecl &d)
Try to emit the initializer of the given declaration as an abstract constant.
A cleanup scope which generates the cleanup blocks lazily.
void setActiveFlag(Address var)
Information for lazily generating a cleanup.
Address getAddress() const
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
Represents a C++ constructor within a class.
Definition DeclCXX.h:2624
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
T * getAttr() const
Definition DeclBase.h:581
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
SourceLocation getLocation() const
Definition DeclBase.h:447
const char * getDeclKindName() const
Definition DeclBase.cpp:169
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
This represents one expression.
Definition Expr.h:112
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3347
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:317
bool isExternallyVisible() const
Definition Decl.h:433
A (possibly-)qualified type.
Definition TypeBase.h:937
@ PDIK_Struct
The type is a struct containing a field whose type is not PCK_Trivial.
Definition TypeBase.h:1484
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1036
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2741
Represents a struct/union/class.
Definition Decl.h:4342
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2850
bool isVectorType() const
Definition TypeBase.h:8807
bool isSamplerT() const
Definition TypeBase.h:8912
bool isRecordType() const
Definition TypeBase.h:8795
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1584
TLSKind getTLSKind() const
Definition Decl.cpp:2181
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2203
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition Decl.cpp:2875
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1241
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2499
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1527
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2864
const Expr * getInit() const
Definition Decl.h:1383
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1232
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1268
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1244
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2711
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:342
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
U cast(CodeGen::Address addr)
Definition Address.h:327
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
static bool objCLifetime()
static bool addAutoInitAnnotation()
static bool addressSpace()
static bool emitNullabilityCheck()
static bool useEHCleanupForArray()
static bool vectorConstants()
static bool aggValueSlotMayOverlap()
static bool dtorCleanups()
static bool dataLayoutTypeAllocSize()
static bool opAllocaCaptureByInit()
static bool opAllocaPreciseLifetime()
static bool cudaSupport()
static bool generateDebugInfo()
bool isEscapingByRef
True if the variable is a __block variable that is captured by an escaping block.
Address addr
The address of the alloca for languages with explicit address space (e.g.
bool isConstantAggregate
True if the variable is of aggregate type and has a constant initializer.
Address getObjectAddress(CIRGenFunction &cgf) const
Returns the address of the object within this declaration.
A cleanup entry that will be promoted onto the EH scope stack at a later point.
clang::CharUnits getPointerAlign() const
cir::PointerType allocaInt8PtrTy
void* in alloca address space