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
14#include "CIRGenFunction.h"
15#include "mlir/IR/Location.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::CIRGen;
25
28 mlir::OpBuilder::InsertPoint ip) {
29 QualType ty = d.getType();
31 cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: address space");
32
33 mlir::Location loc = getLoc(d.getSourceRange());
34 bool nrvo =
35 getContext().getLangOpts().ElideConstructors && d.isNRVOVariable();
36
38 emission.isEscapingByRef = d.isEscapingByref();
39 if (emission.isEscapingByRef)
40 cgm.errorNYI(d.getSourceRange(),
41 "emitAutoVarDecl: decl escaping by reference");
42
43 CharUnits alignment = getContext().getDeclAlign(&d);
44
45 // If the type is variably-modified, emit all the VLA sizes for it.
46 if (ty->isVariablyModifiedType())
48
50
51 Address address = Address::invalid();
52 if (ty->isConstantSizeType()) {
53 // If this value is an array, struct, or vector with a statically
54 // determinable constant initializer, there are optimizations we can do.
55 //
56 // TODO: We should constant-evaluate the initializer of any variable,
57 // as long as it is initialized by a constant expression. Currently,
58 // isConstantInitializer produces wrong answers for structs with
59 // reference or bitfield members, and a few other cases, and checking
60 // for POD-ness protects us from some of these.
61 if (d.getInit() &&
62 (ty->isArrayType() || ty->isRecordType() || ty->isVectorType()) &&
63 (d.isConstexpr() ||
64 ((ty.isPODType(getContext()) ||
65 getContext().getBaseElementType(ty)->isObjCObjectPointerType()) &&
66 d.getInit()->isConstantInitializer(getContext(), false)))) {
67
68 // If the variable's a const type, and it's neither an NRVO
69 // candidate nor a __block variable and has no mutable members,
70 // emit it as a global instead.
71 // Exception is if a variable is located in non-constant address space
72 // in OpenCL.
73 // TODO(cir): perhaps we don't need this at all at CIR since this can
74 // be done as part of lowering down to LLVM.
75 bool needsDtor =
77 if ((!getContext().getLangOpts().OpenCL ||
79 (cgm.getCodeGenOpts().MergeAllConstants && !nrvo &&
80 !d.isEscapingByref() &&
81 ty.isConstantStorage(getContext(), true, !needsDtor))) {
82 cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: type constant");
83 }
84 // Otherwise, tell the initialization code that we're in this case.
85 emission.isConstantAggregate = true;
86 }
87
88 // A normal fixed sized variable becomes an alloca in the entry block,
89 // unless:
90 // - it's an NRVO variable.
91 // - we are compiling OpenMP and it's an OpenMP local variable.
92 if (nrvo) {
93 // The named return value optimization: allocate this variable in the
94 // return slot, so that we can elide the copy when returning this
95 // variable (C++0x [class.copy]p34).
96 address = returnValue;
97
98 if (const RecordDecl *rd = ty->getAsRecordDecl()) {
99 if (const auto *cxxrd = dyn_cast<CXXRecordDecl>(rd);
100 (cxxrd && !cxxrd->hasTrivialDestructor()) ||
101 rd->isNonTrivialToPrimitiveDestroy()) {
102 // In LLVM: Create a flag that is used to indicate when the NRVO was
103 // applied to this variable. Set it to zero to indicate that NRVO was
104 // not applied. For now, use the same approach for CIRGen until we can
105 // be sure it's worth doing something more aggressive.
106 cir::ConstantOp falseNVRO = builder.getFalse(loc);
107 Address nrvoFlag = createTempAlloca(falseNVRO.getType(),
108 CharUnits::One(), loc, "nrvo",
109 /*arraySize=*/nullptr);
110 assert(builder.getInsertionBlock());
111 builder.createStore(loc, falseNVRO, nrvoFlag);
112
113 // Record the NRVO flag for this variable.
114 nrvoFlags[&d] = nrvoFlag.getPointer();
115 emission.nrvoFlag = nrvoFlag.getPointer();
116 }
117 }
118 } else {
119 // A normal fixed sized variable becomes an alloca in the entry block,
120 mlir::Type allocaTy = convertTypeForMem(ty);
121 // Create the temp alloca and declare variable using it.
122 address = createTempAlloca(allocaTy, alignment, loc, d.getName(),
123 /*arraySize=*/nullptr, /*alloca=*/nullptr, ip);
124 declare(address.getPointer(), &d, ty, getLoc(d.getSourceRange()),
125 alignment);
126 }
127 } else {
128 // Non-constant size type
130 if (!didCallStackSave) {
131 // Save the stack.
132 cir::PointerType defaultTy = allocaInt8PtrTy;
134 cgm.getDataLayout().getAlignment(defaultTy, false));
135 Address stack = createTempAlloca(defaultTy, align, loc, "saved_stack");
136
137 mlir::Value v = builder.createStackSave(loc, defaultTy);
138 assert(v.getType() == allocaInt8PtrTy);
139 builder.createStore(loc, v, stack);
140
141 didCallStackSave = true;
142
143 // Push a cleanup block and restore the stack there.
144 // FIXME: in general circumstances, this should be an EH cleanup.
146 }
147
148 VlaSizePair vlaSize = getVLASize(ty);
149 mlir::Type memTy = convertTypeForMem(vlaSize.type);
150
151 // Allocate memory for the array.
152 address =
153 createTempAlloca(memTy, alignment, loc, d.getName(), vlaSize.numElts,
154 /*alloca=*/nullptr, builder.saveInsertionPoint());
155
156 // If we have debug info enabled, properly describe the VLA dimensions for
157 // this type by registering the vla size expression for each of the
158 // dimensions.
160 }
161
162 emission.addr = address;
163 setAddrOfLocalVar(&d, address);
164
165 return emission;
166}
167
168/// Determine whether the given initializer is trivial in the sense
169/// that it requires no code to be generated.
171 if (!init)
172 return true;
173
174 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(init))
175 if (CXXConstructorDecl *constructor = construct->getConstructor())
176 if (constructor->isTrivial() && constructor->isDefaultConstructor() &&
177 !construct->requiresZeroInitialization())
178 return true;
179
180 return false;
181}
182
183static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d,
184 Address addr, bool isVolatile,
185 CIRGenBuilderTy &builder,
186 mlir::TypedAttr constant) {
187 mlir::Type ty = constant.getType();
188 cir::CIRDataLayout layout{cgm.getModule()};
189 uint64_t constantSize = layout.getTypeAllocSize(ty);
190 if (!constantSize)
191 return;
198 // In CIR we want to emit a store for the whole thing, later lowering
199 // prepare to LLVM should unwrap this into the best policy (see asserts
200 // above).
201 //
202 // FIXME(cir): This is closer to memcpy behavior but less optimal, instead of
203 // copy from a global, we just create a cir.const out of it.
204
205 if (addr.getElementType() != ty)
206 addr = addr.withElementType(builder, ty);
207
208 // If the address is an alloca, set the init attribute.
209 // The address is usually and alloca, but there is at least one case where
210 // emitAutoVarInit is called from the OpenACC codegen with an address that
211 // is not an alloca.
212 auto allocaOp = addr.getDefiningOp<cir::AllocaOp>();
213 if (allocaOp)
214 allocaOp.setInitAttr(mlir::UnitAttr::get(&cgm.getMLIRContext()));
215
216 // There are cases where OpenACC codegen calls emitAutoVarInit with a
217 // temporary decl that doesn't have a source range set.
218 mlir::Location loc = builder.getUnknownLoc();
219 if (d.getSourceRange().isValid())
220 loc = cgm.getLoc(d.getSourceRange());
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(), "block decl context for static var");
407 else if (isa<ObjCMethodDecl>(dc))
408 cgm.errorNYI(d.getSourceRange(), "ObjC decl context for static var");
409 else
410 cgm.errorNYI(d.getSourceRange(), "Unknown context for static var decl");
411
412 contextName += "." + d.getNameAsString();
413 return contextName;
414}
415
416// TODO(cir): LLVM uses a Constant base class. Maybe CIR could leverage an
417// interface for all constants?
418cir::GlobalOp
420 cir::GlobalLinkageKind linkage) {
421 // In general, we don't always emit static var decls once before we reference
422 // them. It is possible to reference them before emitting the function that
423 // contains them, and it is possible to emit the containing function multiple
424 // times.
425 if (cir::GlobalOp existingGV = getStaticLocalDeclAddress(&d))
426 return existingGV;
427
428 QualType ty = d.getType();
429 assert(ty->isConstantSizeType() && "VLAs can't be static");
430
431 // Use the label if the variable is renamed with the asm-label extension.
432 if (d.hasAttr<AsmLabelAttr>())
433 errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: asm label");
434
435 std::string name = getStaticDeclName(*this, d);
436
437 mlir::Type lty = getTypes().convertTypeForMem(ty);
439
440 if (d.hasAttr<LoaderUninitializedAttr>() || d.hasAttr<CUDASharedAttr>())
442 "getOrCreateStaticVarDecl: LoaderUninitializedAttr");
444
445 mlir::Attribute init = builder.getZeroInitAttr(convertType(ty));
446
447 cir::GlobalOp gv = builder.createVersionedGlobal(
448 getModule(), getLoc(d.getLocation()), name, lty, false, linkage);
449 // TODO(cir): infer visibility from linkage in global op builder.
450 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage));
451 gv.setInitialValueAttr(init);
452 gv.setAlignment(getASTContext().getDeclAlign(&d).getAsAlign().value());
453
454 if (supportsCOMDAT() && gv.isWeakForLinker())
455 gv.setComdat(true);
456
457 if (d.getTLSKind())
458 errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: TLS");
459
460 setGVProperties(gv, &d);
461
462 // OG checks if the expected address space, denoted by the type, is the
463 // same as the actual address space indicated by attributes. If they aren't
464 // the same, an addrspacecast is emitted when this variable is accessed.
465 // In CIR however, cir.get_global already carries that information in
466 // !cir.ptr type - if this global is in OpenCL local address space, then its
467 // type would be !cir.ptr<..., addrspace(offload_local)>. Therefore we don't
468 // need an explicit address space cast in CIR: they will get emitted when
469 // lowering to LLVM IR.
470
471 // Ensure that the static local gets initialized by making sure the parent
472 // function gets emitted eventually.
473 const Decl *dc = cast<Decl>(d.getDeclContext());
474
475 // We can't name blocks or captured statements directly, so try to emit their
476 // parents.
477 if (isa<BlockDecl>(dc) || isa<CapturedDecl>(dc)) {
478 dc = dc->getNonClosureContext();
479 // FIXME: Ensure that global blocks get emitted.
480 if (!dc)
481 errorNYI(d.getSourceRange(), "non-closure context");
482 }
483
484 GlobalDecl gd;
486 errorNYI(d.getSourceRange(), "C++ constructors static var context");
487 else if (isa<CXXDestructorDecl>(dc))
488 errorNYI(d.getSourceRange(), "C++ destructors static var context");
489 else if (const auto *fd = dyn_cast<FunctionDecl>(dc))
490 gd = GlobalDecl(fd);
491 else {
492 // Don't do anything for Obj-C method decls or global closures. We should
493 // never defer them.
494 assert(isa<ObjCMethodDecl>(dc) && "unexpected parent code decl");
495 }
497 // Disable emission of the parent function for the OpenMP device codegen.
498 errorNYI(d.getSourceRange(), "OpenMP");
499 }
500
501 return gv;
502}
503
505 mlir::Attribute constAttr,
506 CharUnits align) {
507 auto functionName = [&](const DeclContext *dc) -> std::string {
508 if (const auto *fd = dyn_cast<FunctionDecl>(dc)) {
509 if (const auto *cc = dyn_cast<CXXConstructorDecl>(fd))
510 return cc->getNameAsString();
511 if (const auto *cd = dyn_cast<CXXDestructorDecl>(fd))
512 return cd->getNameAsString();
513 return std::string(getMangledName(fd));
514 } else if (const auto *om = dyn_cast<ObjCMethodDecl>(dc)) {
515 return om->getNameAsString();
516 } else if (isa<BlockDecl>(dc)) {
517 return "<block>";
518 } else if (isa<CapturedDecl>(dc)) {
519 return "<captured>";
520 } else {
521 llvm_unreachable("expected a function or method");
522 }
523 };
524
525 // Form a simple per-variable cache of these values in case we find we
526 // want to reuse them.
527 cir::GlobalOp &cacheEntry = initializerConstants[&d];
528 if (!cacheEntry || cacheEntry.getInitialValue() != constAttr) {
529 auto ty = mlir::cast<mlir::TypedAttr>(constAttr).getType();
530 bool isConstant = true;
531
532 std::string name;
533 if (d.hasGlobalStorage())
534 name = getMangledName(&d).str() + ".const";
535 else if (const DeclContext *dc = d.getParentFunctionOrMethod())
536 name = ("__const." + functionName(dc) + "." + d.getName()).str();
537 else
538 llvm_unreachable("local variable has no parent function or method");
539
541 cir::GlobalOp gv = builder.createVersionedGlobal(
542 getModule(), getLoc(d.getLocation()), name, ty, isConstant,
543 cir::GlobalLinkageKind::PrivateLinkage);
544 // TODO(cir): infer visibility from linkage in global op builder.
545 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(
546 cir::GlobalLinkageKind::PrivateLinkage));
547 gv.setInitialValueAttr(constAttr);
548 gv.setAlignment(align.getAsAlign().value());
549 // TODO(cir): Set unnamed address attribute when available in CIR
550
551 cacheEntry = gv;
552 } else if (cacheEntry.getAlignment() < align.getQuantity()) {
553 cacheEntry.setAlignment(align.getAsAlign().value());
554 }
555
556 // Create a GetGlobalOp to get a pointer to the global
558 mlir::Type eltTy = mlir::cast<mlir::TypedAttr>(constAttr).getType();
559 auto ptrTy = builder.getPointerTo(cacheEntry.getSymType());
560 mlir::Value globalPtr = cir::GetGlobalOp::create(
561 builder, getLoc(d.getLocation()), ptrTy, cacheEntry.getSymName());
562 return Address(globalPtr, eltTy, align);
563}
564
565/// Add the initializer for 'd' to the global variable that has already been
566/// created for it. If the initializer has a different type than gv does, this
567/// may free gv and return a different one. Otherwise it just returns gv.
569 const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr) {
570 ConstantEmitter emitter(*this);
571 mlir::TypedAttr init =
572 mlir::cast<mlir::TypedAttr>(emitter.tryEmitForInitializer(d));
573
574 // If constant emission failed, then this should be a C++ static
575 // initializer.
576 if (!init) {
577 cgm.errorNYI(d.getSourceRange(), "static var without initializer");
578 return gv;
579 }
580
581 // TODO(cir): There should be debug code here to assert that the decl size
582 // matches the CIR data layout type alloc size, but the code for calculating
583 // the type alloc size is not implemented yet.
585
586 // The initializer may differ in type from the global. Rewrite
587 // the global to match the initializer. (We have to do this
588 // because some types, like unions, can't be completely represented
589 // in the LLVM type system.)
590 if (gv.getSymType() != init.getType()) {
591 gv.setSymType(init.getType());
592
593 // Normally this should be done with a call to cgm.replaceGlobal(oldGV, gv),
594 // but since at this point the current block hasn't been really attached,
595 // there's no visibility into the GetGlobalOp corresponding to this Global.
596 // Given those constraints, thread in the GetGlobalOp and update it
597 // directly.
599 gvAddr.getAddr().setType(builder.getPointerTo(init.getType()));
600 }
601
602 bool needsDtor =
604
605 gv.setConstant(d.getType().isConstantStorage(
606 getContext(), /*ExcludeCtor=*/true, !needsDtor));
607 gv.setInitialValueAttr(init);
608
609 emitter.finalize(gv);
610
611 if (needsDtor) {
612 // We have a constant initializer, but a nontrivial destructor. We still
613 // need to perform a guarded "initialization" in order to register the
614 // destructor.
615 cgm.errorNYI(d.getSourceRange(), "C++ guarded init");
616 }
617
618 return gv;
619}
620
622 cir::GlobalLinkageKind linkage) {
623 // Check to see if we already have a global variable for this
624 // declaration. This can happen when double-emitting function
625 // bodies, e.g. with complete and base constructors.
626 cir::GlobalOp globalOp = cgm.getOrCreateStaticVarDecl(d, linkage);
627 // TODO(cir): we should have a way to represent global ops as values without
628 // having to emit a get global op. Sometimes these emissions are not used.
629 mlir::Value addr = builder.createGetGlobal(globalOp);
630 auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>();
631 assert(getAddrOp && "expected cir::GetGlobalOp");
632
633 CharUnits alignment = getContext().getDeclAlign(&d);
634
635 // Store into LocalDeclMap before generating initializer to handle
636 // circular references.
637 mlir::Type elemTy = convertTypeForMem(d.getType());
638 setAddrOfLocalVar(&d, Address(addr, elemTy, alignment));
639
640 // We can't have a VLA here, but we can have a pointer to a VLA,
641 // even though that doesn't really make any sense.
642 // Make sure to evaluate VLA bounds now so that we have them for later.
643 if (d.getType()->isVariablyModifiedType()) {
644 cgm.errorNYI(d.getSourceRange(),
645 "emitStaticVarDecl: variably modified type");
646 }
647
648 // Save the type in case adding the initializer forces a type change.
649 mlir::Type expectedType = addr.getType();
650
651 cir::GlobalOp var = globalOp;
652
654
655 // If this value has an initializer, emit it.
656 if (d.getInit())
657 var = addInitializerToStaticVarDecl(d, var, getAddrOp);
658
659 var.setAlignment(alignment.getAsAlign().value());
660
661 // There are a lot of attributes that need to be handled here. Until
662 // we start to support them, we just report an error if there are any.
663 if (d.hasAttrs())
664 cgm.errorNYI(d.getSourceRange(), "static var with attrs");
665
666 if (cgm.getCodeGenOpts().KeepPersistentStorageVariables)
667 cgm.errorNYI(d.getSourceRange(), "static var keep persistent storage");
668
669 // From traditional codegen:
670 // We may have to cast the constant because of the initializer
671 // mismatch above.
672 //
673 // FIXME: It is really dangerous to store this in the map; if anyone
674 // RAUW's the GV uses of this constant will be invalid.
675 mlir::Value castedAddr =
676 builder.createBitcast(getAddrOp.getAddr(), expectedType);
677 localDeclMap.find(&d)->second = Address(castedAddr, elemTy, alignment);
678 cgm.setStaticLocalDeclAddress(&d, var);
679
682}
683
684void CIRGenFunction::emitScalarInit(const Expr *init, mlir::Location loc,
685 LValue lvalue, bool capturedByInit) {
687
688 SourceLocRAIIObject locRAII{*this, loc};
689 mlir::Value value = emitScalarExpr(init);
690 if (capturedByInit) {
691 cgm.errorNYI(init->getSourceRange(), "emitScalarInit: captured by init");
692 return;
693 }
695 emitStoreThroughLValue(RValue::get(value), lvalue, true);
696}
697
699 LValue lvalue, bool capturedByInit) {
700 SourceLocRAIIObject loc{*this, getLoc(init->getSourceRange())};
701 if (capturedByInit) {
702 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
703 return;
704 }
705
706 QualType type = d->getType();
707
708 if (type->isReferenceType()) {
709 RValue rvalue = emitReferenceBindingToExpr(init);
710 if (capturedByInit)
711 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
712 emitStoreThroughLValue(rvalue, lvalue);
713 return;
714 }
716 case cir::TEK_Scalar:
717 emitScalarInit(init, getLoc(d->getSourceRange()), lvalue);
718 return;
719 case cir::TEK_Complex: {
720 mlir::Value complex = emitComplexExpr(init);
721 if (capturedByInit)
722 cgm.errorNYI(init->getSourceRange(),
723 "emitExprAsInit: complex type captured by init");
724 mlir::Location loc = getLoc(init->getExprLoc());
725 emitStoreOfComplex(loc, complex, lvalue,
726 /*isInit*/ true);
727 return;
728 }
730 // The overlap flag here should be calculated.
732 emitAggExpr(init,
736 return;
737 }
738 llvm_unreachable("bad evaluation kind");
739}
740
741void CIRGenFunction::emitDecl(const Decl &d, bool evaluateConditionDecl) {
742 switch (d.getKind()) {
743 case Decl::BuiltinTemplate:
744 case Decl::TranslationUnit:
745 case Decl::ExternCContext:
746 case Decl::Namespace:
747 case Decl::UnresolvedUsingTypename:
748 case Decl::ClassTemplateSpecialization:
749 case Decl::ClassTemplatePartialSpecialization:
750 case Decl::VarTemplateSpecialization:
751 case Decl::VarTemplatePartialSpecialization:
752 case Decl::TemplateTypeParm:
753 case Decl::UnresolvedUsingValue:
754 case Decl::NonTypeTemplateParm:
755 case Decl::CXXDeductionGuide:
756 case Decl::CXXMethod:
757 case Decl::CXXConstructor:
758 case Decl::CXXDestructor:
759 case Decl::CXXConversion:
760 case Decl::Field:
761 case Decl::MSProperty:
762 case Decl::IndirectField:
763 case Decl::ObjCIvar:
764 case Decl::ObjCAtDefsField:
765 case Decl::ParmVar:
766 case Decl::ImplicitParam:
767 case Decl::ClassTemplate:
768 case Decl::VarTemplate:
769 case Decl::FunctionTemplate:
770 case Decl::TypeAliasTemplate:
771 case Decl::TemplateTemplateParm:
772 case Decl::ObjCMethod:
773 case Decl::ObjCCategory:
774 case Decl::ObjCProtocol:
775 case Decl::ObjCInterface:
776 case Decl::ObjCCategoryImpl:
777 case Decl::ObjCImplementation:
778 case Decl::ObjCProperty:
779 case Decl::ObjCCompatibleAlias:
780 case Decl::PragmaComment:
781 case Decl::PragmaDetectMismatch:
782 case Decl::AccessSpec:
783 case Decl::LinkageSpec:
784 case Decl::Export:
785 case Decl::ObjCPropertyImpl:
786 case Decl::FileScopeAsm:
787 case Decl::Friend:
788 case Decl::FriendTemplate:
789 case Decl::Block:
790 case Decl::OutlinedFunction:
791 case Decl::Captured:
792 case Decl::UsingShadow:
793 case Decl::ConstructorUsingShadow:
794 case Decl::ObjCTypeParam:
795 case Decl::Binding:
796 case Decl::UnresolvedUsingIfExists:
797 case Decl::HLSLBuffer:
798 case Decl::HLSLRootSignature:
799 llvm_unreachable("Declaration should not be in declstmts!");
800
801 case Decl::Function: // void X();
802 case Decl::EnumConstant: // enum ? { X = ? }
803 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
804 case Decl::Label: // __label__ x;
805 case Decl::Import:
806 case Decl::MSGuid: // __declspec(uuid("..."))
807 case Decl::TemplateParamObject:
808 case Decl::Empty:
809 case Decl::Concept:
810 case Decl::LifetimeExtendedTemporary:
811 case Decl::RequiresExprBody:
812 case Decl::UnnamedGlobalConstant:
813 // None of these decls require codegen support.
814 return;
815
816 case Decl::Enum: // enum X;
817 case Decl::Record: // struct/union/class X;
818 case Decl::CXXRecord: // struct/union/class X; [C++]
819 case Decl::NamespaceAlias:
820 case Decl::Using: // using X; [C++]
821 case Decl::UsingEnum: // using enum X; [C++]
822 case Decl::UsingDirective: // using namespace X; [C++]
824 return;
825 case Decl::Var:
826 case Decl::Decomposition: {
827 const VarDecl &vd = cast<VarDecl>(d);
828 assert(vd.isLocalVarDecl() &&
829 "Should not see file-scope variables inside a function!");
830 emitVarDecl(vd);
831 if (evaluateConditionDecl)
833 return;
834 }
835 case Decl::OpenACCDeclare:
837 return;
838 case Decl::OpenACCRoutine:
840 return;
841 case Decl::OMPThreadPrivate:
843 return;
844 case Decl::OMPGroupPrivate:
846 return;
847 case Decl::OMPAllocate:
849 return;
850 case Decl::OMPCapturedExpr:
852 return;
853 case Decl::OMPRequires:
855 return;
856 case Decl::OMPDeclareMapper:
858 return;
859 case Decl::OMPDeclareReduction:
861 return;
862 case Decl::Typedef: // typedef int X;
863 case Decl::TypeAlias: { // using X = int; [C++0x]
864 QualType ty = cast<TypedefNameDecl>(d).getUnderlyingType();
866 if (ty->isVariablyModifiedType())
867 cgm.errorNYI(d.getSourceRange(), "emitDecl: variably modified type");
868 return;
869 }
870 case Decl::ImplicitConceptSpecialization:
871 case Decl::TopLevelStmt:
872 case Decl::UsingPack:
873 cgm.errorNYI(d.getSourceRange(),
874 std::string("emitDecl: unhandled decl type: ") +
875 d.getDeclKindName());
876 }
877}
878
880 SourceLocation loc) {
881 if (!sanOpts.has(SanitizerKind::NullabilityAssign))
882 return;
883
885}
886
887namespace {
888struct DestroyObject final : EHScopeStack::Cleanup {
889 DestroyObject(Address addr, QualType type,
890 CIRGenFunction::Destroyer *destroyer)
891 : addr(addr), type(type), destroyer(destroyer) {
893 }
894
895 Address addr;
897 CIRGenFunction::Destroyer *destroyer;
898
899 void emit(CIRGenFunction &cgf, Flags flags) override {
901 cgf.emitDestroy(addr, type, destroyer);
902 }
903};
904
905template <class Derived> struct DestroyNRVOVariable : EHScopeStack::Cleanup {
906 DestroyNRVOVariable(Address addr, QualType type, mlir::Value nrvoFlag)
907 : nrvoFlag(nrvoFlag), addr(addr), ty(type) {}
908
909 mlir::Value nrvoFlag;
910 Address addr;
911 QualType ty;
912
913 void emit(CIRGenFunction &cgf, Flags flags) override {
914 // Along the exceptions path we always execute the dtor.
915 bool nrvo = flags.isForNormalCleanup() && nrvoFlag;
916
917 CIRGenBuilderTy &builder = cgf.getBuilder();
918 mlir::OpBuilder::InsertionGuard guard(builder);
919 if (nrvo) {
920 // If we exited via NRVO, we skip the destructor call.
921 mlir::Location loc = addr.getPointer().getLoc();
922 mlir::Value didNRVO = builder.createFlagLoad(loc, nrvoFlag);
923 mlir::Value notNRVO = builder.createNot(didNRVO);
924 cir::IfOp::create(builder, loc, notNRVO, /*withElseRegion=*/false,
925 [&](mlir::OpBuilder &b, mlir::Location) {
926 static_cast<Derived *>(this)->emitDestructorCall(cgf);
927 builder.createYield(loc);
928 });
929 } else {
930 static_cast<Derived *>(this)->emitDestructorCall(cgf);
931 }
932 }
933
934 virtual ~DestroyNRVOVariable() = default;
935};
936
937struct DestroyNRVOVariableCXX final
938 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
939 DestroyNRVOVariableCXX(Address addr, QualType type,
940 const CXXDestructorDecl *dtor, mlir::Value nrvoFlag)
941 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, nrvoFlag),
942 dtor(dtor) {}
943
944 const CXXDestructorDecl *dtor;
945
946 void emitDestructorCall(CIRGenFunction &cgf) {
948 /*forVirtualBase=*/false,
949 /*delegating=*/false, addr, ty);
950 }
951};
952
953struct CallStackRestore final : EHScopeStack::Cleanup {
954 Address stack;
955 CallStackRestore(Address stack) : stack(stack) {}
956 void emit(CIRGenFunction &cgf, Flags flags) override {
957 mlir::Location loc = stack.getPointer().getLoc();
958 mlir::Value v = cgf.getBuilder().createLoad(loc, stack);
959 cgf.getBuilder().createStackRestore(loc, v);
960 }
961};
962} // namespace
963
964/// Push the standard destructor for the given type as
965/// at least a normal cleanup.
967 Address addr, QualType type) {
968 assert(dtorKind && "cannot push destructor for trivial type");
969
970 CleanupKind cleanupKind = getCleanupKind(dtorKind);
971 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind));
972}
973
975 QualType type, Destroyer *destroyer) {
976 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
977}
978
979/// Destroys all the elements of the given array, beginning from last to first.
980/// The array cannot be zero-length.
981///
982/// \param begin - a type* denoting the first element of the array
983/// \param numElements - the number of elements in the array
984/// \param elementType - the element type of the array
985/// \param destroyer - the function to call to destroy elements
986void CIRGenFunction::emitArrayDestroy(mlir::Value begin,
987 mlir::Value numElements,
988 QualType elementType,
989 CharUnits elementAlign,
990 Destroyer *destroyer) {
991 assert(!elementType->isArrayType());
992
993 // Differently from LLVM traditional codegen, use a higher level
994 // representation instead of lowering directly to a loop.
995 mlir::Type cirElementType = convertTypeForMem(elementType);
996 cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType);
997
998 uint64_t size = 0;
999
1000 // Optimize for a constant array size.
1001 if (auto constantCount = numElements.getDefiningOp<cir::ConstantOp>()) {
1002 if (auto constIntAttr = constantCount.getValueAttr<cir::IntAttr>())
1003 size = constIntAttr.getUInt();
1004 } else {
1005 cgm.errorNYI(begin.getDefiningOp()->getLoc(),
1006 "dynamic-length array expression");
1007 }
1008
1009 auto arrayTy = cir::ArrayType::get(cirElementType, size);
1010 mlir::Value arrayOp = builder.createPtrBitcast(begin, arrayTy);
1011
1012 // Emit the dtor call that will execute for every array element.
1013 cir::ArrayDtor::create(
1014 builder, *currSrcLoc, arrayOp,
1015 [&](mlir::OpBuilder &b, mlir::Location loc) {
1016 auto arg = b.getInsertionBlock()->addArgument(ptrToElmType, loc);
1017 Address curAddr = Address(arg, cirElementType, elementAlign);
1019
1020 // Perform the actual destruction there.
1021 destroyer(*this, curAddr, elementType);
1022
1023 cir::YieldOp::create(builder, loc);
1024 });
1025}
1026
1027/// Immediately perform the destruction of the given object.
1028///
1029/// \param addr - the address of the object; a type*
1030/// \param type - the type of the object; if an array type, all
1031/// objects are destroyed in reverse order
1032/// \param destroyer - the function to call to destroy individual
1033/// elements
1035 Destroyer *destroyer) {
1037 if (!arrayType)
1038 return destroyer(*this, addr, type);
1039
1040 mlir::Value length = emitArrayLength(arrayType, type, addr);
1041
1042 CharUnits elementAlign = addr.getAlignment().alignmentOfArrayElement(
1043 getContext().getTypeSizeInChars(type));
1044
1045 auto constantCount = length.getDefiningOp<cir::ConstantOp>();
1046 if (!constantCount) {
1047 assert(!cir::MissingFeatures::vlas());
1048 cgm.errorNYI("emitDestroy: variable length array");
1049 return;
1050 }
1051
1052 auto constIntAttr = mlir::dyn_cast<cir::IntAttr>(constantCount.getValue());
1053 // If it's constant zero, we can just skip the entire thing.
1054 if (constIntAttr && constIntAttr.getUInt() == 0)
1055 return;
1056
1057 mlir::Value begin = addr.getPointer();
1059 emitArrayDestroy(begin, length, type, elementAlign, destroyer);
1060
1061 // If the array destroy didn't use the length op, we can erase it.
1062 if (constantCount.use_empty())
1063 constantCount.erase();
1064}
1065
1068 switch (kind) {
1069 case QualType::DK_none:
1070 llvm_unreachable("no destroyer for trivial dtor");
1072 return destroyCXXObject;
1076 cgm.errorNYI("getDestroyer: other destruction kind");
1077 return nullptr;
1078 }
1079 llvm_unreachable("Unknown DestructionKind");
1080}
1081
1083 ehStack.pushCleanup<CallStackRestore>(kind, spMem);
1084}
1085
1086/// Enter a destroy cleanup for the given local variable.
1088 const CIRGenFunction::AutoVarEmission &emission,
1089 QualType::DestructionKind dtorKind) {
1090 assert(dtorKind != QualType::DK_none);
1091
1092 // Note that for __block variables, we want to destroy the
1093 // original stack object, not the possibly forwarded object.
1094 Address addr = emission.getObjectAddress(*this);
1095
1096 const VarDecl *var = emission.variable;
1097 QualType type = var->getType();
1098
1099 CleanupKind cleanupKind = NormalAndEHCleanup;
1100 CIRGenFunction::Destroyer *destroyer = nullptr;
1101
1102 switch (dtorKind) {
1103 case QualType::DK_none:
1104 llvm_unreachable("no cleanup for trivially-destructible variable");
1105
1107 // If there's an NRVO flag on the emission, we need a different
1108 // cleanup.
1109 if (emission.nrvoFlag) {
1110 assert(!type->isArrayType());
1111 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1112 ehStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1113 emission.nrvoFlag);
1114 return;
1115 }
1116 // Otherwise, this is handled below.
1117 break;
1118
1122 cgm.errorNYI(var->getSourceRange(),
1123 "emitAutoVarTypeCleanup: other dtor kind");
1124 return;
1125 }
1126
1127 // If we haven't chosen a more specific destroyer, use the default.
1128 if (!destroyer)
1129 destroyer = getDestroyer(dtorKind);
1130
1132 ehStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1133}
1134
1136 if (auto *dd = dyn_cast_if_present<DecompositionDecl>(vd)) {
1137 for (auto *b : dd->flat_bindings())
1138 if (auto *hd = b->getHoldingVar())
1139 emitVarDecl(*hd);
1140 }
1141}
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::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
mlir::Value createNot(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:944
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:3723
mlir::Value getPointer() const
Definition Address.h:95
mlir::Type getElementType() const
Definition Address.h:122
static Address invalid()
Definition Address.h:73
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:135
mlir::Operation * getDefiningOp() const
Get the operation which defines this address.
Definition Address.h:138
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::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)
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.
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.
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...
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.
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 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 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 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.
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:1548
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
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:1449
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:573
bool hasAttrs() const
Definition DeclBase.h:518
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
SourceLocation getLocation() const
Definition DeclBase.h:439
const char * getDeclKindName() const
Definition DeclBase.cpp:169
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
This represents one expression.
Definition Expr.h:112
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition Expr.cpp:3346
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
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:1478
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8428
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:2695
Represents a struct/union/class.
Definition Decl.h:4324
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:338
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:2426
bool isArrayType() const
Definition TypeBase.h:8638
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
bool isVectorType() const
Definition TypeBase.h:8678
bool isSamplerT() const
Definition TypeBase.h:8779
bool isRecordType() const
Definition TypeBase.h:8666
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:1569
TLSKind getTLSKind() const
Definition Decl.cpp:2179
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2201
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
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:2497
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1512
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2862
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
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:1253
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1229
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2709
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ 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
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:341
@ 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 shouldSplitConstantStore()
static bool shouldUseMemSetToInitialize()
static bool dtorCleanups()
static bool shouldUseBZeroPlusStoresToInitialize()
static bool shouldCreateMemCpyFromGlobal()
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.
cir::PointerType allocaInt8PtrTy
void* in alloca address space