clang 24.0.0git
CXXABILowering.cpp
Go to the documentation of this file.
1//==- CXXABILowering.cpp - lower C++ operations to target-specific ABI form -=//
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#include "PassDetail.h"
11
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"
26
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/ADT/TypeSwitch.h"
29
30using namespace mlir;
31using namespace cir;
32
33namespace mlir {
34#define GEN_PASS_DEF_CXXABILOWERING
35#include "clang/CIR/Dialect/Passes.h.inc"
36} // namespace mlir
37
38namespace {
39// Check an attribute for legality. An attribute is only currently potentially
40// illegal if it contains a type, member pointers are our source of illegality
41// in regards to attributes.
42bool isCXXABIAttributeLegal(const mlir::TypeConverter &tc,
43 mlir::Attribute attr) {
44 // If we don't have an attribute, it can't have a type!
45 if (!attr)
46 return true;
47
48 // None of the OpenACC/OMP attributes contain a type of concern, so we can
49 // just treat them as legal.
50 if (isa<mlir::acc::OpenACCDialect, mlir::omp::OpenMPDialect>(
51 attr.getDialect()))
52 return true;
53
54 // These attributes either don't contain a type, or don't contain a type that
55 // can have a data member/method.
56 if (isa<mlir::DenseArrayAttr, mlir::FloatAttr, mlir::UnitAttr,
57 mlir::StringAttr, mlir::IntegerAttr, mlir::SymbolRefAttr,
58 cir::AnnotationAttr>(attr))
59 return true;
60
61 // Tablegen'ed always-legal attributes:
62 if (isa<
64#include "clang/CIR/Dialect/IR/CIRLowering.inc"
66 >(attr))
67 return true;
68
69 // Data Member and method are ALWAYS illegal.
70 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
71 attr))
72 return false;
73
74 return llvm::TypeSwitch<mlir::Attribute, bool>(attr)
75 // These attributes just have a type, so they are legal if their type is.
76 .Case<cir::ZeroAttr>(
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()); })
92
93 // Collection attributes are legal if ALL of the attributes in them are
94 // also legal.
95 .Case<mlir::ArrayAttr>([&tc](mlir::ArrayAttr array) {
96 return llvm::all_of(array.getValue(), [&tc](mlir::Attribute attr) {
97 return isCXXABIAttributeLegal(tc, attr);
98 });
99 })
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());
103 });
104 })
105 // These attributes have sub-attributes that we should check for legality.
106 .Case<cir::ConstArrayAttr>([&tc](cir::ConstArrayAttr array) {
107 return tc.isLegal(array.getType()) &&
108 isCXXABIAttributeLegal(tc, array.getElts());
109 })
110 .Case<cir::GlobalViewAttr>([&tc](cir::GlobalViewAttr gva) {
111 return tc.isLegal(gva.getType()) &&
112 isCXXABIAttributeLegal(tc, gva.getIndices());
113 })
114 .Case<cir::VTableAttr>([&tc](cir::VTableAttr vta) {
115 return tc.isLegal(vta.getType()) &&
116 isCXXABIAttributeLegal(tc, vta.getData());
117 })
118 .Case<cir::TypeInfoAttr>([&tc](cir::TypeInfoAttr tia) {
119 return tc.isLegal(tia.getType()) &&
120 isCXXABIAttributeLegal(tc, tia.getData());
121 })
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());
127 })
128 .Case<cir::ConstRecordAttr>([&tc](cir::ConstRecordAttr cra) {
129 return tc.isLegal(cra.getType()) &&
130 isCXXABIAttributeLegal(tc, cra.getMembers());
131 })
132 // We did an audit of all of our attributes (both in OpenACC and CIR), so
133 // it shouldn't be dangerous to consider everything we haven't considered
134 // 'illegal'. Any 'new' attributes will end up asserting in
135 // 'rewriteAttribute' to make sure we consider them here. Otherwise, we
136 // wouldn't discover a problematic new attribute until it contains a
137 // member/method.
138 .Default(false);
139}
140
141mlir::Attribute rewriteAttribute(const mlir::TypeConverter &tc,
142 mlir::MLIRContext *ctx, mlir::Attribute attr) {
143 // If the attribute is legal, there is no reason to rewrite it. This also
144 // filters out 'null' attributes.
145 if (isCXXABIAttributeLegal(tc, attr))
146 return attr;
147
148 // This switch needs to be kept in sync with the potentially-legal type switch
149 // from isCXXABIAttributeLegal. IF we miss any, this will end up causing
150 // verification/transformation issues later, often in the form of
151 // unrealized-conversion-casts.
152
153 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
154 // These attributes just have a type, so convert just the type.
155 .Case<cir::ZeroAttr>([&tc](cir::ZeroAttr za) {
156 return cir::ZeroAttr::get(tc.convertType(za.getType()));
157 })
158 .Case<cir::PoisonAttr>([&tc](cir::PoisonAttr pa) {
159 return cir::PoisonAttr::get(tc.convertType(pa.getType()));
160 })
161 .Case<cir::UndefAttr>([&tc](cir::UndefAttr uda) {
162 return cir::UndefAttr::get(tc.convertType(uda.getType()));
163 })
164 .Case<mlir::TypeAttr>([&tc](mlir::TypeAttr ta) {
165 return mlir::TypeAttr::get(tc.convertType(ta.getValue()));
166 })
167 .Case<cir::ConstPtrAttr>([&tc](cir::ConstPtrAttr cpa) {
168 return cir::ConstPtrAttr::get(tc.convertType(cpa.getType()),
169 cpa.getValue());
170 })
171 .Case<cir::CXXCtorAttr>([&tc](cir::CXXCtorAttr ca) {
172 return cir::CXXCtorAttr::get(tc.convertType(ca.getType()),
173 ca.getCtorKind(), ca.getIsTrivial());
174 })
175 .Case<cir::CXXDtorAttr>([&tc](cir::CXXDtorAttr da) {
176 return cir::CXXDtorAttr::get(tc.convertType(da.getType()),
177 da.getIsTrivial());
178 })
179 .Case<cir::CXXAssignAttr>([&tc](cir::CXXAssignAttr aa) {
180 return cir::CXXAssignAttr::get(tc.convertType(aa.getType()),
181 aa.getAssignKind(), aa.getIsTrivial());
182 })
183 // Collection attributes need to transform all of the attributes inside of
184 // them.
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);
190 })
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()));
196
197 return mlir::DictionaryAttr::get(ctx, elts);
198 })
199 // These attributes have sub-attributes that need converting too.
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());
205 })
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())));
211 })
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())));
217 })
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())));
223 })
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());
232 })
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())));
238 })
239 .DefaultUnreachable("unrewritten illegal attribute kind");
240}
241
242#define GET_ABI_LOWERING_PATTERNS
243#include "clang/CIR/Dialect/IR/CIRLowering.inc"
244#undef GET_ABI_LOWERING_PATTERNS
245
246struct CXXABILoweringPass
247 : public impl::CXXABILoweringBase<CXXABILoweringPass> {
248 CXXABILoweringPass() = default;
249 void runOnOperation() override;
250};
251
252/// A generic ABI lowering rewrite pattern. This conversion pattern matches any
253/// CIR dialect operations with at least one operand or result of an
254/// ABI-dependent type. This conversion pattern rewrites the matched operation
255/// by replacing all its ABI-dependent operands and results with their
256/// lowered counterparts.
257class CIRGenericCXXABILoweringPattern : public mlir::ConversionPattern {
258public:
259 CIRGenericCXXABILoweringPattern(mlir::MLIRContext *context,
260 const mlir::TypeConverter &typeConverter)
261 : mlir::ConversionPattern(typeConverter, MatchAnyOpTypeTag(),
262 /*benefit=*/1, context) {}
263
264 mlir::LogicalResult
265 matchAndRewrite(mlir::Operation *op, llvm::ArrayRef<mlir::Value> operands,
266 mlir::ConversionPatternRewriter &rewriter) const override {
267 // Do not match on operations that have dedicated ABI lowering rewrite rules
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();
273
274 const mlir::TypeConverter *typeConverter = getTypeConverter();
275 assert(typeConverter &&
276 "CIRGenericCXXABILoweringPattern requires a type converter");
277 bool operandsAndResultsLegal = typeConverter->isLegal(op);
278 bool regionsLegal =
279 std::all_of(op->getRegions().begin(), op->getRegions().end(),
280 [typeConverter](mlir::Region &region) {
281 return typeConverter->isLegal(&region);
282 });
283 bool attrsLegal =
284 llvm::all_of(op->getAttrs(), [typeConverter](mlir::NamedAttribute na) {
285 return isCXXABIAttributeLegal(*typeConverter, na.getValue());
286 });
287
288 if (operandsAndResultsLegal && regionsLegal && attrsLegal) {
289 // The operation does not have any CXXABI-dependent operands or results,
290 // the match fails.
291 return mlir::failure();
292 }
293
294 mlir::OperationState loweredOpState(op->getLoc(), op->getName());
295 loweredOpState.addOperands(operands);
296 loweredOpState.addSuccessors(op->getSuccessors());
297
298 // Lower all attributes.
299 llvm::SmallVector<mlir::NamedAttribute> attrs;
300 for (const mlir::NamedAttribute &na : op->getAttrs())
301 attrs.push_back(
302 {na.getName(),
303 rewriteAttribute(*typeConverter, op->getContext(), na.getValue())});
304 loweredOpState.addAttributes(attrs);
305
306 // Lower all result types
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);
312
313 // Lower all regions
314 for (mlir::Region &region : op->getRegions()) {
315 mlir::Region *loweredRegion = loweredOpState.addRegion();
316 rewriter.inlineRegionBefore(region, *loweredRegion, loweredRegion->end());
317 if (mlir::failed(
318 rewriter.convertRegionTypes(loweredRegion, *getTypeConverter())))
319 return mlir::failure();
320 }
321
322 // Clone the operation with lowered operand types and result types
323 mlir::Operation *loweredOp = rewriter.create(loweredOpState);
324
325 rewriter.replaceOp(op, loweredOp);
326 return mlir::success();
327 }
328};
329
330} // namespace
331
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);
337
338 cir::AllocaOp loweredOp = cir::AllocaOp::create(
339 rewriter, op.getLoc(), loweredAllocaPtrTy, op.getName(),
340 op.getAlignmentAttr(), /*dynAllocSize=*/adaptor.getDynAllocSize());
341 loweredOp.setInit(op.getInit());
342 loweredOp.setConstant(op.getConstant());
343 loweredOp.setAnnotationsAttr(op.getAnnotationsAttr());
344
345 rewriter.replaceOp(op, loweredOp);
346 return mlir::success();
347}
348
349mlir::LogicalResult CIRCastOpABILowering::matchAndRewrite(
350 cir::CastOp op, OpAdaptor adaptor,
351 mlir::ConversionPatternRewriter &rewriter) const {
352 mlir::Type srcTy = op.getSrc().getType();
353
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);
362 else
363 loweredResult = lowerModule->getCXXABI().lowerMethodBitcast(
364 op, destTy, adaptor.getSrc(), rewriter);
365 rewriter.replaceOp(op, loweredResult);
366 return mlir::success();
367 }
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);
373 else
374 loweredResult = lowerModule->getCXXABI().lowerMethodToBoolCast(
375 op, adaptor.getSrc(), rewriter);
376 rewriter.replaceOp(op, loweredResult);
377 return mlir::success();
378 }
379 default:
380 break;
381 }
382 }
383
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();
389}
390
391// Helper function to lower a value for things like an initializer.
392static mlir::TypedAttr lowerInitialValue(const LowerModule *lowerModule,
393 const mlir::DataLayout &layout,
394 const mlir::TypeConverter &tc,
395 mlir::Type ty,
396 mlir::Attribute initVal) {
397 if (mlir::isa<cir::DataMemberType>(ty)) {
398 // Members without a CIR field index (e.g. no_unique_address empty fields)
399 // are represented by an explicit byte offset instead of a field path.
400 if (auto offsetVal =
401 mlir::dyn_cast_if_present<cir::DataMemberOffsetAttr>(initVal))
402 return lowerModule->getCXXABI().lowerDataMemberOffsetConstant(offsetVal,
403 layout, tc);
404 auto dataMemberVal = mlir::cast_if_present<cir::DataMemberAttr>(initVal);
405 return lowerModule->getCXXABI().lowerDataMemberConstant(dataMemberVal,
406 layout, tc);
407 }
408 if (mlir::isa<cir::MethodType>(ty)) {
409 auto methodVal = mlir::cast_if_present<cir::MethodAttr>(initVal);
410 return lowerModule->getCXXABI().lowerMethodConstant(methodVal, layout, tc);
411 }
412
413 if (auto arrTy = mlir::dyn_cast<cir::ArrayType>(ty)) {
414 auto loweredArrTy = mlir::cast<cir::ArrayType>(tc.convertType(arrTy));
415
416 if (!initVal)
417 return {};
418
419 if (auto zeroVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
420 return cir::ZeroAttr::get(loweredArrTy);
421
422 auto arrayVal = mlir::cast<cir::ConstArrayAttr>(initVal);
423
424 // String-literal arrays store their bytes as a StringAttr in `elts`. The
425 // backing i8 element type is never rewritten by the CXX ABI type
426 // converter, so the attribute is already legal and can be passed through
427 // unchanged.
428 if (mlir::isa<mlir::StringAttr>(arrayVal.getElts())) {
429 assert(loweredArrTy == arrTy &&
430 "string-literal array type should not change under CXX ABI");
431 return arrayVal;
432 }
433
434 auto arrayElts = mlir::cast<ArrayAttr>(arrayVal.getElts());
435 SmallVector<mlir::Attribute> loweredElements;
436 loweredElements.reserve(arrTy.getSize());
437 for (const mlir::Attribute &attr : arrayElts) {
438 auto typedAttr = cast<mlir::TypedAttr>(attr);
439 loweredElements.push_back(lowerInitialValue(
440 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
441 }
442
443 return cir::ConstArrayAttr::get(
444 loweredArrTy, mlir::ArrayAttr::get(ty.getContext(), loweredElements),
445 arrayVal.getTrailingZerosNum());
446 }
447
448 if (auto recordTy = mlir::dyn_cast<cir::RecordType>(ty)) {
449 auto convertedTy =
450 mlir::dyn_cast<cir::RecordType>(tc.convertType(recordTy));
451 if (!convertedTy)
452 return {};
453
454 if (auto recVal = mlir::dyn_cast_if_present<cir::ZeroAttr>(initVal))
455 return cir::ZeroAttr::get(convertedTy);
456
457 if (auto undefVal = mlir::dyn_cast_if_present<cir::UndefAttr>(initVal))
458 return cir::UndefAttr::get(convertedTy);
459
460 // This might not be possible from Clang directly, but we can get here with
461 // hand-written IR.
462 if (auto poisonVal = mlir::dyn_cast_if_present<cir::PoisonAttr>(initVal))
463 return cir::PoisonAttr::get(convertedTy);
464
465 if (auto recVal =
466 mlir::dyn_cast_if_present<cir::ConstRecordAttr>(initVal)) {
467 auto recordMembers = mlir::cast<ArrayAttr>(recVal.getMembers());
468
469 SmallVector<mlir::Attribute> loweredMembers;
470 loweredMembers.reserve(recordMembers.size());
471
472 for (const mlir::Attribute &attr : recordMembers) {
473 auto typedAttr = cast<mlir::TypedAttr>(attr);
474 loweredMembers.push_back(lowerInitialValue(
475 lowerModule, layout, tc, typedAttr.getType(), typedAttr));
476 }
477
478 return cir::ConstRecordAttr::get(
479 convertedTy, mlir::ArrayAttr::get(ty.getContext(), loweredMembers));
480 }
481
482 assert(!initVal && "Record init val type not handled");
483 return {};
484 }
485
486 // Pointers can contain record types, which can change.
487 if (auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty)) {
488 auto convertedTy = mlir::cast<cir::PointerType>(tc.convertType(ptrTy));
489 // pointers don't change other than their types.
490
491 if (auto gva = mlir::dyn_cast_if_present<cir::GlobalViewAttr>(initVal))
492 return cir::GlobalViewAttr::get(convertedTy, gva.getSymbol(),
493 gva.getIndices());
494
495 if (auto blockAddr =
496 mlir::dyn_cast_if_present<cir::BlockAddrInfoAttr>(initVal)) {
497 assert(convertedTy == ptrTy && "BlockAddrInfo type should not change");
498 return blockAddr;
499 }
500
501 auto constPtr = mlir::cast_if_present<cir::ConstPtrAttr>(initVal);
502 if (!constPtr)
503 return {};
504 return cir::ConstPtrAttr::get(convertedTy, constPtr.getValue());
505 }
506
507 assert(ty == tc.convertType(ty) &&
508 "cir.global or constant operand is not an CXXABI-dependent type");
509
510 // Every other type can be left alone.
511 return cast<mlir::TypedAttr>(initVal);
512}
513
514mlir::LogicalResult CIRConstantOpABILowering::matchAndRewrite(
515 cir::ConstantOp op, OpAdaptor adaptor,
516 mlir::ConversionPatternRewriter &rewriter) const {
517
518 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
519 mlir::TypedAttr newValue = lowerInitialValue(
520 lowerModule, layout, *getTypeConverter(), op.getType(), op.getValue());
521 rewriter.replaceOpWithNewOp<ConstantOp>(op, newValue);
522 return mlir::success();
523}
524
525mlir::LogicalResult CIRCmpOpABILowering::matchAndRewrite(
526 cir::CmpOp op, OpAdaptor adaptor,
527 mlir::ConversionPatternRewriter &rewriter) const {
528 mlir::Type type = op.getLhs().getType();
529
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);
537 else
538 loweredResult = cir::CmpOp::create(
539 rewriter, op.getLoc(), getTypeConverter()->convertType(op.getType()),
540 adaptor.getKind(), adaptor.getLhs(), adaptor.getRhs());
541
542 rewriter.replaceOp(op, loweredResult);
543 return mlir::success();
544}
545
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());
552
553 for (const auto &[i, argType] : llvm::enumerate(opFuncType.getInputs())) {
554 mlir::Type loweredArgType = getTypeConverter()->convertType(argType);
555 if (!loweredArgType)
556 return mlir::failure();
557 signatureConversion.addInputs(i, loweredArgType);
558 }
559
560 mlir::Type loweredResultType =
561 getTypeConverter()->convertType(opFuncType.getReturnType());
562 if (!loweredResultType)
563 return mlir::failure();
564
565 auto loweredFuncType =
566 cir::FuncType::get(signatureConversion.getConvertedTypes(),
567 loweredResultType, /*isVarArg=*/opFuncType.isVarArg());
568
569 // Create a new cir.func operation for the CXXABI-lowered function.
570 cir::FuncOp loweredFuncOp = rewriter.cloneWithoutRegions(op);
571 loweredFuncOp.setFunctionType(loweredFuncType);
572
574 for (const mlir::NamedAttribute &na : op->getAttrs())
575 attrs.push_back(
576 {na.getName(), rewriteAttribute(*getTypeConverter(), op->getContext(),
577 na.getValue())});
578
579 loweredFuncOp->setAttrs(attrs);
580
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();
586
587 rewriter.eraseOp(op);
588 return mlir::success();
589}
590
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);
596 if (!loweredTy)
597 return mlir::failure();
598
599 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
600
601 mlir::Attribute loweredInit = lowerInitialValue(
602 lowerModule, layout, *getTypeConverter(), ty, op.getInitialValueAttr());
603
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();
609}
610
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();
618}
619
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();
627}
628
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();
635
636 cir::UsualDeleteParamsAttr deleteParams = op.getDeleteParams();
637 bool cookieRequired = deleteParams.getSize() || op.getElementDtorAttr();
638
639 assert(!deleteParams.getDestroyingDelete() &&
640 "destroying delete not legal on arrays");
641 assert(!deleteParams.getTypeAwareDelete() &&
642 "type-aware delete not legal on arrays");
643
644 const CIRCXXABI &cxxABI = lowerModule->getCXXABI();
645 CIRBaseBuilderTy cirBuilder(rewriter);
646
647 // Read the array cookie (or compute the void* pointer for the
648 // non-cookie case) before creating the cleanup scope. The cookie read
649 // produces values that are needed by both the destruction loop in the
650 // body region (numElements for the array.dtor) and the operator
651 // delete[] call in the cleanup region (deletePtr / numElements for the
652 // total-size computation), so it must dominate both regions.
653 mlir::Value deletePtr;
654 mlir::Value numElements;
655 cir::PointerType ptrTy;
656 clang::CharUnits cookieSize;
657 mlir::DataLayout dl(op->getParentOfType<mlir::ModuleOp>());
658 unsigned ptrWidth =
659 lowerModule->getTarget().getPointerWidth(clang::LangAS::Default);
660 cir::IntType sizeTy = cirBuilder.getUIntNTy(ptrWidth);
661
662 if (cookieRequired) {
663 ptrTy = mlir::cast<cir::PointerType>(loweredAddress.getType());
664 cxxABI.readArrayCookie(loc, loweredAddress, dl, cirBuilder, numElements,
665 deletePtr, cookieSize);
666 } else {
667 deletePtr = cir::CastOp::create(rewriter, loc, cirBuilder.getVoidPtrTy(),
668 cir::CastKind::bitcast, loweredAddress);
669 }
670
671 // Create a cleanup scope to wrap the ArrayDtor operation (if needed) and
672 // call the array delete operator from the cleanup region. If no exceptions
673 // are thrown during the array dtor, the normal control flow will call the
674 // delete operator. The ArrayDtor operation will get its own cleanup region
675 // when it is expanded during LoweringPrepare. If an exception is thrown, the
676 // exception handling flow will be connected to the cleanup region here to
677 // call the delete operator on the exception path.
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,
683 /*bodyBuilder=*/
684 [&](mlir::OpBuilder &b, mlir::Location l) {
685 if (dtorFn) {
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) {
690 mlir::Value arg =
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);
697 });
698 if (op.getDtorMayThrow())
699 arrayDtor.setDtorMayThrow(true);
700 }
701 cir::YieldOp::create(b, l);
702 },
703 /*cleanupBuilder=*/
704 [&](mlir::OpBuilder &b, mlir::Location l) {
706 callArgs.push_back(deletePtr);
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()));
715 allocSize =
716 cir::AddOp::create(b, l, sizeTy, allocSize, cookieSizeVal);
717 callArgs.push_back(allocSize);
718 }
719 if (deleteParams.getAlignment()) {
720 auto alignVal = cir::ConstantOp::create(
721 b, l, cir::IntAttr::get(sizeTy, *deleteParams.getAlignment()));
722 callArgs.push_back(alignVal);
723 }
724
725 auto deleteCall =
726 cir::CallOp::create(b, l, deleteFn, cir::VoidType(), callArgs);
727 // operator delete[] is implicitly nothrow per [basic.stc.dynamic],
728 // matching classic CodeGen's `nounwind` attribute on the call.
729 deleteCall.setNothrowAttr(b.getUnitAttr());
730 cir::YieldOp::create(b, l);
731 });
732
733 rewriter.eraseOp(op);
734 return mlir::success();
735}
736
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();
744}
745
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();
753}
754
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();
762}
763
764mlir::LogicalResult CIRGetMethodOpABILowering::matchAndRewrite(
765 cir::GetMethodOp op, OpAdaptor adaptor,
766 mlir::ConversionPatternRewriter &rewriter) const {
767 mlir::Value callee;
768 mlir::Value thisArg;
769 lowerModule->getCXXABI().lowerGetMethod(
770 op, callee, thisArg, adaptor.getMethod(), adaptor.getObject(), rewriter);
771 rewriter.replaceOp(op, {callee, thisArg});
772 return mlir::success();
773}
774
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();
783}
784
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();
792}
793
794namespace {
795// A small type to handle type conversion for the the CXXABILoweringPass.
796// Even though this is a CIR-to-CIR pass, we are eliminating some CIR types.
797// Most importantly, this pass solves recursive type conversion problems by
798// keeping a call stack.
799class CIRABITypeConverter : public mlir::TypeConverter {
800
801 mlir::MLIRContext &context;
802
803 // Recursive structure detection.
804 // We store one entry per thread here, and rely on locking. This works the
805 // same way as the LLVM-IR lowering does it, which has a similar problem.
806 DenseMap<uint64_t, std::unique_ptr<SmallVector<cir::RecordType>>>
807 conversionCallStack;
808 llvm::sys::SmartRWMutex<true> callStackMutex;
809
810 // In order to let us 'change the names' back after the fact, we collect them
811 // along the way. They should only be added/accessed via the thread-safe
812 // functions below.
813 llvm::SmallVector<cir::RecordType> convertedRecordTypes;
814 llvm::sys::SmartRWMutex<true> recordTypeMutex;
815
816 // This provides a stack for the RecordTypes being processed on the current
817 // thread, which lets us solve recursive conversions. This implementation is
818 // cribbed from the LLVMTypeConverter which solves a similar but not identical
819 // problem.
820 SmallVector<cir::RecordType> &getCurrentThreadRecursiveStack() {
821 {
822 // Most of the time, the entry already exists in the map.
823 std::shared_lock<decltype(callStackMutex)> lock(callStackMutex,
824 std::defer_lock);
825 if (context.isMultithreadingEnabled())
826 lock.lock();
827 auto recursiveStack = conversionCallStack.find(llvm::get_threadid());
828 if (recursiveStack != conversionCallStack.end())
829 return *recursiveStack->second;
830 }
831
832 // First time this thread gets here, we have to get an exclusive access to
833 // insert in the map
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;
839 }
840
841 void addConvertedRecordType(cir::RecordType rt) {
842 std::unique_lock<decltype(recordTypeMutex)> lock(recordTypeMutex);
843 convertedRecordTypes.push_back(rt);
844 }
845
846 llvm::SmallVector<mlir::Type> convertRecordMemberTypes(cir::RecordType type) {
847 llvm::SmallVector<mlir::Type> loweredMemberTypes;
848 loweredMemberTypes.reserve(type.getNumElements());
849
850 if (mlir::failed(convertTypes(type.getMembers(), loweredMemberTypes)))
851 return {};
852
853 return loweredMemberTypes;
854 }
855
856 cir::RecordType convertRecordType(cir::RecordType type) {
857 // Unnamed record types can't be referred to recursively, so we can just
858 // convert this one. It also doesn't have uniqueness problems, so we can
859 // just do a conversion on it.
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,
871 u.getMemberKinds());
872 }
873 auto s = mlir::cast<cir::StructType>(type);
874 return cir::StructType::get(type.getContext(), converted,
875 type.getPacked(), s.getIsClass(),
876 s.getMemberKinds());
877 }
878
879 assert(!type.isIncomplete() || type.getMembers().empty());
880
881 // If the type has already been converted, we can just return, since there
882 // is nothing to do. Also, if it is incomplete, it can't have invalid
883 // members! So we can skip transforming it.
884 if (type.isIncomplete() || type.isABIConvertedRecord())
885 return type;
886
887 SmallVectorImpl<cir::RecordType> &recursiveStack =
888 getCurrentThreadRecursiveStack();
889
890 cir::RecordType convertedType;
891 if (mlir::isa<cir::UnionType>(type))
892 convertedType =
893 cir::UnionType::get(type.getContext(), type.getABIConvertedName());
894 else
895 convertedType =
896 cir::StructType::get(type.getContext(), type.getABIConvertedName(),
897 mlir::cast<cir::StructType>(type).getIsClass());
898
899 // This type has already been converted, just return it.
900 if (convertedType.isComplete())
901 return convertedType;
902
903 // We put the existing 'type' into the vector if we're in the process of
904 // converting it (and pop it when we're done). To prevent recursion,
905 // just return the 'incomplete' version, and the 'top level' version of this
906 // call will call 'complete' on it.
907 if (llvm::is_contained(recursiveStack, type))
908 return convertedType;
909
910 recursiveStack.push_back(type);
911 llvm::scope_exit popConvertingType(
912 [&recursiveStack]() { recursiveStack.pop_back(); });
913
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");
918
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;
927 }
928
929public:
930 CIRABITypeConverter(mlir::MLIRContext &ctx, mlir::DataLayout &dataLayout,
931 cir::LowerModule &lowerModule)
932 : context(ctx) {
933 addConversion([&](mlir::Type type) -> mlir::Type { return type; });
934 // This is necessary in order to convert CIR pointer types that are
935 // pointing to CIR types that we are lowering in this pass.
936 addConversion([&](cir::PointerType type) -> mlir::Type {
937 mlir::Type loweredPointeeType = convertType(type.getPointee());
938 if (!loweredPointeeType)
939 return {};
940 return cir::PointerType::get(type.getContext(), loweredPointeeType,
941 type.getAddrSpace());
942 });
943 addConversion([&](cir::ArrayType type) -> mlir::Type {
944 mlir::Type loweredElementType = convertType(type.getElementType());
945 if (!loweredElementType)
946 return {};
947 return cir::ArrayType::get(loweredElementType, type.getSize());
948 });
949
950 addConversion([&](cir::DataMemberType type) -> mlir::Type {
951 mlir::Type abiType =
952 lowerModule.getCXXABI().lowerDataMemberType(type, *this);
953 return convertType(abiType);
954 });
955 addConversion([&](cir::MethodType type) -> mlir::Type {
956 mlir::Type abiType = lowerModule.getCXXABI().lowerMethodType(type, *this);
957 return convertType(abiType);
958 });
959 // This is necessary in order to convert CIR function types that have
960 // argument or return types that use CIR types that we are lowering in
961 // this pass.
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)))
966 return {};
967
968 mlir::Type loweredReturnType = convertType(type.getReturnType());
969 if (!loweredReturnType)
970 return {};
971
972 return cir::FuncType::get(loweredInputTypes, loweredReturnType,
973 /*isVarArg=*/type.getVarArg());
974 });
975 addConversion([&](cir::StructType type) -> mlir::Type {
976 return convertRecordType(type);
977 });
978 addConversion([&](cir::UnionType type) -> mlir::Type {
979 return convertRecordType(type);
980 });
981 }
982
983 void restoreRecordTypeNames() {
984 std::unique_lock<decltype(recordTypeMutex)> lock(recordTypeMutex);
985
986 for (auto rt : convertedRecordTypes)
988 }
989};
990} // namespace
991
992static void
993populateCXXABIConversionTarget(mlir::ConversionTarget &target,
994 const mlir::TypeConverter &typeConverter) {
995 target.addLegalOp<mlir::ModuleOp>();
996
997 // The ABI lowering pass is interested in CIR operations with operands or
998 // results of CXXABI-dependent types, or CIR operations with regions whose
999 // block arguments are of CXXABI-dependent types.
1000 target.addDynamicallyLegalDialect<cir::CIRDialect>(
1001 [&typeConverter](mlir::Operation *op) {
1002 if (!typeConverter.isLegal(op))
1003 return false;
1004
1005 bool attrs = llvm::all_of(
1006 op->getAttrs(), [&typeConverter](const mlir::NamedAttribute &a) {
1007 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1008 });
1009
1010 return attrs &&
1011 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1012 [&typeConverter](mlir::Region &region) {
1013 return typeConverter.isLegal(&region);
1014 });
1015 });
1016
1017 target.addDynamicallyLegalDialect<mlir::acc::OpenACCDialect>(
1018 [&typeConverter](mlir::Operation *op) {
1019 if (!typeConverter.isLegal(op))
1020 return false;
1021
1022 bool attrs = llvm::all_of(
1023 op->getAttrs(), [&typeConverter](const mlir::NamedAttribute &a) {
1024 return isCXXABIAttributeLegal(typeConverter, a.getValue());
1025 });
1026
1027 return attrs &&
1028 std::all_of(op->getRegions().begin(), op->getRegions().end(),
1029 [&typeConverter](mlir::Region &region) {
1030 return typeConverter.isLegal(&region);
1031 });
1032 });
1033
1034 // Some CIR ops needs special checking for legality
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());
1039 });
1040
1041 return attrs && typeConverter.isLegal(op.getFunctionType());
1042 });
1043 target.addDynamicallyLegalOp<cir::GlobalOp>(
1044 [&typeConverter](cir::GlobalOp op) {
1045 return typeConverter.isLegal(op.getSymType());
1046 });
1047 // Operations that do not use any special types must be explicitly marked as
1048 // illegal to trigger processing here.
1049 target.addIllegalOp<cir::DeleteArrayOp>();
1050 target.addIllegalOp<cir::DynamicCastOp>();
1051 target.addIllegalOp<cir::VTableGetTypeInfoOp>();
1052}
1053
1054//===----------------------------------------------------------------------===//
1055// The Pass
1056//===----------------------------------------------------------------------===//
1057
1058void CXXABILoweringPass::runOnOperation() {
1059 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1060 mlir::MLIRContext *ctx = mod.getContext();
1061
1062 std::unique_ptr<cir::LowerModule> lowerModule = cir::createLowerModule(mod);
1063 // If lower module is not available, skip the ABI lowering pass.
1064 if (!lowerModule) {
1065 mod.emitWarning("Cannot create a CIR lower module, skipping the ")
1066 << getName() << " pass";
1067 return;
1068 }
1069
1070 mlir::DataLayout dataLayout(mod);
1071 CIRABITypeConverter typeConverter(*ctx, dataLayout, *lowerModule);
1072
1073 mlir::RewritePatternSet patterns(ctx);
1074 patterns.add<CIRGenericCXXABILoweringPattern>(patterns.getContext(),
1075 typeConverter);
1076 patterns.add<
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);
1081
1082 mlir::ConversionTarget target(*ctx);
1083 populateCXXABIConversionTarget(target, typeConverter);
1084
1085 llvm::SmallVector<mlir::Operation *> ops;
1086 ops.push_back(mod);
1087 cir::collectUnreachable(mod, ops);
1088
1089 if (failed(mlir::applyPartialConversion(ops, target, std::move(patterns))))
1090 signalPassFailure();
1091
1092 typeConverter.restoreRecordTypeNames();
1093}
1094
1095std::unique_ptr<Pass> mlir::createCXXABILoweringPass() {
1096 return std::make_unique<CXXABILoweringPass>();
1097}
#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.
Definition CIRCXXABI.cpp:25
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
Definition LowerModule.h:46
bool isComplete() const
Definition CIRTypes.h:123
void removeABIConversionNamePrefix()
Definition CIRTypes.cpp:677
void complete(llvm::ArrayRef< mlir::Type > members, bool packed, mlir::Type padding, llvm::ArrayRef< RecordMemberKind > memberKinds)
padding is union-only.
Definition CIRTypes.cpp:638
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
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)
Definition HeaderFile.h:38
RangeSelector callArgs(std::string ID)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCXXABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)