You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tf_dialect.cpp 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "tf_dialect.h"
  15. #include <mlir/Dialect/Traits.h>
  16. #include <mlir/IR/Attributes.h>
  17. #include <mlir/IR/Builders.h>
  18. #include <mlir/IR/Dialect.h>
  19. #include <mlir/IR/DialectImplementation.h>
  20. #include <mlir/IR/Location.h>
  21. #include <mlir/IR/Matchers.h>
  22. #include <mlir/IR/MLIRContext.h>
  23. #include <mlir/IR/OpDefinition.h>
  24. #include <mlir/IR/OpImplementation.h>
  25. #include <mlir/IR/Operation.h>
  26. #include <mlir/IR/OperationSupport.h>
  27. #include <mlir/IR/PatternMatch.h>
  28. #include <mlir/IR/TypeUtilities.h>
  29. #include <mlir/IR/Types.h>
  30. #include <mlir/IR/Value.h>
  31. #include <mlir/IR/Verifier.h>
  32. #include <mlir/Interfaces/CallInterfaces.h>
  33. #include <mlir/Interfaces/DerivedAttributeOpInterface.h>
  34. #include <mlir/Interfaces/InferTypeOpInterface.h>
  35. #include <mlir/Interfaces/LoopLikeInterface.h>
  36. #include <mlir/Interfaces/SideEffectInterfaces.h>
  37. #include <mlir/Parser.h>
  38. #include <mlir/Support/LogicalResult.h>
  39. #include <mlir/Transforms/InliningUtils.h>
  40. #include "tf_attributes.h"
  41. #include "tf_side_effects.h"
  42. #include "tf_traits.h"
  43. namespace mlir {
  44. static LogicalResult Verify(...)
  45. {
  46. return success();
  47. }
  48. static LogicalResult VerifyPartitionedCall(...)
  49. {
  50. return success();
  51. }
  52. static LogicalResult VerifyStridedSliceBase(...)
  53. {
  54. return success();
  55. }
  56. static LogicalResult VerifyUnsortedSegmentReduction(...)
  57. {
  58. return success();
  59. }
  60. namespace TF {
  61. TensorFlowDialect::TensorFlowDialect(MLIRContext* context)
  62. : Dialect(/*name=*/"tf", context, TypeID::get<TensorFlowDialect>())
  63. {
  64. addOperations<
  65. #define GET_OP_LIST
  66. #include "tf_all_ops.cc.inc"
  67. >();
  68. addTypes<
  69. #define HANDLE_TF_TYPE(tftype, enumerant, name) tftype##Type,
  70. #define HANDLE_LAST_TF_TYPE(tftype, enumerant, name) tftype##Type
  71. #include "tf_types.def"
  72. >();
  73. // addInterfaces<TFInlinerInterface, TFDecodeAttributesInterface,
  74. // TFConstantFoldInterface>();
  75. addAttributes<ShapeAttr, FuncAttr>();
  76. // Support unknown operations because not all TensorFlow operations are
  77. // registered.
  78. allowUnknownOperations();
  79. // for (const auto &hook : *TensorFlowDialect::additional_operation_hooks_) {
  80. // hook(*this);
  81. // }
  82. }
  83. namespace {
  84. ShapeAttr ParseShapeAttr(MLIRContext* context, StringRef spec, Location loc)
  85. {
  86. auto emit_error = [&, spec]() {
  87. emitError(loc, "invalid TensorFlow shape attribute: ") << spec;
  88. return nullptr;
  89. };
  90. if (!spec.consume_front("shape<")) return emit_error();
  91. if (spec.consume_front("*>"))
  92. return mlir::TF::ShapeAttr::get(context, llvm::None);
  93. SmallVector<int64_t, 4> shape;
  94. while (!spec.consume_front(">"))
  95. {
  96. int64_t dim;
  97. if (spec.consume_front("?"))
  98. dim = -1;
  99. else if (spec.consumeInteger(10, dim) || dim < 0)
  100. return emit_error();
  101. spec.consume_front("x");
  102. shape.push_back(dim);
  103. }
  104. return mlir::TF::ShapeAttr::get(context, llvm::makeArrayRef(shape));
  105. }
  106. // Parses a #tf.func attribute of the following format:
  107. //
  108. // #tf.func<@symbol, {attr = "value"}>
  109. //
  110. // where the first element is a SymbolRefAttr and the second element is a
  111. // DictionaryAttr.
  112. FuncAttr ParseFuncAttr(MLIRContext* context, StringRef spec, Location loc)
  113. {
  114. auto emit_error = [&, spec]() {
  115. emitError(loc, "invalid TensorFlow func attribute: ") << spec;
  116. return nullptr;
  117. };
  118. if (!spec.consume_front("func<")) return emit_error();
  119. size_t func_name_num_read = 0;
  120. Attribute func_name_attr = mlir::parseAttribute(spec, context, func_name_num_read);
  121. if (!func_name_attr || !func_name_attr.isa<SymbolRefAttr>())
  122. return emit_error();
  123. spec = spec.drop_front(func_name_num_read);
  124. if (!spec.consume_front(", ")) return emit_error();
  125. size_t func_attrs_num_read = 0;
  126. Attribute func_attrs_attr = mlir::parseAttribute(spec, context, func_attrs_num_read);
  127. if (!func_attrs_attr || !func_attrs_attr.isa<DictionaryAttr>())
  128. return emit_error();
  129. spec = spec.drop_front(func_attrs_num_read);
  130. if (!spec.consume_front(">")) return emit_error();
  131. return mlir::TF::FuncAttr::get(context, func_name_attr.cast<SymbolRefAttr>(),
  132. func_attrs_attr.cast<DictionaryAttr>());
  133. }
  134. } // namespace
  135. Attribute TensorFlowDialect::parseAttribute(DialectAsmParser& parser,
  136. Type type) const
  137. {
  138. auto spec = parser.getFullSymbolSpec();
  139. Location loc = parser.getEncodedSourceLoc(parser.getNameLoc());
  140. if (spec.startswith("shape")) return ParseShapeAttr(getContext(), spec, loc);
  141. if (spec.startswith("func")) return ParseFuncAttr(getContext(), spec, loc);
  142. return (emitError(loc, "unknown TensorFlow attribute: " + spec), nullptr);
  143. }
  144. // Parses a type registered to this dialect.
  145. Type TensorFlowDialect::parseType(DialectAsmParser& parser) const
  146. {
  147. StringRef data;
  148. if (parser.parseKeyword(&data)) return Type();
  149. #define HANDLE_TF_TYPE(tftype, enumerant, name) \
  150. if (data == name) return tftype##Type::get(getContext());
  151. // Custom TensorFlow types are handled separately at the end as they do partial
  152. // match.
  153. #define HANDLE_CUSTOM_TF_TYPE(tftype, enumerant, name)
  154. // NOLINTNEXTLINE
  155. #include "tf_types.def"
  156. llvm::SMLoc loc = parser.getNameLoc();
  157. if (data.startswith("resource"))
  158. {
  159. Type ret = ParseResourceType(parser);
  160. if (!ret) parser.emitError(loc, "invalid resource type");
  161. return ret;
  162. }
  163. if (data.startswith("variant"))
  164. {
  165. Type ret = ParseVariantType(parser);
  166. if (!ret) parser.emitError(loc, "invalid variant type");
  167. return ret;
  168. }
  169. return (parser.emitError(loc, "unknown TensorFlow type: " + data), nullptr);
  170. }
  171. namespace {
  172. template<typename TypeWithSubtype>
  173. Type ParseTypeWithSubtype(MLIRContext* context, DialectAsmParser& parser)
  174. {
  175. // Default type without inferred subtypes.
  176. if (failed(parser.parseOptionalLess())) return TypeWithSubtype::get(context);
  177. // Most types with subtypes have only one subtype.
  178. SmallVector<TensorType, 1> subtypes;
  179. do
  180. {
  181. TensorType tensor_ty;
  182. if (parser.parseType(tensor_ty)) return Type();
  183. // Each of the subtypes should be a valid TensorFlow type.
  184. // TODO(jpienaar): Remove duplication.
  185. if (!IsValidTFTensorType(tensor_ty))
  186. {
  187. parser.emitError(parser.getNameLoc()) << "invalid subtype: " << tensor_ty;
  188. return Type();
  189. }
  190. subtypes.push_back(tensor_ty);
  191. } while (succeeded(parser.parseOptionalComma()));
  192. if (parser.parseGreater()) return Type();
  193. return TypeWithSubtype::get(subtypes, context);
  194. }
  195. } // anonymous namespace
  196. Type TensorFlowDialect::ParseResourceType(DialectAsmParser& parser) const
  197. {
  198. return ParseTypeWithSubtype<ResourceType>(getContext(), parser);
  199. }
  200. Type TensorFlowDialect::ParseVariantType(DialectAsmParser& parser) const
  201. {
  202. return ParseTypeWithSubtype<VariantType>(getContext(), parser);
  203. }
  204. Operation* TensorFlowDialect::materializeConstant(OpBuilder& builder,
  205. Attribute value, Type type,
  206. Location loc)
  207. {
  208. return builder.create<ConstOp>(loc, type, value);
  209. }
  210. // Builds a constant op with the specified attribute `value`. The result
  211. // op's type is deduced from `value`; if `value` is of scalar type,
  212. // wraps it up with a tensor type of empty shape.
  213. // TODO(jpienaar): This one differs from the autogenerated one as it takes an
  214. // attribute but always creates an ElementsAttr internally.
  215. void ConstOp::build(OpBuilder& builder, OperationState& result,
  216. Attribute value)
  217. {
  218. ShapedType type;
  219. if (auto elem_attr = value.dyn_cast<ElementsAttr>())
  220. {
  221. return ConstOp::build(builder, result, elem_attr);
  222. }
  223. else if (value.isa<BoolAttr, FloatAttr, IntegerAttr>())
  224. {
  225. // All TensorFlow types must be tensor types. In the build() method,
  226. // we want to provide more flexibility by allowing attributes of scalar
  227. // types. But we need to wrap it up with ElementsAttr to construct
  228. // valid TensorFlow constants.
  229. type = RankedTensorType::get(/*shape=*/ {}, value.getType());
  230. return ConstOp::build(builder, result, DenseElementsAttr::get(type, value));
  231. }
  232. // TODO(jpienaar): support other TensorFlow specific types.
  233. llvm_unreachable("unsupported attribute type for building tf.Const");
  234. }
  235. void ConstOp::build(OpBuilder& builder, OperationState& result, Type type,
  236. Attribute value)
  237. {
  238. // Handle the case where the type and value are already tensors.
  239. if (type.isa<TensorType>() && value.isa<ElementsAttr>())
  240. {
  241. result.addTypes(type);
  242. result.addAttribute("value", value);
  243. return;
  244. }
  245. // Otherwise, default to the attribute builder.
  246. ConstOp::build(builder, result, value);
  247. assert(type == result.types[0] && "type mismatch in construction");
  248. }
  249. Region& WhileRegionOp::getLoopBody()
  250. {
  251. return body();
  252. }
  253. bool WhileRegionOp::isDefinedOutsideOfLoop(Value value)
  254. {
  255. // If the Op defining the value exists and the defining op is outside the
  256. // scope of this WhileRegion, then we can infer that its defined outside.
  257. // The defining Op is outside the scope of this WhileRegion if this
  258. // WhileRegionOp is not an ancestor of the defining op in the parent chain.
  259. Operation* def_op = value.getDefiningOp();
  260. return def_op && !getOperation()->isAncestor(def_op);
  261. }
  262. LogicalResult WhileRegionOp::moveOutOfLoop(
  263. llvm::ArrayRef<mlir::Operation*> ops)
  264. {
  265. // Move the hoisted value to just before the while.
  266. Operation* while_op = this->getOperation();
  267. for (auto op : ops) op->moveBefore(while_op);
  268. return success();
  269. }
  270. } // namespace TF
  271. } // namespace mlir
  272. #define GET_OP_CLASSES
  273. #include "tf_all_ops.cc.inc"