clang 24.0.0git
CIRGenExprConstant.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 Constant Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Address.h"
14#include "CIRGenCXXABI.h"
16#include "CIRGenModule.h"
17#include "CIRGenRecordLayout.h"
18#include "mlir/IR/Attributes.h"
19#include "mlir/IR/BuiltinAttributeInterfaces.h"
20#include "mlir/IR/BuiltinAttributes.h"
21#include "clang/AST/APValue.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/CharUnits.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/Support/ErrorHandling.h"
36#include <functional>
37#include <iterator>
38#include <optional>
39
40using namespace clang;
41using namespace clang::CIRGen;
42
43/// Collects the initializer elements for the members of \p recordTy that are
44/// stored, in order, taking a zero initializer for any member left unset.
45/// \p elements is indexed by member, which is not the same as being indexed by
46/// stored element. A zero-width bit-field owns no bytes and so takes no
47/// element at all. Fails if a member has no zero initializer.
48static bool
52 for (auto [idx, memberTy] : llvm::enumerate(recordTy.getMembers())) {
53 if (!cir::memberOwnsBytes(memberTy))
54 continue;
55 mlir::Attribute elt = elements[idx];
56 if (!elt) {
57 elt = builder.getZeroInitAttr(memberTy);
58 if (!elt)
59 return false;
60 }
61 stored.push_back(elt);
62 }
63 return true;
64}
65
66//===----------------------------------------------------------------------===//
67// ConstantAggregateBuilder
68//===----------------------------------------------------------------------===//
69
70namespace {
72// A class to manage the list of 'initializers' for building the record
73// initialization. This abstracts out the APValue and the InitListExpr.
74class RecordBuilderInitList {
75 unsigned initIdx = 0;
76 bool isUnion = false;
77 std::variant<APValue, const InitListExpr *> value;
78
79 bool holdsExpr() const {
80 return std::holds_alternative<const InitListExpr *>(value);
81 }
82
83 bool holdsAPValue() const { return std::holds_alternative<APValue>(value); }
84
85 const Expr *getExpr() {
86 assert(holdsExpr());
87 return std::get<const InitListExpr *>(value)->getInit(initIdx);
88 }
89
90 mlir::Location getExprLoc(CIRGenModule &cgm) {
91 assert(holdsExpr());
92 return cgm.getLoc(std::get<const InitListExpr *>(value)->getBeginLoc());
93 }
94
95 const APValue getAPVal() {
96 assert(holdsAPValue());
97 if (isUnion)
98 return std::get<APValue>(value).getUnionValue();
99 return std::get<APValue>(value).getStructField(initIdx);
100 }
101
102public:
103 RecordBuilderInitList(const RecordDecl *rd, APValue val)
104 : isUnion(rd->isUnion()), value(val) {}
105 RecordBuilderInitList(const RecordDecl *rd, const InitListExpr *ile)
106 : isUnion(rd->isUnion()), value(ile) {
107 assert(ile);
108 }
109
110 bool empty() const {
111 if (auto *const *ile = std::get_if<const InitListExpr *>(&value))
112 return initIdx >= (*ile)->getNumInits();
113
114 // This branch is likely always true, but we guard against it being 'none'
115 // anyway.
116 if (isUnion)
117 return !std::get<APValue>(value).isUnion();
118
119 return initIdx >= std::get<APValue>(value).getStructNumFields();
120 }
121
122 const FieldDecl *getActiveUnionField() const {
123 if (holdsExpr())
124 return std::get<const InitListExpr *>(value)
125 ->getInitializedFieldInUnion();
126 return std::get<APValue>(value).getUnionField();
127 }
128
129 // Return whether this is a field that should be skipped for one reason or
130 // another.
131 bool shouldSkip(const FieldDecl *fd) {
132 if (fd->isUnnamedBitField())
133 return true;
134
135 if (holdsExpr() && isa_and_nonnull<NoInitExpr>(getExpr()))
136 return true;
137
138 return false;
139 }
140
141 // Advance the iterator on a 'skipped' field. Note in the case of an
142 // init-list this doesn't advance if its an unnamed bitfield, as those aren't
143 // represented in the AST.
144 void advanceSkip(const FieldDecl *fd) {
145 assert(!isUnion);
146 if (holdsExpr() && fd->isUnnamedBitField())
147 return;
148 ++initIdx;
149 }
150 // Advance the iterator on a 'normal' field, which always just increments the
151 // index.
152 void advance() {
153 assert(!isUnion);
154 ++initIdx;
155 }
156
157 APValue getBase(unsigned idx) {
158 // We could potentially handle this with init-list, but we just skip it
159 // because classic codegen does. If we decide to, we'll probably have to do
160 // something where we get through the init-list elements to make this work
161 // right (sub-init-list?).
162 assert(holdsAPValue());
163
164 return std::get<APValue>(value).getStructBase(idx);
165 }
166
167 bool hasSideEffects(const ASTContext &ctx) {
168 if (holdsExpr() && getExpr()->HasSideEffects(ctx))
169 return true;
170 // APValue never has side effects.
171 return false;
172 }
173
174 mlir::Attribute emit(ConstantEmitter &emitter, QualType fieldTy) {
175 if (holdsExpr()) {
176 const Expr *e = getExpr();
177 return e ? emitter.tryEmitPrivateForMemory(e, fieldTy)
178 : emitter.emitNullForMemory(getExprLoc(emitter.cgm), fieldTy);
179 }
180 return emitter.tryEmitPrivateForMemory(getAPVal(), fieldTy);
181 }
182};
183
184llvm::APInt bitfieldStorageToAPInt(mlir::Attribute attr, unsigned storageSize,
185 bool isBigEndian) {
186 // An empty attribute is just zero of the correct size.
187 if (!attr)
188 return llvm::APInt(storageSize, 0);
189 // An int type is just the value held in the attribute.
190 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr))
191 return intAttr.getValue();
192
193 // Else we are in the array case, we have to create the big APInt, and fill it
194 // up.
195 llvm::APInt result(storageSize, 0);
196 auto elts = mlir::cast<mlir::ArrayAttr>(
197 mlir::cast<cir::ConstArrayAttr>(attr).getElts());
198
199 unsigned numBytes = elts.size();
200 for (unsigned i = 0; i != numBytes; ++i) {
201 unsigned byteIdx = isBigEndian ? numBytes - 1 - i : i;
202 llvm::APInt byte =
203 mlir::cast<cir::IntAttr>(elts[i]).getValue().zextOrTrunc(8);
204 result.insertBits(byte, byteIdx * 8);
205 }
206 return result;
207}
208
209mlir::Attribute apIntToBitfieldStorage(CIRGenModule &cgm,
210 mlir::Type storageType,
211 const llvm::APInt &value,
212 bool isBigEndian) {
213 // If we'ere an int, just return the new value.
214 if (mlir::isa<cir::IntTypeInterface>(storageType))
215 return cir::IntAttr::get(storageType, value);
216
217 // Array of bytes case, fill up an array.
218 CIRGenBuilderTy &builder = cgm.getBuilder();
219 auto arrayTy = mlir::cast<cir::ArrayType>(storageType);
220
221 unsigned numBytes = arrayTy.getSize();
222 cir::IntType byteTy = builder.getUInt8Ty();
224
225 for (unsigned i = 0; i != numBytes; ++i) {
226 unsigned byteIdx = isBigEndian ? numBytes - 1 - i : i;
227 bytes[i] = cir::IntAttr::get(byteTy, value.extractBits(8, byteIdx * 8));
228 }
229 return cir::ConstArrayAttr::get(
230 arrayTy, mlir::ArrayAttr::get(builder.getContext(), bytes));
231}
232
233// Bitfields are lowered to either an integer type, or a series of bytes, see
234// getBitfieldStorageType. Because of this, we have to figure out how to store
235// this init value in those. Do this by converting the current value in the
236// 'storage' type to an APInt so we can do our masking correctly, then convert
237// back. The int path is trivial (getValue/create a new one with the new
238// value). The array type requires breaking it up into its constituent values.
239mlir::Attribute updateBitfieldInit(CIRGenModule &cgm,
240 mlir::Attribute existingVal,
241 cir::IntAttr newVal, bool isSigned,
242 const CIRGenBitFieldInfo &bfInfo) {
243 bool isBigEndian = cgm.getDataLayout().isBigEndian();
244 llvm::APInt result =
245 bitfieldStorageToAPInt(existingVal, bfInfo.storageSize, isBigEndian);
246
247 llvm::APInt curValue = newVal.getValue();
248 // Make sure we truncate (or properly extend) the existing value for the
249 // number of bits in the bitfield. The AST/Sema doesn't do a good job of
250 // making sure this is done.
251 if (isSigned)
252 curValue = curValue.sextOrTrunc(bfInfo.size);
253 else
254 curValue = curValue.zextOrTrunc(bfInfo.size);
255
256 // Extend to the full storage size so we can shift/mask.
257 curValue = curValue.zext(bfInfo.storageSize);
258
259 // bfInfo.offset is already adjusted for endianness, so no endian-changes need
260 // to happen here.
261 curValue = curValue.shl(bfInfo.offset);
262 llvm::APInt mask(bfInfo.storageSize, 0);
263 mask.setBits(bfInfo.offset, bfInfo.offset + bfInfo.size);
264
265 result &= ~mask;
266 result |= curValue;
267
268 return apIntToBitfieldStorage(cgm, bfInfo.storageType, result, isBigEndian);
269}
270
271mlir::Attribute
272setBitfieldInit(CIRGenModule &cgm, const CIRGenRecordLayout &cirLayout,
273 CIRGenBuilderTy &builder, const FieldDecl *field,
274 mlir::Attribute existingVal, mlir::Attribute newVal) {
275 const CIRGenBitFieldInfo &info = cirLayout.getBitFieldInfo(field);
276 auto intAttr = mlir::dyn_cast<cir::IntAttr>(newVal);
277 // This could alternatively be a 'bool' attr here, so do a quick fixup to
278 // get the value correctly initialized.
279 if (!intAttr) {
280 auto boolAttr = mlir::cast<cir::BoolAttr>(newVal);
281 intAttr = cir::IntAttr::get(
282 builder.getUIntNTy(1), llvm::APInt(/*numBits=*/1, boolAttr.getValue()));
283 }
284
285 return updateBitfieldInit(
286 cgm, existingVal, intAttr,
287 field->getType()->isSignedIntegerOrEnumerationType(), info);
288}
289
290// Handle potentially-overlapping field rewrite for the const subobject records.
291mlir::Attribute asBaseSubobject(CIRGenBuilderTy &builder, mlir::Attribute attr,
292 cir::RecordType baseSubobjTy) {
293 auto typedAttr = mlir::cast<mlir::TypedAttr>(attr);
294 if (typedAttr.getType() == baseSubobjTy)
295 return attr;
296
297 if (mlir::isa<cir::ZeroAttr>(attr))
298 return builder.getZeroInitAttr(baseSubobjTy);
299
300 auto recordAttr = mlir::cast<cir::ConstRecordAttr>(attr);
301 mlir::ArrayAttr members = recordAttr.getMembers();
303 members.begin(), members.begin() + baseSubobjTy.getNumElements());
304
305 // The base-subobject type is assumed to be a prefix of the complete-object
306 // type (i.e. the complete type minus tail padding). Verify that assumption
307 // holds so a layout change doesn't silently produce a wrong initializer.
308 //
309 // ConstRecordAttr's members skip zero-width bit-fields and store a
310 // bit-field's storage type rather than the bit-field type itself (see
311 // ConstRecordAttr::verify), so baseSubobjTy's raw member list has to be
312 // filtered the same way before comparing against baseMembers index-for-
313 // index.
314 assert(llvm::all_of(
315 llvm::zip_equal(baseMembers,
316 llvm::map_range(llvm::make_filter_range(
317 baseSubobjTy.getMembers(),
320 [](const auto &pair) {
321 auto &[member, baseTy] = pair;
322 return mlir::cast<mlir::TypedAttr>(member).getType() == baseTy;
323 }) &&
324 "base-subobject member type does not match complete-object member "
325 "type at the same index");
326
327 return cir::ConstRecordAttr::get(baseSubobjTy,
328 builder.getArrayAttr(baseMembers));
329}
330
331mlir::Attribute buildRecordHelper(ConstantEmitter &emitter,
332 const RecordDecl *rd,
333 const RecordDecl *vtableBaseTy,
334 RecordBuilderInitList inits, bool handleBases,
335 CharUnits offsetInDerived,
336 bool asBaseSubObj) {
337 CIRGenModule &cgm = emitter.cgm;
338 CIRGenBuilderTy &builder = cgm.getBuilder();
339 const CIRGenRecordLayout &cirLayout =
341 cir::RecordType recordTy = asBaseSubObj ? cirLayout.getBaseSubobjectCIRType()
342 : cirLayout.getCIRType();
343 // Unions in CIR are represented by all of their types, so we should be able
344 // to just initialize it with whatever the active field is.
345 if (rd->isUnion()) {
346 if (inits.empty())
347 return builder.getZeroInitAttr(recordTy);
348
349 const FieldDecl *activeField = inits.getActiveUnionField();
350 if (!activeField || activeField->isZeroSize(cgm.getASTContext()))
351 return builder.getZeroInitAttr(recordTy);
352
353 mlir::Attribute eltAttr = inits.emit(emitter, activeField->getType());
354 if (!eltAttr)
355 return {};
356
357 if (activeField->isBitField())
358 eltAttr = setBitfieldInit(cgm, cirLayout, builder, activeField,
359 /*existingVal=*/{}, eltAttr);
360
361 return cir::ConstRecordAttr::get(recordTy, builder.getArrayAttr({eltAttr}));
362 }
363
365
366 if (auto *cxxrd = dyn_cast<CXXRecordDecl>(rd)) {
367 const ASTRecordLayout &astLayout =
368 emitter.cgm.getASTContext().getASTRecordLayout(cxxrd);
369 if (astLayout.hasOwnVFPtr()) {
371 cir::GlobalViewAttr vptr =
373 BaseSubobject(cxxrd, offsetInDerived),
374 cast<CXXRecordDecl>(vtableBaseTy));
375 assert(vptr && "failed to get vtable address point");
376 elements[0] = vptr;
377 }
378
379 unsigned baseNo = 0;
380 for (const CXXBaseSpecifier &base : cxxrd->bases()) {
381 // Our init-list implementation here just skips bases because classic
382 // compiler does (see the comment in buildRecord). We perhaps COULD do
383 // this, but for now we'll skip them.
384 if (!handleBases)
385 return {};
386
387 if (base.isVirtual())
388 continue;
389
390 const auto *baseDecl = base.getType()->castAsCXXRecordDecl();
391
392 unsigned curBaseNo = baseNo++;
393
394 if (!cirLayout.hasNonVirtualBaseCIRField(baseDecl))
395 continue;
396
397 APValue baseValue = inits.getBase(curBaseNo);
398
399 const ASTRecordLayout &derivedLayout =
401 CharUnits baseOff =
402 offsetInDerived + derivedLayout.getBaseClassOffset(baseDecl);
403
404 unsigned baseFieldIdx = cirLayout.getNonVirtualBaseCIRFieldNo(baseDecl);
405 elements[baseFieldIdx] = buildRecordHelper(
406 emitter, baseDecl, vtableBaseTy, RecordBuilderInitList(rd, baseValue),
407 handleBases, baseOff, /*asBaseSubObj=*/true);
408 }
409
410 if (cxxrd->getNumVBases()) {
411 cgm.errorNYI(cxxrd->getSourceRange(),
412 "buildRecordHelper: virtual base classes");
413 return {};
414 }
415 }
416
417 for (const FieldDecl *field : rd->fields()) {
418 // If we don't have any initializers left, we'll just zero-init below. This
419 // isn't perfectly accurate to classic compiler, since we are potentially
420 // zero-initing padding (instead of leaving it undef), but that is a
421 // complexity we can deal with later if we find it necessary.
422 if (inits.empty())
423 break;
424
425 if (inits.shouldSkip(field)) {
426 inits.advanceSkip(field);
427 continue;
428 }
429
430 // If we didn't lay it out, there is nothing to initialize. This is
431 // either zero size or nothing at all. IF our init has side effects, we
432 // cannot const init this.
433 if (!cirLayout.hasCIRField(field)) {
434 if (inits.hasSideEffects(cgm.getASTContext()))
435 return {};
436 inits.advance();
437 continue;
438 }
439
440 // A run of bit-fields shares one access unit, and every field of the run
441 // is numbered as that unit, so their bits pack into a single element.
442 unsigned fieldIdx = cirLayout.getCIRFieldNo(field);
443
444 mlir::Attribute eltAttr = inits.emit(emitter, field->getType());
445 inits.advance();
446
447 if (!eltAttr)
448 return {};
449
450 if (field->isBitField()) {
451 elements[fieldIdx] = setBitfieldInit(cgm, cirLayout, builder, field,
452 elements[fieldIdx], eltAttr);
453 } else {
454 if (field->isPotentiallyOverlapping()) {
455 if (auto expectedTy = mlir::dyn_cast<cir::RecordType>(
456 recordTy.getMembers()[fieldIdx]))
457 eltAttr = asBaseSubobject(builder, eltAttr, expectedTy);
458 }
459 elements[fieldIdx] = eltAttr;
460 }
461 }
462
463 // Anything we haven't initialized, we try to zero init. We could/should
464 // probably leave the padding as undef if !CGM.ZeroInitPadding, but that ends
465 // up being quite an additional bit of complexity (but could be implemented in
466 // the field searching above).
468 if (!collectStoredInitializers(builder, recordTy, elements, storedElements))
469 return {};
470
471 return builder.getConstRecordOrZeroAttr(builder.getArrayAttr(storedElements),
472 recordTy);
473}
474
475mlir::Attribute buildRecord(ConstantEmitter &emitter, InitListExpr *ile,
476 QualType valTy) {
477 // Bail out if we have base classes. We could support these, but they only
478 // arise in C++1z where we will have already constant folded most
479 // interesting cases. FIXME: There are still a few more cases we can handle
480 // this way.
481 const bool handleBases = false;
482 const RecordDecl *rd = ile->getType()->castAsRecordDecl();
483 return buildRecordHelper(emitter, rd, rd, RecordBuilderInitList(rd, ile),
484 handleBases, CharUnits::Zero(),
485 /*asBaseSubObj=*/false);
486}
487
488mlir::Attribute buildRecord(ConstantEmitter &emitter, const APValue &val,
489 QualType valTy) {
490 const RecordDecl *rd =
491 valTy->castAs<clang::RecordType>()->getDecl()->getDefinitionOrSelf();
492 return buildRecordHelper(emitter, rd, rd, RecordBuilderInitList(rd, val),
493 /*handleBases=*/true, CharUnits::Zero(),
494 /*asBaseSubObj=*/false);
495}
496} // namespace ConstRecordBuilder
497
498//===----------------------------------------------------------------------===//
499// ConstExprEmitter
500//===----------------------------------------------------------------------===//
501
502// This class only needs to handle arrays, structs and unions.
503//
504// In LLVM codegen, when outside C++11 mode, those types are not constant
505// folded, while all other types are handled by constant folding.
506//
507// In CIR codegen, instead of folding things here, we should defer that work
508// to MLIR: do not attempt to do much here.
509class ConstExprEmitter
510 : public StmtVisitor<ConstExprEmitter, mlir::Attribute, QualType> {
511 CIRGenModule &cgm;
512 [[maybe_unused]] ConstantEmitter &emitter;
513
514public:
515 ConstExprEmitter(ConstantEmitter &emitter)
516 : cgm(emitter.cgm), emitter(emitter) {}
517
518 //===--------------------------------------------------------------------===//
519 // Visitor Methods
520 //===--------------------------------------------------------------------===//
521
522 mlir::Attribute VisitStmt(Stmt *s, QualType t) { return {}; }
523
524 mlir::Attribute VisitConstantExpr(ConstantExpr *ce, QualType t) {
525 if (mlir::Attribute result = emitter.tryEmitConstantExpr(ce))
526 return result;
527 return Visit(ce->getSubExpr(), t);
528 }
529
530 mlir::Attribute VisitParenExpr(ParenExpr *pe, QualType t) {
531 return Visit(pe->getSubExpr(), t);
532 }
533
534 mlir::Attribute
535 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *pe,
536 QualType t) {
537 return Visit(pe->getReplacement(), t);
538 }
539
540 mlir::Attribute VisitGenericSelectionExpr(GenericSelectionExpr *ge,
541 QualType t) {
542 return Visit(ge->getResultExpr(), t);
543 }
544
545 mlir::Attribute VisitChooseExpr(ChooseExpr *ce, QualType t) {
546 return Visit(ce->getChosenSubExpr(), t);
547 }
548
549 mlir::Attribute VisitCompoundLiteralExpr(CompoundLiteralExpr *e, QualType t) {
550 return Visit(e->getInitializer(), t);
551 }
552
553 mlir::Attribute VisitCastExpr(CastExpr *e, QualType destType) {
554 if (const auto *ece = dyn_cast<ExplicitCastExpr>(e))
555 cgm.emitExplicitCastExprType(ece,
556 const_cast<CIRGenFunction *>(emitter.cgf));
557
558 Expr *subExpr = e->getSubExpr();
559
560 switch (e->getCastKind()) {
561 case CK_ToUnion:
562 case CK_AddressSpaceConversion:
563 case CK_ReinterpretMemberPointer:
564 cgm.errorNYI(e->getBeginLoc(), "ConstExprEmitter::VisitCastExpr");
565 return {};
566
567 case CK_DerivedToBaseMemberPointer:
568 case CK_BaseToDerivedMemberPointer:
569 // Return {} to let the APValue evaluator handle member pointer type
570 // conversions. The APValue::MemberPointer case in tryEmitPrivate
571 // already builds the correct GEP path for cross-class member pointers.
572 return {};
573
574 case CK_LValueToRValue:
575 case CK_AtomicToNonAtomic:
576 case CK_NonAtomicToAtomic:
577 case CK_NoOp:
578 case CK_ConstructorConversion:
579 return Visit(subExpr, destType);
580
581 case CK_IntToOCLSampler:
582 llvm_unreachable("global sampler variables are not generated");
583
584 case CK_Dependent:
585 llvm_unreachable("saw dependent cast!");
586
587 case CK_BuiltinFnToFnPtr:
588 llvm_unreachable("builtin functions are handled elsewhere");
589
590 // These will never be supported.
591 case CK_ObjCObjectLValueCast:
592 case CK_ARCProduceObject:
593 case CK_ARCConsumeObject:
594 case CK_ARCReclaimReturnedObject:
595 case CK_ARCExtendBlockObject:
596 case CK_CopyAndAutoreleaseBlockObject:
597 return {};
598
599 // These don't need to be handled here because Evaluate knows how to
600 // evaluate them in the cases where they can be folded.
601 case CK_BitCast:
602 case CK_ToVoid:
603 case CK_Dynamic:
604 case CK_LValueBitCast:
605 case CK_LValueToRValueBitCast:
606 case CK_NullToMemberPointer:
607 case CK_UserDefinedConversion:
608 case CK_CPointerToObjCPointerCast:
609 case CK_BlockPointerToObjCPointerCast:
610 case CK_AnyPointerToBlockPointerCast:
611 case CK_ArrayToPointerDecay:
612 case CK_FunctionToPointerDecay:
613 case CK_BaseToDerived:
614 case CK_DerivedToBase:
615 case CK_UncheckedDerivedToBase:
616 case CK_MemberPointerToBoolean:
617 case CK_VectorSplat:
618 case CK_FloatingRealToComplex:
619 case CK_FloatingComplexToReal:
620 case CK_FloatingComplexToBoolean:
621 case CK_FloatingComplexCast:
622 case CK_FloatingComplexToIntegralComplex:
623 case CK_IntegralRealToComplex:
624 case CK_IntegralComplexToReal:
625 case CK_IntegralComplexToBoolean:
626 case CK_IntegralComplexCast:
627 case CK_IntegralComplexToFloatingComplex:
628 case CK_PointerToIntegral:
629 case CK_PointerToBoolean:
630 case CK_NullToPointer:
631 case CK_IntegralCast:
632 case CK_BooleanToSignedIntegral:
633 case CK_IntegralToPointer:
634 case CK_IntegralToBoolean:
635 case CK_IntegralToFloating:
636 case CK_FloatingToIntegral:
637 case CK_FloatingToBoolean:
638 case CK_FloatingCast:
639 case CK_FloatingToFixedPoint:
640 case CK_FixedPointToFloating:
641 case CK_FixedPointCast:
642 case CK_FixedPointToBoolean:
643 case CK_FixedPointToIntegral:
644 case CK_IntegralToFixedPoint:
645 case CK_ZeroToOCLOpaqueType:
646 case CK_MatrixCast:
647 case CK_HLSLArrayRValue:
648 case CK_HLSLVectorTruncation:
649 case CK_HLSLMatrixTruncation:
650 case CK_HLSLElementwiseCast:
651 case CK_HLSLAggregateSplatCast:
652 return {};
653 }
654 llvm_unreachable("Invalid CastKind");
655 }
656
657 mlir::Attribute VisitCXXDefaultInitExpr(CXXDefaultInitExpr *die, QualType t) {
658 // No need for a DefaultInitExprScope: we don't handle 'this' in a
659 // constant expression.
660 return Visit(die->getExpr(), t);
661 }
662
663 mlir::Attribute VisitExprWithCleanups(ExprWithCleanups *e, QualType t) {
664 // Since this about constant emission no need to wrap this under a scope.
665 return Visit(e->getSubExpr(), t);
666 }
667
668 mlir::Attribute VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *e,
669 QualType t) {
670 return Visit(e->getSubExpr(), t);
671 }
672
673 mlir::Attribute VisitImplicitValueInitExpr(ImplicitValueInitExpr *e,
674 QualType t) {
675 return cgm.emitNullConstantAttr(t);
676 }
677
678 mlir::Attribute VisitInitListExpr(InitListExpr *ile, QualType t) {
679 if (ile->isTransparent())
680 return Visit(ile->getInit(0), t);
681
682 if (ile->getType()->isArrayType()) {
683 // If we return null here, the non-constant initializer will take care of
684 // it, but we would prefer to handle it here.
686 return {};
687 }
688
689 if (ile->getType()->isRecordType()) {
690 return ConstRecordBuilder::buildRecord(emitter, ile, t);
691 }
692
693 if (ile->getType()->isVectorType()) {
694 // If we return null here, the non-constant initializer will take care of
695 // it, but we would prefer to handle it here.
697 return {};
698 }
699
700 return {};
701 }
702
703 mlir::Attribute VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *e,
704 QualType destType) {
705 mlir::Attribute c = Visit(e->getBase(), destType);
706 if (!c)
707 return {};
708
709 cgm.errorNYI(e->getBeginLoc(),
710 "ConstExprEmitter::VisitDesignatedInitUpdateExpr");
711 return {};
712 }
713
714 mlir::Attribute VisitCXXConstructExpr(CXXConstructExpr *e, QualType ty) {
715 if (!e->getConstructor()->isTrivial())
716 return {};
717
718 // Only default and copy/move constructors can be trivial.
719 if (e->getNumArgs()) {
720 assert(e->getNumArgs() == 1 && "trivial ctor with > 1 argument");
722 "trivial ctor has argument but isn't a copy/move ctor");
723
724 Expr *arg = e->getArg(0);
725 assert(cgm.getASTContext().hasSameUnqualifiedType(ty, arg->getType()) &&
726 "argument to copy ctor is of wrong type");
727
728 // Look through the temporary; it's just converting the value to an lvalue
729 // to pass it to the constructor.
730 if (auto const *mte = dyn_cast<MaterializeTemporaryExpr>(arg))
731 return Visit(mte->getSubExpr(), ty);
732
733 // TODO: Investigate whether there are cases that can fall through to here
734 // that need to be handled. This is missing in classic codegen also.
736
737 // Don't try to support arbitrary lvalue-to-rvalue conversions for now.
738 return {};
739 }
740
741 return cgm.getBuilder().getZeroInitAttr(cgm.convertType(ty));
742 }
743
744 mlir::Attribute VisitStringLiteral(StringLiteral *e, QualType t) {
745 // This is a string literal initializing an array in an initializer.
746 return cgm.getConstantArrayFromStringLiteral(e);
747 }
748
749 mlir::Attribute VisitObjCEncodeExpr(ObjCEncodeExpr *e, QualType t) {
750 cgm.errorNYI(e->getBeginLoc(), "ConstExprEmitter::VisitObjCEncodeExpr");
751 return {};
752 }
753
754 mlir::Attribute VisitUnaryExtension(const UnaryOperator *e, QualType t) {
755 return Visit(e->getSubExpr(), t);
756 }
757
758 // Utility methods
759 mlir::Type convertType(QualType t) { return cgm.convertType(t); }
760};
761
762// TODO(cir): this can be shared with LLVM's codegen
764 if (const auto *at = type->getAs<AtomicType>()) {
765 return cgm.getASTContext().getQualifiedType(at->getValueType(),
766 type.getQualifiers());
767 }
768 return type;
769}
770} // namespace
771
772//===----------------------------------------------------------------------===//
773// ConstantLValueEmitter
774//===----------------------------------------------------------------------===//
775
776namespace {
777/// A struct which can be used to peephole certain kinds of finalization
778/// that normally happen during l-value emission.
779struct ConstantLValue {
780 llvm::PointerUnion<mlir::Value, mlir::Attribute> value;
781 bool hasOffsetApplied;
782
783 /*implicit*/ ConstantLValue(std::nullptr_t)
784 : value(nullptr), hasOffsetApplied(false) {}
785 /*implicit*/ ConstantLValue(cir::GlobalViewAttr address)
786 : value(address), hasOffsetApplied(false) {}
787 /*implicit*/ ConstantLValue(cir::GlobalOffsetAttr address)
788 : value(address), hasOffsetApplied(true) {}
789 /*implicit*/ ConstantLValue(cir::BlockAddrInfoAttr address)
790 : value(address), hasOffsetApplied(true) {}
791
792 ConstantLValue() : value(nullptr), hasOffsetApplied(false) {}
793};
794
795/// A helper class for emitting constant l-values.
796class ConstantLValueEmitter
797 : public ConstStmtVisitor<ConstantLValueEmitter, ConstantLValue> {
798 CIRGenModule &cgm;
799 ConstantEmitter &emitter;
800 const APValue &value;
801 QualType destType;
802
803 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
804 friend StmtVisitorBase;
805
806public:
807 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
808 QualType destType)
809 : cgm(emitter.cgm), emitter(emitter), value(value), destType(destType) {}
810
811 mlir::Attribute tryEmit();
812
813private:
814 mlir::Attribute tryEmitAbsolute(mlir::Type destTy);
815 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
816
817 ConstantLValue VisitStmt(const Stmt *s) { return nullptr; }
818 ConstantLValue VisitConstantExpr(const ConstantExpr *e);
819 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *e);
820 ConstantLValue VisitStringLiteral(const StringLiteral *e);
821 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *e);
822 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *e);
823 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *e);
824 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *e);
825 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *e);
826 ConstantLValue VisitCallExpr(const CallExpr *e);
827 ConstantLValue VisitBlockExpr(const BlockExpr *e);
828 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *e);
829 ConstantLValue
830 VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e);
831
832 /// Return GEP-like value offset, or std::nullopt if the offset doesn't
833 /// designate a subelement of \p ty and must be described as a byte offset.
834 /// A null ArrayAttr means the offset is zero, so no indexing is needed.
835 std::optional<mlir::ArrayAttr> getOffsetIndices(mlir::Type ty) {
836 int64_t offset = value.getLValueOffset().getQuantity();
837 cir::CIRDataLayout layout(cgm.getModule());
838 SmallVector<int64_t, 3> idxVec;
839 if (!cgm.getBuilder().computeGlobalViewIndicesFromFlatOffset(
840 offset, ty, layout, idxVec))
841 return std::nullopt;
842
843 llvm::SmallVector<mlir::Attribute, 3> indices;
844 for (int64_t i : idxVec) {
845 mlir::IntegerAttr intAttr = cgm.getBuilder().getI32IntegerAttr(i);
846 indices.push_back(intAttr);
847 }
848
849 if (indices.empty())
850 return mlir::ArrayAttr{};
851 return cgm.getBuilder().getArrayAttr(indices);
852 }
853
854 /// Apply the value offset to the given constant.
855 ConstantLValue applyOffset(ConstantLValue &c) {
856 // Handle attribute constant LValues.
857 if (auto attr = mlir::dyn_cast<mlir::Attribute>(c.value)) {
858 if (auto gv = mlir::dyn_cast<cir::GlobalViewAttr>(attr)) {
859 auto baseTy = mlir::cast<cir::PointerType>(gv.getType()).getPointee();
860 mlir::Type destTy = cgm.getTypes().convertTypeForMem(destType);
861 assert(!gv.getIndices() && "Global view is already indexed");
862 std::optional<mlir::ArrayAttr> indices = getOffsetIndices(baseTy);
863 if (!indices)
864 return cir::GlobalOffsetAttr::get(
865 destTy, gv.getSymbol(), value.getLValueOffset().getQuantity());
866 return cir::GlobalViewAttr::get(destTy, gv.getSymbol(), *indices);
867 }
868 llvm_unreachable("Unsupported attribute type to offset");
869 }
870
871 cgm.errorNYI("ConstantLValue: non-attribute offset");
872 return {};
873 }
874};
875
876} // namespace
877
878mlir::Attribute ConstantLValueEmitter::tryEmit() {
879 const APValue::LValueBase &base = value.getLValueBase();
880
881 // The destination type should be a pointer or reference
882 // type, but it might also be a cast thereof.
883 //
884 // FIXME: the chain of casts required should be reflected in the APValue.
885 // We need this in order to correctly handle things like a ptrtoint of a
886 // non-zero null pointer and addrspace casts that aren't trivially
887 // represented in LLVM IR.
888 mlir::Type destTy = cgm.getTypes().convertTypeForMem(destType);
889 assert((mlir::isa<cir::PointerType>(destTy) ||
890 mlir::isa<cir::IntType>(destTy)) &&
891 "constant lvalue destination must be pointer or integer");
892
893 // If there's no base at all, this is a null or absolute pointer,
894 // possibly cast back to an integer type.
895 if (!base)
896 return tryEmitAbsolute(destTy);
897
898 // Otherwise, try to emit the base.
899 ConstantLValue result = tryEmitBase(base);
900
901 // If that failed, we're done.
902 llvm::PointerUnion<mlir::Value, mlir::Attribute> &value = result.value;
903 if (!value)
904 return {};
905
906 // Apply the offset if necessary and not already done.
907 if (!result.hasOffsetApplied)
908 value = applyOffset(result).value;
909
910 // CIR does not yet support signing constant lvalue initializers with pointer
911 // authentication. Classic CodeGen signs the offset-adjusted pointer here
912 // before the final pointer cast or ptrtoint conversion.
913 if (PointerAuthQualifier pointerAuth = destType.getPointerAuth()) {
914 cgm.errorNYI("ConstantLValueEmitter: pointer authentication");
915 return {};
916 }
917
918 // Convert to the appropriate type; this could be an lvalue for
919 // an integer. FIXME: performAddrSpaceCast
920 if (auto attr = mlir::dyn_cast<mlir::Attribute>(value)) {
921 if (auto gv = mlir::dyn_cast<cir::GlobalViewAttr>(attr))
922 return cir::GlobalViewAttr::get(destTy, gv.getSymbol(), gv.getIndices());
923
924 if (mlir::isa<cir::PointerType>(destTy))
925 return attr;
926 }
927
928 cgm.errorNYI("ConstantLValueEmitter: non-attribute pointer or integer");
929 return {};
930}
931
932/// Try to emit an absolute l-value, such as a null pointer or an integer
933/// bitcast to pointer type.
934mlir::Attribute ConstantLValueEmitter::tryEmitAbsolute(mlir::Type destTy) {
935 // If we're producing a pointer, this is easy.
936 auto destPtrTy = mlir::cast<cir::PointerType>(destTy);
937 return cgm.getBuilder().getConstPtrAttr(
938 destPtrTy, value.getLValueOffset().getQuantity());
939}
940
941ConstantLValue
942ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
943 // Handle values.
944 if (const ValueDecl *d = base.dyn_cast<const ValueDecl *>()) {
945 // The constant always points to the canonical declaration. We want to look
946 // at properties of the most recent declaration at the point of emission.
947 d = cast<ValueDecl>(d->getMostRecentDecl());
948
949 if (d->hasAttr<WeakRefAttr>()) {
950 cgm.errorNYI(d->getSourceRange(),
951 "ConstantLValueEmitter: emit pointer base for weakref");
952 return {};
953 }
954
955 if (auto *fd = dyn_cast<FunctionDecl>(d)) {
956 cir::FuncOp fop = cgm.getAddrOfFunction(fd);
957 CIRGenBuilderTy &builder = cgm.getBuilder();
958 mlir::MLIRContext *mlirContext = builder.getContext();
959 // Use the destination pointer type (e.g. struct field type), not
960 // fop.getFunctionType(), so initializers stay valid when a no-prototype
961 // FuncOp is later replaced by a prototyped definition with the same
962 // symbol. CIR allows the view type to differ from the symbol's type.
963 mlir::Type destTy = cgm.getTypes().convertTypeForMem(destType);
964 cir::PointerType ptrTy =
965 mlir::isa<cir::PointerType>(destTy)
966 ? mlir::cast<cir::PointerType>(destTy)
967 : cir::PointerType::get(fop.getFunctionType());
968 mlir::StringAttr symName = fop.getSymNameAttr();
969 // On the HIP host, the address of a kernel is the address of its kernel
970 // handle, not of its device stub. CUDA uses the device stub itself as
971 // the kernel handle.
972 if (cgm.getLangOpts().HIP && !cgm.getLangOpts().CUDAIsDevice &&
973 fd->hasAttr<CUDAGlobalAttr>())
974 symName = mlir::cast<cir::GlobalOp>(
975 cgm.getCUDARuntime().getKernelHandle(fop, fd))
976 .getSymNameAttr();
977 return cir::GlobalViewAttr::get(
978 ptrTy, mlir::FlatSymbolRefAttr::get(mlirContext, symName));
979 }
980
981 if (auto *vd = dyn_cast<VarDecl>(d)) {
982 // We can never refer to a variable with local storage.
983 if (!vd->hasLocalStorage()) {
984 if (vd->isFileVarDecl() || vd->hasExternalStorage())
985 return cgm.getAddrOfGlobalVarAttr(vd);
986
987 if (vd->isLocalVarDecl()) {
988 cir::GlobalLinkageKind linkage = cgm.getCIRLinkageVarDefinition(vd);
989 return cgm.getBuilder().getGlobalViewAttr(
990 cgm.getOrCreateStaticVarDecl(*vd, linkage));
991 }
992 }
993 }
994
995 if (isa<MSGuidDecl>(d))
996 cgm.errorNYI(d->getSourceRange(), "ConstantLValueEmitter: MSGuidDecl");
997
998 if (const auto *gcd = dyn_cast<UnnamedGlobalConstantDecl>(d))
999 return cgm.getBuilder().getGlobalViewAttr(
1001
1002 if (const auto *tpo = dyn_cast<TemplateParamObjectDecl>(d))
1003 return cgm.getBuilder().getGlobalViewAttr(
1005
1006 return {};
1007 }
1008
1009 // Handle typeid(T).
1010 if (TypeInfoLValue typeInfo = base.dyn_cast<TypeInfoLValue>())
1012 cgm.getBuilder().getUnknownLoc(), QualType(typeInfo.getType(), 0)));
1013
1014 // Otherwise, it must be an expression.
1015 return Visit(base.get<const Expr *>());
1016}
1017
1018ConstantLValue ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *e) {
1019 cgm.errorNYI(e->getSourceRange(), "ConstantLValueEmitter: constant expr");
1020 return {};
1021}
1022
1023static cir::GlobalViewAttr
1025 const CompoundLiteralExpr *e) {
1026 CIRGenModule &cgm = emitter.cgm;
1027 CIRGenBuilderTy &builder = cgm.getBuilder();
1029
1030 if (cir::GlobalOp addr = cgm.getAddrOfConstantCompoundLiteralIfEmitted(e))
1031 return builder.getGlobalViewAttr(addr);
1032
1034 mlir::Attribute c =
1035 emitter.tryEmitForInitializer(e->getInitializer(), e->getType());
1036 if (!c) {
1037 assert(!e->isFileScope() &&
1038 "file-scope compound literal did not have constant initializer!");
1039 return {};
1040 }
1041
1042 auto typedInit = mlir::cast<mlir::TypedAttr>(c);
1043 bool isConstant = e->getType().isConstantStorage(cgm.getASTContext(),
1044 /*ExcludeCtor=*/true,
1045 /*ExcludeDtor=*/false);
1046
1047 std::string name = cgm.getUniqueGlobalName(".compoundliteral");
1048 mlir::Location loc = cgm.getLoc(e->getSourceRange());
1049 cir::GlobalOp gv =
1050 cgm.createGlobalOp(loc, name, typedInit.getType(), isConstant);
1051 gv.setLinkage(cir::GlobalLinkageKind::InternalLinkage);
1052 gv.setAlignment(align.getAsAlign().value());
1054
1055 emitter.finalize(gv);
1057 return builder.getGlobalViewAttr(gv);
1058}
1059
1060ConstantLValue
1061ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *e) {
1062 ConstantEmitter compoundLiteralEmitter(cgm, emitter.cgf);
1063 compoundLiteralEmitter.setInConstantContext(emitter.isInConstantContext());
1064 return tryEmitGlobalCompoundLiteral(compoundLiteralEmitter, e);
1065}
1066
1067ConstantLValue
1068ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *e) {
1070}
1071
1072ConstantLValue
1073ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *e) {
1074 cgm.errorNYI(e->getSourceRange(), "ConstantLValueEmitter: objc encode expr");
1075 return {};
1076}
1077
1078ConstantLValue
1079ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *e) {
1080 cgm.errorNYI(e->getSourceRange(),
1081 "ConstantLValueEmitter: objc string literal");
1082 return {};
1083}
1084
1085ConstantLValue
1086ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *e) {
1087 cgm.errorNYI(e->getSourceRange(), "ConstantLValueEmitter: objc boxed expr");
1088 return {};
1089}
1090
1091ConstantLValue
1092ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *e) {
1094}
1095
1096ConstantLValue
1097ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *e) {
1098 // A label address taken in a constant context, e.g. a static computed-goto
1099 // dispatch table `static const void *tbl[] = {&&L1, &&L2}`. GotoSolver later
1100 // collects this block-address attribute (here, from a global initializer) so
1101 // the label survives and joins the indirect branch's successors. A label is
1102 // always function-local, so cgf is set here.
1103 assert(emitter.cgf && "label address in a constant requires a function");
1104 CIRGenFunction &cgf = *const_cast<CIRGenFunction *>(emitter.cgf);
1105 auto func = cast<cir::FuncOp>(cgf.curFn);
1106 return cir::BlockAddrInfoAttr::get(&cgf.getMLIRContext(), func.getSymName(),
1107 e->getLabel()->getName());
1108}
1109
1110ConstantLValue ConstantLValueEmitter::VisitCallExpr(const CallExpr *e) {
1111 cgm.errorNYI(e->getSourceRange(), "ConstantLValueEmitter: call expr");
1112 return {};
1113}
1114
1115ConstantLValue ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *e) {
1116 cgm.errorNYI(e->getSourceRange(), "ConstantLValueEmitter: block expr");
1117 return {};
1118}
1119
1120ConstantLValue
1121ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *e) {
1122 if (e->isTypeOperand())
1125 e->getTypeOperand(cgm.getASTContext())));
1127 cgm.getLoc(e->getSourceRange()), e->getExprOperand()->getType()));
1128}
1129
1130ConstantLValue ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1131 const MaterializeTemporaryExpr *e) {
1132 assert(e->getStorageDuration() == SD_Static);
1133 const Expr *inner = e->getSubExpr()->skipRValueSubobjectAdjustments();
1134 mlir::Operation *global = cgm.getAddrOfGlobalTemporary(e, inner);
1135 return ConstantLValue(
1136 cgm.getBuilder().getGlobalViewAttr(mlir::cast<cir::GlobalOp>(global)));
1137}
1138
1139//===----------------------------------------------------------------------===//
1140// ConstantEmitter
1141//===----------------------------------------------------------------------===//
1142
1144 initializeNonAbstract();
1145 return markIfFailed(tryEmitPrivateForVarInit(d));
1146}
1147
1149 QualType destType) {
1150 initializeNonAbstract();
1151 return markIfFailed(tryEmitPrivateForMemory(e, destType));
1152}
1153
1155 QualType destType) {
1156 initializeNonAbstract();
1157 auto c = tryEmitPrivateForMemory(value, destType);
1158 assert(c && "couldn't emit constant value non-abstractly?");
1159 return c;
1160}
1161
1162void ConstantEmitter::finalize(cir::GlobalOp gv) {
1163 assert(initializedNonAbstract &&
1164 "finalizing emitter that was used for abstract emission?");
1165 assert(!finalized && "finalizing emitter multiple times");
1166 assert(!gv.isDeclaration());
1167#ifndef NDEBUG
1168 // Note that we might also be Failed.
1169 finalized = true;
1170#endif // NDEBUG
1171}
1172
1173mlir::Attribute
1175 AbstractStateRAII state(*this, true);
1176 return tryEmitPrivateForVarInit(d);
1177}
1178
1180 assert((!initializedNonAbstract || finalized || failed) &&
1181 "not finalized after being initialized for non-abstract emission");
1182}
1183
1184static mlir::TypedAttr emitNullConstantForBase(CIRGenModule &cgm,
1185 mlir::Type baseType,
1186 const CXXRecordDecl *baseDecl);
1187
1188static mlir::TypedAttr emitNullConstant(CIRGenModule &cgm, const RecordDecl *rd,
1189 bool asCompleteObject) {
1190 const CIRGenRecordLayout &layout = cgm.getTypes().getCIRGenRecordLayout(rd);
1191 mlir::Type ty = (asCompleteObject ? layout.getCIRType()
1192 : layout.getBaseSubobjectCIRType());
1193 auto recordTy = mlir::cast<cir::RecordType>(ty);
1194
1195 unsigned numElements = rd->isUnion() ? 1 : recordTy.getNumElements();
1196 SmallVector<mlir::Attribute> elements(numElements);
1197
1198 auto *cxxrd = dyn_cast<CXXRecordDecl>(rd);
1199 // Fill in all the bases.
1200 if (cxxrd) {
1201 for (const CXXBaseSpecifier &base : cxxrd->bases()) {
1202 if (base.isVirtual()) {
1203 // Ignore virtual bases; if we're laying out for a complete
1204 // object, we'll lay these out later.
1205 continue;
1206 }
1207
1208 const auto *baseDecl = base.getType()->castAsCXXRecordDecl();
1209 // Ignore empty bases.
1211 base.getType()) ||
1212 cgm.getASTContext()
1213 .getASTRecordLayout(baseDecl)
1215 .isZero())
1216 continue;
1217
1218 unsigned fieldIndex = layout.getNonVirtualBaseCIRFieldNo(baseDecl);
1219 mlir::Type baseType = recordTy.getElementType(fieldIndex);
1220 elements[fieldIndex] = emitNullConstantForBase(cgm, baseType, baseDecl);
1221 }
1222 }
1223
1224 // Fill in all the fields.
1225 for (const FieldDecl *field : rd->fields()) {
1226 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1227 // will fill in later.)
1228 if (!field->isBitField() &&
1230 unsigned fieldIndex = layout.getCIRFieldNo(field);
1231 elements[fieldIndex] = cgm.emitNullConstantAttr(field->getType());
1232 }
1233
1234 // For unions, stop after the first named field.
1235 if (rd->isUnion()) {
1236 if (field->getIdentifier())
1237 break;
1238 if (const auto *fieldRD = field->getType()->getAsRecordDecl())
1239 if (fieldRD->findFirstNamedDataMember())
1240 break;
1241 }
1242 }
1243
1244 // Fill in the virtual bases, if we're working with the complete object.
1245 if (cxxrd && asCompleteObject) {
1246 for ([[maybe_unused]] const CXXBaseSpecifier &vbase : cxxrd->vbases()) {
1247 cgm.errorNYI(vbase.getSourceRange(), "emitNullConstant: virtual base");
1248 return {};
1249 }
1250 }
1251
1252 mlir::MLIRContext *mlirContext = recordTy.getContext();
1253
1254 // A union takes a single element, for whichever member stands in for the
1255 // active one.
1256 if (rd->isUnion()) {
1257 if (!elements[0])
1258 elements[0] =
1259 cgm.getBuilder().getZeroInitAttr(recordTy.getElementType(0));
1260 return cir::ConstRecordAttr::get(
1261 recordTy, mlir::ArrayAttr::get(mlirContext, elements));
1262 }
1263
1264 // Now go through all other fields and zero them out.
1266 if (!collectStoredInitializers(cgm.getBuilder(), recordTy, elements,
1267 storedElements))
1268 return {};
1269
1270 return cir::ConstRecordAttr::get(
1271 recordTy, mlir::ArrayAttr::get(mlirContext, storedElements));
1272}
1273
1274/// Emit the null constant for a base subobject.
1275static mlir::TypedAttr emitNullConstantForBase(CIRGenModule &cgm,
1276 mlir::Type baseType,
1277 const CXXRecordDecl *baseDecl) {
1278 const CIRGenRecordLayout &baseLayout =
1279 cgm.getTypes().getCIRGenRecordLayout(baseDecl);
1280
1281 // Just zero out bases that don't have any pointer to data members.
1282 if (baseLayout.isZeroInitializableAsBase())
1283 return cgm.getBuilder().getZeroInitAttr(baseType);
1284
1285 // Otherwise, we can just use its null constant.
1286 return emitNullConstant(cgm, baseDecl, /*asCompleteObject=*/false);
1287}
1288
1290 // Make a quick check if variable can be default NULL initialized
1291 // and avoid going through rest of code which may do, for c++11,
1292 // initialization of memory to all NULLs.
1293 if (!d.hasLocalStorage()) {
1294 QualType ty = cgm.getASTContext().getBaseElementType(d.getType());
1295 if (ty->isRecordType()) {
1296 if (const auto *e = dyn_cast_or_null<CXXConstructExpr>(d.getInit())) {
1297 const CXXConstructorDecl *cd = e->getConstructor();
1298 if (cd->isTrivial() && cd->isDefaultConstructor())
1299 return cgm.emitNullConstantAttr(d.getType());
1300 }
1301 }
1302 }
1303 inConstantContext = d.hasConstantInitialization();
1304
1305 const Expr *e = d.getInit();
1306 assert(e && "No initializer to emit");
1307
1308 QualType destType = d.getType();
1309
1310 if (!destType->isReferenceType()) {
1311 QualType nonMemoryDestType = getNonMemoryType(cgm, destType);
1312 if (mlir::Attribute c = ConstExprEmitter(*this).Visit(const_cast<Expr *>(e),
1313 nonMemoryDestType))
1314 return emitForMemory(c, destType);
1315 }
1316
1317 // Try to emit the initializer. Note that this can allow some things that
1318 // are not allowed by tryEmitPrivateForMemory alone.
1319 if (const APValue *value = d.evaluateValue())
1320 return tryEmitPrivateForMemory(*value, destType);
1321
1322 return {};
1323}
1324
1326 QualType destType) {
1327 AbstractStateRAII state{*this, true};
1328 return tryEmitPrivate(e, destType);
1329}
1330
1332 if (!ce->hasAPValueResult())
1333 return {};
1334
1335 QualType retType = ce->getType();
1336 if (ce->isGLValue())
1337 retType = cgm.getASTContext().getLValueReferenceType(retType);
1338
1339 return emitAbstract(ce->getBeginLoc(), ce->getAPValueResult(), retType);
1340}
1341
1343 QualType destType) {
1344 QualType nonMemoryDestType = getNonMemoryType(cgm, destType);
1345 mlir::TypedAttr c = tryEmitPrivate(e, nonMemoryDestType);
1346 if (c) {
1347 mlir::Attribute attr = emitForMemory(c, destType);
1348 return mlir::cast<mlir::TypedAttr>(attr);
1349 }
1350 return nullptr;
1351}
1352
1354 QualType destType) {
1355 QualType nonMemoryDestType = getNonMemoryType(cgm, destType);
1356 mlir::Attribute c = tryEmitPrivate(value, nonMemoryDestType);
1357 return (c ? emitForMemory(c, destType) : nullptr);
1358}
1359
1360mlir::Attribute ConstantEmitter::emitAbstract(const Expr *e,
1361 QualType destType) {
1362 AbstractStateRAII state{*this, true};
1363 mlir::Attribute c = mlir::cast<mlir::Attribute>(tryEmitPrivate(e, destType));
1364 if (!c)
1365 cgm.errorNYI(e->getSourceRange(),
1366 "emitAbstract failed, emit null constaant");
1367 return c;
1368}
1369
1371 const APValue &value,
1372 QualType destType) {
1373 AbstractStateRAII state(*this, true);
1374 mlir::Attribute c = tryEmitPrivate(value, destType);
1375 if (!c)
1376 cgm.errorNYI(loc, "emitAbstract failed, emit null constaant");
1377 return c;
1378}
1379
1380mlir::Attribute ConstantEmitter::emitNullForMemory(mlir::Location loc,
1382 QualType t) {
1383 cir::ConstantOp cstOp =
1384 cgm.emitNullConstant(t, loc).getDefiningOp<cir::ConstantOp>();
1385 assert(cstOp && "expected cir.const op");
1386 return emitForMemory(cgm, cstOp.getValue(), t);
1387}
1388
1389mlir::Attribute ConstantEmitter::emitForMemory(mlir::Attribute c,
1390 QualType destType) {
1391 return emitForMemory(cgm, c, destType);
1392}
1393
1395 mlir::Attribute c,
1396 QualType destType) {
1397 // For an _Atomic-qualified constant, we may need to add tail padding.
1398 if (const auto *at = destType->getAs<AtomicType>()) {
1399 QualType destValueType = at->getValueType();
1400 c = emitForMemory(cgm, c, destValueType);
1401
1402 uint64_t innerSize = cgm.getASTContext().getTypeSize(destValueType);
1403 uint64_t outerSize = cgm.getASTContext().getTypeSize(destType);
1404 if (innerSize == outerSize)
1405 return c;
1406
1407 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1408 cgm.errorNYI("emitForMemory: tail padding in atomic initializer");
1409 }
1410
1411 // In HLSL bool vectors are stored in memory as a vector of i32
1412 if (destType->isExtVectorBoolType() &&
1413 !destType->isPackedVectorBoolType(cgm.getASTContext())) {
1414 cgm.errorNYI("emitForMemory: zero-extend HLSL bool vectors");
1415 }
1416
1417 // CIR represents source types as literally as possible. Some types, such as
1418 // bool and _BitInt(N), are kept at their literal width here and expanded to
1419 // their wider "in memory" types during lowering to the LLVM dialect, so the
1420 // constant is already in the right form and needs no adjustment.
1421
1422 return c;
1423}
1424
1425mlir::TypedAttr ConstantEmitter::tryEmitPrivate(const Expr *e,
1426 QualType destType) {
1427 assert(!destType->isVoidType() && "can't emit a void constant");
1428
1429 if (mlir::Attribute c =
1430 ConstExprEmitter(*this).Visit(const_cast<Expr *>(e), destType))
1431 return llvm::dyn_cast<mlir::TypedAttr>(c);
1432
1433 Expr::EvalResult result;
1434
1435 bool success = false;
1436
1437 if (destType->isReferenceType())
1438 success = e->EvaluateAsLValue(result, cgm.getASTContext());
1439 else
1440 success =
1441 e->EvaluateAsRValue(result, cgm.getASTContext(), inConstantContext);
1442
1443 if (success && !result.hasSideEffects()) {
1444 mlir::Attribute c = tryEmitPrivate(result.Val, destType);
1445 return llvm::dyn_cast<mlir::TypedAttr>(c);
1446 }
1447
1448 return nullptr;
1449}
1450
1451mlir::Attribute ConstantEmitter::tryEmitPrivate(const APValue &value,
1452 QualType destType) {
1453 auto &builder = cgm.getBuilder();
1454 switch (value.getKind()) {
1455 case APValue::None:
1457 cgm.errorNYI("ConstExprEmitter::tryEmitPrivate none or indeterminate");
1458 return {};
1459 case APValue::Int: {
1460 mlir::Type ty = cgm.convertType(destType);
1461 if (mlir::isa<cir::BoolType>(ty))
1462 return builder.getCIRBoolAttr(value.getInt().getZExtValue());
1463 assert(mlir::isa<cir::IntType>(ty) && "expected integral type");
1464 return cir::IntAttr::get(ty, value.getInt());
1465 }
1466 case APValue::Float: {
1467 mlir::Type ty = cgm.convertType(destType);
1468 assert(mlir::isa<cir::FPTypeInterface>(ty) &&
1469 "expected floating-point type");
1470 return cir::FPAttr::get(ty, value.getFloat());
1471 }
1472 case APValue::Array: {
1473 const ArrayType *arrayTy = cgm.getASTContext().getAsArrayType(destType);
1474 const QualType arrayElementTy = arrayTy->getElementType();
1475 const unsigned numElements = value.getArraySize();
1476 const unsigned numInitElts = value.getArrayInitializedElts();
1477
1478 mlir::TypedAttr filler;
1479 if (value.hasArrayFiller()) {
1480 mlir::Attribute fillerTemp =
1481 tryEmitPrivate(value.getArrayFiller(), arrayElementTy);
1482 if (!fillerTemp)
1483 return {};
1484 filler = dyn_cast<mlir::TypedAttr>(fillerTemp);
1485 if (!filler) {
1486 cgm.errorNYI("ConstExprEmitter::tryEmitPrivate array filler should "
1487 "always be typed");
1488 return {};
1489 }
1490 }
1491
1492 CIRGenBuilderTy &builder = cgm.getBuilder();
1493 cir::ArrayType desiredType =
1494 cast<cir::ArrayType>(cgm.convertType(destType));
1495
1497 if (!filler || builder.isNullValue(filler))
1498 elts.reserve(numInitElts);
1499 else
1500 elts.reserve(numElements);
1501
1502 // Fill in the known values.
1503 for (unsigned i = 0; i < numInitElts; ++i) {
1504 const APValue &arrayElement = value.getArrayInitializedElt(i);
1505 const mlir::Attribute element =
1506 tryEmitPrivateForMemory(arrayElement, arrayElementTy);
1507 if (!element)
1508 return {};
1509
1510 elts.push_back(element);
1511 }
1512
1513 // If we have an actual value we have to insert for the filler, do so now.
1514 if (filler && !builder.isNullValue(filler))
1515 elts.insert(elts.end(), numElements - elts.size(), filler);
1516
1517 // Remove all null values at the end, so they become 'trailing zeroes'.
1518 while (!elts.empty() && builder.isNullValue(elts.back()))
1519 elts.pop_back();
1520
1521 // For flexible array members, we need to adjust the size of our result to
1522 // match this.
1523 if (desiredType.getSize() == 0 && numElements > 0) {
1524 desiredType =
1525 cir::ArrayType::get(desiredType.getElementType(), numElements);
1526 }
1527
1528 if (elts.empty())
1529 return cir::ZeroAttr::get(desiredType);
1530
1531 return cir::ConstArrayAttr::get(
1532 desiredType, mlir::ArrayAttr::get(builder.getContext(), elts));
1533 }
1534 case APValue::Vector: {
1535 const QualType elementType =
1536 destType->castAs<VectorType>()->getElementType();
1537 const unsigned numElements = value.getVectorLength();
1538
1540 elements.reserve(numElements);
1541
1542 for (unsigned i = 0; i < numElements; ++i) {
1543 const mlir::Attribute element =
1544 tryEmitPrivateForMemory(value.getVectorElt(i), elementType);
1545 if (!element)
1546 return {};
1547 elements.push_back(element);
1548 }
1549
1550 const auto desiredVecTy =
1551 mlir::cast<cir::VectorType>(cgm.convertType(destType));
1552
1553 return cir::ConstVectorAttr::get(
1554 desiredVecTy,
1555 mlir::ArrayAttr::get(cgm.getBuilder().getContext(), elements));
1556 }
1559
1560 const ValueDecl *memberDecl = value.getMemberPointerDecl();
1561 if (!memberDecl)
1562 return builder.getZeroInitAttr(cgm.convertType(destType));
1563
1564 if (auto const *cxxDecl = dyn_cast<CXXMethodDecl>(memberDecl)) {
1565 auto ty = mlir::cast<cir::MethodType>(cgm.convertType(destType));
1566 if (cxxDecl->isVirtual())
1567 return cgm.getCXXABI().buildVirtualMethodAttr(ty, cxxDecl);
1568
1569 cir::FuncOp methodFuncOp =
1570 cgm.getAddrOfFunction(cxxDecl, ty.getMemberFuncTy());
1571 return cgm.getBuilder().getMethodAttr(ty, methodFuncOp);
1572 }
1573
1574 auto cirTy = mlir::cast<cir::DataMemberType>(cgm.convertType(destType));
1575 const auto *mpt = destType->castAs<MemberPointerType>();
1576 const auto *destClass = mpt->getMostRecentCXXRecordDecl();
1577
1578 // Empty [[no_unique_address]] fields have no CIR field index; represent the
1579 // pointer-to-data-member by its concrete byte offset.
1580 if (const auto *fieldDecl = dyn_cast<FieldDecl>(memberDecl);
1581 fieldDecl && cgm.isEmptyFieldForMemberPointer(fieldDecl)) {
1582 const ASTContext &astContext = cgm.getASTContext();
1583 CharUnits offset =
1584 astContext.getMemberPointerPathAdjustment(value) +
1585 astContext.toCharUnitsFromBits(astContext.getFieldOffset(fieldDecl));
1586 return cir::DataMemberOffsetAttr::get(cirTy, offset.getQuantity());
1587 }
1588
1589 std::optional<llvm::SmallVector<int32_t>> path =
1590 cgm.buildMemberPath(destClass, memberDecl);
1591 if (!path)
1592 return {};
1593 return builder.getDataMemberAttr(cirTy, *path);
1594 }
1595 case APValue::LValue:
1596 return ConstantLValueEmitter(*this, value, destType).tryEmit();
1597 case APValue::Struct:
1598 case APValue::Union:
1599 return ConstRecordBuilder::buildRecord(*this, value, destType);
1601 case APValue::ComplexFloat: {
1602 mlir::Type desiredType = cgm.convertType(destType);
1603 auto complexType = mlir::dyn_cast<cir::ComplexType>(desiredType);
1604
1605 mlir::Type complexElemTy = complexType.getElementType();
1606 if (isa<cir::IntType>(complexElemTy)) {
1607 const llvm::APSInt &real = value.getComplexIntReal();
1608 const llvm::APSInt &imag = value.getComplexIntImag();
1609 return cir::ConstComplexAttr::get(builder.getContext(), complexType,
1610 cir::IntAttr::get(complexElemTy, real),
1611 cir::IntAttr::get(complexElemTy, imag));
1612 }
1613
1614 assert(isa<cir::FPTypeInterface>(complexElemTy) &&
1615 "expected floating-point type");
1616 const llvm::APFloat &real = value.getComplexFloatReal();
1617 const llvm::APFloat &imag = value.getComplexFloatImag();
1618 return cir::ConstComplexAttr::get(builder.getContext(), complexType,
1619 cir::FPAttr::get(complexElemTy, real),
1620 cir::FPAttr::get(complexElemTy, imag));
1621 }
1622 case APValue::FixedPoint: {
1623 mlir::Type ty = cgm.convertType(destType);
1624 return cir::IntAttr::get(ty, value.getFixedPoint().getValue());
1625 }
1627 const AddrLabelExpr *lhsExpr = value.getAddrLabelDiffLHS();
1628 const AddrLabelExpr *rhsExpr = value.getAddrLabelDiffRHS();
1629
1630 // Both labels belong to the function currently being emitted. The actual
1631 // subtraction (ptrtoint of each block address, subtract, then truncate to
1632 // the result type) is deferred to the LowerToLLVM pass, which is where
1633 // block addresses are resolved to concrete basic blocks.
1634 mlir::Type resultType = cgm.getTypes().convertType(destType);
1635 auto intResultType = mlir::cast<cir::IntType>(resultType);
1636 auto func = cast<cir::FuncOp>(cgf->curFn);
1637 return cir::BlockAddrDiffAttr::get(
1638 builder.getContext(), intResultType, func.getSymName(),
1639 lhsExpr->getLabel()->getName(), rhsExpr->getLabel()->getName());
1640 }
1641
1642 case APValue::Matrix:
1643 cgm.errorNYI("ConstExprEmitter::tryEmitPrivate matrix");
1644 return {};
1645
1647 llvm_unreachable("std::meta::info is consteval-only type");
1648 }
1649 llvm_unreachable("Unknown APValue kind");
1650}
1651
1652mlir::Value CIRGenModule::emitNullConstant(QualType t, mlir::Location loc) {
1653 return builder.getConstant(loc, emitNullConstantAttr(t));
1654}
1655
1656mlir::Value CIRGenModule::getNullPointer(cir::PointerType ptrTy, QualType qt,
1657 mlir::Location loc) {
1658 return getTargetCIRGenInfo().getNullPointer(*this, ptrTy, qt, loc);
1659}
1660
1662 if (t->getAs<PointerType>())
1663 return builder.getConstNullPtrAttr(getTypes().convertTypeForMem(t));
1664
1665 if (getTypes().isZeroInitializable(t))
1666 return builder.getZeroInitAttr(getTypes().convertTypeForMem(t));
1667
1668 if (const ConstantArrayType *cat =
1669 getASTContext().getAsConstantArrayType(t)) {
1670 QualType elementTy = cat->getElementType();
1671 mlir::TypedAttr elementAttr = emitNullConstantAttr(elementTy);
1672 if (!elementAttr)
1673 return {};
1674
1675 auto arrayTy = mlir::cast<cir::ArrayType>(getTypes().convertTypeForMem(t));
1676
1677 if (builder.isNullValue(elementAttr))
1678 return cir::ZeroAttr::get(arrayTy);
1679
1680 llvm::SmallVector<mlir::Attribute> elements(cat->getZExtSize(),
1681 elementAttr);
1682 return cir::ConstArrayAttr::get(
1683 arrayTy, mlir::ArrayAttr::get(builder.getContext(), elements));
1684 }
1685
1686 if (const RecordType *rt = t->getAs<RecordType>())
1687 return ::emitNullConstant(*this, rt->getDecl(), /*asCompleteObject=*/true);
1688
1689 assert(t->isMemberDataPointerType() &&
1690 "Should only see pointers to data members here!");
1691
1693}
1694
1695mlir::TypedAttr
1697 return ::emitNullConstant(*this, record, false);
1698}
Defines the clang::ASTContext interface.
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines enum values for all the target-independent builtin functions.
static bool emit(llvm::SmallVectorImpl< std::byte > &Code, const T &Val)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static QualType getNonMemoryType(CodeGenModule &CGM, QualType type)
static mlir::TypedAttr emitNullConstant(CIRGenModule &cgm, const RecordDecl *rd, bool asCompleteObject)
static mlir::TypedAttr emitNullConstantForBase(CIRGenModule &cgm, mlir::Type baseType, const CXXRecordDecl *baseDecl)
Emit the null constant for a base subobject.
static bool collectStoredInitializers(CIRGenBuilderTy &builder, cir::RecordType recordTy, llvm::ArrayRef< mlir::Attribute > elements, llvm::SmallVectorImpl< mlir::Attribute > &stored)
Collects the initializer elements for the members of recordTy that are stored, in order,...
static cir::GlobalViewAttr tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter, const CompoundLiteralExpr *e)
static ParseState advance(ParseState S, size_t N)
Definition Parsing.cpp:137
cir::GlobalViewAttr getGlobalViewAttr(cir::GlobalOp globalOp, mlir::ArrayAttr indices={})
Get constant address of a global variable as an MLIR attribute.
cir::BoolAttr getCIRBoolAttr(bool state)
mlir::TypedAttr getZeroInitAttr(mlir::Type ty)
mlir::TypedAttr getConstPtrAttr(mlir::Type type, int64_t value)
bool isBigEndian() const
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:150
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:649
size_t getNumElements() const
Definition CIRTypes.h:188
QualType getType() const
Definition APValue.cpp:123
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool hasArrayFiller() const
Definition APValue.h:699
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:691
APSInt & getInt()
Definition APValue.h:573
APSInt & getComplexIntImag()
Definition APValue.h:611
ValueKind getKind() const
Definition APValue.h:537
unsigned getArrayInitializedElts() const
Definition APValue.h:710
APFixedPoint & getFixedPoint()
Definition APValue.h:595
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
const AddrLabelExpr * getAddrLabelDiffRHS() const
Definition APValue.h:777
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
APValue & getArrayFiller()
Definition APValue.h:702
unsigned getVectorLength() const
Definition APValue.h:655
unsigned getArraySize() const
Definition APValue.h:714
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
const AddrLabelExpr * getAddrLabelDiffLHS() const
Definition APValue.h:773
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4619
LabelDecl * getLabel() const
Definition Expr.h:4642
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
cir::DataMemberAttr getDataMemberAttr(cir::DataMemberType ty, llvm::ArrayRef< int32_t > path)
mlir::Attribute getConstRecordOrZeroAttr(mlir::ArrayAttr arrayAttr, cir::RecordType recordTy)
bool isNullValue(mlir::Attribute attr) const
cir::IntType getUIntNTy(int n)
virtual mlir::Operation * getKernelHandle(cir::FuncOp fn, GlobalDecl gd)=0
virtual cir::GlobalViewAttr getVTableAddressPointAttr(BaseSubobject base, const CXXRecordDecl *vtableClass)=0
Get the address point of the vtable for the given base subobject as a constant suitable for a global ...
mlir::Operation * curFn
The current function or global initializer that is generated code for.
mlir::MLIRContext & getMLIRContext()
This class organizes the cross-function state that is used while generating CIR code.
cir::GlobalOp getAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *gcd)
mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt, mlir::Location loc)
Get target specific null pointer.
cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd)
clang::ASTContext & getASTContext() const
CIRGenCUDARuntime & getCUDARuntime()
CIRGenBuilderTy & getBuilder()
std::string getUniqueGlobalName(const std::string &baseName)
cir::GlobalOp getAddrOfTemplateParamObject(const TemplateParamObjectDecl *tpo)
Get the GlobalOp of a template parameter object.
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record)
Return a null constant appropriate for zero-initializing a base class with the given type.
const cir::CIRDataLayout & getDataLayout() const
cir::FuncOp getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType=nullptr, bool forVTable=false, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
Return the address of the given function.
mlir::TypedAttr emitNullConstantAttr(QualType t)
mlir::Operation * getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte, const Expr *init)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
static void setInitializer(cir::GlobalOp &op, mlir::Attribute value)
cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d)
Return the mlir::GlobalViewAttr for the address of the given global.
const clang::LangOptions & getLangOpts() const
cir::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
const TargetCIRGenInfo & getTargetCIRGenInfo()
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt)
Returns a null attribute to represent either a null method or null data member, depending on the type...
cir::GlobalOp getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *e)
mlir::Value emitNullConstant(QualType t, mlir::Location loc)
Return the result of value-initializing the given type, i.e.
CIRGenCXXABI & getCXXABI() const
cir::GlobalViewAttr getAddrOfConstantStringFromLiteral(const StringLiteral *s, llvm::StringRef name=".str")
Return a global symbol reference to a constant array for the given string literal.
void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *e, cir::GlobalOp gv)
This class handles record and union layout info while lowering AST types to CIR types.
cir::RecordType getCIRType() const
Return the "complete object" LLVM type associated with this record.
cir::RecordType getBaseSubobjectCIRType() const
Return the "base subobject" LLVM type associated with this record.
bool hasNonVirtualBaseCIRField(const CXXRecordDecl *rd) const
const CIRGenBitFieldInfo & getBitFieldInfo(const clang::FieldDecl *fd) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getCIRFieldNo(const clang::FieldDecl *fd) const
Return cir::RecordType element number that corresponds to the field FD.
bool hasCIRField(const clang::FieldDecl *fd) const
bool isZeroInitializableAsBase() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer when considered as a bas...
unsigned getNonVirtualBaseCIRFieldNo(const CXXRecordDecl *rd) const
const CIRGenRecordLayout & getCIRGenRecordLayout(const clang::RecordDecl *rd)
Return record layout info for the given record decl.
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
mlir::Attribute emitForMemory(mlir::Attribute c, QualType destType)
mlir::Attribute emitNullForMemory(mlir::Location loc, QualType t)
mlir::TypedAttr tryEmitPrivate(const Expr *e, QualType destType)
mlir::Attribute tryEmitPrivateForVarInit(const VarDecl &d)
mlir::Attribute tryEmitPrivateForMemory(const Expr *e, QualType destTy)
mlir::Attribute emitAbstract(const Expr *e, QualType destType)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
mlir::Attribute tryEmitAbstract(const Expr *e, QualType destType)
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.
mlir::Attribute emitForInitializer(const APValue &value, QualType destType)
mlir::Attribute tryEmitConstantExpr(const ConstantExpr *ce)
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isTypeOperand() const
Definition ExprCXX.h:889
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:168
Expr * getExprOperand() const
Definition ExprCXX.h:900
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprCXX.h:907
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
APValue getAPValueResult() const
Definition Expr.cpp:419
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1177
bool hasAPValueResult() const
Definition Expr.h:1202
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4994
This represents one expression.
Definition Expr.h:114
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:289
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3311
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3414
bool isZeroSize(const ASTContext &Ctx) const
Determine if this field is a subobject of zero size, that is, either a zero-length bit-field or a fie...
Definition Decl.cpp:4857
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3417
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition Decl.cpp:4895
const Expr * getSubExpr() const
Definition Expr.h:1107
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2516
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5845
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:189
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:467
const Expr * getSubExpr() const
Definition Expr.h:2268
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
StringLiteral * getFunctionName()
Definition Expr.h:2118
A (possibly-)qualified type.
Definition TypeBase.h:938
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1037
Represents a struct/union/class.
Definition Decl.h:4476
field_range fields() const
Definition Decl.h:4679
Encodes a location in the source.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isUnion() const
Definition Decl.h:4079
bool isVoidType() const
Definition TypeBase.h:9068
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
bool isArrayType() const
Definition TypeBase.h:8782
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isExtVectorBoolType() const
Definition TypeBase.h:8830
bool isMemberDataPointerType() const
Definition TypeBase.h:8775
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isVectorType() const
Definition TypeBase.h:8822
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isRecordType() const
Definition TypeBase.h:8810
Expr * getSubExpr() const
Definition Expr.h:2354
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2661
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2568
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
Represents a GCC generic vector type.
Definition TypeBase.h:4273
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:135
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:126
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
bool isEmptyRecordForLayout(const ASTContext &Ctx, QualType T)
Return true iff a structure contains only empty base classes (per isEmptyRecordForLayout) and fields ...
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ComplexType > complexType
const internal::VariadicDynCastAllOfMatcher< Decl, FieldDecl > fieldDecl
Matches field declarations.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
inits_range inits()
U cast(CodeGen::Address addr)
Definition Address.h:327
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
static bool ctorConstLvalueToRvalueConversion()
static bool addressSpace()
static bool addressPointerAuthInfo()
static bool constEmitterArrayILE()
static bool constEmitterVectorILE()
Record with information about how a bitfield should be accessed.
unsigned offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the c...
unsigned storageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned size
The total size of the bit-field, in bits.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Definition Expr.h:661