Elffuss BraidHub

kikocis/ncnn public

master · 25.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 is the base operation definition file for TensorFlow.
17//
18// This file includes the definition for the TensorFlow dialect, base TensorFlow
19// op, and various commonly used TensorFlow traits, types, attributes, and
20// builders.
21
22#ifndef TF_OP_BASE
23#define TF_OP_BASE
24
25include "mlir/IR/OpBase.td"
26include "mlir/Interfaces/SideEffectInterfaces.td"
27
28//===----------------------------------------------------------------------===//
29// TensorFlow dialect definitions
30//===----------------------------------------------------------------------===//
31
32def TF_Dialect : Dialect {
33 let name = "tf";
34
35 let description = [{
36The TensorFlow dialect.
37
38This dialect maps to TensorFlow operations.
39
40Invariants:
41
42* All values are of Tensor type (in particular, scalars are
43 represented using zero-dimensional tensors);
44
45TODO: Make invariants more structured so that we can reference them in ops.
46 }];
47
48 let cppNamespace = "::mlir::TF";
49}
50
51//===----------------------------------------------------------------------===//
52// TensorFlow traits
53//===----------------------------------------------------------------------===//
54
55// Specify this trait if the op requires all outputs to have the same type and
56// the inputs either have the same type as result or a ref type corresponding to
57// the result type.
58def TF_OperandsSameAsResultsTypeOrRef : NativeOpTrait<
59 "TF::OperandsSameAsResultsTypeOrRef">;
60
61// Op has the same operand and result element types (or type itself, if scalar)
62// after resolving reference types (i.e., after converting reference types to
63// their corresponding TensorFlow or standard types).
64def TF_SameOperandsAndResultElementTypeResolveRef : NativeOpTrait<
65 "TF::SameOperandsAndResultElementTypeResolveRef">;
66
67// Op has the same operand and result types after resolving reference types
68// (i.e., after converting reference types to their corresponding TensorFlow or
69// standard types).
70def TF_SameOperandsAndResultTypeResolveRef : NativeOpTrait<
71 "TF::SameOperandsAndResultTypeResolveRef">;
72
73// Layout agnostic operations do not depend on the operands data layout (data
74// format), as an example all element wise operations are layout agnostic.
75def TF_LayoutAgnostic : NativeOpTrait<"TF::LayoutAgnostic">;
76
77// Trait to indicate operations that cannot be duplicated as they might carry
78// certain state around within their implementations.
79def TF_CannotDuplicate : NativeOpTrait<"TF::CannotDuplicate">;
80
81// Trait to indicate an operation cannot be constant folded.
82def TF_NoConstantFold : NativeOpTrait<"TF::NoConstantFold">;
83
84// Coefficient wise binary operation with implicit broadcasting support, for
85// example tf.Sub operation.
86def TF_CwiseBinary : NativeOpTrait<"TF::CwiseBinary">;
87
88// Coefficient wise unary operation, for example tf.Sqrt operation.
89def TF_CwiseUnary : NativeOpTrait<"TF::CwiseUnary">;
90
91// Variant of broadcastable trait that considers TF's subtype behavior.
92class TF_OpIsBroadcastableToRes<int opId, int resId> : And<[
93 TCOpResIsShapedTypePred<opId, resId>,
94 CPred<"mlir::TF::BroadcastCompatible("
95 "$_op.getOperand(" # opId # ").getType(), "
96 "$_op.getResult(" # resId # ").getType())">]>;
97
98
99class TF_AllTypesMatchPred<list<string> values> :
100 CPred<"TF::AreCastCompatible(llvm::makeArrayRef({" #
101 !interleave(values, ", ") # "}))">;
102
103class TF_AllTypesMatch<list<string> names> :
104 PredOpTrait<
105 "all of {" # !interleave(names, ", ") #
106 "} have dynamically equal types ",
107 TF_AllTypesMatchPred<
108 !foreach(n, names, !subst("$_self", "$" # n, "$_self.getType()"))>>;
109
110//===----------------------------------------------------------------------===//
111// Rank/Shape helpers.
112//===----------------------------------------------------------------------===//
113
114class TF_OperandIsUnrankedPred<int n> :
115 CPred<"$_op.getOperand(" # n # ").getType().isa<UnrankedTensorType>()">;
116
117class TF_ResultIsUnrankedPred<int n> :
118 CPred<"$_op.getResult(" # n # ").getType().isa<UnrankedTensorType>()">;
119
120// Returns true if the n-th operand has unknown rank or has rank m.
121class TF_OperandHasRank<int n, int m> :
122 PredOpTrait<"operand " # n # " is " # m # "-D",
123 Or<[TF_OperandIsUnrankedPred<n>,
124 CPred<"$_op.getOperand(" # n #
125 ").getType().cast<ShapedType>().getRank() == " # m>]>>;
126
127// Returns true if the n-th result has unknown rank or has rank m.
128class TF_ResultHasRank<int n, int m> :
129 PredOpTrait<"result " # n # " is " # m # "-D",
130 Or<[TF_ResultIsUnrankedPred<n>,
131 CPred<"$_op.getResult(" # n #
132 ").getType().cast<ShapedType>().getRank() == " # m>]>>;
133
134//===----------------------------------------------------------------------===//
135// TensorFlow op side effects
136//===----------------------------------------------------------------------===//
137
138class TF_ResourceBase<string resourceKind> :
139 Resource<!strconcat("::mlir::TF::ResourceEffects::", resourceKind)> {
140}
141
142def TF_VariableResource : TF_ResourceBase<"Variable">;
143def TF_StackResource : TF_ResourceBase<"Stack">;
144def TF_TensorArrayResource : TF_ResourceBase<"TensorArray">;
145def TF_SummaryResource : TF_ResourceBase<"Summary">;
146def TF_LookupTableResource : TF_ResourceBase<"LookupTable">;
147def TF_DatasetSeedGeneratorResource : TF_ResourceBase<"DatasetSeedGenerator">;
148def TF_DatasetMemoryCacheResource : TF_ResourceBase<"DatasetMemoryCache">;
149def TF_DatasetIteratorResource : TF_ResourceBase<"DatasetIterator">;
150def TF_TPUEmbeddingResource : TF_ResourceBase<"TPUEmbedding">;
151
152def TF_VariableRead : MemRead<TF_VariableResource>;
153def TF_StackRead : MemRead<TF_StackResource>;
154def TF_TensorArrayRead : MemRead<TF_TensorArrayResource>;
155def TF_LookupTableRead : MemRead<TF_LookupTableResource>;
156def TF_DatasetSeedGeneratorRead : MemRead<TF_DatasetSeedGeneratorResource>;
157def TF_DatasetMemoryCacheRead : MemRead<TF_DatasetMemoryCacheResource>;
158def TF_DatasetIteratorRead : MemRead<TF_DatasetIteratorResource>;
159
160def TF_VariableWrite : MemWrite<TF_VariableResource>;
161def TF_StackWrite : MemWrite<TF_StackResource>;
162def TF_TensorArrayWrite : MemWrite<TF_TensorArrayResource>;
163def TF_SummaryWrite : MemWrite<TF_SummaryResource>;
164def TF_LookupTableWrite : MemWrite<TF_LookupTableResource>;
165def TF_DatasetSeedGeneratorWrite : MemWrite<TF_DatasetSeedGeneratorResource>;
166def TF_DatasetMemoryCacheWrite : MemWrite<TF_DatasetMemoryCacheResource>;
167def TF_DatasetIteratorWrite : MemWrite<TF_DatasetIteratorResource>;
168
169def TF_VariableAlloc : MemAlloc<TF_VariableResource>;
170def TF_StackAlloc : MemAlloc<TF_StackResource>;
171def TF_TensorArrayAlloc : MemAlloc<TF_TensorArrayResource>;
172def TF_SummaryAlloc : MemAlloc<TF_SummaryResource>;
173def TF_LookupTableAlloc : MemAlloc<TF_LookupTableResource>;
174def TF_DatasetSeedGeneratorAlloc : MemAlloc<TF_DatasetSeedGeneratorResource>;
175def TF_DatasetMemoryCacheAlloc : MemAlloc<TF_DatasetMemoryCacheResource>;
176def TF_DatasetIteratorAlloc : MemAlloc<TF_DatasetIteratorResource>;
177
178def TF_StackFree : MemFree<TF_StackResource>;
179def TF_TensorArrayFree : MemFree<TF_TensorArrayResource>;
180def TF_SummaryFree : MemFree<TF_SummaryResource>;
181def TF_DatasetSeedGeneratorFree : MemFree<TF_DatasetSeedGeneratorResource>;
182def TF_DatasetMemoryCacheFree : MemFree<TF_DatasetMemoryCacheResource>;
183def TF_DatasetIteratorFree : MemFree<TF_DatasetIteratorResource>;
184
185def TF_TPUEmbeddingSideEffect : MemoryEffects<[MemWrite<TF_TPUEmbeddingResource>]>;
186
187//===----------------------------------------------------------------------===//
188// TensorFlow op definitions
189//===----------------------------------------------------------------------===//
190
191class TF_Op<string mnemonic, list<OpTrait> traits = []> :
192 Op<TF_Dialect, mnemonic, traits>;
193
194//===----------------------------------------------------------------------===//
195// TensorFlow attribute definitions
196//===----------------------------------------------------------------------===//
197
198class TF_TensorFlowAttr <string name, string description> :
199 Attr<CPred<"$_self.isa<mlir::TF::" # name # "Attr>()">,
200 "TensorFlow " # description # " attribute">;
201
202def TF_ShapeAttr : TF_TensorFlowAttr<"Shape", "shape"> {
203 let returnType = "llvm::Optional<llvm::ArrayRef<int64_t>>";
204 let convertFromStorage = "$_self.cast<mlir::TF::ShapeAttr>().getValue()";
205
206 // Create a ranked shape attr by default.
207 let constBuilderCall = "mlir::TF::ShapeAttr::get($_builder.getContext(), $0)";
208}
209
210def TF_ShapeAttrArray :
211 TypedArrayAttrBase<TF_ShapeAttr, "tensorflow shape attribute array">;
212
213//===----------------------------------------------------------------------===//
214// TensorFlow type definitions
215//===----------------------------------------------------------------------===//
216
217// Any tensor element type defined in the TensorFlow dialect
218def TF_TFDialectType :
219 Type<CPred<"$_self.isa<mlir::TF::TensorFlowType>()">, "TensorFlow type">;
220
221// Class for any TensorFlow dialect specific type
222class TF_TensorFlowType <string name, string description> :
223 Type<CPred<"$_self.isa<mlir::TF::" # name # "Type>()">,
224 "TensorFlow " # description # " type">,
225 BuildableType<"getType<mlir::TF::" # name # "Type>()">;
226
227//===----------------------------------------------------------------------===//
228// Reference types
229
230// Float reference types
231def TF_Float16Ref : TF_TensorFlowType<"HalfRef", "f16ref">;
232def TF_Float32Ref : TF_TensorFlowType<"FloatRef", "f32ref">;
233def TF_Float64Ref : TF_TensorFlowType<"DoubleRef", "f64ref">;
234def TF_Bfloat16Ref : TF_TensorFlowType<"Bfloat16Ref", "bf16ref">;
235
236// Complex reference types
237def TF_Complex64Ref : TF_TensorFlowType<"Complex64Ref", "complex64ref">;
238def TF_Complex128Ref : TF_TensorFlowType<"Complex128Ref", "complex128ref">;
239
240// Integer reference types
241def TF_Int8Ref : TF_TensorFlowType<"Int8Ref", "i8ref">;
242def TF_Int16Ref : TF_TensorFlowType<"Int16Ref", "i16ref">;
243def TF_Int32Ref : TF_TensorFlowType<"Int32Ref", "i32ref">;
244def TF_Int64Ref : TF_TensorFlowType<"Int64Ref", "i64ref">;
245
246def TF_Uint8Ref : TF_TensorFlowType<"Uint8Ref", "ui8ref">;
247def TF_Uint16Ref : TF_TensorFlowType<"Uint16Ref", "ui16ref">;
248def TF_Uint32Ref : TF_TensorFlowType<"Uint32Ref", "ui32ref">;
249def TF_Uint64Ref : TF_TensorFlowType<"Uint64Ref", "ui64ref">;
250
251// Quantized reference types
252def TF_Qint8Ref : TF_TensorFlowType<"Qint8Ref", "qint8ref">;
253def TF_Qint16Ref : TF_TensorFlowType<"Qint16Ref", "qint16ref">;
254def TF_Qint32Ref : TF_TensorFlowType<"Qint32Ref", "qint32ref">;
255def TF_Quint8Ref : TF_TensorFlowType<"Quint8Ref", "quint8ref">;
256def TF_Quint16Ref : TF_TensorFlowType<"Quint16Ref", "quint16ref">;
257
258// Other reference types
259def TF_BoolRef : TF_TensorFlowType<"BoolRef", "boolref">;
260def TF_ResourceRef : TF_TensorFlowType<"ResourceRef", "resourceref">;
261def TF_StrRef : TF_TensorFlowType<"StringRef", "stringref">;
262def TF_VariantRef : TF_TensorFlowType<"VariantRef", "variantref">;
263
264//===----------------------------------------------------------------------===//
265// Integer types (including corresponding reference types)
266
267def TF_Bool : AnyTypeOf<[I<1>, TF_BoolRef], "bool">;
268
269def TF_Int8 : AnyTypeOf<[I8, TF_Int8Ref], "8-bit integer">;
270def TF_Int16 : AnyTypeOf<[I16, TF_Int16Ref], "16-bit integer">;
271def TF_Int32 : AnyTypeOf<[I32, TF_Int32Ref], "32-bit integer">;
272def TF_Int64 : AnyTypeOf<[I64, TF_Int64Ref], "64-bit integer">;
273def TF_I32OrI64 : AnyTypeOf<[I32, I64, TF_Int32Ref, TF_Int64Ref],
274 "32/64-bit signed integer">;
275
276def TF_Uint8 : AnyTypeOf<[UI<8>, TF_Uint8Ref], "8-bit unsigned integer">;
277def TF_Uint16 : AnyTypeOf<[UI<16>, TF_Uint16Ref], "16-bit unsigned integer">;
278def TF_Uint32 : AnyTypeOf<[UI<32>, TF_Uint32Ref], "32-bit unsigned integer">;
279def TF_Uint64 : AnyTypeOf<[UI<64>, TF_Uint64Ref], "64-bit unsigned integer">;
280
281// Any unsigned integer type
282def TF_UInt : AnyTypeOf<[TF_Uint8, TF_Uint16, TF_Uint32, TF_Uint64],
283 "unsigned integer">;
284
285// Any signed integer type
286def TF_SInt : AnyTypeOf<[TF_Int8, TF_Int16, TF_Int32, TF_Int64],
287 "signed integer">;
288
289// Any integer type
290def TF_Int : AnyTypeOf<[TF_SInt, TF_UInt], "integer">;
291
292// Tensor types
293def TF_BoolTensor : TensorOf<[TF_Bool]>;
294
295def TF_IntTensor : TensorOf<[TF_Int]>;
296def TF_Int8Tensor : TensorOf<[TF_Int8]>;
297def TF_Int16Tensor : TensorOf<[TF_Int16]>;
298def TF_Int32Tensor : TensorOf<[TF_Int32]>;
299def TF_Int64Tensor : TensorOf<[TF_Int64]>;
300def TF_I32OrI64Tensor : TensorOf<[TF_I32OrI64]>;
301
302def TF_Uint8Tensor : TensorOf<[TF_Uint8]>;
303def TF_Uint16Tensor : TensorOf<[TF_Uint16]>;
304def TF_Uint32Tensor : TensorOf<[TF_Uint32]>;
305def TF_Uint64Tensor : TensorOf<[TF_Uint64]>;
306
307//===----------------------------------------------------------------------===//
308// Quantized types (including corresponding reference types)
309
310def TF_Qint8 : AnyTypeOf<
311 [TF_TensorFlowType<"Qint8", "qint8">, TF_Qint8Ref],
312 "8-bit quantized integer">;
313def TF_Qint16 : AnyTypeOf<
314 [TF_TensorFlowType<"Qint16", "qint16">, TF_Qint16Ref],
315 "16-bit quantized integer">;
316def TF_Qint32 : AnyTypeOf<
317 [TF_TensorFlowType<"Qint32", "qint32">, TF_Qint32Ref],
318 "32-bit quantized integer">;
319def TF_Quint8 : AnyTypeOf<
320 [TF_TensorFlowType<"Quint8", "quint8">, TF_Quint8Ref],
321 "8-bit quantized unsigned integer">;
322def TF_Quint16 : AnyTypeOf<
323 [TF_TensorFlowType<"Quint16", "quint16">, TF_Quint16Ref],
324 "16-bit quantized unsigned integer">;
325
326// Any quantized type
327def TF_Quantized : AnyTypeOf<
328 [TF_Qint8, TF_Qint16, TF_Qint32, TF_Quint8, TF_Quint16], "quantized">;
329
330//===----------------------------------------------------------------------===//
331// Floating-point types (including corresponding reference types)
332
333def TF_Float16 : AnyTypeOf<[F16, TF_Float16Ref], "16-bit float">;
334def TF_Float32 : AnyTypeOf<[F32, TF_Float32Ref], "32-bit float">;
335def TF_Float64 : AnyTypeOf<[F64, TF_Float64Ref], "64-bit float">;
336def TF_Bfloat16 : AnyTypeOf<[BF16, TF_Bfloat16Ref], "bfloat16">;
337
338def TF_F32OrF64 : AnyTypeOf<[TF_Float32, TF_Float64], "32/64-bit float">;
339
340def TF_Float : AnyTypeOf<
341 [TF_Float16, TF_Float32, TF_Float64, TF_Bfloat16],
342 "floating-point">;
343
344// Tensor types
345def TF_FloatTensor : TensorOf<[TF_Float]>;
346def TF_F32OrF64Tensor : TensorOf<[TF_F32OrF64]>;
347def TF_Float16Tensor : TensorOf<[TF_Float16]>;
348def TF_Float32Tensor : TensorOf<[TF_Float32]>;
349def TF_Float64Tensor : TensorOf<[TF_Float64]>;
350def TF_Bfloat16Tensor : TensorOf<[TF_Bfloat16]>;
351
352//===----------------------------------------------------------------------===//
353// Complex types (including corresponding reference types)
354
355// TODO(suderman): Remove TF_Complex64 and use a standard ops declaration, along
356// with the associated cleanup.
357def TF_Complex64 : AnyTypeOf<[Complex<F<32>>, TF_Complex64Ref],
358 "64-bit complex">;
359def TF_Complex128 : AnyTypeOf<[Complex<F<64>>, TF_Complex128Ref],
360 "128-bit complex">;
361def TF_Complex : AnyTypeOf<[TF_Complex64, TF_Complex128], "complex">;
362
363// Tensor types
364def TF_ComplexTensor : TensorOf<[TF_Complex]>;
365def TF_Complex64Tensor : TensorOf<[TF_Complex64]>;
366def TF_Complex128Tensor : TensorOf<[TF_Complex128]>;
367
368//===----------------------------------------------------------------------===//
369// String/variant/resource types (including corresponding reference types)
370
371def TF_Str : AnyTypeOf<
372 [TF_TensorFlowType<"String", "str">, TF_StrRef], "string">;
373def TF_StrTensor : TensorOf<[TF_Str]>;
374
375def TF_Variant : AnyTypeOf<
376 [TF_TensorFlowType<"Variant", "var">, TF_VariantRef], "variant">;
377def TF_VariantTensor : TensorOf<[TF_Variant]>;
378
379def TF_Resource : AnyTypeOf<
380 [TF_TensorFlowType<"Resource", "res">, TF_ResourceRef], "resource">;
381def TF_ResourceTensor : TensorOf<[TF_Resource]>;
382
383//===----------------------------------------------------------------------===//
384// Multi-category type constraints
385
386def TF_IntOrF32OrF64Tensor: TensorOf<[TF_Int, TF_F32OrF64]>;
387def TF_FpOrI32OrI64Tensor : TensorOf<[TF_Float, TF_I32OrI64]>;
388def TF_IntOrFpTensor : TensorOf<[TF_Int, TF_Float]>;
389def TF_SintOrFpTensor : TensorOf<[TF_SInt, TF_Float]>;
390def TF_FpOrComplexTensor : TensorOf<[TF_Float, TF_Complex]>;
391
392def TF_Number : AnyTypeOf<
393 [TF_Int, TF_Float, TF_Quantized, TF_Complex], "number">;
394def TF_NumberTensor : TensorOf<[TF_Number]>;
395
396def TF_NumberNotQuantizedOrStr :
397 AnyTypeOf<[TF_Float, TF_SInt, TF_Complex, TF_Uint8, TF_Str]>;
398def TF_NumberNotQuantizedOrStrTensor : TensorOf<[TF_NumberNotQuantizedOrStr]>;
399
400//===----------------------------------------------------------------------===//
401// Tensor and tensor element types
402
403// Any tensor element type allowed in TensorFlow ops
404// (see https://www.tensorflow.org/api_docs/python/tf/dtypes/DType)
405def TF_ElementType : Type<Or<[TF_Float.predicate,
406 TF_Complex.predicate,
407 TF_Int.predicate,
408 TF_Bool.predicate,
409 TF_TFDialectType.predicate]>,
410 "tf.dtype">;
411
412// Any TensorFlow tensor type
413def TF_Tensor : TensorOf<[TF_ElementType]>;
414
415//===----------------------------------------------------------------------===//
416// TensorFlow attribute definitions
417//===----------------------------------------------------------------------===//
418
419//===----------------------------------------------------------------------===//
420// Tensorflow devices metadata
421
422// Tensorflow GPU device metadata.
423def TF_GpuDeviceMetadata : StructAttr<"GpuDeviceMetadata", TF_Dialect, [
424 // GPU device compute capability: major:minor.
425 StructFieldAttr<"cc_major", I32Attr>,
426 StructFieldAttr<"cc_minor", I32Attr>
427]>;
428
429//===----------------------------------------------------------------------===//
430// String attribute constraints
431
432// A string attribute whose value are one of the values in `cases`.
433class TF_AnyStrAttrOf<list<string> cases> : StringBasedAttr<
434 CPred<!foldl(
435 "$_self.cast<StringAttr>().getValue() == \"" # !head(cases) # "\"",
436 !foreach(case, !tail(cases),
437 "$_self.cast<StringAttr>().getValue() == \"" # case # "\""),
438 prev, cur, prev # " || " # cur)>,
439 "string attribute whose value is " #
440 !foldl(/*init*/!head(cases), /*list*/!tail(cases),
441 prev, cur, prev # ", or " # cur)>;
442
443// TODO: Use EnumAttr to define the common attribute cases
444
445def TF_ConvnetDataFormatAttr : StringBasedAttr<
446 CPred<"$_self.cast<StringAttr>().getValue() == \"NHWC\" || " #
447 "$_self.cast<StringAttr>().getValue() == \"NCHW\"">,
448 "'NHWC' or 'NCHW' convnet data format">;
449
450//===----------------------------------------------------------------------===//
451// Type attributes
452
453// A derived attribute that returns the size of `idx`-th ODS-declared variadic
454// operand.
455class TF_DerivedOperandSizeAttr<int idx> : DerivedAttr<
456 "size_t",
457 "auto range = getODSOperands(" # idx # ");\n"
458 "return std::distance(range.begin(), range.end());",
459 [{ $_builder.getI64IntegerAttr($_self) }]>;
460
461// A derived attribute that returns the element type of `idx`-th ODS-declared
462// operand. If the `idx`-th operand is a variadic operand, then this attribute
463// just returns the element type of its first tensor, which is only meaningful
464// when the variadic operand has at least one tensor and the tensors all have
465// the same element type.
466class TF_DerivedOperandTypeAttr<int idx> : DerivedTypeAttr<
467 "return mlir::getElementTypeOrSelf(*getODSOperands(" # idx # ").begin());">;
468
469// A derived attribute that returns the element types of the tensors in the
470// actual value pack that corresponds to the `idx`-th ODS-declared variadic
471// operand. This returns a list of element types so it is used for variadic
472// operands that can have different element types.
473class TF_DerivedOperandTypeListAttr<int idx> : DerivedAttr<
474 "mlir::OperandElementTypeRange",
475 "auto values = getODSOperands(" # idx # ");\n"
476 "return {mlir::OperandElementTypeIterator(values.begin()), "
477 "mlir::OperandElementTypeIterator(values.end())};",
478 [{
479 ArrayAttr::get($_ctx,
480 [&]() {
481 llvm::SmallVector<Attribute, 4> ret;
482 for (auto t : $_self)
483 ret.push_back(TypeAttr::get(t));
484 return ret;
485 }())
486 }]
487>;
488
489// A derived attribute that returns the shapes of the tensors in the actual
490// value pack that corresponds to the `idx`-th ODS-declared variadic operand.
491// This returns a list of shapes so it is used for variadic operands that
492// can have different shapes.
493class TF_DerivedOperandShapeListAttr<int idx> : DerivedAttr<
494 "::mlir::TF::OperandShapeRange",
495 "auto values = getODSOperands(" # idx # ");\n"
496 "return {mlir::TF::OperandShapeIterator(values.begin()), "
497 "mlir::TF::OperandShapeIterator(values.end())};",
498 [{
499 ArrayAttr::get($_ctx,
500 [&](){
501 llvm::SmallVector<Attribute, 4> ret;
502 for (auto shape : $_self)
503 ret.push_back(mlir::TF::ShapeAttr::get($_ctx, shape));
504 return ret;
505 }())
506 }]
507>;
508
509// A derived attribute that returns the size of `idx`-th ODS-declared variadic
510// result.
511class TF_DerivedResultSizeAttr<int idx> : DerivedAttr<
512 "size_t",
513 "auto range = getODSResults(" # idx # ");\n"
514 "return std::distance(range.begin(), range.end());",
515 [{ $_builder.getI64IntegerAttr($_self) }]>;
516
517// A derived attribute that returns the element type of `idx`-th ODS-declared
518// result. If the `idx`-th result is a variadic result, then this attribute
519// just returns the element type of its first tensor, which is only meaningful
520// when the variadic result has at least one tensor and the tensors all have
521// the same element type.
522class TF_DerivedResultTypeAttr<int idx> : DerivedTypeAttr<
523 "return mlir::getElementTypeOrSelf(*getODSResults(" # idx # ").begin());">;
524
525// A derived attribute that returns the element types of the tensors in the
526// actual value pack that corresponds to the `idx`-th ODS-declared variadic
527// result. This returns a list of element types so it is used for variadic
528// results that can have different element types.
529class TF_DerivedResultTypeListAttr<int idx> : DerivedAttr<
530 "mlir::ResultElementTypeRange",
531 "auto values = getODSResults(" # idx # ");\n"
532 "return {mlir::ResultElementTypeIterator(values.begin()), "
533 "mlir::ResultElementTypeIterator(values.end())};",
534 [{
535 ArrayAttr::get($_ctx,
536 [&]() {
537 llvm::SmallVector<Attribute, 4> ret;
538 for (auto t : $_self)
539 ret.push_back(TypeAttr::get(t));
540 return ret;
541 }())
542 }]
543>;
544
545// A derived attribute that returns the shapes of the tensors in the actual
546// value pack that corresponds to the `idx`-th ODS-declared variadic result.
547// This returns a list of shapes so it is used for variadic results that
548// can have different shapes.
549class TF_DerivedResultShapeListAttr<int idx> : DerivedAttr<
550 "mlir::TF::ResultShapeRange",
551 "auto values = getODSResults(" # idx # ");\n"
552 "return {mlir::TF::ResultShapeIterator(values.begin()), "
553 "mlir::TF::ResultShapeIterator(values.end())};",
554 [{
555 ArrayAttr::get($_ctx,
556 [&](){
557 llvm::SmallVector<Attribute, 4> ret;
558 for (auto shape : $_self)
559 ret.push_back(mlir::TF::ShapeAttr::get($_ctx, shape));
560 return ret;
561 }())
562 }]
563>;
564
565// A derived attribute that returns the shape of the first result type.
566def TF_DerivedResultShapeAttr : DerivedAttr<"ShapedType",
567 "return (*getOperation()->result_type_begin()).cast<ShapedType>();",
568 [{ mlir::TF::ShapeAttr::get($_ctx, $_self) }]>;
569
570def TF_IntTypeAttr : TypeAttrBase<"IntegerType", "integer type"> {
571 let returnType = "Type";
572}
573
574//===----------------------------------------------------------------------===//
575// TensorFlow common builders
576//===----------------------------------------------------------------------===//
577
578// Mixin class defining a builder for binary ops supporting broadcast
579// behavior. The result type has the same element type as both operands.
580class WithBroadcastableBinOpBuilder {
581 list<OpBuilder> builders = [
582 OpBuilder<(ins "Value":$x, "Value":$y),
583 [{
584 auto resultType =
585 OpTrait::util::getBroadcastedType(x.getType(), y.getType());
586 if (!resultType)
587 mlir::emitError($_state.location, "non-broadcastable operands");
588 return build($_builder, $_state, resultType, x, y);
589}]>];
590}
591
592// Mixin class defining a builder for comparison ops supporting broadcast
593// behavior. The result type has bool element type.
594class WithBroadcastableCmpOpBuilder {
595 list<OpBuilder> builders = [
596 OpBuilder<(ins "Value":$x, "Value":$y),
597 [{
598 Type resultType;
599 if (x.getType().isa<UnrankedTensorType>() ||
600 y.getType().isa<UnrankedTensorType>()) {
601 resultType = UnrankedTensorType::get($_builder.getI1Type());
602 } else {
603 SmallVector<int64_t, 4> resultShape;
604 if (!OpTrait::util::getBroadcastedShape(
605 x.getType().cast<ShapedType>().getShape(),
606 y.getType().cast<ShapedType>().getShape(), resultShape)) {
607 mlir::emitError($_state.location,
608 "operands have no broadcastable shapes");
609 }
610
611 resultType = RankedTensorType::get(resultShape, $_builder.getI1Type());
612 }
613 return build($_builder, $_state, resultType, x, y);
614}]>];
615}
616
617#endif // TF_OP_BASE