12#include "mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc"
13#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc"
14#include "mlir/IR/PatternMatch.h"
15#include "mlir/Interfaces/DataLayoutInterfaces.h"
16#include "mlir/Pass/Pass.h"
17#include "mlir/Transforms/DialectConversion.h"
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/ADT/TypeSwitch.h"
34#define GEN_PASS_DEF_CXXABILOWERING
35#include "clang/CIR/Dialect/Passes.h.inc"
42bool isCXXABIAttributeLegal(
const mlir::TypeConverter &tc,
43 mlir::Attribute
attr) {
50 if (isa<mlir::acc::OpenACCDialect, mlir::omp::OpenMPDialect>(
56 if (
isa<mlir::DenseArrayAttr, mlir::FloatAttr, mlir::UnitAttr,
57 mlir::StringAttr, mlir::IntegerAttr, mlir::SymbolRefAttr,
58 cir::AnnotationAttr>(
attr))
64#include
"clang/CIR/Dialect/IR/CIRLowering.inc"
70 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
74 return llvm::TypeSwitch<mlir::Attribute, bool>(
attr)
77 [&tc](cir::ZeroAttr za) {
return tc.isLegal(za.getType()); })
78 .Case<cir::PoisonAttr>(
79 [&tc](cir::PoisonAttr pa) {
return tc.isLegal(pa.getType()); })
80 .Case<cir::UndefAttr>(
81 [&tc](cir::UndefAttr uda) {
return tc.isLegal(uda.getType()); })
82 .Case<mlir::TypeAttr>(
83 [&tc](mlir::TypeAttr ta) {
return tc.isLegal(ta.getValue()); })
84 .Case<cir::ConstPtrAttr>(
85 [&tc](cir::ConstPtrAttr cpa) {
return tc.isLegal(cpa.getType()); })
86 .Case<cir::CXXCtorAttr>(
87 [&tc](cir::CXXCtorAttr ca) {
return tc.isLegal(ca.getType()); })
88 .Case<cir::CXXDtorAttr>(
89 [&tc](cir::CXXDtorAttr da) {
return tc.isLegal(da.getType()); })
90 .Case<cir::CXXAssignAttr>(
91 [&tc](cir::CXXAssignAttr aa) {
return tc.isLegal(aa.getType()); })
95 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
96 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute
attr) {
97 return isCXXABIAttributeLegal(tc, attr);
100 .Case<mlir::DictionaryAttr>([&tc](mlir::DictionaryAttr dict) {
101 return llvm::all_of(dict.getValue(), [&tc](mlir::NamedAttribute na) {
102 return isCXXABIAttributeLegal(tc, na.getValue());
106 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
107 return tc.isLegal(array.getType()) &&
108 isCXXABIAttributeLegal(tc, array.getElts());
110 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
111 return tc.isLegal(gva.getType()) &&
112 isCXXABIAttributeLegal(tc, gva.getIndices());
114 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
115 return tc.isLegal(vta.getType()) &&
116 isCXXABIAttributeLegal(tc, vta.getData());
118 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
119 return tc.isLegal(tia.getType()) &&
120 isCXXABIAttributeLegal(tc, tia.getData());
122 .Case<cir::DynamicCastInfoAttr>([&tc](cir::DynamicCastInfoAttr dcia) {
123 return isCXXABIAttributeLegal(tc, dcia.getSrcRtti()) &&
124 isCXXABIAttributeLegal(tc, dcia.getDestRtti()) &&
125 isCXXABIAttributeLegal(tc, dcia.getRuntimeFunc()) &&
126 isCXXABIAttributeLegal(tc, dcia.getBadCastFunc());
128 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
129 return tc.isLegal(cra.getType()) &&
130 isCXXABIAttributeLegal(tc, cra.getMembers());
141mlir::Attribute rewriteAttribute(
const mlir::TypeConverter &tc,
142 mlir::MLIRContext *ctx, mlir::Attribute attr) {
145 if (isCXXABIAttributeLegal(tc, attr))
153 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
155 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
156 return cir::ZeroAttr::get(tc.convertType(za.getType()));
158 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
159 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
161 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
162 return cir::UndefAttr::get(tc.convertType(uda.getType()));
164 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
165 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
167 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
168 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
171 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
172 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
173 ca.getCtorKind(), ca.getIsTrivial());
175 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
176 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
179 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
180 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
181 aa.getAssignKind(), aa.getIsTrivial());
185 .Case<mlir::ArrayAttr>([&tc, ctx](mlir::ArrayAttr array) {
187 for (mlir::Attribute a : array.getValue())
188 elts.push_back(rewriteAttribute(tc, ctx, a));
189 return mlir::ArrayAttr::get(ctx, elts);
191 .Case<mlir::DictionaryAttr>([&tc, ctx](mlir::DictionaryAttr dict) {
193 for (mlir::NamedAttribute na : dict.getValue())
194 elts.emplace_back(na.getName(),
195 rewriteAttribute(tc, ctx, na.getValue()));
197 return mlir::DictionaryAttr::get(ctx, elts);
200 .Case<cir::ConstArrayAttr>([&tc, ctx](cir::ConstArrayAttr array) {
201 return cir::ConstArrayAttr::get(
202 ctx, tc.convertType(array.getType()),
203 rewriteAttribute(tc, ctx, array.getElts()),
204 array.getTrailingZerosNum());
206 .Case<cir::GlobalViewAttr>([&tc, ctx](cir::GlobalViewAttr gva) {
207 return cir::GlobalViewAttr::get(
208 tc.convertType(gva.getType()), gva.getSymbol(),
209 mlir::cast<mlir::ArrayAttr>(
210 rewriteAttribute(tc, ctx, gva.getIndices())));
212 .Case<cir::VTableAttr>([&tc, ctx](cir::VTableAttr vta) {
213 return cir::VTableAttr::get(
214 tc.convertType(vta.getType()),
215 mlir::cast<mlir::ArrayAttr>(
216 rewriteAttribute(tc, ctx, vta.getData())));
218 .Case<cir::TypeInfoAttr>([&tc, ctx](cir::TypeInfoAttr tia) {
219 return cir::TypeInfoAttr::get(
220 tc.convertType(tia.getType()),
221 mlir::cast<mlir::ArrayAttr>(
222 rewriteAttribute(tc, ctx, tia.getData())));
224 .Case<cir::DynamicCastInfoAttr>([&tc,
225 ctx](cir::DynamicCastInfoAttr dcia) {
226 return cir::DynamicCastInfoAttr::get(
227 mlir::cast<cir::GlobalViewAttr>(
228 rewriteAttribute(tc, ctx, dcia.getSrcRtti())),
229 mlir::cast<cir::GlobalViewAttr>(
230 rewriteAttribute(tc, ctx, dcia.getDestRtti())),
231 dcia.getRuntimeFunc(), dcia.getBadCastFunc(), dcia.getOffsetHint());
233 .Case<cir::ConstRecordAttr>([&tc, ctx](cir::ConstRecordAttr cra) {
234 return cir::ConstRecordAttr::get(
235 ctx, tc.convertType(cra.getType()),
236 mlir::cast<mlir::ArrayAttr>(
237 rewriteAttribute(tc, ctx, cra.getMembers())));
239 .DefaultUnreachable(
"unrewritten illegal attribute kind");
242#define GET_ABI_LOWERING_PATTERNS
243#include "clang/CIR/Dialect/IR/CIRLowering.inc"
244#undef GET_ABI_LOWERING_PATTERNS
246struct CXXABILoweringPass
247 :
public impl::CXXABILoweringBase<CXXABILoweringPass> {
248 CXXABILoweringPass() =
default;
249 void runOnOperation()
override;
257class CIRGenericCXXABILoweringPattern :
public mlir::ConversionPattern {
259 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
260 const mlir::TypeConverter &typeConverter)
261 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
265 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
266 mlir::ConversionPatternRewriter &rewriter)
const override {
268 if (llvm::isa<cir::AllocaOp, cir::BaseDataMemberOp, cir::BaseMethodOp,
269 cir::CastOp, cir::CmpOp, cir::ConstantOp, cir::DeleteArrayOp,
270 cir::DerivedDataMemberOp, cir::DerivedMethodOp, cir::FuncOp,
271 cir::GetMethodOp, cir::GetRuntimeMemberOp, cir::GlobalOp>(op))
272 return mlir::failure();
274 const mlir::TypeConverter *typeConverter = getTypeConverter();
275 assert(typeConverter &&
276 "CIRGenericCXXABILoweringPattern requires a type converter");
277 bool operandsAndResultsLegal = typeConverter->isLegal(op);
279 std::all_of(op->getRegions().begin(), op->getRegions().end(),
280 [typeConverter](mlir::Region ®ion) {
281 return typeConverter->isLegal(®ion);
284 llvm::all_of(op->getAttrs(), [typeConverter](mlir::NamedAttribute na) {
285 return isCXXABIAttributeLegal(*typeConverter, na.getValue());
288 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
291 return mlir::failure();
294 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
295 loweredOpState.addOperands(operands);
296 loweredOpState.addSuccessors(op->getSuccessors());
299 llvm::SmallVector<mlir::NamedAttribute> attrs;
300 for (
const mlir::NamedAttribute &na : op->getAttrs())
303 rewriteAttribute(*typeConverter, op->getContext(), na.getValue())});
304 loweredOpState.addAttributes(attrs);
307 llvm::SmallVector<mlir::Type> loweredResultTypes;
308 loweredResultTypes.reserve(op->getNumResults());
309 for (mlir::Type result : op->getResultTypes())
310 loweredResultTypes.push_back(typeConverter->convertType(result));
311 loweredOpState.addTypes(loweredResultTypes);
314 for (mlir::Region ®ion : op->getRegions()) {
315 mlir::Region *loweredRegion = loweredOpState.addRegion();
316 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
318 rewriter.convertRegionTypes(loweredRegion, *getTypeConverter())))
319 return mlir::failure();
323 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
325 rewriter.replaceOp(op, loweredOp);
326 return mlir::success();
332mlir::LogicalResult CIRAllocaOpABILowering::matchAndRewrite(
333 cir::AllocaOp op, OpAdaptor adaptor,
334 mlir::ConversionPatternRewriter &rewriter)
const {
335 mlir::Type allocaPtrTy = op.getType();
336 mlir::Type loweredAllocaPtrTy = getTypeConverter()->convertType(allocaPtrTy);
338 cir::AllocaOp loweredOp = cir::AllocaOp::create(
339 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
340 op.getAlignmentAttr(), adaptor.getDynAllocSize());
341 loweredOp.setInit(op.getInit());
342 loweredOp.setConstant(op.getConstant());
343 loweredOp.setAnnotationsAttr(op.getAnnotationsAttr());
345 rewriter.replaceOp(op, loweredOp);
346 return mlir::success();
349mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
350 cir::CastOp op, OpAdaptor adaptor,
351 mlir::ConversionPatternRewriter &rewriter)
const {
352 mlir::Type srcTy = op.getSrc().getType();
354 if (mlir::isa<cir::DataMemberType, cir::MethodType>(srcTy)) {
355 switch (op.getKind()) {
356 case cir::CastKind::bitcast: {
357 mlir::Type destTy = getTypeConverter()->convertType(op.getType());
358 mlir::Value loweredResult;
359 if (mlir::isa<cir::DataMemberType>(srcTy))
360 loweredResult = lowerModule->getCXXABI().lowerDataMemberBitcast(
361 op, destTy, adaptor.getSrc(), rewriter);
363 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
364 op, destTy, adaptor.getSrc(), rewriter);
365 rewriter.replaceOp(op, loweredResult);
366 return mlir::success();
368 case cir::CastKind::member_ptr_to_bool: {
369 mlir::Value loweredResult;
370 if (mlir::isa<cir::DataMemberType>(srcTy))
371 loweredResult = lowerModule->getCXXABI().lowerDataMemberToBoolCast(
372 op, adaptor.getSrc(), rewriter);
374 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
375 op, adaptor.getSrc(), rewriter);
376 rewriter.replaceOp(op, loweredResult);
377 return mlir::success();
384 mlir::Value loweredResult = cir::CastOp::create(
385 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
386 adaptor.getKind(), adaptor.getSrc());
387 rewriter.replaceOp(op, loweredResult);
388 return mlir::success();
393 const mlir::DataLayout &layout,
394 const mlir::TypeConverter &tc,
396 mlir::Attribute initVal) {
397 if (mlir::isa<cir::DataMemberType>(ty)) {
401 mlir::dyn_cast_if_present<cir::DataMemberOffsetAttr>(initVal))
404 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
408 if (mlir::isa<cir::MethodType>(ty)) {
409 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
413 if (
auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
414 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
419 if (
auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
420 return cir::ZeroAttr::get(loweredArrTy);
422 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
428 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
429 assert(loweredArrTy == arrTy &&
430 "string-literal array type should not change under CXX ABI");
434 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
436 loweredElements.reserve(arrTy.getSize());
437 for (
const mlir::Attribute &attr : arrayElts) {
438 auto typedAttr = cast<mlir::TypedAttr>(attr);
440 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
443 return cir::ConstArrayAttr::get(
444 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
445 arrayVal.getTrailingZerosNum());
448 if (
auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
450 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
454 if (
auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
455 return cir::ZeroAttr::get(convertedTy);
457 if (
auto undefVal = mlir::dyn_cast_if_present<cir::UndefAttr>(initVal))
458 return cir::UndefAttr::get(convertedTy);
462 if (
auto poisonVal = mlir::dyn_cast_if_present<cir::PoisonAttr>(initVal))
463 return cir::PoisonAttr::get(convertedTy);
466 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
467 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
470 loweredMembers.reserve(recordMembers.size());
472 for (
const mlir::Attribute &attr : recordMembers) {
473 auto typedAttr = cast<mlir::TypedAttr>(attr);
475 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
478 return cir::ConstRecordAttr::get(
479 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
482 assert(!initVal &&
"Record init val type not handled");
487 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
488 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
491 if (
auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
492 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
496 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
497 assert(convertedTy == ptrTy &&
"BlockAddrInfo type should not change");
501 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
504 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
507 assert(ty == tc.convertType(ty) &&
508 "cir.global or constant operand is not an CXXABI-dependent type");
511 return cast<mlir::TypedAttr>(initVal);
514mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
515 cir::ConstantOp op, OpAdaptor adaptor,
516 mlir::ConversionPatternRewriter &rewriter)
const {
518 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
520 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
521 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
522 return mlir::success();
525mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
526 cir::CmpOp op, OpAdaptor adaptor,
527 mlir::ConversionPatternRewriter &rewriter)
const {
528 mlir::Type type = op.getLhs().getType();
530 mlir::Value loweredResult;
531 if (mlir::isa<cir::DataMemberType>(type))
532 loweredResult = lowerModule->getCXXABI().lowerDataMemberCmp(
533 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
534 else if (mlir::isa<cir::MethodType>(type))
535 loweredResult = lowerModule->getCXXABI().lowerMethodCmp(
536 op, adaptor.getLhs(), adaptor.getRhs(), rewriter);
538 loweredResult = cir::CmpOp::create(
539 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
540 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
542 rewriter.replaceOp(op, loweredResult);
543 return mlir::success();
546mlir::LogicalResult CIRFuncOpABILowering::matchAndRewrite(
547 cir::FuncOp op, OpAdaptor adaptor,
548 mlir::ConversionPatternRewriter &rewriter)
const {
549 cir::FuncType opFuncType = op.getFunctionType();
550 mlir::TypeConverter::SignatureConversion signatureConversion(
551 opFuncType.getNumInputs());
553 for (
const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
554 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
556 return mlir::failure();
557 signatureConversion.addInputs(i, loweredArgType);
560 mlir::Type loweredResultType =
561 getTypeConverter()->convertType(opFuncType.getReturnType());
562 if (!loweredResultType)
563 return mlir::failure();
565 auto loweredFuncType =
566 cir::FuncType::get(signatureConversion.getConvertedTypes(),
567 loweredResultType, opFuncType.isVarArg());
570 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
571 loweredFuncOp.setFunctionType(loweredFuncType);
574 for (
const mlir::NamedAttribute &na : op->getAttrs())
576 {na.getName(), rewriteAttribute(*getTypeConverter(), op->getContext(),
579 loweredFuncOp->setAttrs(attrs);
581 rewriter.inlineRegionBefore(op.getBody(), loweredFuncOp.getBody(),
582 loweredFuncOp.end());
583 if (mlir::failed(rewriter.convertRegionTypes(
584 &loweredFuncOp.getBody(), *getTypeConverter(), &signatureConversion)))
585 return mlir::failure();
587 rewriter.eraseOp(op);
588 return mlir::success();
591mlir::LogicalResult CIRGlobalOpABILowering::matchAndRewrite(
592 cir::GlobalOp op, OpAdaptor adaptor,
593 mlir::ConversionPatternRewriter &rewriter)
const {
594 mlir::Type ty = op.getSymType();
595 mlir::Type loweredTy = getTypeConverter()->convertType(ty);
597 return mlir::failure();
599 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
602 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
604 auto newOp = mlir::cast<cir::GlobalOp>(rewriter.clone(*op.getOperation()));
605 newOp.setInitialValueAttr(loweredInit);
606 newOp.setSymType(loweredTy);
607 rewriter.replaceOp(op, newOp);
608 return mlir::success();
611mlir::LogicalResult CIRBaseDataMemberOpABILowering::matchAndRewrite(
612 cir::BaseDataMemberOp op, OpAdaptor adaptor,
613 mlir::ConversionPatternRewriter &rewriter)
const {
614 mlir::Value loweredResult = lowerModule->getCXXABI().lowerBaseDataMember(
615 op, adaptor.getSrc(), rewriter);
616 rewriter.replaceOp(op, loweredResult);
617 return mlir::success();
620mlir::LogicalResult CIRBaseMethodOpABILowering::matchAndRewrite(
621 cir::BaseMethodOp op, OpAdaptor adaptor,
622 mlir::ConversionPatternRewriter &rewriter)
const {
623 mlir::Value loweredResult =
624 lowerModule->getCXXABI().lowerBaseMethod(op, adaptor.getSrc(), rewriter);
625 rewriter.replaceOp(op, loweredResult);
626 return mlir::success();
629mlir::LogicalResult CIRDeleteArrayOpABILowering::matchAndRewrite(
630 cir::DeleteArrayOp op, OpAdaptor adaptor,
631 mlir::ConversionPatternRewriter &rewriter)
const {
632 mlir::FlatSymbolRefAttr deleteFn = op.getDeleteFnAttr();
633 mlir::Location loc = op->getLoc();
634 mlir::Value loweredAddress = adaptor.getAddress();
636 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParams();
637 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
639 assert(!deleteParams.getDestroyingDelete() &&
640 "destroying delete not legal on arrays");
641 assert(!deleteParams.getTypeAwareDelete() &&
642 "type-aware delete not legal on arrays");
644 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
653 mlir::Value deletePtr;
654 mlir::Value numElements;
655 cir::PointerType ptrTy;
657 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
660 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
662 if (cookieRequired) {
663 ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
664 cxxABI.
readArrayCookie(loc, loweredAddress, dl, cirBuilder, numElements,
665 deletePtr, cookieSize);
667 deletePtr = cir::CastOp::create(rewriter, loc, cirBuilder.getVoidPtrTy(),
668 cir::CastKind::bitcast, loweredAddress);
678 mlir::FlatSymbolRefAttr dtorFn = op.getElementDtorAttr();
679 cir::CleanupKind cleanupKind =
680 op.getDtorMayThrow() ? cir::CleanupKind::All : cir::CleanupKind::Normal;
681 cir::CleanupScopeOp::create(
682 rewriter, loc, cleanupKind,
684 [&](mlir::OpBuilder &b, mlir::Location l) {
686 auto eltPtrTy = cir::PointerType::get(ptrTy.getPointee());
687 auto arrayDtor = cir::ArrayDtor::create(
688 b, l, loweredAddress, numElements,
689 [&](mlir::OpBuilder &bb, mlir::Location ll) {
691 bb.getInsertionBlock()->addArgument(eltPtrTy, ll);
692 auto dtorCall = cir::CallOp::create(
693 bb, ll, dtorFn, cir::VoidType(), mlir::ValueRange{
arg});
694 if (!op.getDtorMayThrow())
695 dtorCall.setNothrowAttr(bb.getUnitAttr());
696 cir::YieldOp::create(bb, ll);
698 if (op.getDtorMayThrow())
699 arrayDtor.setDtorMayThrow(
true);
701 cir::YieldOp::create(b, l);
704 [&](mlir::OpBuilder &b, mlir::Location l) {
707 if (deleteParams.getSize()) {
708 uint64_t eltSizeBytes = dl.getTypeSizeInBits(ptrTy.getPointee()) / 8;
709 auto eltSizeVal = cir::ConstantOp::create(
710 b, l, cir::IntAttr::get(sizeTy, eltSizeBytes));
711 mlir::Value allocSize =
712 cir::MulOp::create(b, l, sizeTy, eltSizeVal, numElements);
713 auto cookieSizeVal = cir::ConstantOp::create(
714 b, l, cir::IntAttr::get(sizeTy, cookieSize.
getQuantity()));
716 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
719 if (deleteParams.getAlignment()) {
720 auto alignVal = cir::ConstantOp::create(
721 b, l, cir::IntAttr::get(sizeTy, *deleteParams.getAlignment()));
726 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
729 deleteCall.setNothrowAttr(b.getUnitAttr());
730 cir::YieldOp::create(b, l);
733 rewriter.eraseOp(op);
734 return mlir::success();
737mlir::LogicalResult CIRDerivedDataMemberOpABILowering::matchAndRewrite(
738 cir::DerivedDataMemberOp op, OpAdaptor adaptor,
739 mlir::ConversionPatternRewriter &rewriter)
const {
740 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedDataMember(
741 op, adaptor.getSrc(), rewriter);
742 rewriter.replaceOp(op, loweredResult);
743 return mlir::success();
746mlir::LogicalResult CIRDerivedMethodOpABILowering::matchAndRewrite(
747 cir::DerivedMethodOp op, OpAdaptor adaptor,
748 mlir::ConversionPatternRewriter &rewriter)
const {
749 mlir::Value loweredResult = lowerModule->getCXXABI().lowerDerivedMethod(
750 op, adaptor.getSrc(), rewriter);
751 rewriter.replaceOp(op, loweredResult);
752 return mlir::success();
755mlir::LogicalResult CIRDynamicCastOpABILowering::matchAndRewrite(
756 cir::DynamicCastOp op, OpAdaptor adaptor,
757 mlir::ConversionPatternRewriter &rewriter)
const {
758 mlir::Value loweredResult =
759 lowerModule->getCXXABI().lowerDynamicCast(op, rewriter);
760 rewriter.replaceOp(op, loweredResult);
761 return mlir::success();
764mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
765 cir::GetMethodOp op, OpAdaptor adaptor,
766 mlir::ConversionPatternRewriter &rewriter)
const {
769 lowerModule->getCXXABI().lowerGetMethod(
770 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
771 rewriter.replaceOp(op, {callee, thisArg});
772 return mlir::success();
775mlir::LogicalResult CIRGetRuntimeMemberOpABILowering::matchAndRewrite(
776 cir::GetRuntimeMemberOp op, OpAdaptor adaptor,
777 mlir::ConversionPatternRewriter &rewriter)
const {
778 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
779 mlir::Operation *newOp = lowerModule->getCXXABI().lowerGetRuntimeMember(
780 op, resTy, adaptor.getAddr(), adaptor.getMember(), rewriter);
781 rewriter.replaceOp(op, newOp);
782 return mlir::success();
785mlir::LogicalResult CIRVTableGetTypeInfoOpABILowering::matchAndRewrite(
786 cir::VTableGetTypeInfoOp op, OpAdaptor adaptor,
787 mlir::ConversionPatternRewriter &rewriter)
const {
788 mlir::Value loweredResult =
789 lowerModule->getCXXABI().lowerVTableGetTypeInfo(op, rewriter);
790 rewriter.replaceOp(op, loweredResult);
791 return mlir::success();
799class CIRABITypeConverter :
public mlir::TypeConverter {
801 mlir::MLIRContext &context;
806 DenseMap<uint64_t, std::unique_ptr<SmallVector<cir::RecordType>>>
808 llvm::sys::SmartRWMutex<true> callStackMutex;
813 llvm::SmallVector<cir::RecordType> convertedRecordTypes;
814 llvm::sys::SmartRWMutex<true> recordTypeMutex;
820 SmallVector<cir::RecordType> &getCurrentThreadRecursiveStack() {
823 std::shared_lock<
decltype(callStackMutex)> lock(callStackMutex,
825 if (context.isMultithreadingEnabled())
827 auto recursiveStack = conversionCallStack.find(llvm::get_threadid());
828 if (recursiveStack != conversionCallStack.end())
829 return *recursiveStack->second;
834 std::unique_lock<
decltype(callStackMutex)> lock(callStackMutex);
835 auto recursiveStackInserted = conversionCallStack.insert(
836 std::make_pair(llvm::get_threadid(),
837 std::make_unique<SmallVector<cir::RecordType>>()));
838 return *recursiveStackInserted.first->second;
841 void addConvertedRecordType(cir::RecordType rt) {
842 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
843 convertedRecordTypes.push_back(rt);
846 llvm::SmallVector<mlir::Type> convertRecordMemberTypes(cir::RecordType type) {
847 llvm::SmallVector<mlir::Type> loweredMemberTypes;
848 loweredMemberTypes.reserve(
type.getNumElements());
850 if (mlir::failed(convertTypes(
type.getMembers(), loweredMemberTypes)))
853 return loweredMemberTypes;
856 cir::RecordType convertRecordType(cir::RecordType type) {
860 if (!
type.getName()) {
861 llvm::SmallVector<mlir::Type> converted = convertRecordMemberTypes(type);
862 assert(converted.size() ==
type.getNumElements() &&
863 "member conversion must be one type in, one type out for the "
864 "kinds to carry over by index");
865 if (
auto u = mlir::dyn_cast<cir::UnionType>(type)) {
866 mlir::Type loweredPadding;
867 if (mlir::Type pad = u.getPadding())
868 loweredPadding = convertType(pad);
869 return cir::UnionType::get(
type.getContext(), converted,
870 type.getPacked(), loweredPadding,
873 auto s = mlir::cast<cir::StructType>(type);
874 return cir::StructType::get(
type.getContext(), converted,
875 type.getPacked(), s.getIsClass(),
879 assert(!
type.isIncomplete() ||
type.getMembers().empty());
884 if (
type.isIncomplete() ||
type.isABIConvertedRecord())
887 SmallVectorImpl<cir::RecordType> &recursiveStack =
888 getCurrentThreadRecursiveStack();
890 cir::RecordType convertedType;
891 if (mlir::isa<cir::UnionType>(type))
893 cir::UnionType::get(
type.getContext(),
type.getABIConvertedName());
896 cir::StructType::get(
type.getContext(),
type.getABIConvertedName(),
897 mlir::cast<cir::StructType>(type).getIsClass());
901 return convertedType;
907 if (llvm::is_contained(recursiveStack, type))
908 return convertedType;
910 recursiveStack.push_back(type);
911 llvm::scope_exit popConvertingType(
912 [&recursiveStack]() { recursiveStack.pop_back(); });
914 SmallVector<mlir::Type> convertedMembers = convertRecordMemberTypes(type);
915 assert(convertedMembers.size() ==
type.getNumElements() &&
916 "member conversion must be one type in, one type out for the kinds "
917 "to carry over by index");
919 mlir::Type loweredPadding;
920 if (
auto u = mlir::dyn_cast<cir::UnionType>(type))
921 if (mlir::Type pad = u.getPadding())
922 loweredPadding = convertType(pad);
923 convertedType.
complete(convertedMembers,
type.getPacked(), loweredPadding,
924 type.getMemberKinds());
925 addConvertedRecordType(convertedType);
926 return convertedType;
930 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
931 cir::LowerModule &lowerModule)
933 addConversion([&](mlir::Type type) -> mlir::Type {
return type; });
936 addConversion([&](cir::PointerType type) -> mlir::Type {
937 mlir::Type loweredPointeeType = convertType(
type.getPointee());
938 if (!loweredPointeeType)
940 return cir::PointerType::get(
type.getContext(), loweredPointeeType,
941 type.getAddrSpace());
943 addConversion([&](cir::ArrayType type) -> mlir::Type {
944 mlir::Type loweredElementType = convertType(
type.getElementType());
945 if (!loweredElementType)
947 return cir::ArrayType::get(loweredElementType,
type.getSize());
950 addConversion([&](cir::DataMemberType type) -> mlir::Type {
953 return convertType(abiType);
955 addConversion([&](cir::MethodType type) -> mlir::Type {
957 return convertType(abiType);
962 addConversion([&](cir::FuncType type) -> mlir::Type {
963 llvm::SmallVector<mlir::Type> loweredInputTypes;
964 loweredInputTypes.reserve(
type.getNumInputs());
965 if (mlir::failed(convertTypes(
type.getInputs(), loweredInputTypes)))
968 mlir::Type loweredReturnType = convertType(
type.getReturnType());
969 if (!loweredReturnType)
972 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
975 addConversion([&](cir::StructType type) -> mlir::Type {
976 return convertRecordType(type);
978 addConversion([&](cir::UnionType type) -> mlir::Type {
979 return convertRecordType(type);
983 void restoreRecordTypeNames() {
984 std::unique_lock<
decltype(recordTypeMutex)> lock(recordTypeMutex);
986 for (
auto rt : convertedRecordTypes)
994 const mlir::TypeConverter &typeConverter) {
995 target.addLegalOp<mlir::ModuleOp>();
1000 target.addDynamicallyLegalDialect<cir::CIRDialect>(
1001 [&typeConverter](mlir::Operation *op) {
1002 if (!typeConverter.isLegal(op))
1005 bool attrs = llvm::all_of(
1006 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1007 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1011 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1012 [&typeConverter](mlir::Region ®ion) {
1013 return typeConverter.isLegal(®ion);
1017 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
1018 [&typeConverter](mlir::Operation *op) {
1019 if (!typeConverter.isLegal(op))
1022 bool attrs = llvm::all_of(
1023 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1024 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1028 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1029 [&typeConverter](mlir::Region ®ion) {
1030 return typeConverter.isLegal(®ion);
1035 target.addDynamicallyLegalOp<cir::FuncOp>([&typeConverter](cir::FuncOp op) {
1036 bool attrs = llvm::all_of(
1037 op->getAttrs(), [&typeConverter](
const mlir::NamedAttribute &a) {
1038 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1041 return attrs && typeConverter.isLegal(op.getFunctionType());
1043 target.addDynamicallyLegalOp<cir::GlobalOp>(
1044 [&typeConverter](cir::GlobalOp op) {
1045 return typeConverter.isLegal(op.getSymType());
1049 target.addIllegalOp<cir::DeleteArrayOp>();
1050 target.addIllegalOp<cir::DynamicCastOp>();
1051 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1058void CXXABILoweringPass::runOnOperation() {
1059 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1060 mlir::MLIRContext *ctx = mod.getContext();
1065 mod.emitWarning(
"Cannot create a CIR lower module, skipping the ")
1070 mlir::DataLayout dataLayout(mod);
1071 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1073 mlir::RewritePatternSet patterns(ctx);
1074 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1077#define GET_ABI_LOWERING_PATTERNS_LIST
1078#include "clang/CIR/Dialect/IR/CIRLowering.inc"
1079#undef GET_ABI_LOWERING_PATTERNS_LIST
1080 >(patterns.getContext(), typeConverter, dataLayout, *lowerModule);
1082 mlir::ConversionTarget target(*ctx);
1085 llvm::SmallVector<mlir::Operation *> ops;
1089 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1090 signalPassFailure();
1092 typeConverter.restoreRecordTypeNames();
1096 return std::make_unique<CXXABILoweringPass>();
#define CXX_ABI_ALWAYS_LEGAL_ATTRS
static void populateCXXABIConversionTarget(mlir::ConversionTarget &target, const mlir::TypeConverter &typeConverter)
static mlir::TypedAttr lowerInitialValue(const LowerModule *lowerModule, const mlir::DataLayout &layout, const mlir::TypeConverter &tc, mlir::Type ty, mlir::Attribute initVal)
virtual mlir::Type lowerMethodType(cir::MethodType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer type to its ABI type.
void readArrayCookie(mlir::Location loc, mlir::Value elementPtr, const mlir::DataLayout &dataLayout, CIRBaseBuilderTy &builder, mlir::Value &numElements, mlir::Value &allocPtr, clang::CharUnits &cookieSize) const
Read the array cookie for a dynamically-allocated array whose first element is at elementPtr.
virtual mlir::TypedAttr lowerDataMemberConstant(cir::DataMemberAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer constant to a constant of the ABI type.
virtual mlir::TypedAttr lowerDataMemberOffsetConstant(cir::DataMemberOffsetAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given by-offset data member pointer constant (used for members with no CIR field index,...
virtual mlir::TypedAttr lowerMethodConstant(cir::MethodAttr attr, const mlir::DataLayout &layout, const mlir::TypeConverter &typeConverter) const =0
Lower the given member function pointer constant to a constant of the ABI type.
virtual mlir::Type lowerDataMemberType(cir::DataMemberType type, const mlir::TypeConverter &typeConverter) const =0
Lower the given data member pointer type to its ABI type.
CIRCXXABI & getCXXABI() const
void removeABIConversionNamePrefix()
void complete(llvm::ArrayRef< mlir::Type > members, bool packed, mlir::Type padding, llvm::ArrayRef< RecordMemberKind > memberKinds)
padding is union-only.
CharUnits - This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
void collectUnreachable(mlir::Operation *parent, llvm::SmallVectorImpl< mlir::Operation * > &ops)
Collect ops in blocks that are unreachable from their region's entry, appending them to ops.
std::unique_ptr< LowerModule > createLowerModule(mlir::ModuleOp module)
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
StringRef getName(const HeaderType T)
bool isa(CodeGen::Address addr)
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCXXABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)