Elffuss BraidHub

kikocis/ncnn public

master · 13.0 KiBRawPermalink
1/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16// This file defines the types used in the standard MLIR TensorFlow dialect.
17
18#ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_TYPES_H_
19#define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_TYPES_H_
20
21#include "mlir/IR/BuiltinTypes.h" // from @llvm-project
22#include "mlir/IR/Diagnostics.h" // from @llvm-project
23#include "mlir/IR/Location.h" // from @llvm-project
24#include "mlir/IR/Operation.h" // from @llvm-project
25#include "mlir/IR/TypeUtilities.h" // from @llvm-project
26#include "mlir/IR/Types.h" // from @llvm-project
27
28namespace mlir {
29namespace TF {
30//===----------------------------------------------------------------------===//
31// Utility iterators
32//===----------------------------------------------------------------------===//
33
34// An iterator for the tensor shapes of an op's operands of shaped types.
35// Returns llvm::None if a operand is unranked; returns ArrayRef<int64_t> as the
36// shape otherwise.
37class OperandShapeIterator final
38 : public llvm::mapped_iterator<Operation::operand_iterator,
39 llvm::Optional<ArrayRef<int64_t> > (*)(
40 Value)>
41{
42public:
43 using reference = llvm::Optional<ArrayRef<int64_t> >;
44
45 /// Initializes the operand shape iterator to the specified operand iterator.
46 explicit OperandShapeIterator(Operation::operand_iterator it);
47};
48
49using OperandShapeRange = iterator_range<OperandShapeIterator>;
50
51// An iterator for the tensor shapes of an op's results of shaped types.
52// Returns llvm::None if a result is unranked; returns ArrayRef<int64_t> as the
53// shape otherwise.
54class ResultShapeIterator final
55 : public llvm::mapped_iterator<Operation::result_iterator,
56 llvm::Optional<ArrayRef<int64_t> > (*)(
57 Value)>
58{
59public:
60 using reference = llvm::Optional<ArrayRef<int64_t> >;
61
62 /// Initializes the result shape iterator to the specified result iterator.
63 explicit ResultShapeIterator(Operation::result_iterator it);
64};
65
66using ResultShapeRange = iterator_range<ResultShapeIterator>;
67
68//===----------------------------------------------------------------------===//
69// TensorFlow types
70//===----------------------------------------------------------------------===//
71
72// The base class in the TensorFlow type hierarchy.
73class TensorFlowType : public Type
74{
75public:
76 using Type::Type;
77
78 // Support method to enable LLVM-style type casting.
79 static bool classof(Type type);
80};
81
82// Returns true if the specified type is a valid TensorFlow element type.
83static inline bool IsValidTFElementType(Type type)
84{
85 return type.isa<ComplexType, FloatType, IntegerType, TensorFlowType>();
86}
87
88// Returns true if this is a valid TensorFlow tensor type.
89static inline bool IsValidTFTensorType(Type type)
90{
91 // TensorFlow types should be tensors of one of the valid TensorFlow element
92 // types.
93 if (auto tensor_ty = type.dyn_cast<TensorType>())
94 return IsValidTFElementType(tensor_ty.getElementType());
95 return false;
96}
97
98namespace detail {
99// Common implementation of TensorFlow types. The template argument indicates
100// the concrete derived class per CRTP.
101template<typename Derived>
102class TensorFlowTypeImpl
103 : public Type::TypeBase<Derived, TensorFlowType, TypeStorage>
104{
105public:
106 using Base = typename Type::TypeBase<Derived, TensorFlowType, TypeStorage>;
107 using TFBase = TensorFlowTypeImpl<Derived>;
108 using Base::Base;
109};
110} // namespace detail
111
112// TensorFlowRefType class supports all the ref types in TensorFlow dialect.
113class TensorFlowRefType : public TensorFlowType
114{
115public:
116 using TensorFlowType::TensorFlowType;
117
118 // Checks if a type is TensorFlow Ref type.
119 static bool classof(Type type);
120
121 // Converts a type to the corresponding TensorFlowRef type.
122 static TensorFlowType get(Type type);
123 static TensorFlowType getChecked(Type type, MLIRContext* context,
124 Location loc)
125 {
126 if (failed(verify(loc, type)))
127 {
128 return TensorFlowRefType();
129 }
130 return get(type);
131 }
132
133 static LogicalResult verify(Location loc, Type type)
134 {
135 // type should be a valid TensorFlow type.
136 if (!IsValidTFTensorType(type))
137 {
138 return emitError(loc) << "invalid TensorFlow type: " << type;
139 }
140 return success();
141 }
142
143 // Converts a TensorFlowRef type to the corresponding TensorFlow or standard
144 // type.
145 Type RemoveRef();
146};
147
148// Returns the corresponding TensorFlow or standard type from TensorFlowRef
149// type.
150static inline Type GetDefaultTypeOf(TensorFlowRefType type)
151{
152 return type.RemoveRef();
153}
154
155// Returns the element type if `type` is a `ShapedType` and the type itself
156// otherwise, converting `TensorFlowRef` type to corresponding `TensorFlow` or
157// standard type if necessary.
158static inline Type GetElementTypeOrSelfResolveRef(Type type)
159{
160 Type element_type = mlir::getElementTypeOrSelf(type);
161 if (auto ref_type = element_type.dyn_cast<mlir::TF::TensorFlowRefType>())
162 {
163 element_type = ref_type.RemoveRef();
164 }
165 return element_type;
166}
167
168#define HANDLE_TF_TYPE(tftype, enumerant, name) \
169 class tftype##Type : public detail::TensorFlowTypeImpl<tftype##Type> \
170 { \
171 public: \
172 using TFBase::TFBase; \
173 };
174
175// Custom TensorFlow types are defined separately.
176#define HANDLE_CUSTOM_TF_TYPE(tftype, enumerant, name)
177
178// NOLINTNEXTLINE
179#include "tf_types.def"
180
181namespace detail {
182// Storage type contains inferred subtypes for TypeWithSubtype.
183class TypeWithSubtypeStorage : public TypeStorage
184{
185public:
186 using KeyTy = ArrayRef<TensorType>;
187
188 // NOLINTNEXTLINE
189 static TypeWithSubtypeStorage* construct(TypeStorageAllocator& allocator,
190 const KeyTy& key)
191 {
192 ArrayRef<TensorType> subtypes = allocator.copyInto(key);
193 return new (allocator.allocate<TypeWithSubtypeStorage>())
194 TypeWithSubtypeStorage(subtypes);
195 }
196
197 explicit TypeWithSubtypeStorage(const KeyTy& key)
198 : subtypes_(key)
199 {
200 }
201
202 bool operator==(const KeyTy& key) const
203 {
204 return key == subtypes_;
205 }
206
207 static llvm::hash_code hashKey(const KeyTy& key)
208 {
209 return llvm::hash_combine_range(key.begin(), key.end());
210 }
211
212 KeyTy subtypes_;
213};
214
215// Common implementation of TensorFlow types with subtypes. These subtypes are
216// opaque and their interpretation depends on the actual underlying type.
217// The template argument indicates the concrete derived class per CRTP. Concrete
218// classes must implement the following:
219// - `static std::string getTypeName()` that returns the name of the type for
220// verification logging.
221template<typename Derived>
222class TypeWithSubtypeImpl
223 : public Type::TypeBase<Derived, TensorFlowType, TypeWithSubtypeStorage>
224{
225public:
226 using Base = Type::TypeBase<Derived, TensorFlowType, TypeWithSubtypeStorage>;
227 using TFBase = TypeWithSubtypeImpl<Derived>;
228 using Base::Base;
229
230 static Derived get(ArrayRef<TensorType> subtypes, MLIRContext* context)
231 {
232 return Base::get(context, subtypes);
233 }
234
235 static Derived getChecked(ArrayRef<TensorType> subtypes, MLIRContext* context,
236 Location loc)
237 {
238 return Base::getChecked(loc, subtypes);
239 }
240 static Derived getChecked(function_ref<InFlightDiagnostic()> emitError,
241 MLIRContext* context,
242 ArrayRef<TensorType> subtypes)
243 {
244 return Base::getChecked(emitError, context, subtypes);
245 }
246
247 static Derived get(MLIRContext* context)
248 {
249 return get({}, context);
250 }
251
252 static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
253 ArrayRef<TensorType> subtypes)
254 {
255 // Each of the subtypes should be a valid TensorFlow type.
256 for (TensorType subtype : subtypes)
257 {
258 if (!IsValidTFTensorType(subtype))
259 {
260 return emitError() << "invalid " << Derived::getTypeName()
261 << " subtype: " << subtype;
262 }
263 }
264 return success();
265 }
266
267 ArrayRef<TensorType> getSubtypes()
268 {
269 return Base::getImpl()->subtypes_;
270 }
271};
272} // namespace detail
273
274// TensorFlowTypeWithSubtype class supports all the types with subtypes in
275// TensorFlow dialect.
276class TensorFlowTypeWithSubtype : public TensorFlowType
277{
278public:
279 using TensorFlowType::TensorFlowType;
280
281 // Checks if a type is TensorFlow type with subtypes.
282 static bool classof(Type type);
283
284 // Converts a TypeWithSubtype type to the same type but without its subtypes.
285 Type RemoveSubtypes();
286
287 // Returns the subtypes.
288 ArrayRef<TensorType> GetSubtypes();
289};
290
291// Returns the corresponding TensorFlow type with subtypes but without its
292// subtypes.
293static inline Type GetDefaultTypeOf(TensorFlowTypeWithSubtype type)
294{
295 return type.RemoveSubtypes();
296}
297
298// TensorFlow resource type is used to support TensorFlow resource variables,
299// which represent shared, persistent state manipulated by a TensorFlow program.
300// ResourceType stores shape and datatype for subtypes unlike most other data
301// types that don't have any associated information.
302class ResourceType : public detail::TypeWithSubtypeImpl<ResourceType>
303{
304public:
305 using TFBase::TFBase;
306 static std::string getTypeName()
307 {
308 return "ResourceType";
309 }
310};
311
312// TensorFlow variant type is used to support arbitrary custom C++ data types.
313// VariantType stores inferred shape and datatype for subtypes unlike most other
314// data types that don't have any associated information. For example, variants
315// encoding TensorList type stores the common shape and dtype of the list
316// elements as the only subtype.
317class VariantType : public detail::TypeWithSubtypeImpl<VariantType>
318{
319public:
320 using TFBase::TFBase;
321 static std::string getTypeName()
322 {
323 return "VariantType";
324 }
325};
326
327// Given two types `a` and `b`, returns a refined type which is cast compatible
328// with both `a` and `b` and is equal to or more precise than both of them. It
329// returns empty Type if the input types are not cast compatible.
330// Provides option to ignore ref types on 'a'. This is useful for TF ops that
331// might allow operands to either be same as result type or be a ref type
332// corresponding to it.
333mlir::Type GetCastCompatibleType(mlir::Type a, mlir::Type b,
334 bool may_ignore_ref_type_a);
335
336// Returns whether two arrays of Type are broadcast compatible.
337bool BroadcastCompatible(TypeRange lhs, TypeRange rhs);
338
339// Returns whether the two elemental types are compatible. Shapes are compatible
340// if:
341// - the types are statically equal
342// - could be dynamically equal
343// - considering dynamic shapes equal unless contradictory info known;
344// - element types are equivalent, modulo subtypes possible be less exact
345// (e.g., a resource type without subtype is considered compatible with
346// resource type with known subtype).
347// Provide option to ignore ref types on 'lhs'.
348bool HasCompatibleElementTypes(Type lhs, Type rhs,
349 bool may_ignore_ref_type_lhs = false);
350
351// Returns true if all TensorFlow types can be cast to one
352// another. In other words, a single run-time value is legal for both the types.
353// For example, tensor<*xf32>, tensor<?xf32> and tensor<3xf32> are cast
354// compatible.
355bool AreCastCompatible(TypeRange types);
356
357// Returns true if corresponding elements of lhs and rhs AreCastCompatible and
358// lhs and rhs are the same length.
359bool ArraysAreCastCompatible(TypeRange lhs, TypeRange rhs);
360
361// If `ty` is a tensor type and its element type has subtypes, then returns a
362// new type of same shape but dropped subtypes for the element type.
363// Otherwise, if `ty` has subtypes, then returns corresponding type with dropped
364// subtypes.
365// Otherwise, returns the original type `ty`.
366Type DropSubTypes(Type ty);
367
368// If `ty` is a tensor type and has elements of a ref type, then returns a new
369// type of same shape but corresponding non-ref type as element type.
370// Otherwise, if `ty` is a ref type, then returns corresponding non-ref type.
371// Otherwise, returns the original type `ty`.
372Type DropRefType(Type ty);
373
374// Convenience call for executing both `DropRefType` and `DropSubTypes`.
375Type DropRefAndSubTypes(Type ty);
376
377} // end namespace TF
378} // end namespace mlir
379
380#endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_TYPES_H_