clang 22.0.0git
CIRTypes.cpp
Go to the documentation of this file.
1//===- CIRTypes.cpp - MLIR CIR Types --------------------------------------===//
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 file defines the types in the CIR dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "mlir/IR/BuiltinAttributes.h"
16#include "mlir/IR/DialectImplementation.h"
17#include "mlir/IR/MLIRContext.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/TypeSwitch.h"
26
27//===----------------------------------------------------------------------===//
28// CIR Helpers
29//===----------------------------------------------------------------------===//
30bool cir::isSized(mlir::Type ty) {
31 if (auto sizedTy = mlir::dyn_cast<cir::SizedTypeInterface>(ty))
32 return sizedTy.isSized();
34 return false;
35}
36
37//===----------------------------------------------------------------------===//
38// CIR Custom Parser/Printer Signatures
39//===----------------------------------------------------------------------===//
40
41static mlir::ParseResult
42parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector<mlir::Type> &params,
43 bool &isVarArg);
44static void printFuncTypeParams(mlir::AsmPrinter &p,
45 mlir::ArrayRef<mlir::Type> params,
46 bool isVarArg);
47//===----------------------------------------------------------------------===//
48// CIR Custom Parser/Printer Signatures
49//===----------------------------------------------------------------------===//
50
51static mlir::ParseResult
52parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector<mlir::Type> &params,
53 bool &isVarArg);
54
55static void printFuncTypeParams(mlir::AsmPrinter &p,
56 mlir::ArrayRef<mlir::Type> params,
57 bool isVarArg);
58
59//===----------------------------------------------------------------------===//
60// AddressSpace
61//===----------------------------------------------------------------------===//
62
63mlir::ParseResult parseTargetAddressSpace(mlir::AsmParser &p,
64 cir::TargetAddressSpaceAttr &attr);
65
66void printTargetAddressSpace(mlir::AsmPrinter &p,
67 cir::TargetAddressSpaceAttr attr);
68
69//===----------------------------------------------------------------------===//
70// Get autogenerated stuff
71//===----------------------------------------------------------------------===//
72
73namespace cir {
74
75#include "clang/CIR/Dialect/IR/CIRTypeConstraints.cpp.inc"
76
77} // namespace cir
78
79#define GET_TYPEDEF_CLASSES
80#include "clang/CIR/Dialect/IR/CIROpsTypes.cpp.inc"
81
82using namespace mlir;
83using namespace cir;
84
85//===----------------------------------------------------------------------===//
86// General CIR parsing / printing
87//===----------------------------------------------------------------------===//
88
89Type CIRDialect::parseType(DialectAsmParser &parser) const {
90 llvm::SMLoc typeLoc = parser.getCurrentLocation();
91 llvm::StringRef mnemonic;
92 Type genType;
93
94 // Try to parse as a tablegen'd type.
95 OptionalParseResult parseResult =
96 generatedTypeParser(parser, &mnemonic, genType);
97 if (parseResult.has_value())
98 return genType;
99
100 // Type is not tablegen'd: try to parse as a raw C++ type.
101 return StringSwitch<function_ref<Type()>>(mnemonic)
102 .Case("record", [&] { return RecordType::parse(parser); })
103 .Default([&] {
104 parser.emitError(typeLoc) << "unknown CIR type: " << mnemonic;
105 return Type();
106 })();
107}
108
109void CIRDialect::printType(Type type, DialectAsmPrinter &os) const {
110 // Try to print as a tablegen'd type.
111 if (generatedTypePrinter(type, os).succeeded())
112 return;
113
114 // TODO(CIR) Attempt to print as a raw C++ type.
115 llvm::report_fatal_error("printer is missing a handler for this type");
116}
117
118//===----------------------------------------------------------------------===//
119// RecordType Definitions
120//===----------------------------------------------------------------------===//
121
122Type RecordType::parse(mlir::AsmParser &parser) {
123 FailureOr<AsmParser::CyclicParseReset> cyclicParseGuard;
124 const llvm::SMLoc loc = parser.getCurrentLocation();
125 const mlir::Location eLoc = parser.getEncodedSourceLoc(loc);
126 bool packed = false;
127 bool padded = false;
128 RecordKind kind;
129 mlir::MLIRContext *context = parser.getContext();
130
131 if (parser.parseLess())
132 return {};
133
134 // TODO(cir): in the future we should probably separate types for different
135 // source language declarations such as cir.record and cir.union
136 if (parser.parseOptionalKeyword("struct").succeeded())
137 kind = RecordKind::Struct;
138 else if (parser.parseOptionalKeyword("union").succeeded())
139 kind = RecordKind::Union;
140 else if (parser.parseOptionalKeyword("class").succeeded())
141 kind = RecordKind::Class;
142 else {
143 parser.emitError(loc, "unknown record type");
144 return {};
145 }
146
147 mlir::StringAttr name;
148 parser.parseOptionalAttribute(name);
149
150 // Is a self reference: ensure referenced type was parsed.
151 if (name && parser.parseOptionalGreater().succeeded()) {
152 RecordType type = getChecked(eLoc, context, name, kind);
153 if (succeeded(parser.tryStartCyclicParse(type))) {
154 parser.emitError(loc, "invalid self-reference within record");
155 return {};
156 }
157 return type;
158 }
159
160 // Is a named record definition: ensure name has not been parsed yet.
161 if (name) {
162 RecordType type = getChecked(eLoc, context, name, kind);
163 cyclicParseGuard = parser.tryStartCyclicParse(type);
164 if (failed(cyclicParseGuard)) {
165 parser.emitError(loc, "record already defined");
166 return {};
167 }
168 }
169
170 if (parser.parseOptionalKeyword("packed").succeeded())
171 packed = true;
172
173 if (parser.parseOptionalKeyword("padded").succeeded())
174 padded = true;
175
176 // Parse record members or lack thereof.
177 bool incomplete = true;
178 llvm::SmallVector<mlir::Type> members;
179 if (parser.parseOptionalKeyword("incomplete").failed()) {
180 incomplete = false;
181 const auto delimiter = AsmParser::Delimiter::Braces;
182 const auto parseElementFn = [&parser, &members]() {
183 return parser.parseType(members.emplace_back());
184 };
185 if (parser.parseCommaSeparatedList(delimiter, parseElementFn).failed())
186 return {};
187 }
188
189 if (parser.parseGreater())
190 return {};
191
192 // Try to create the proper record type.
193 ArrayRef<mlir::Type> membersRef(members); // Needed for template deduction.
194 mlir::Type type = {};
195 if (name && incomplete) { // Identified & incomplete
196 type = getChecked(eLoc, context, name, kind);
197 } else if (!name && !incomplete) { // Anonymous & complete
198 type = getChecked(eLoc, context, membersRef, packed, padded, kind);
199 } else if (!incomplete) { // Identified & complete
200 type = getChecked(eLoc, context, membersRef, name, packed, padded, kind);
201 // If the record has a self-reference, its type already exists in a
202 // incomplete state. In this case, we must complete it.
203 if (mlir::cast<RecordType>(type).isIncomplete())
204 mlir::cast<RecordType>(type).complete(membersRef, packed, padded);
206 } else { // anonymous & incomplete
207 parser.emitError(loc, "anonymous records must be complete");
208 return {};
209 }
210
211 return type;
212}
213
214void RecordType::print(mlir::AsmPrinter &printer) const {
215 FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrintGuard;
216 printer << '<';
217
218 switch (getKind()) {
219 case RecordKind::Struct:
220 printer << "struct ";
221 break;
222 case RecordKind::Union:
223 printer << "union ";
224 break;
225 case RecordKind::Class:
226 printer << "class ";
227 break;
228 }
229
230 if (getName())
231 printer << getName();
232
233 // Current type has already been printed: print as self reference.
234 cyclicPrintGuard = printer.tryStartCyclicPrint(*this);
235 if (failed(cyclicPrintGuard)) {
236 printer << '>';
237 return;
238 }
239
240 // Type not yet printed: continue printing the entire record.
241 printer << ' ';
242
243 if (getPacked())
244 printer << "packed ";
245
246 if (getPadded())
247 printer << "padded ";
248
249 if (isIncomplete()) {
250 printer << "incomplete";
251 } else {
252 printer << "{";
253 llvm::interleaveComma(getMembers(), printer);
254 printer << "}";
255 }
256
257 printer << '>';
258}
259
260mlir::LogicalResult
261RecordType::verify(function_ref<mlir::InFlightDiagnostic()> emitError,
262 llvm::ArrayRef<mlir::Type> members, mlir::StringAttr name,
263 bool incomplete, bool packed, bool padded,
264 RecordType::RecordKind kind) {
265 if (name && name.getValue().empty())
266 return emitError() << "identified records cannot have an empty name";
267 return mlir::success();
268}
269
270::llvm::ArrayRef<mlir::Type> RecordType::getMembers() const {
271 return getImpl()->members;
272}
273
274bool RecordType::isIncomplete() const { return getImpl()->incomplete; }
275
276mlir::StringAttr RecordType::getName() const { return getImpl()->name; }
277
278bool RecordType::getIncomplete() const { return getImpl()->incomplete; }
279
280bool RecordType::getPacked() const { return getImpl()->packed; }
281
282bool RecordType::getPadded() const { return getImpl()->padded; }
283
284cir::RecordType::RecordKind RecordType::getKind() const {
285 return getImpl()->kind;
286}
287
288void RecordType::complete(ArrayRef<Type> members, bool packed, bool padded) {
290 if (mutate(members, packed, padded).failed())
291 llvm_unreachable("failed to complete record");
292}
293
294/// Return the largest member of in the type.
295///
296/// Recurses into union members never returning a union as the largest member.
297Type RecordType::getLargestMember(const ::mlir::DataLayout &dataLayout) const {
298 assert(isUnion() && "Only call getLargestMember on unions");
299 llvm::ArrayRef<Type> members = getMembers();
300 // If the union is padded, we need to ignore the last member,
301 // which is the padding.
302 return *std::max_element(
303 members.begin(), getPadded() ? members.end() - 1 : members.end(),
304 [&](Type lhs, Type rhs) {
305 return dataLayout.getTypeABIAlignment(lhs) <
306 dataLayout.getTypeABIAlignment(rhs) ||
307 (dataLayout.getTypeABIAlignment(lhs) ==
308 dataLayout.getTypeABIAlignment(rhs) &&
309 dataLayout.getTypeSize(lhs) < dataLayout.getTypeSize(rhs));
310 });
311}
312
313bool RecordType::isLayoutIdentical(const RecordType &other) {
314 if (getImpl() == other.getImpl())
315 return true;
316
317 if (getPacked() != other.getPacked())
318 return false;
319
320 return getMembers() == other.getMembers();
321}
322
323//===----------------------------------------------------------------------===//
324// Data Layout information for types
325//===----------------------------------------------------------------------===//
326
327llvm::TypeSize
328PointerType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
329 ::mlir::DataLayoutEntryListRef params) const {
330 // FIXME: improve this in face of address spaces
332 return llvm::TypeSize::getFixed(64);
333}
334
336PointerType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
337 ::mlir::DataLayoutEntryListRef params) const {
338 // FIXME: improve this in face of address spaces
340 return 8;
341}
342
343llvm::TypeSize
344RecordType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
345 mlir::DataLayoutEntryListRef params) const {
346 if (isUnion())
347 return dataLayout.getTypeSize(getLargestMember(dataLayout));
348
349 auto recordSize = static_cast<uint64_t>(computeStructSize(dataLayout));
350 return llvm::TypeSize::getFixed(recordSize * 8);
351}
352
354RecordType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
355 ::mlir::DataLayoutEntryListRef params) const {
356 if (isUnion())
357 return dataLayout.getTypeABIAlignment(getLargestMember(dataLayout));
358
359 // Packed structures always have an ABI alignment of 1.
360 if (getPacked())
361 return 1;
362 return computeStructAlignment(dataLayout);
363}
364
365unsigned
366RecordType::computeStructSize(const mlir::DataLayout &dataLayout) const {
367 assert(isComplete() && "Cannot get layout of incomplete records");
368
369 // This is a similar algorithm to LLVM's StructLayout.
370 unsigned recordSize = 0;
371 uint64_t recordAlignment = 1;
372
373 for (mlir::Type ty : getMembers()) {
374 // This assumes that we're calculating size based on the ABI alignment, not
375 // the preferred alignment for each type.
376 const uint64_t tyAlign =
377 (getPacked() ? 1 : dataLayout.getTypeABIAlignment(ty));
378
379 // Add padding to the struct size to align it to the abi alignment of the
380 // element type before than adding the size of the element.
381 recordSize = llvm::alignTo(recordSize, tyAlign);
382 recordSize += dataLayout.getTypeSize(ty);
383
384 // The alignment requirement of a struct is equal to the strictest alignment
385 // requirement of its elements.
386 recordAlignment = std::max(tyAlign, recordAlignment);
387 }
388
389 // At the end, add padding to the struct to satisfy its own alignment
390 // requirement. Otherwise structs inside of arrays would be misaligned.
391 recordSize = llvm::alignTo(recordSize, recordAlignment);
392 return recordSize;
393}
394
395// We also compute the alignment as part of computeStructSize, but this is more
396// efficient. Ideally, we'd like to compute both at once and cache the result,
397// but that's implemented yet.
398// TODO(CIR): Implement a way to cache the result.
400RecordType::computeStructAlignment(const mlir::DataLayout &dataLayout) const {
401 assert(isComplete() && "Cannot get layout of incomplete records");
402
403 // This is a similar algorithm to LLVM's StructLayout.
404 uint64_t recordAlignment = 1;
405 for (mlir::Type ty : getMembers())
406 recordAlignment =
407 std::max(dataLayout.getTypeABIAlignment(ty), recordAlignment);
408
409 return recordAlignment;
410}
411
412uint64_t RecordType::getElementOffset(const ::mlir::DataLayout &dataLayout,
413 unsigned idx) const {
414 assert(idx < getMembers().size() && "access not valid");
415
416 // All union elements are at offset zero.
417 if (isUnion() || idx == 0)
418 return 0;
419
420 assert(isComplete() && "Cannot get layout of incomplete records");
421 assert(idx < getNumElements());
422 llvm::ArrayRef<mlir::Type> members = getMembers();
423
424 unsigned offset = 0;
425
426 for (mlir::Type ty :
427 llvm::make_range(members.begin(), std::next(members.begin(), idx))) {
428 // This matches LLVM since it uses the ABI instead of preferred alignment.
429 const llvm::Align tyAlign =
430 llvm::Align(getPacked() ? 1 : dataLayout.getTypeABIAlignment(ty));
431
432 // Add padding if necessary to align the data element properly.
433 offset = llvm::alignTo(offset, tyAlign);
434
435 // Consume space for this data item
436 offset += dataLayout.getTypeSize(ty);
437 }
438
439 // Account for padding, if necessary, for the alignment of the field whose
440 // offset we are calculating.
441 const llvm::Align tyAlign = llvm::Align(
442 getPacked() ? 1 : dataLayout.getTypeABIAlignment(members[idx]));
443 offset = llvm::alignTo(offset, tyAlign);
444
445 return offset;
446}
447
448//===----------------------------------------------------------------------===//
449// IntType Definitions
450//===----------------------------------------------------------------------===//
451
452Type IntType::parse(mlir::AsmParser &parser) {
453 mlir::MLIRContext *context = parser.getBuilder().getContext();
454 llvm::SMLoc loc = parser.getCurrentLocation();
455 bool isSigned;
456 unsigned width;
457
458 if (parser.parseLess())
459 return {};
460
461 // Fetch integer sign.
462 llvm::StringRef sign;
463 if (parser.parseKeyword(&sign))
464 return {};
465 if (sign == "s")
466 isSigned = true;
467 else if (sign == "u")
468 isSigned = false;
469 else {
470 parser.emitError(loc, "expected 's' or 'u'");
471 return {};
472 }
473
474 if (parser.parseComma())
475 return {};
476
477 // Fetch integer size.
478 if (parser.parseInteger(width))
479 return {};
480 if (width < IntType::minBitwidth() || width > IntType::maxBitwidth()) {
481 parser.emitError(loc, "expected integer width to be from ")
482 << IntType::minBitwidth() << " up to " << IntType::maxBitwidth();
483 return {};
484 }
485
486 if (parser.parseGreater())
487 return {};
488
489 return IntType::get(context, width, isSigned);
490}
491
492void IntType::print(mlir::AsmPrinter &printer) const {
493 char sign = isSigned() ? 's' : 'u';
494 printer << '<' << sign << ", " << getWidth() << '>';
495}
496
497llvm::TypeSize
498IntType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
499 mlir::DataLayoutEntryListRef params) const {
500 return llvm::TypeSize::getFixed(getWidth());
501}
502
503uint64_t IntType::getABIAlignment(const mlir::DataLayout &dataLayout,
504 mlir::DataLayoutEntryListRef params) const {
505 return (uint64_t)(getWidth() / 8);
506}
507
508mlir::LogicalResult
509IntType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
510 unsigned width, bool isSigned) {
511 if (width < IntType::minBitwidth() || width > IntType::maxBitwidth())
512 return emitError() << "IntType only supports widths from "
513 << IntType::minBitwidth() << " up to "
514 << IntType::maxBitwidth();
515 return mlir::success();
516}
517
519 return width == 8 || width == 16 || width == 32 || width == 64;
520}
521
522//===----------------------------------------------------------------------===//
523// Floating-point type definitions
524//===----------------------------------------------------------------------===//
525
526const llvm::fltSemantics &SingleType::getFloatSemantics() const {
527 return llvm::APFloat::IEEEsingle();
528}
529
530llvm::TypeSize
531SingleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
532 mlir::DataLayoutEntryListRef params) const {
533 return llvm::TypeSize::getFixed(getWidth());
534}
535
537SingleType::getABIAlignment(const mlir::DataLayout &dataLayout,
538 mlir::DataLayoutEntryListRef params) const {
539 return (uint64_t)(getWidth() / 8);
540}
541
542const llvm::fltSemantics &DoubleType::getFloatSemantics() const {
543 return llvm::APFloat::IEEEdouble();
544}
545
546llvm::TypeSize
547DoubleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
548 mlir::DataLayoutEntryListRef params) const {
549 return llvm::TypeSize::getFixed(getWidth());
550}
551
553DoubleType::getABIAlignment(const mlir::DataLayout &dataLayout,
554 mlir::DataLayoutEntryListRef params) const {
555 return (uint64_t)(getWidth() / 8);
556}
557
558const llvm::fltSemantics &FP16Type::getFloatSemantics() const {
559 return llvm::APFloat::IEEEhalf();
560}
561
562llvm::TypeSize
563FP16Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
564 mlir::DataLayoutEntryListRef params) const {
565 return llvm::TypeSize::getFixed(getWidth());
566}
567
568uint64_t FP16Type::getABIAlignment(const mlir::DataLayout &dataLayout,
569 mlir::DataLayoutEntryListRef params) const {
570 return (uint64_t)(getWidth() / 8);
571}
572
573const llvm::fltSemantics &BF16Type::getFloatSemantics() const {
574 return llvm::APFloat::BFloat();
575}
576
577llvm::TypeSize
578BF16Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
579 mlir::DataLayoutEntryListRef params) const {
580 return llvm::TypeSize::getFixed(getWidth());
581}
582
583uint64_t BF16Type::getABIAlignment(const mlir::DataLayout &dataLayout,
584 mlir::DataLayoutEntryListRef params) const {
585 return (uint64_t)(getWidth() / 8);
586}
587
588const llvm::fltSemantics &FP80Type::getFloatSemantics() const {
589 return llvm::APFloat::x87DoubleExtended();
590}
591
592llvm::TypeSize
593FP80Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
594 mlir::DataLayoutEntryListRef params) const {
595 // Though only 80 bits are used for the value, the type is 128 bits in size.
596 return llvm::TypeSize::getFixed(128);
597}
598
599uint64_t FP80Type::getABIAlignment(const mlir::DataLayout &dataLayout,
600 mlir::DataLayoutEntryListRef params) const {
601 return 16;
602}
603
604const llvm::fltSemantics &FP128Type::getFloatSemantics() const {
605 return llvm::APFloat::IEEEquad();
606}
607
608llvm::TypeSize
609FP128Type::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
610 mlir::DataLayoutEntryListRef params) const {
611 return llvm::TypeSize::getFixed(getWidth());
612}
613
614uint64_t FP128Type::getABIAlignment(const mlir::DataLayout &dataLayout,
615 mlir::DataLayoutEntryListRef params) const {
616 return 16;
617}
618
619const llvm::fltSemantics &LongDoubleType::getFloatSemantics() const {
620 return mlir::cast<cir::FPTypeInterface>(getUnderlying()).getFloatSemantics();
621}
622
623llvm::TypeSize
624LongDoubleType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
625 mlir::DataLayoutEntryListRef params) const {
626 return mlir::cast<mlir::DataLayoutTypeInterface>(getUnderlying())
627 .getTypeSizeInBits(dataLayout, params);
628}
629
631LongDoubleType::getABIAlignment(const mlir::DataLayout &dataLayout,
632 mlir::DataLayoutEntryListRef params) const {
633 return mlir::cast<mlir::DataLayoutTypeInterface>(getUnderlying())
634 .getABIAlignment(dataLayout, params);
635}
636
637//===----------------------------------------------------------------------===//
638// ComplexType Definitions
639//===----------------------------------------------------------------------===//
640
641llvm::TypeSize
642cir::ComplexType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
643 mlir::DataLayoutEntryListRef params) const {
644 // C17 6.2.5p13:
645 // Each complex type has the same representation and alignment requirements
646 // as an array type containing exactly two elements of the corresponding
647 // real type.
648
649 return dataLayout.getTypeSizeInBits(getElementType()) * 2;
650}
651
653cir::ComplexType::getABIAlignment(const mlir::DataLayout &dataLayout,
654 mlir::DataLayoutEntryListRef params) const {
655 // C17 6.2.5p13:
656 // Each complex type has the same representation and alignment requirements
657 // as an array type containing exactly two elements of the corresponding
658 // real type.
659
660 return dataLayout.getTypeABIAlignment(getElementType());
661}
662
663FuncType FuncType::clone(TypeRange inputs, TypeRange results) const {
664 assert(results.size() == 1 && "expected exactly one result type");
665 return get(llvm::to_vector(inputs), results[0], isVarArg());
666}
667
668// Custom parser that parses function parameters of form `(<type>*, ...)`.
669static mlir::ParseResult
671 bool &isVarArg) {
672 isVarArg = false;
673 return p.parseCommaSeparatedList(
674 AsmParser::Delimiter::Paren, [&]() -> mlir::ParseResult {
675 if (isVarArg)
676 return p.emitError(p.getCurrentLocation(),
677 "variadic `...` must be the last parameter");
678 if (succeeded(p.parseOptionalEllipsis())) {
679 isVarArg = true;
680 return success();
681 }
682 mlir::Type type;
683 if (failed(p.parseType(type)))
684 return failure();
685 params.push_back(type);
686 return success();
687 });
688}
689
690static void printFuncTypeParams(mlir::AsmPrinter &p,
691 mlir::ArrayRef<mlir::Type> params,
692 bool isVarArg) {
693 p << '(';
694 llvm::interleaveComma(params, p,
695 [&p](mlir::Type type) { p.printType(type); });
696 if (isVarArg) {
697 if (!params.empty())
698 p << ", ";
699 p << "...";
700 }
701 p << ')';
702}
703
704/// Get the C-style return type of the function, which is !cir.void if the
705/// function returns nothing and the actual return type otherwise.
706mlir::Type FuncType::getReturnType() const {
707 if (hasVoidReturn())
708 return cir::VoidType::get(getContext());
709 return getOptionalReturnType();
710}
711
712/// Get the MLIR-style return type of the function, which is an empty
713/// ArrayRef if the function returns nothing and a single-element ArrayRef
714/// with the actual return type otherwise.
715llvm::ArrayRef<mlir::Type> FuncType::getReturnTypes() const {
716 if (hasVoidReturn())
717 return {};
718 // Can't use getOptionalReturnType() here because llvm::ArrayRef hold a
719 // pointer to its elements and doesn't do lifetime extension. That would
720 // result in returning a pointer to a temporary that has gone out of scope.
721 return getImpl()->optionalReturnType;
722}
723
724// Does the fuction type return nothing?
725bool FuncType::hasVoidReturn() const { return !getOptionalReturnType(); }
726
727mlir::LogicalResult
728FuncType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
729 llvm::ArrayRef<mlir::Type> argTypes, mlir::Type returnType,
730 bool isVarArg) {
731 if (mlir::isa_and_nonnull<cir::VoidType>(returnType))
732 return emitError()
733 << "!cir.func cannot have an explicit 'void' return type";
734 return mlir::success();
735}
736
737//===----------------------------------------------------------------------===//
738// BoolType
739//===----------------------------------------------------------------------===//
740
741llvm::TypeSize
742BoolType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
743 ::mlir::DataLayoutEntryListRef params) const {
744 return llvm::TypeSize::getFixed(8);
745}
746
748BoolType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
749 ::mlir::DataLayoutEntryListRef params) const {
750 return 1;
751}
752
753//===----------------------------------------------------------------------===//
754// VPtrType Definitions
755//===----------------------------------------------------------------------===//
756
757llvm::TypeSize
758VPtrType::getTypeSizeInBits(const mlir::DataLayout &dataLayout,
759 mlir::DataLayoutEntryListRef params) const {
760 // FIXME: consider size differences under different ABIs
761 return llvm::TypeSize::getFixed(64);
762}
763
764uint64_t VPtrType::getABIAlignment(const mlir::DataLayout &dataLayout,
765 mlir::DataLayoutEntryListRef params) const {
766 // FIXME: consider alignment differences under different ABIs
767 return 8;
768}
769
770//===----------------------------------------------------------------------===//
771// ArrayType Definitions
772//===----------------------------------------------------------------------===//
773
774llvm::TypeSize
775ArrayType::getTypeSizeInBits(const ::mlir::DataLayout &dataLayout,
776 ::mlir::DataLayoutEntryListRef params) const {
777 return getSize() * dataLayout.getTypeSizeInBits(getElementType());
778}
779
781ArrayType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
782 ::mlir::DataLayoutEntryListRef params) const {
783 return dataLayout.getTypeABIAlignment(getElementType());
784}
785
786//===----------------------------------------------------------------------===//
787// VectorType Definitions
788//===----------------------------------------------------------------------===//
789
790llvm::TypeSize cir::VectorType::getTypeSizeInBits(
791 const ::mlir::DataLayout &dataLayout,
792 ::mlir::DataLayoutEntryListRef params) const {
793 return llvm::TypeSize::getFixed(
794 getSize() * dataLayout.getTypeSizeInBits(getElementType()));
795}
796
798cir::VectorType::getABIAlignment(const ::mlir::DataLayout &dataLayout,
799 ::mlir::DataLayoutEntryListRef params) const {
800 return llvm::NextPowerOf2(dataLayout.getTypeSizeInBits(*this));
801}
802
803mlir::LogicalResult cir::VectorType::verify(
804 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
805 mlir::Type elementType, uint64_t size) {
806 if (size == 0)
807 return emitError() << "the number of vector elements must be non-zero";
808 return success();
809}
810
811//===----------------------------------------------------------------------===//
812// TargetAddressSpace definitions
813//===----------------------------------------------------------------------===//
814
815cir::TargetAddressSpaceAttr
816cir::toCIRTargetAddressSpace(mlir::MLIRContext &context, clang::LangAS langAS) {
817 return cir::TargetAddressSpaceAttr::get(
818 &context,
819 IntegerAttr::get(&context,
820 llvm::APSInt(clang::toTargetAddressSpace(langAS))));
821}
822
823bool cir::isMatchingAddressSpace(cir::TargetAddressSpaceAttr cirAS,
824 clang::LangAS as) {
825 // If there is no CIR target attr, consider it "default" and only match
826 // when the AST address space is LangAS::Default.
827 if (!cirAS)
828 return as == clang::LangAS::Default;
829
830 if (!isTargetAddressSpace(as))
831 return false;
832
833 return cirAS.getValue().getUInt() == toTargetAddressSpace(as);
834}
835
836mlir::ParseResult parseTargetAddressSpace(mlir::AsmParser &p,
837 cir::TargetAddressSpaceAttr &attr) {
838 if (failed(p.parseKeyword("target_address_space")))
839 return mlir::failure();
840
841 if (failed(p.parseLParen()))
842 return mlir::failure();
843
844 int32_t targetValue;
845 if (failed(p.parseInteger(targetValue)))
846 return p.emitError(p.getCurrentLocation(),
847 "expected integer address space value");
848
849 if (failed(p.parseRParen()))
850 return p.emitError(p.getCurrentLocation(),
851 "expected ')' after address space value");
852
853 mlir::MLIRContext *context = p.getBuilder().getContext();
854 attr = cir::TargetAddressSpaceAttr::get(
855 context, p.getBuilder().getUI32IntegerAttr(targetValue));
856 return mlir::success();
857}
858
859// The custom printer for the `addrspace` parameter in `!cir.ptr`.
860// in the format of `target_address_space(N)`.
861void printTargetAddressSpace(mlir::AsmPrinter &p,
862 cir::TargetAddressSpaceAttr attr) {
863 p << "target_address_space(" << attr.getValue().getUInt() << ")";
864}
865
866//===----------------------------------------------------------------------===//
867// CIR Dialect
868//===----------------------------------------------------------------------===//
869
870void CIRDialect::registerTypes() {
871 // Register tablegen'd types.
872 addTypes<
873#define GET_TYPEDEF_LIST
874#include "clang/CIR/Dialect/IR/CIROpsTypes.cpp.inc"
875 >();
876
877 // Register raw C++ types.
878 // TODO(CIR) addTypes<RecordType>();
879}
Provides definitions for the various language-specific address spaces.
mlir::ParseResult parseTargetAddressSpace(mlir::AsmParser &p, cir::TargetAddressSpaceAttr &attr)
Definition CIRTypes.cpp:836
void printTargetAddressSpace(mlir::AsmPrinter &p, cir::TargetAddressSpaceAttr attr)
Definition CIRTypes.cpp:861
mlir::ParseResult parseTargetAddressSpace(mlir::AsmParser &p, cir::TargetAddressSpaceAttr &attr)
Definition CIRTypes.cpp:836
static mlir::ParseResult parseFuncTypeParams(mlir::AsmParser &p, llvm::SmallVector< mlir::Type > &params, bool &isVarArg)
Definition CIRTypes.cpp:670
static void printFuncTypeParams(mlir::AsmPrinter &p, mlir::ArrayRef< mlir::Type > params, bool isVarArg)
Definition CIRTypes.cpp:690
void printTargetAddressSpace(mlir::AsmPrinter &p, cir::TargetAddressSpaceAttr attr)
Definition CIRTypes.cpp:861
static Decl::Kind getKind(const Decl *D)
static LiveVariablesImpl & getImpl(void *x)
bool isValidFundamentalIntWidth(unsigned width)
Definition CIRTypes.cpp:518
bool isSized(mlir::Type ty)
Returns true if the type is a CIR sized type.
Definition CIRTypes.cpp:30
bool isMatchingAddressSpace(cir::TargetAddressSpaceAttr cirAS, clang::LangAS as)
Definition CIRTypes.cpp:823
cir::TargetAddressSpaceAttr toCIRTargetAddressSpace(mlir::MLIRContext &context, clang::LangAS langAS)
Definition CIRTypes.cpp:816
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
unsigned toTargetAddressSpace(LangAS AS)
LangAS
Defines the address space values used by the address space qualifier of QualType.
unsigned long uint64_t
float __ovld __cnfn sign(float)
Returns 1.0 if x > 0, -0.0 if x = -0.0, +0.0 if x = +0.0, or -1.0 if x < 0.
static bool unsizedTypes()
static bool dataLayoutPtrHandlingBasedOnLangAS()
static bool astRecordDeclAttr()