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