clang 24.0.0git
LowerItaniumCXXABI.cpp
Go to the documentation of this file.
1//===---- LowerItaniumCXXABI.cpp - Emit CIR code Itanium-specific code ---===//
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 provides CIR lowering logic targeting the Itanium C++ ABI. The class in
10// this file generates records that follow the Itanium C++ ABI, which is
11// documented at:
12// https://itanium-cxx-abi.github.io/cxx-abi/abi.html
13// https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
14//
15// It also supports the closely-related ARM ABI, documented at:
16// https://developer.arm.com/documentation/ihi0041/g/
17//
18// This file partially mimics clang/lib/CodeGen/ItaniumCXXABI.cpp. The queries
19// are adapted to operate on the CIR dialect, however.
20//
21//===----------------------------------------------------------------------===//
22
23#include "CIRCXXABI.h"
24#include "LowerModule.h"
25#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
26#include "mlir/IR/ImplicitLocOpBuilder.h"
28#include "llvm/Support/ErrorHandling.h"
29
30namespace cir {
31
32namespace {
33
34class LowerItaniumCXXABI : public CIRCXXABI {
35protected:
36 bool useARMMethodPtrABI;
37 bool use32BitVTableOffsetABI;
38
39public:
40 LowerItaniumCXXABI(LowerModule &lm, bool useARMMethodPtrABI = false,
41 bool use32BitVTableOffsetABI = false)
42 : CIRCXXABI(lm), useARMMethodPtrABI(useARMMethodPtrABI),
43 use32BitVTableOffsetABI(use32BitVTableOffsetABI) {}
44
45 /// Lower the given data member pointer type to its ABI type. The returned
46 /// type is also a CIR type.
47 virtual mlir::Type
48 lowerDataMemberType(cir::DataMemberType type,
49 const mlir::TypeConverter &typeConverter) const override;
50
51 mlir::Type
52 lowerMethodType(cir::MethodType type,
53 const mlir::TypeConverter &typeConverter) const override;
54
55 mlir::TypedAttr lowerDataMemberConstant(
56 cir::DataMemberAttr attr, const mlir::DataLayout &layout,
57 const mlir::TypeConverter &typeConverter) const override;
58
59 mlir::TypedAttr lowerDataMemberOffsetConstant(
60 cir::DataMemberOffsetAttr attr, const mlir::DataLayout &layout,
61 const mlir::TypeConverter &typeConverter) const override;
62
63 mlir::TypedAttr
64 lowerMethodConstant(cir::MethodAttr attr, const mlir::DataLayout &layout,
65 const mlir::TypeConverter &typeConverter) const override;
66
67 mlir::Operation *
68 lowerGetRuntimeMember(cir::GetRuntimeMemberOp op, mlir::Type loweredResultTy,
69 mlir::Value loweredAddr, mlir::Value loweredMember,
70 mlir::OpBuilder &builder) const override;
71
72 void lowerGetMethod(cir::GetMethodOp op, mlir::Value &callee,
73 mlir::Value &thisArg, mlir::Value loweredMethod,
74 mlir::Value loweredObjectPtr,
75 mlir::ConversionPatternRewriter &rewriter) const override;
76
77 mlir::Value lowerBaseDataMember(cir::BaseDataMemberOp op,
78 mlir::Value loweredSrc,
79 mlir::OpBuilder &builder) const override;
80
81 mlir::Value lowerDerivedDataMember(cir::DerivedDataMemberOp op,
82 mlir::Value loweredSrc,
83 mlir::OpBuilder &builder) const override;
84
85 mlir::Value lowerBaseMethod(cir::BaseMethodOp op, mlir::Value loweredSrc,
86 mlir::OpBuilder &builder) const override;
87
88 mlir::Value lowerDerivedMethod(cir::DerivedMethodOp op,
89 mlir::Value loweredSrc,
90 mlir::OpBuilder &builder) const override;
91
92 mlir::Value lowerDataMemberCmp(cir::CmpOp op, mlir::Value loweredLhs,
93 mlir::Value loweredRhs,
94 mlir::OpBuilder &builder) const override;
95
96 mlir::Value lowerMethodCmp(cir::CmpOp op, mlir::Value loweredLhs,
97 mlir::Value loweredRhs,
98 mlir::OpBuilder &builder) const override;
99
100 mlir::Value lowerDataMemberBitcast(cir::CastOp op, mlir::Type loweredDstTy,
101 mlir::Value loweredSrc,
102 mlir::OpBuilder &builder) const override;
103
104 mlir::Value
105 lowerDataMemberToBoolCast(cir::CastOp op, mlir::Value loweredSrc,
106 mlir::OpBuilder &builder) const override;
107
108 mlir::Value lowerMethodBitcast(cir::CastOp op, mlir::Type loweredDstTy,
109 mlir::Value loweredSrc,
110 mlir::OpBuilder &builder) const override;
111
112 mlir::Value lowerMethodToBoolCast(cir::CastOp op, mlir::Value loweredSrc,
113 mlir::OpBuilder &builder) const override;
114
115 mlir::Value lowerDynamicCast(cir::DynamicCastOp op,
116 mlir::OpBuilder &builder) const override;
117 mlir::Value lowerVTableGetTypeInfo(cir::VTableGetTypeInfoOp op,
118 mlir::OpBuilder &builder) const override;
119
120 clang::CharUnits
121 getArrayCookieSizeImpl(clang::CharUnits elementAlign) const override;
122
123 mlir::Value readArrayCookieImpl(mlir::Location loc, mlir::Value allocPtr,
124 clang::CharUnits cookieSize,
125 clang::CharUnits cookieAlignment,
126 const mlir::DataLayout &dataLayout,
127 CIRBaseBuilderTy &builder) const override;
128};
129
130} // namespace
131
132std::unique_ptr<CIRCXXABI> createItaniumCXXABI(LowerModule &lm) {
133 switch (lm.getCXXABIKind()) {
134 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
135 // include the other 32-bit ARM oddities: constructor/destructor return values
136 // and array cookies.
137 case clang::TargetCXXABI::GenericAArch64:
138 return std::make_unique<LowerItaniumCXXABI>(
139 lm,
140 /*useARMMethodPtrABI=*/true,
141 /*use32BitVTableOffsetABI=*/false);
142 case clang::TargetCXXABI::AppleARM64:
143 // TODO: this isn't quite right, clang uses AppleARM64CXXABI which inherits
144 // from ARMCXXABI. We'll have to follow suit.
146 return std::make_unique<LowerItaniumCXXABI>(
147 lm,
148 /*useARMMethodPtrABI=*/true,
149 /*use32BitVTableOffsetABI=*/true);
150
151 case clang::TargetCXXABI::GenericItanium:
152 return std::make_unique<LowerItaniumCXXABI>(lm);
153
154 case clang::TargetCXXABI::GenericARM:
155 case clang::TargetCXXABI::iOS:
156 case clang::TargetCXXABI::WatchOS:
157 case clang::TargetCXXABI::Fuchsia:
158 case clang::TargetCXXABI::GenericMIPS:
159 case clang::TargetCXXABI::WebAssembly:
160 case clang::TargetCXXABI::XL:
161 // FIXME: these ABIS are not yet implemented by CIR. The error is reported
162 // by consumers of LowerModule/CIRCXXABI when missing CIRCXXABI is
163 // encountered.
164 return nullptr;
165 case clang::TargetCXXABI::Microsoft:
166 llvm_unreachable("Microsoft ABI is not Itanium-based");
167 }
168 llvm_unreachable("bad ABI kind");
169}
170
171static cir::IntType getPtrDiffCIRTy(LowerModule &lm) {
172 const clang::TargetInfo &target = lm.getTarget();
175 return cir::IntType::get(lm.getMLIRContext(), target.getTypeWidth(ptrdiffTy),
176 target.isTypeSigned(ptrdiffTy));
177}
178
179mlir::Type LowerItaniumCXXABI::lowerDataMemberType(
180 cir::DataMemberType type, const mlir::TypeConverter &typeConverter) const {
181 // Itanium C++ ABI 2.3.1:
182 // A data member pointer is represented as the data member's offset in bytes
183 // from the address point of an object of the base type, as a ptrdiff_t.
184 return getPtrDiffCIRTy(lm);
185}
186
187mlir::Type LowerItaniumCXXABI::lowerMethodType(
188 cir::MethodType type, const mlir::TypeConverter &typeConverter) const {
189 // Itanium C++ ABI 2.3.2:
190 // In all representations, the basic ABI properties of member function
191 // pointer types are those of the following class, where fnptr_t is the
192 // appropriate function-pointer type for a member function of this type:
193 //
194 // struct {
195 // fnptr_t ptr;
196 // ptrdiff_t adj;
197 // };
198
199 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lm);
200
201 // Note that clang CodeGen emits struct{ptrdiff_t, ptrdiff_t} for member
202 // function pointers. Let's follow this approach.
203 mlir::Type members[] = {ptrdiffCIRTy, ptrdiffCIRTy};
204 return cir::StructType::get(type.getContext(), members, /*packed=*/false,
205 /*is_class=*/false,
207}
208
209mlir::TypedAttr LowerItaniumCXXABI::lowerDataMemberConstant(
210 cir::DataMemberAttr attr, const mlir::DataLayout &layout,
211 const mlir::TypeConverter &typeConverter) const {
212 int64_t memberOffset;
213 if (attr.isNullPtr()) {
214 // Itanium C++ ABI 2.3:
215 // A NULL pointer is represented as -1.
216 memberOffset = -1;
217 } else {
218 // Itanium C++ ABI 2.3:
219 // A pointer to data member is an offset from the base address of
220 // the class object containing it, represented as a ptrdiff_t.
221 // Walk the GEP-style path, accumulating the byte offset at each step.
222 memberOffset = 0;
223 mlir::Type currentTy = attr.getType().getClassTy();
224 for (int32_t idx : attr.getPath()) {
225 auto recTy = mlir::cast<cir::RecordType>(currentTy);
226 memberOffset += static_cast<int64_t>(recTy.getElementOffset(layout, idx));
227 currentTy = recTy.getMembers()[idx];
228 }
229 }
230
231 mlir::Type abiTy = lowerDataMemberType(attr.getType(), typeConverter);
232 return cir::IntAttr::get(abiTy, memberOffset);
233}
234
235mlir::TypedAttr LowerItaniumCXXABI::lowerDataMemberOffsetConstant(
236 cir::DataMemberOffsetAttr attr, const mlir::DataLayout &layout,
237 const mlir::TypeConverter &typeConverter) const {
238 // Itanium C++ ABI 2.3:
239 // A pointer to data member is an offset from the base address of the class
240 // object containing it, represented as a ptrdiff_t.
241 // The offset is already known (the member has no CIR field index).
242 mlir::Type abiTy = lowerDataMemberType(attr.getType(), typeConverter);
243 return cir::IntAttr::get(abiTy, static_cast<int64_t>(attr.getOffset()));
244}
245
246mlir::TypedAttr LowerItaniumCXXABI::lowerMethodConstant(
247 cir::MethodAttr attr, const mlir::DataLayout &layout,
248 const mlir::TypeConverter &typeConverter) const {
249 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lm);
250
251 auto loweredMethodTy = mlir::cast<cir::StructType>(
252 lowerMethodType(attr.getType(), typeConverter));
253
254 auto zero = cir::IntAttr::get(ptrdiffCIRTy, 0);
255
256 // Itanium C++ ABI 2.3.2:
257 // In all representations, the basic ABI properties of member function
258 // pointer types are those of the following class, where fnptr_t is the
259 // appropriate function-pointer type for a member function of this type:
260 //
261 // struct {
262 // fnptr_t ptr;
263 // ptrdiff_t adj;
264 // };
265
266 if (attr.isNull()) {
267 // Itanium C++ ABI 2.3.2:
268 //
269 // In the standard representation, a null member function pointer is
270 // represented with ptr set to a null pointer. The value of adj is
271 // unspecified for null member function pointers.
272 //
273 // clang CodeGen emits struct{null, null} for null member function pointers.
274 // Let's do the same here.
275 return cir::ConstRecordAttr::get(
276 loweredMethodTy, mlir::ArrayAttr::get(attr.getContext(), {zero, zero}));
277 }
278
279 if (attr.isVirtual()) {
280 if (useARMMethodPtrABI) {
281 // ARM C++ ABI 3.2.1:
282 // This ABI specifies that adj contains twice the this
283 // adjustment, plus 1 if the member function is virtual. The
284 // least significant bit of adj then makes exactly the same
285 // discrimination as the least significant bit of ptr does for
286 // Itanium.
288 auto ptr =
289 cir::IntAttr::get(ptrdiffCIRTy, attr.getVtableOffset().value());
290 auto one = cir::IntAttr::get(ptrdiffCIRTy, 1);
291 return cir::ConstRecordAttr::get(
292 loweredMethodTy, mlir::ArrayAttr::get(attr.getContext(), {ptr, one}));
293 }
294
295 // Itanium C++ ABI 2.3.2:
296 //
297 // In the standard representation, a member function pointer for a
298 // virtual function is represented with ptr set to 1 plus the function's
299 // v-table entry offset (in bytes), converted to a function pointer as if
300 // by reinterpret_cast<fnptr_t>(uintfnptr_t(1 + offset)), where
301 // uintfnptr_t is an unsigned integer of the same size as fnptr_t.
302 auto ptr =
303 cir::IntAttr::get(ptrdiffCIRTy, 1 + attr.getVtableOffset().value());
304 return cir::ConstRecordAttr::get(
305 loweredMethodTy, mlir::ArrayAttr::get(attr.getContext(), {ptr, zero}));
306 }
307
308 // Itanium C++ ABI 2.3.2:
309 //
310 // A member function pointer for a non-virtual member function is
311 // represented with ptr set to a pointer to the function, using the base
312 // ABI's representation of function pointers.
313 auto ptr = cir::GlobalViewAttr::get(ptrdiffCIRTy, attr.getSymbol().value());
314 return cir::ConstRecordAttr::get(
315 loweredMethodTy, mlir::ArrayAttr::get(attr.getContext(), {ptr, zero}));
316}
317
318mlir::Operation *LowerItaniumCXXABI::lowerGetRuntimeMember(
319 cir::GetRuntimeMemberOp op, mlir::Type loweredResultTy,
320 mlir::Value loweredAddr, mlir::Value loweredMember,
321 mlir::OpBuilder &builder) const {
322 auto byteTy = cir::IntType::get(op.getContext(), 8, true);
323 auto bytePtrTy = cir::PointerType::get(
324 byteTy,
325 mlir::cast<cir::PointerType>(op.getAddr().getType()).getAddrSpace());
326 auto objectBytesPtr = cir::CastOp::create(
327 builder, op.getLoc(), bytePtrTy, cir::CastKind::bitcast, op.getAddr());
328 auto memberBytesPtr = cir::PtrStrideOp::create(
329 builder, op.getLoc(), bytePtrTy, objectBytesPtr, loweredMember);
330 return cir::CastOp::create(builder, op.getLoc(), op.getType(),
331 cir::CastKind::bitcast, memberBytesPtr);
332}
333
334void LowerItaniumCXXABI::lowerGetMethod(
335 cir::GetMethodOp op, mlir::Value &callee, mlir::Value &thisArg,
336 mlir::Value loweredMethod, mlir::Value loweredObjectPtr,
337 mlir::ConversionPatternRewriter &rewriter) const {
338 // In the Itanium and ARM ABIs, method pointers have the form:
339 // struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
340 //
341 // In the Itanium ABI:
342 // - method pointers are virtual if (memptr.ptr & 1) is nonzero
343 // - the this-adjustment is (memptr.adj)
344 // - the virtual offset is (memptr.ptr - 1)
345 //
346 // In the ARM ABI:
347 // - method pointers are virtual if (memptr.adj & 1) is nonzero
348 // - the this-adjustment is (memptr.adj >> 1)
349 // - the virtual offset is (memptr.ptr)
350 // ARM uses 'adj' for the virtual flag because Thumb functions
351 // may be only single-byte aligned.
352 //
353 // If the member is virtual, the adjusted 'this' pointer points
354 // to a vtable pointer from which the virtual offset is applied.
355 //
356 // If the member is non-virtual, memptr.ptr is the address of
357 // the function to call.
358
359 mlir::ImplicitLocOpBuilder locBuilder(op.getLoc(), rewriter);
360 mlir::Type calleePtrTy = op.getCallee().getType();
361
362 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lm);
363 mlir::Value ptrdiffOne =
364 cir::ConstantOp::create(locBuilder, cir::IntAttr::get(ptrdiffCIRTy, 1));
365
366 mlir::Value rawAdj =
367 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredMethod, 1);
368 mlir::Value adj = rawAdj;
369 if (useARMMethodPtrABI)
370 adj = cir::ShiftOp::create(locBuilder, ptrdiffCIRTy, adj, ptrdiffOne,
371 /*isLeftShift=*/false);
372
373 // Apply the adjustment to the 'this' pointer.
374 mlir::Type thisVoidPtrTy =
375 cir::PointerType::get(cir::VoidType::get(locBuilder.getContext()),
376 op.getObject().getType().getAddrSpace());
377 mlir::Value thisVoidPtr = cir::CastOp::create(
378 locBuilder, thisVoidPtrTy, cir::CastKind::bitcast, loweredObjectPtr);
379 thisArg =
380 cir::PtrStrideOp::create(locBuilder, thisVoidPtrTy, thisVoidPtr, adj);
381
382 // Load the "ptr" field of the member function pointer and determine if it
383 // points to a virtual function.
384 mlir::Value methodPtrField =
385 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredMethod, 0);
386 mlir::Value virtualBit;
387 if (useARMMethodPtrABI)
388 virtualBit = cir::AndOp::create(locBuilder, rawAdj, ptrdiffOne);
389 else
390 virtualBit = cir::AndOp::create(locBuilder, methodPtrField, ptrdiffOne);
391 mlir::Value isVirtual = cir::CmpOp::create(locBuilder, cir::CmpOpKind::eq,
392 virtualBit, ptrdiffOne);
393
397
398 auto buildVirtualCallee = [&](mlir::OpBuilder &b, mlir::Location loc) {
399 // Load vtable pointer.
400 // Note that vtable pointer always point to the global address space.
401 auto vtablePtrTy =
402 cir::PointerType::get(cir::IntType::get(b.getContext(), 8, true));
403 auto vtablePtrPtrTy = cir::PointerType::get(
404 vtablePtrTy, op.getObject().getType().getAddrSpace());
405 auto vtablePtrPtr = cir::CastOp::create(b, loc, vtablePtrPtrTy,
406 cir::CastKind::bitcast, thisArg);
408 mlir::Value vtablePtr =
409 cir::LoadOp::create(b, loc, vtablePtrPtr, /*isDeref=*/false,
410 /*isVolatile=*/false,
411 /*isNontemporal=*/false,
412 /*alignment=*/mlir::IntegerAttr(),
413 /*sync_scope=*/cir::SyncScopeKindAttr{},
414 /*mem_order=*/cir::MemOrderAttr(),
415 /*invariant=*/false);
416
417 // Apply the offset.
418 // On ARM64, to reserve extra space in virtual member function pointers,
419 // we only pay attention to the low 32 bits of the offset.
420 mlir::Value vtableOffset = methodPtrField;
421 if (!useARMMethodPtrABI)
422 vtableOffset = cir::SubOp::create(b, loc, vtableOffset.getType(),
423 vtableOffset, ptrdiffOne);
424 if (use32BitVTableOffsetABI)
425 llvm_unreachable("AppleARM64 method ptr abi NYI");
426
430
431 // Apply the offset to the vtable pointer and get the pointer to the target
432 // virtual function. Then load that pointer to get the callee.
433 mlir::Value vfpAddr = cir::PtrStrideOp::create(locBuilder, vtablePtrTy,
434 vtablePtr, vtableOffset);
435 auto vfpPtrTy = cir::PointerType::get(calleePtrTy);
436 mlir::Value vfpPtr = cir::CastOp::create(locBuilder, vfpPtrTy,
437 cir::CastKind::bitcast, vfpAddr);
438 auto fnPtr = cir::LoadOp::create(b, loc, vfpPtr,
439 /*isDeref=*/false, /*isVolatile=*/false,
440 /*isNontemporal=*/false,
441 /*alignment=*/mlir::IntegerAttr(),
442 /*sync_scope=*/cir::SyncScopeKindAttr{},
443 /*mem_order=*/cir::MemOrderAttr(),
444 /*invariant=*/false);
445
446 cir::YieldOp::create(b, loc, fnPtr.getResult());
448 };
449
450 callee = cir::TernaryOp::create(
451 locBuilder, isVirtual, /*thenBuilder=*/buildVirtualCallee,
452 /*elseBuilder=*/
453 [&](mlir::OpBuilder &b, mlir::Location loc) {
454 auto fnPtr = cir::CastOp::create(b, loc, calleePtrTy,
455 cir::CastKind::int_to_ptr,
456 methodPtrField);
457 cir::YieldOp::create(b, loc, fnPtr.getResult());
458 })
459 .getResult();
460}
461
462static mlir::Value lowerDataMemberCast(mlir::Operation *op,
463 mlir::Value loweredSrc,
464 std::int64_t offset,
465 bool isDerivedToBase,
466 mlir::OpBuilder &builder) {
467 if (offset == 0)
468 return loweredSrc;
469 mlir::Location loc = op->getLoc();
470 mlir::Type ty = loweredSrc.getType();
471
472 auto getConstantInt = [&](int64_t value) -> cir::ConstantOp {
473 return cir::ConstantOp::create(builder, loc, cir::IntAttr::get(ty, value));
474 };
475
476 cir::ConstantOp nullValue = getConstantInt(-1);
477 auto isNull = cir::CmpOp::create(builder, loc, cir::CmpOpKind::eq, loweredSrc,
478 nullValue);
479
480 cir::ConstantOp offsetValue = getConstantInt(offset);
481 mlir::Value adjustedPtr;
482 if (isDerivedToBase)
483 adjustedPtr = cir::SubOp::create(builder, loc, loweredSrc, offsetValue,
484 cir::OverflowFlags::NoSignedWrap);
485 else
486 adjustedPtr = cir::AddOp::create(builder, loc, loweredSrc, offsetValue,
487 cir::OverflowFlags::NoSignedWrap);
488
489 return cir::SelectOp::create(builder, loc, ty, isNull, loweredSrc,
490 adjustedPtr);
491}
492
493mlir::Value
494LowerItaniumCXXABI::lowerBaseDataMember(cir::BaseDataMemberOp op,
495 mlir::Value loweredSrc,
496 mlir::OpBuilder &builder) const {
497 return lowerDataMemberCast(op, loweredSrc, op.getOffset().getSExtValue(),
498 /*isDerivedToBase=*/true, builder);
499}
500
501mlir::Value
502LowerItaniumCXXABI::lowerDerivedDataMember(cir::DerivedDataMemberOp op,
503 mlir::Value loweredSrc,
504 mlir::OpBuilder &builder) const {
505 return lowerDataMemberCast(op, loweredSrc, op.getOffset().getSExtValue(),
506 /*isDerivedToBase=*/false, builder);
507}
508
509static mlir::Value lowerMethodCast(mlir::Operation *op, mlir::Value loweredSrc,
510 std::int64_t offset, bool isDerivedToBase,
511 bool useARMMethodPtrABI,
512 LowerModule &lowerMod,
513 mlir::OpBuilder &builder) {
514 if (offset == 0)
515 return loweredSrc;
516
517 // The this-adjustment is left-shifted by 1 on ARM, since the low bit of the
518 // adjustment field is used to encode whether the member function is virtual.
519 if (useARMMethodPtrABI)
520 offset <<= 1;
521
522 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lowerMod);
523 auto adjField = cir::ExtractMemberOp::create(builder, op->getLoc(),
524 ptrdiffCIRTy, loweredSrc, 1);
525
526 auto offsetValue = cir::ConstantOp::create(
527 builder, op->getLoc(), cir::IntAttr::get(ptrdiffCIRTy, offset));
528 mlir::Value adjustedAdjField;
529 if (isDerivedToBase)
530 adjustedAdjField =
531 cir::SubOp::create(builder, op->getLoc(), adjField, offsetValue,
532 cir::OverflowFlags::NoSignedWrap);
533 else
534 adjustedAdjField =
535 cir::AddOp::create(builder, op->getLoc(), adjField, offsetValue,
536 cir::OverflowFlags::NoSignedWrap);
537
538 return cir::InsertMemberOp::create(builder, op->getLoc(), loweredSrc, 1,
539 adjustedAdjField);
540}
541
542mlir::Value
543LowerItaniumCXXABI::lowerBaseMethod(cir::BaseMethodOp op,
544 mlir::Value loweredSrc,
545 mlir::OpBuilder &builder) const {
546 return lowerMethodCast(op, loweredSrc, op.getOffset().getSExtValue(),
547 /*isDerivedToBase=*/true, useARMMethodPtrABI, lm,
548 builder);
549}
550
551mlir::Value
552LowerItaniumCXXABI::lowerDerivedMethod(cir::DerivedMethodOp op,
553 mlir::Value loweredSrc,
554 mlir::OpBuilder &builder) const {
555 return lowerMethodCast(op, loweredSrc, op.getOffset().getSExtValue(),
556 /*isDerivedToBase=*/false, useARMMethodPtrABI, lm,
557 builder);
558}
559
560mlir::Value
561LowerItaniumCXXABI::lowerDataMemberCmp(cir::CmpOp op, mlir::Value loweredLhs,
562 mlir::Value loweredRhs,
563 mlir::OpBuilder &builder) const {
564 return cir::CmpOp::create(builder, op.getLoc(), op.getKind(), loweredLhs,
565 loweredRhs);
566}
567
568mlir::Value LowerItaniumCXXABI::lowerMethodCmp(cir::CmpOp op,
569 mlir::Value loweredLhs,
570 mlir::Value loweredRhs,
571 mlir::OpBuilder &builder) const {
572 assert(op.getKind() == cir::CmpOpKind::eq ||
573 op.getKind() == cir::CmpOpKind::ne);
574
575 mlir::ImplicitLocOpBuilder locBuilder(op.getLoc(), builder);
576 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lm);
577 mlir::Value ptrdiffZero =
578 cir::ConstantOp::create(locBuilder, cir::IntAttr::get(ptrdiffCIRTy, 0));
579
580 mlir::Value lhsPtrField =
581 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredLhs, 0);
582 mlir::Value rhsPtrField =
583 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredRhs, 0);
584 mlir::Value ptrCmp =
585 cir::CmpOp::create(locBuilder, op.getKind(), lhsPtrField, rhsPtrField);
586 mlir::Value ptrCmpToNull =
587 cir::CmpOp::create(locBuilder, op.getKind(), lhsPtrField, ptrdiffZero);
588
589 mlir::Value lhsAdjField =
590 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredLhs, 1);
591 mlir::Value rhsAdjField =
592 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredRhs, 1);
593 mlir::Value adjCmp =
594 cir::CmpOp::create(locBuilder, op.getKind(), lhsAdjField, rhsAdjField);
595
596 auto create_and = [&](mlir::Value lhs, mlir::Value rhs) {
597 return cir::AndOp::create(locBuilder, lhs.getType(), lhs, rhs);
598 };
599 auto create_or = [&](mlir::Value lhs, mlir::Value rhs) {
600 return cir::OrOp::create(locBuilder, lhs.getType(), lhs, rhs);
601 };
602
603 // Null member function pointers on ARM clear the low bit of Adj,
604 // so the zero condition has to check that neither low bit is set.
605 if (useARMMethodPtrABI) {
606 mlir::Value one =
607 cir::ConstantOp::create(locBuilder, cir::IntAttr::get(ptrdiffCIRTy, 1));
608
609 // The low bit of the adjustment field is used to encode whether the member
610 // function is virtual, but the ARM ABI specifies that for null pointers
611 // this bit must be clear. Therefore, to test whether the member pointer is
612 // null, we need to check that bit.
613 //
614 // If we are performing an equality check, ptrCmpToNull indicates that both
615 // pointers are null (if they are equal -- we only actually test lhs).
616 // If we are performing an inequality check, ptrCmpToNull indicates that
617 // one of the pointers is not null.
618 //
619 // To apply the ARM-specific logic, if either virtual bit is set, they
620 // cannot both be null (equality case -- ptrCmpToNull &= orAdjAnd1CmpZero),
621 // and if either virtual bit is set, one of the pointers is not null
622 // (inequality case -- ptrCmpToNull |= orAdjAnd1CmpZero).
623 mlir::Value orAdj = create_or(lhsAdjField, rhsAdjField);
624 mlir::Value orAdjAnd1 = create_and(orAdj, one);
625 mlir::Value orAdjAnd1CmpZero =
626 cir::CmpOp::create(locBuilder, op.getKind(), orAdjAnd1, ptrdiffZero);
627
628 if (op.getKind() == cir::CmpOpKind::eq)
629 ptrCmpToNull = create_and(ptrCmpToNull, orAdjAnd1CmpZero);
630 else
631 ptrCmpToNull = create_or(ptrCmpToNull, orAdjAnd1CmpZero);
632 }
633
634 mlir::Value result;
635 if (op.getKind() == cir::CmpOpKind::eq) {
636 // (lhs.ptr == null || lhs.adj == rhs.adj) && lhs.ptr == rhs.ptr
637 result = create_and(ptrCmp, create_or(ptrCmpToNull, adjCmp));
638 } else {
639 // lhs.ptr == rhs.ptr && (lhs.ptr == null || lhs.adj == rhs.adj)
640 result = create_or(ptrCmp, create_and(ptrCmpToNull, adjCmp));
641 }
642
643 return result;
644}
645
646mlir::Value LowerItaniumCXXABI::lowerDataMemberBitcast(
647 cir::CastOp op, mlir::Type loweredDstTy, mlir::Value loweredSrc,
648 mlir::OpBuilder &builder) const {
649 if (loweredSrc.getType() == loweredDstTy)
650 return loweredSrc;
651
652 return cir::CastOp::create(builder, op.getLoc(), loweredDstTy,
653 cir::CastKind::bitcast, loweredSrc);
654}
655
656mlir::Value LowerItaniumCXXABI::lowerDataMemberToBoolCast(
657 cir::CastOp op, mlir::Value loweredSrc, mlir::OpBuilder &builder) const {
658 // Itanium C++ ABI 2.3:
659 // A NULL pointer is represented as -1.
660 auto nullAttr = cir::IntAttr::get(getPtrDiffCIRTy(lm), -1);
661 auto nullValue = cir::ConstantOp::create(builder, op.getLoc(), nullAttr);
662 return cir::CmpOp::create(builder, op.getLoc(), cir::CmpOpKind::ne,
663 loweredSrc, nullValue);
664}
665
666mlir::Value
667LowerItaniumCXXABI::lowerMethodBitcast(cir::CastOp op, mlir::Type loweredDstTy,
668 mlir::Value loweredSrc,
669 mlir::OpBuilder &builder) const {
670 if (loweredSrc.getType() == loweredDstTy)
671 return loweredSrc;
672
673 return loweredSrc;
674}
675
676mlir::Value LowerItaniumCXXABI::lowerMethodToBoolCast(
677 cir::CastOp op, mlir::Value loweredSrc, mlir::OpBuilder &builder) const {
678 mlir::ImplicitLocOpBuilder locBuilder(op.getLoc(), builder);
679
680 // Itanium C++ ABI 2.3.2:
681 //
682 // In the standard representation, a null member function pointer is
683 // represented with ptr set to a null pointer. The value of adj is
684 // unspecified for null member function pointers.
685 cir::IntType ptrdiffCIRTy = getPtrDiffCIRTy(lm);
686 mlir::Value ptrdiffZero =
687 cir::ConstantOp::create(locBuilder, cir::IntAttr::get(ptrdiffCIRTy, 0));
688 mlir::Value ptrField =
689 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredSrc, 0);
690
691 mlir::Value result =
692 cir::CmpOp::create(locBuilder, cir::CmpOpKind::ne, ptrField, ptrdiffZero);
693
694 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
695 // (the virtual bit) is set.
696 if (useARMMethodPtrABI) {
697 mlir::Value one =
698 cir::ConstantOp::create(locBuilder, cir::IntAttr::get(ptrdiffCIRTy, 1));
699 mlir::Value adj =
700 cir::ExtractMemberOp::create(locBuilder, ptrdiffCIRTy, loweredSrc, 1);
701 mlir::Value virtualBit =
702 cir::AndOp::create(locBuilder, ptrdiffCIRTy, adj, one);
703 mlir::Value isVirtual = cir::CmpOp::create(locBuilder, cir::CmpOpKind::ne,
704 virtualBit, ptrdiffZero);
705 result = cir::OrOp::create(locBuilder, result, isVirtual);
706 }
707
708 return result;
709}
710
711static void buildBadCastCall(mlir::OpBuilder &builder, mlir::Location loc,
712 mlir::FlatSymbolRefAttr badCastFuncRef) {
713 // TODO(cir): set the runtime calling convention to this call.
715 auto callOp = cir::CallOp::create(builder, loc, badCastFuncRef,
716 /*resType=*/cir::VoidType(),
717 /*operands=*/mlir::ValueRange{});
718 callOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
719 builder.getUnitAttr());
720
721 cir::UnreachableOp::create(builder, loc);
722 builder.clearInsertionPoint();
723}
724
725static mlir::Value buildDynamicCastAfterNullCheck(cir::DynamicCastOp op,
726 mlir::OpBuilder &builder) {
727 mlir::Location loc = op->getLoc();
728 mlir::Value srcValue = op.getSrc();
729 cir::DynamicCastInfoAttr castInfo = op.getInfo().value();
730
731 // TODO(cir): consider address space
733
734 auto voidPtrTy =
735 cir::PointerType::get(cir::VoidType::get(builder.getContext()));
736
737 mlir::Value srcPtr = cir::CastOp::create(builder, loc, voidPtrTy,
738 cir::CastKind::bitcast, srcValue);
739 mlir::Value srcRtti =
740 cir::ConstantOp::create(builder, loc, castInfo.getSrcRtti());
741 mlir::Value destRtti =
742 cir::ConstantOp::create(builder, loc, castInfo.getDestRtti());
743 mlir::Value offsetHint =
744 cir::ConstantOp::create(builder, loc, castInfo.getOffsetHint());
745
746 mlir::FlatSymbolRefAttr dynCastFuncRef = castInfo.getRuntimeFunc();
747 mlir::Value dynCastFuncArgs[4] = {srcPtr, srcRtti, destRtti, offsetHint};
748
749 // TODO(cir): set the runtime calling convention to this call.
751
752 mlir::Value castedPtr = cir::CallOp::create(builder, loc, dynCastFuncRef,
753 voidPtrTy, dynCastFuncArgs)
754 .getResult();
755
756 assert(mlir::isa<cir::PointerType>(castedPtr.getType()) &&
757 "the return value of __dynamic_cast should be a ptr");
758
759 /// C++ [expr.dynamic.cast]p9:
760 /// A failed cast to reference type throws std::bad_cast
761 if (op.isRefCast()) {
762 // Emit a cir.if that checks the casted value.
763 mlir::Value null = cir::ConstantOp::create(
764 builder, loc,
765 cir::ConstPtrAttr::get(castedPtr.getType(),
766 builder.getI64IntegerAttr(0)));
767 mlir::Value castedPtrIsNull =
768 cir::CmpOp::create(builder, loc, cir::CmpOpKind::eq, castedPtr, null);
769 cir::IfOp::create(builder, loc, castedPtrIsNull, false,
770 [&](mlir::OpBuilder &, mlir::Location) {
771 buildBadCastCall(builder, loc,
772 castInfo.getBadCastFunc());
773 });
774 }
775
776 // Note that castedPtr is a void*. Cast it to a pointer to the destination
777 // type before return.
778 return cir::CastOp::create(builder, loc, op.getType(), cir::CastKind::bitcast,
779 castedPtr);
780}
781
783 cir::DynamicCastOp op, cir::LowerModule &lm, mlir::OpBuilder &builder) {
784 mlir::Location loc = op.getLoc();
785 bool vtableUsesRelativeLayout = op.getRelativeLayout();
786
787 // TODO(cir): consider address space of the vtable pointer.
789
790 mlir::Type vtableElemTy;
791 uint64_t vtableElemAlign;
792 if (vtableUsesRelativeLayout) {
793 vtableElemTy =
794 cir::IntType::get(builder.getContext(), 32, /*isSigned=*/true);
795 vtableElemAlign = 4;
796 } else {
797 vtableElemTy = getPtrDiffCIRTy(lm);
798 vtableElemAlign = llvm::divideCeil(
800 }
801
802 mlir::Type vtableElemPtrTy = cir::PointerType::get(vtableElemTy);
803 mlir::Type i64Ty = cir::IntType::get(builder.getContext(), /*width=*/64,
804 /*isSigned=*/true);
805
806 // Access vtable to get the offset from the given object to its containing
807 // complete object.
808 // TODO: Add a specialized operation to get the object offset?
809 auto vptrPtr = cir::VTableGetVPtrOp::create(builder, loc, op.getSrc());
810 mlir::Value vptr = cir::LoadOp::create(
811 builder, loc, vptrPtr,
812 /*isDeref=*/false,
813 /*is_volatile=*/false,
814 /*isNontemporal=*/false,
815 /*alignment=*/builder.getI64IntegerAttr(vtableElemAlign),
816 /*sync_scope=*/cir::SyncScopeKindAttr(),
817 /*mem_order=*/cir::MemOrderAttr(),
818 /*invariant=*/false);
819 mlir::Value elementPtr = cir::CastOp::create(builder, loc, vtableElemPtrTy,
820 cir::CastKind::bitcast, vptr);
821 mlir::Value minusTwo =
822 cir::ConstantOp::create(builder, loc, cir::IntAttr::get(i64Ty, -2));
823 mlir::Value offsetToTopSlotPtr = cir::PtrStrideOp::create(
824 builder, loc, vtableElemPtrTy, elementPtr, minusTwo);
825 mlir::Value offsetToTop = cir::LoadOp::create(
826 builder, loc, offsetToTopSlotPtr,
827 /*isDeref=*/false,
828 /*is_volatile=*/false,
829 /*isNontemporal=*/false,
830 /*alignment=*/builder.getI64IntegerAttr(vtableElemAlign),
831 /*sync_scope=*/cir::SyncScopeKindAttr(),
832 /*mem_order=*/cir::MemOrderAttr(),
833 /*invariant=*/false);
834
835 // Add the offset to the given pointer to get the cast result.
836 // Cast the input pointer to a uint8_t* to allow pointer arithmetic.
837 mlir::Type u8PtrTy =
838 cir::PointerType::get(cir::IntType::get(builder.getContext(), /*width=*/8,
839 /*isSigned=*/false),
840 op.getSrc().getType().getAddrSpace());
841 mlir::Value srcBytePtr = cir::CastOp::create(
842 builder, loc, u8PtrTy, cir::CastKind::bitcast, op.getSrc());
843 auto dstBytePtr =
844 cir::PtrStrideOp::create(builder, loc, u8PtrTy, srcBytePtr, offsetToTop);
845 // Cast the result to a void*.
846 return cir::CastOp::create(builder, loc, op.getType(), cir::CastKind::bitcast,
847 dstBytePtr);
848}
849
850mlir::Value
851LowerItaniumCXXABI::lowerDynamicCast(cir::DynamicCastOp op,
852 mlir::OpBuilder &builder) const {
853 mlir::Location loc = op->getLoc();
854 mlir::Value srcValue = op.getSrc();
855
857
858 if (op.isRefCast())
859 return buildDynamicCastAfterNullCheck(op, builder);
860
861 mlir::Value srcValueIsNotNull = cir::CastOp::create(
862 builder, loc, cir::BoolType::get(builder.getContext()),
863 cir::CastKind::ptr_to_bool, srcValue);
864 return cir::TernaryOp::create(
865 builder, loc, srcValueIsNotNull,
866 [&](mlir::OpBuilder &, mlir::Location) {
867 mlir::Value castedValue =
868 op.isCastToVoid()
869 ? buildDynamicCastToVoidAfterNullCheck(op, lm, builder)
870 : buildDynamicCastAfterNullCheck(op, builder);
871 cir::YieldOp::create(builder, loc, castedValue);
872 },
873 [&](mlir::OpBuilder &, mlir::Location) {
874 mlir::Value null = cir::ConstantOp::create(
875 builder, loc,
876 cir::ConstPtrAttr::get(op.getType(),
877 builder.getI64IntegerAttr(0)));
878 cir::YieldOp::create(builder, loc, null);
879 })
880 .getResult();
881}
882mlir::Value
883LowerItaniumCXXABI::lowerVTableGetTypeInfo(cir::VTableGetTypeInfoOp op,
884 mlir::OpBuilder &builder) const {
885 mlir::Location loc = op->getLoc();
886 auto offset = cir::ConstantOp::create(
887 builder, op->getLoc(), cir::IntAttr::get(getPtrDiffCIRTy(lm), -1));
888
889 // Cast the vptr to type_info-ptr, so that we can go backwards 1 pointer.
890 auto vptrCast = cir::CastOp::create(builder, loc, op.getType(),
891 cir::CastKind::bitcast, op.getVptr());
892
893 return cir::PtrStrideOp::create(builder, loc, vptrCast.getType(), vptrCast,
894 offset)
895 .getResult();
896}
897
898clang::CharUnits LowerItaniumCXXABI::getArrayCookieSizeImpl(
899 clang::CharUnits elementAlign) const {
900 // The array cookie is a size_t; pad that up to the element alignment.
901 // The cookie is actually right-justified in that space.
902 clang::CharUnits sizeOfSizeT =
903 clang::CharUnits::fromQuantity(getPtrSizeInBits() / 8);
904 return std::max(sizeOfSizeT, elementAlign);
905}
906
907mlir::Value LowerItaniumCXXABI::readArrayCookieImpl(
908 mlir::Location loc, mlir::Value allocPtr, clang::CharUnits cookieSize,
909 clang::CharUnits cookieAlignment, const mlir::DataLayout &dataLayout,
910 CIRBaseBuilderTy &builder) const {
911 unsigned ptrSizeInBits = getPtrSizeInBits();
912 mlir::ptr::MemorySpaceAttrInterface addrSpace =
913 mlir::cast<cir::PointerType>(allocPtr.getType()).getAddrSpace();
914 auto u8PtrTy = builder.getPointerTo(builder.getUIntNTy(8), addrSpace);
915 auto ptrDiffTy = builder.getSIntNTy(ptrSizeInBits);
916 auto sizeTy = builder.getUIntNTy(ptrSizeInBits);
917
918 // The element count is right-justified in the cookie.
919 clang::CharUnits sizeOfSizeT =
920 clang::CharUnits::fromQuantity(ptrSizeInBits / 8);
921 clang::CharUnits countOffset = cookieSize - sizeOfSizeT;
922
923 mlir::Value countBytePtr = allocPtr;
924 clang::CharUnits countAlignment = cookieAlignment;
925 if (!countOffset.isZero()) {
926 mlir::Value offsetVal = cir::ConstantOp::create(
927 builder, loc, cir::IntAttr::get(ptrDiffTy, countOffset.getQuantity()));
928 countBytePtr =
929 cir::PtrStrideOp::create(builder, loc, u8PtrTy, allocPtr, offsetVal);
930 countAlignment = cookieAlignment.alignmentAtOffset(countOffset);
931 }
932
933 auto countPtrTy = cir::PointerType::get(sizeTy, addrSpace);
934 mlir::Value countPtr = cir::CastOp::create(
935 builder, loc, countPtrTy, cir::CastKind::bitcast, countBytePtr);
936 return cir::LoadOp::create(
937 builder, loc, countPtr, /*isDeref=*/false, /*isVolatile=*/false,
938 /*isNontemporal=*/false,
939 builder.getI64IntegerAttr(countAlignment.getQuantity()),
940 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
941 /*invariant=*/false);
942}
943
944} // namespace cir
cir::PointerType getPointerTo(mlir::Type ty)
cir::IntType getUIntNTy(int n)
cir::IntType getSIntNTy(int n)
mlir::MLIRContext * getMLIRContext()
Definition LowerModule.h:79
clang::TargetCXXABI::Kind getCXXABIKind() const
Definition LowerModule.h:49
const clang::TargetInfo & getTarget() const
Definition LowerModule.h:70
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
Definition CIRTypes.cpp:151
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Exposes information about the current target.
Definition TargetInfo.h:228
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:415
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition TargetInfo.h:501
static mlir::Value lowerDataMemberCast(mlir::Operation *op, mlir::Value loweredSrc, std::int64_t offset, bool isDerivedToBase, mlir::OpBuilder &builder)
std::unique_ptr< CIRCXXABI > createItaniumCXXABI(LowerModule &lm)
Creates an Itanium-family ABI.
static mlir::Value buildDynamicCastAfterNullCheck(cir::DynamicCastOp op, mlir::OpBuilder &builder)
static cir::IntType getPtrDiffCIRTy(LowerModule &lm)
static mlir::Value buildDynamicCastToVoidAfterNullCheck(cir::DynamicCastOp op, cir::LowerModule &lm, mlir::OpBuilder &builder)
static mlir::Value lowerMethodCast(mlir::Operation *op, mlir::Value loweredSrc, std::int64_t offset, bool isDerivedToBase, bool useARMMethodPtrABI, LowerModule &lowerMod, mlir::OpBuilder &builder)
static void buildBadCastCall(mlir::OpBuilder &builder, mlir::Location loc, mlir::FlatSymbolRefAttr badCastFuncRef)
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t
static bool addressSpace()
static bool appleArm64CXXABI()
static bool emitCFICheck()
static bool emitVFEInfo()
static bool emitWPDInfo()
static bool emitTypeCheck()
static bool pointerAuthentication()
static bool opFuncCallingConv()
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:148