tvm
Loading...
Searching...
No Matches
base_expr.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
24#ifndef TVM_IR_BASE_EXPR_H_
25#define TVM_IR_BASE_EXPR_H_
26
27#include <tvm/ffi/cast.h>
28#include <tvm/ffi/dtype.h>
29#include <tvm/ffi/extra/structural_mutate.h>
30#include <tvm/ffi/extra/structural_visit.h>
31#include <tvm/ffi/reflection/registry.h>
32#include <tvm/ffi/string.h>
33#include <tvm/ir/location.h>
34
35#include <cstddef>
36#include <cstdint>
37#include <optional>
38#include <type_traits>
39
40namespace tvm {
41
54class TypeNode : public ffi::Object {
55 public:
60 mutable Location loc = UnknownLoc();
61
62 static void RegisterReflection() {
63 namespace refl = tvm::ffi::reflection;
64 // loc do not participate in structural equal and hash.
65 refl::ObjectDef<TypeNode>().def_ro("loc", &TypeNode::loc, refl::DefaultValue(UnknownLoc()),
66 refl::AttachFieldFlag::SEqHashIgnore());
67 }
68
69 static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
70 static constexpr bool _type_s_eq_hash_subclass_kind_fixed = true;
71
72 static constexpr const uint32_t _type_child_slots = 14;
73 TVM_FFI_DECLARE_OBJECT_INFO("ir.Type", TypeNode, ffi::Object);
74};
75
80class Type : public ffi::ObjectRef {
81 public:
84
86};
87
94class MissingTypeNode final : public TypeNode {
95 public:
96 static void RegisterReflection() {
97 namespace refl = tvm::ffi::reflection;
98 refl::ObjectDef<MissingTypeNode>();
99 }
100
102};
103
111
118class OpaqueTypeNode final : public TypeNode {
119 public:
120 static void RegisterReflection() {
121 namespace refl = tvm::ffi::reflection;
122 refl::ObjectDef<OpaqueTypeNode>();
123 }
124
126};
127
135
143class PrimTypeNode final : public TypeNode {
144 public:
148 DLDataType dtype;
149
150 static void RegisterReflection() {
151 namespace refl = tvm::ffi::reflection;
152 refl::ObjectDef<PrimTypeNode>().def_ro("dtype", &PrimTypeNode::dtype);
153 }
155};
156
157/*
158 * \brief Managed reference to PrimTypeNode.
159 * \sa PrimTypeNode
160 */
161class PrimType final : public Type {
162 public:
167 TVM_TIRX_DLL explicit PrimType(DLDataType dtype);
168
175 TVM_TIRX_DLL PrimType(DLDataTypeCode code, int bits, int lanes = 1);
176
178 TVM_TIRX_DLL static PrimType Int(int bits, int lanes = 1);
180 TVM_TIRX_DLL static PrimType UInt(int bits, int lanes = 1);
182 TVM_TIRX_DLL static PrimType Float(int bits, int lanes = 1);
184 TVM_TIRX_DLL static PrimType BFloat(int bits, int lanes = 1);
195 TVM_TIRX_DLL static PrimType ScalableVector(DLDataTypeCode code, int bits, int lanes);
196
198 TVM_FFI_INLINE DLDataTypeCode code() const {
199 return static_cast<DLDataTypeCode>(static_cast<int>(get()->dtype.code));
200 }
201
203 TVM_FFI_INLINE int32_t bits() const { return get()->dtype.bits; }
204
209 TVM_FFI_INLINE int32_t lanes() const {
210 int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
211 if (TVM_FFI_PREDICT_FALSE(encoded_lanes < 0)) {
212 TVM_FFI_THROW(InternalError)
213 << "Can't fetch the lanes of a scalable vector at a compile time.";
214 }
215 return encoded_lanes;
216 }
217
222 TVM_FFI_INLINE bool MatchesElementType(DLDataTypeCode code, int bits) const {
223 DLDataType dtype = get()->dtype;
224 return dtype.code == static_cast<uint8_t>(code) && dtype.bits == bits;
225 }
226
231 template <typename... Codes>
232 TVM_FFI_INLINE bool MatchesCode(Codes... codes) const {
233 uint8_t dtype_code = get()->dtype.code;
234 return ((dtype_code == static_cast<uint8_t>(codes)) || ...);
235 }
236
238 TVM_FFI_INLINE bool IsScalar() const {
239 int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
240 return encoded_lanes == 1;
241 }
242
244 TVM_FFI_INLINE bool IsVoid() const {
245 DLDataType dtype = get()->dtype;
246 return dtype.code == static_cast<uint8_t>(DLDataTypeCode::kDLOpaqueHandle) && dtype.bits == 0 &&
247 static_cast<int16_t>(dtype.lanes) == 0;
248 }
249
251 TVM_FFI_INLINE bool IsScalableVector() const {
252 return static_cast<int16_t>(get()->dtype.lanes) < -1;
253 }
254
256 TVM_FFI_INLINE bool IsFixedLengthVector() const {
257 return static_cast<int16_t>(get()->dtype.lanes) > 1;
258 }
259
266 TVM_FFI_INLINE size_t StorageBytes() const {
267 DLDataType dtype = get()->dtype;
268 int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
269 if (TVM_FFI_PREDICT_FALSE(encoded_lanes < 0)) {
270 TVM_FFI_THROW(InternalError)
271 << "Cannot compute compile-time storage bytes for non-fixed vector type " << dtype;
272 }
273 return static_cast<size_t>(
274 (static_cast<uint64_t>(dtype.bits) * static_cast<uint64_t>(dtype.lanes) + 7) / 8);
275 }
276
278 TVM_FFI_INLINE PrimType WithCode(DLDataTypeCode code) const {
279 DLDataType dtype = get()->dtype;
280 int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
281 if (encoded_lanes < -1) {
282 return ScalableVector(code, dtype.bits, -encoded_lanes);
283 }
284 return PrimType(code, dtype.bits, encoded_lanes);
285 }
286
288 TVM_FFI_INLINE PrimType WithBits(int bits) const {
289 DLDataType dtype = get()->dtype;
290 int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
291 if (encoded_lanes < -1) {
292 return ScalableVector(this->code(), bits, -encoded_lanes);
293 }
294 return PrimType(this->code(), bits, encoded_lanes);
295 }
296
298 TVM_FFI_INLINE PrimType WithLanes(int lanes) const {
299 return PrimType(this->code(), this->bits(), lanes);
300 }
301
303 TVM_FFI_INLINE int32_t VScaleFactor() const {
304 int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
305 if (encoded_lanes >= -1) {
306 TVM_FFI_THROW(InternalError) << "A fixed length vector doesn't have a vscale factor.";
307 }
308 return -encoded_lanes;
309 }
310
312};
313
314inline bool operator==(const PrimType& lhs, const PrimType& rhs) {
315 return lhs->dtype == rhs->dtype;
316}
317
318inline bool operator!=(const PrimType& lhs, const PrimType& rhs) { return !(lhs == rhs); }
319
324class ExprNode : public ffi::Object {
325 public:
331
338 mutable Type ty = MissingType();
339
340 static void RegisterReflection() {
341 namespace refl = tvm::ffi::reflection;
342 // loc does not participate in structural equal and hash.
343 refl::ObjectDef<ExprNode>()
344 .def_ro("loc", &ExprNode::loc, refl::DefaultValue(UnknownLoc()),
345 refl::AttachFieldFlag::SEqHashIgnore())
346 .def_ro("ty", &ExprNode::ty, refl::DefaultValue(MissingType()));
347 }
348
349 static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
350
351 static constexpr const uint32_t _type_child_slots = 64;
352 TVM_FFI_DECLARE_OBJECT_INFO("ir.Expr", ExprNode, ffi::Object);
353};
354
359class Expr : public ffi::ObjectRef {
360 public:
361 // Expressions do not implicitly compare by object identity or address. Callers must name
362 // whether they intend object identity, structural equality, or primitive symbolic comparison.
363 bool operator==(const Expr& other) const = delete;
364 bool operator!=(const Expr& other) const = delete;
365 bool operator<(const Expr& other) const = delete;
366
367 explicit Expr(ffi::ObjectPtr<ExprNode> node) : ffi::ObjectRef(std::move(node)) {
368 TVM_FFI_CHECK(defined(), ValueError) << "Expr expects a defined node";
369 }
370
372};
373
375class StagingExprNode : public ExprNode {
376 public:
377 static void RegisterReflection() { ffi::reflection::ObjectDef<StagingExprNode>(); }
378 static constexpr const uint32_t _type_child_slots = 4;
380};
381
387
394class OpaqueExprNode : public ExprNode {
395 public:
396 static void RegisterReflection() {
397 namespace refl = tvm::ffi::reflection;
398 refl::ObjectDef<OpaqueExprNode>();
399 }
400
401 static constexpr const uint32_t _type_child_slots = 2;
403};
404
406class OpaqueExpr : public Expr {
407 public:
408 explicit OpaqueExpr(ffi::ObjectPtr<OpaqueExprNode> node) : Expr(std::move(node)) {}
409
411};
412
413class Call;
414
420template <typename ExpectedType>
421class TypedExpr : public Expr {
422 public:
424 ExpectedType ty() const {
425 const auto* node = get();
426 TVM_FFI_DCHECK(node != nullptr);
427 const auto* ty_node = node->ExprNode::ty.template as<typename ExpectedType::ContainerType>();
428 TVM_FFI_DCHECK(ty_node != nullptr);
429 return ffi::GetRef<ExpectedType>(ty_node);
430 }
431
432 explicit TypedExpr(ffi::ObjectPtr<ExprNode> node) : Expr(std::move(node)) {}
433
435 static constexpr bool _type_container_is_exact = false;
436};
437
447class PrimExpr : public TypedExpr<PrimType> {
448 public:
449 using TypedExpr<PrimType>::ty;
450
456 TVM_TIRX_DLL PrimExpr(Call call); // NOLINT(*)
457
462 TVM_TIRX_DLL PrimExpr(int32_t value); // NOLINT(*)
467 TVM_TIRX_DLL PrimExpr(float value); // NOLINT(*)
468
469 explicit PrimExpr(ffi::ObjectPtr<ExprNode> node) : TypedExpr<PrimType>(std::move(node)) {}
470
472 static constexpr bool _type_container_is_exact = false;
473};
474
486
487namespace ffi {
488template <>
489inline constexpr bool use_default_type_traits_v<PrimType> = false;
490
491template <>
492struct TypeTraits<PrimType> : public ObjectRefWithFallbackTraitsBase<PrimType, DLDataType> {
493 TVM_FFI_INLINE static PrimType ConvertFallbackValue(DLDataType dtype) { return PrimType(dtype); }
494};
495
496template <typename ExpectedType>
497inline constexpr bool use_default_type_traits_v<TypedExpr<ExpectedType>> = false;
498
499template <typename ExpectedType>
500struct TypeTraits<TypedExpr<ExpectedType>>
501 : public ObjectRefTypeTraitsBase<TypedExpr<ExpectedType>> {
502 TVM_FFI_INLINE static bool CheckAnyStrict(const TVMFFIAny* src) {
503 if (src->type_index == TypeIndex::kTVMFFINone) {
505 }
506 if (src->type_index < TypeIndex::kTVMFFIStaticObjectBegin ||
507 !details::IsObjectInstance<ExprNode>(src->type_index)) {
508 return false;
509 }
510 // Non-owning: this only reads `ty`, and the owning form's incref/decref pair costs two
511 // atomics per check on a path every typed field assignment takes.
512 const auto* expr = details::ObjectUnsafe::RawObjectPtrFromUnowned<ExprNode>(src->v_obj);
513 return details::AnyUnsafe::CheckAnyViewStrict<ExpectedType>(expr->ty);
514 }
515
516 TVM_FFI_INLINE static std::string GetMismatchTypeInfo(const TVMFFIAny* src) {
517 if (src->type_index >= TypeIndex::kTVMFFIStaticObjectBegin && src->v_obj != nullptr &&
518 details::IsObjectInstance<ExprNode>(src->type_index)) {
519 const auto* expr = details::ObjectUnsafe::RawObjectPtrFromUnowned<ExprNode>(src->v_obj);
520 if (expr->ty.defined()) {
521 const auto* prim_ty = expr->ty.as<PrimTypeNode>();
522 std::string ty =
523 prim_ty ? std::string(ffi::DLDataTypeToString(prim_ty->dtype)) : expr->ty.GetTypeKey();
524 return TypeIndexToTypeKey(src->type_index) + "[ty=" + ty + "]";
525 }
526 }
527 return TypeTraitsBase::GetMismatchTypeInfo(src);
528 }
529};
530
531} // namespace ffi
532
533} // namespace tvm
534
535#endif // TVM_IR_BASE_EXPR_H_
Managed reference to CallNode.
Definition expr.h:972
Base type of all the expressions.
Definition base_expr.h:324
Type ty
The deduced or annotated type of the expression.
Definition base_expr.h:338
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition base_expr.h:349
TVM_FFI_DECLARE_OBJECT_INFO("ir.Expr", ExprNode, ffi::Object)
Location loc
Location that points to the original source code. Reserved debug information.
Definition base_expr.h:330
static constexpr const uint32_t _type_child_slots
Definition base_expr.h:351
static void RegisterReflection()
Definition base_expr.h:340
Managed reference to ExprNode.
Definition base_expr.h:359
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Expr, ffi::ObjectRef, ExprNode)
bool operator==(const Expr &other) const =delete
bool operator!=(const Expr &other) const =delete
Expr(ffi::ObjectPtr< ExprNode > node)
Definition base_expr.h:367
bool operator<(const Expr &other) const =delete
View over a scalar signed or unsigned integer expression of any bit width.
Definition base_expr.h:481
static constexpr bool _type_container_is_exact
Definition base_expr.h:484
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(IntExpr, PrimExpr, ExprNode)
Non-nullable source-location metadata.
Definition location.h:91
Type information that has not been supplied or computed.
Definition base_expr.h:94
static void RegisterReflection()
Definition base_expr.h:96
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.MissingType", MissingTypeNode, TypeNode)
Managed reference to the MissingTypeNode singleton.
Definition base_expr.h:105
TVM_TIRX_DLL MissingType()
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(MissingType, Type, MissingTypeNode)
Base node for opaque construction-time expressions.
Definition base_expr.h:394
static constexpr const uint32_t _type_child_slots
Definition base_expr.h:401
TVM_FFI_DECLARE_OBJECT_INFO("ir.OpaqueExpr", OpaqueExprNode, ExprNode)
static void RegisterReflection()
Definition base_expr.h:396
Managed reference to OpaqueExprNode.
Definition base_expr.h:406
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(OpaqueExpr, Expr, OpaqueExprNode)
OpaqueExpr(ffi::ObjectPtr< OpaqueExprNode > node)
Definition base_expr.h:408
Type marker for opaque construction-time expressions.
Definition base_expr.h:118
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.OpaqueType", OpaqueTypeNode, TypeNode)
static void RegisterReflection()
Definition base_expr.h:120
Managed reference to OpaqueTypeNode.
Definition base_expr.h:129
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(OpaqueType, Type, OpaqueTypeNode)
TVM_TIRX_DLL OpaqueType()
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition base_expr.h:447
static constexpr bool _type_container_is_exact
Definition base_expr.h:472
TVM_TIRX_DLL PrimExpr(int32_t value)
construct from integer.
TVM_TIRX_DLL PrimExpr(float value)
construct from float.
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PrimExpr, TypedExpr< PrimType >, ExprNode)
PrimExpr(ffi::ObjectPtr< ExprNode > node)
Definition base_expr.h:469
TVM_TIRX_DLL PrimExpr(Call call)
Construct from a call after checking that its result type is PrimType.
Primitive data types used in the low-level IR.
Definition base_expr.h:143
DLDataType dtype
The raw DLPack dtype represented by this primitive type.
Definition base_expr.h:148
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.PrimType", PrimTypeNode, TypeNode)
static void RegisterReflection()
Definition base_expr.h:150
Definition base_expr.h:161
TVM_FFI_INLINE DLDataTypeCode code() const
Definition base_expr.h:198
static TVM_TIRX_DLL PrimType Void()
Construct the void sentinel type, encoded as handle(0, 0).
static TVM_TIRX_DLL PrimType Bool(int lanes=1)
Construct a boolean type with fixed lanes.
static TVM_TIRX_DLL PrimType BFloat(int bits, int lanes=1)
Construct a bfloat type with fixed lanes.
TVM_FFI_INLINE bool IsVoid() const
Whether this type is the void sentinel handle(0, 0).
Definition base_expr.h:244
TVM_FFI_INLINE PrimType WithLanes(int lanes) const
Return the same scalar element type with a fixed lane count.
Definition base_expr.h:298
TVM_FFI_INLINE bool IsScalableVector() const
Whether this type is a scalable vector.
Definition base_expr.h:251
TVM_TIRX_DLL PrimType(DLDataTypeCode code, int bits, int lanes=1)
Construct from DLPack dtype fields.
static TVM_TIRX_DLL PrimType ScalableVector(DLDataTypeCode code, int bits, int lanes)
Construct a scalable vector type.
TVM_FFI_INLINE int32_t bits() const
Definition base_expr.h:203
TVM_FFI_INLINE bool IsFixedLengthVector() const
Whether this type is a fixed-length vector.
Definition base_expr.h:256
TVM_FFI_INLINE bool IsScalar() const
Whether this type is a scalar, excluding fixed and scalable vectors.
Definition base_expr.h:238
TVM_FFI_INLINE bool MatchesCode(Codes... codes) const
Check whether the dtype code matches any of the provided DLPack codes.
Definition base_expr.h:232
TVM_FFI_INLINE bool MatchesElementType(DLDataTypeCode code, int bits) const
Check the scalar element code and bit width.
Definition base_expr.h:222
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PrimType, Type, PrimTypeNode)
static TVM_TIRX_DLL PrimType Int(int bits, int lanes=1)
Construct a signed integer type with fixed lanes.
TVM_FFI_INLINE int32_t VScaleFactor() const
Definition base_expr.h:303
static TVM_TIRX_DLL PrimType UInt(int bits, int lanes=1)
Construct an unsigned integer type with fixed lanes.
TVM_FFI_INLINE int32_t lanes() const
Definition base_expr.h:209
TVM_FFI_INLINE PrimType WithBits(int bits) const
Return the same type with a different scalar bit width, preserving code and lanes.
Definition base_expr.h:288
TVM_TIRX_DLL PrimType(DLDataType dtype)
Construct from a raw DLPack dtype.
TVM_FFI_INLINE size_t StorageBytes() const
Return the number of bytes needed to store one value of this type.
Definition base_expr.h:266
TVM_FFI_INLINE PrimType WithCode(DLDataTypeCode code) const
Return the same type with a different dtype code, preserving bits and lanes.
Definition base_expr.h:278
static TVM_TIRX_DLL PrimType Float(int bits, int lanes=1)
Construct a floating-point type with fixed lanes.
Base node for traversable expressions eliminated during compilation.
Definition base_expr.h:375
TVM_FFI_DECLARE_OBJECT_INFO("ir.StagingExpr", StagingExprNode, ExprNode)
static constexpr const uint32_t _type_child_slots
Definition base_expr.h:378
static void RegisterReflection()
Definition base_expr.h:377
Managed reference to a staging expression.
Definition base_expr.h:383
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(StagingExpr, Expr, StagingExprNode)
Type is the base type of all types.
Definition base_expr.h:54
static constexpr const uint32_t _type_child_slots
Definition base_expr.h:72
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition base_expr.h:69
static constexpr bool _type_s_eq_hash_subclass_kind_fixed
Definition base_expr.h:70
TVM_FFI_DECLARE_OBJECT_INFO("ir.Type", TypeNode, ffi::Object)
static void RegisterReflection()
Definition base_expr.h:62
Location loc
Location that points to the original source code. Reserved debug information.
Definition base_expr.h:60
Managed reference to TypeNode.
Definition base_expr.h:80
static TVM_TIRX_DLL Type Missing()
Construct a MissingType for type information not yet populated.
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Type, ffi::ObjectRef, TypeNode)
Typed reference/view over an expression whose result type is a specific Type subtype.
Definition base_expr.h:421
static constexpr bool _type_container_is_exact
Definition base_expr.h:435
ExpectedType ty() const
Definition base_expr.h:424
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(TypedExpr, Expr, ExprNode)
TypedExpr(ffi::ObjectPtr< ExprNode > node)
Definition base_expr.h:432
Reference to the shared immutable unknown location.
Definition location.h:105
Source locations and source-text lookup.
constexpr bool use_default_type_traits_v< PrimType >
Definition base_expr.h:489
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition attr.h:23
bool operator!=(const PrimType &lhs, const PrimType &rhs)
Definition base_expr.h:318
bool operator==(const PrimType &lhs, const PrimType &rhs)
Definition base_expr.h:314
#define TVM_TIRX_DLL
Definition base.h:83
static TVM_FFI_INLINE PrimType ConvertFallbackValue(DLDataType dtype)
Definition base_expr.h:493
static TVM_FFI_INLINE bool CheckAnyStrict(const TVMFFIAny *src)
Definition base_expr.h:502
static TVM_FFI_INLINE std::string GetMismatchTypeInfo(const TVMFFIAny *src)
Definition base_expr.h:516