1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/compiler/mlir/tensorflow/utils/verify_suitable_for_graph_export.h"
17 
18 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
19 #include "mlir/IR/Visitors.h"  // from @llvm-project
20 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
21 
22 namespace tensorflow {
23 namespace {
24 
25 constexpr char kInvalidExecutorGraphMsg[] =
26     "functions must be of a single Graph with single op Islands: ";
27 
28 }  // namespace
29 
VerifyExportSuitable(mlir::ModuleOp module)30 mlir::LogicalResult VerifyExportSuitable(mlir::ModuleOp module) {
31   mlir::WalkResult result = module.walk([&](mlir::func::FuncOp function) {
32     if (!llvm::hasSingleElement(function)) {
33       function.emitError(kInvalidExecutorGraphMsg)
34           << "only single block functions are supported";
35       return mlir::WalkResult::interrupt();
36     }
37 
38     auto block = function.front().without_terminator();
39     auto graph = llvm::dyn_cast<mlir::tf_executor::GraphOp>(block.begin());
40     if (!graph) {
41       block.begin()->emitError(kInvalidExecutorGraphMsg)
42           << "first op in function is not a tf_executor.graph";
43       return mlir::WalkResult::interrupt();
44     }
45 
46     if (!hasSingleElement(block)) {
47       function.emitError(kInvalidExecutorGraphMsg)
48           << "function does not only contain a single tf_executor.graph";
49       return mlir::WalkResult::interrupt();
50     }
51 
52     for (mlir::Operation& op : graph.GetBody()) {
53       auto island = llvm::dyn_cast<mlir::tf_executor::IslandOp>(op);
54       if (!island) continue;
55 
56       if (!island.WrapsSingleOp()) {
57         island.emitError(kInvalidExecutorGraphMsg)
58             << "tf_executor.island must perfectly wrap a single op";
59         return mlir::WalkResult::interrupt();
60       }
61     }
62 
63     return mlir::WalkResult::advance();
64   });
65 
66   return mlir::failure(result.wasInterrupted());
67 }
68 
69 }  // namespace tensorflow
70