| 1 | //===- TypeTest.cpp - Type API unit tests ---------------------------------===// |
| 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 "mlir/IR/BuiltinTypes.h" |
| 10 | #include "mlir/IR/Dialect.h" |
| 11 | #include "mlir/IR/Types.h" |
| 12 | #include "mlir/IR/Value.h" |
| 13 | #include "gtest/gtest.h" |
| 14 | |
| 15 | using namespace mlir; |
| 16 | |
| 17 | /// Mock implementations of a Type hierarchy |
| 18 | struct LeafType; |
| 19 | |
| 20 | struct MiddleType : Type::TypeBase<MiddleType, Type, TypeStorage> { |
| 21 | using Base::Base; |
| 22 | |
| 23 | static constexpr StringLiteral name = "test.middle" ; |
| 24 | |
| 25 | static bool classof(Type ty) { |
| 26 | return ty.getTypeID() == TypeID::get<LeafType>() || Base::classof(val: ty); |
| 27 | } |
| 28 | }; |
| 29 | |
| 30 | struct LeafType : Type::TypeBase<LeafType, MiddleType, TypeStorage> { |
| 31 | using Base::Base; |
| 32 | |
| 33 | static constexpr StringLiteral name = "test.leaf" ; |
| 34 | }; |
| 35 | |
| 36 | struct FakeDialect : Dialect { |
| 37 | FakeDialect(MLIRContext *context) |
| 38 | : Dialect(getDialectNamespace(), context, TypeID::get<FakeDialect>()) { |
| 39 | addTypes<MiddleType, LeafType>(); |
| 40 | } |
| 41 | static constexpr ::llvm::StringLiteral getDialectNamespace() { |
| 42 | return ::llvm::StringLiteral("fake" ); |
| 43 | } |
| 44 | }; |
| 45 | |
| 46 | TEST(Type, Casting) { |
| 47 | MLIRContext ctx; |
| 48 | ctx.loadDialect<FakeDialect>(); |
| 49 | |
| 50 | Type intTy = IntegerType::get(&ctx, 8); |
| 51 | Type nullTy; |
| 52 | MiddleType middleTy = MiddleType::get(ctx: &ctx); |
| 53 | MiddleType leafTy = LeafType::get(ctx: &ctx); |
| 54 | Type leaf2Ty = LeafType::get(ctx: &ctx); |
| 55 | |
| 56 | EXPECT_TRUE(isa<IntegerType>(intTy)); |
| 57 | EXPECT_FALSE(isa<FunctionType>(intTy)); |
| 58 | EXPECT_FALSE(isa_and_present<IntegerType>(nullTy)); |
| 59 | EXPECT_TRUE(isa<MiddleType>(middleTy)); |
| 60 | EXPECT_FALSE(isa<LeafType>(middleTy)); |
| 61 | EXPECT_TRUE(isa<MiddleType>(leafTy)); |
| 62 | EXPECT_TRUE(isa<LeafType>(leaf2Ty)); |
| 63 | EXPECT_TRUE(isa<LeafType>(leafTy)); |
| 64 | |
| 65 | EXPECT_TRUE(static_cast<bool>(dyn_cast<IntegerType>(intTy))); |
| 66 | EXPECT_FALSE(static_cast<bool>(dyn_cast<FunctionType>(intTy))); |
| 67 | EXPECT_FALSE(static_cast<bool>(cast_if_present<FunctionType>(nullTy))); |
| 68 | EXPECT_FALSE(static_cast<bool>(dyn_cast_if_present<IntegerType>(nullTy))); |
| 69 | |
| 70 | EXPECT_EQ(8u, cast<IntegerType>(intTy).getWidth()); |
| 71 | } |
| 72 | |