1 /* Copyright 2017 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 #ifndef TENSORFLOW_COMPILER_JIT_SHAPE_INFERENCE_HELPERS_H_
17 #define TENSORFLOW_COMPILER_JIT_SHAPE_INFERENCE_HELPERS_H_
18 
19 #include <vector>
20 
21 #include "tensorflow/core/graph/graph.h"
22 
23 namespace tensorflow {
24 
25 // Helper class to temporarily remove, then replace, the back edges in a
26 // graph. Simple algorithms for shape inference don't work with cycles, and this
27 // class can be used to remove cycles before running inference and replace them
28 // after. Correct usage requires exactly one call to Remove(), followed by any
29 // number of calls to RemovedEdges() and at most one call to Replace(). The call
30 // to Replace() is optional if the graph will be discarded without being
31 // executed, e.g., if it is being used purely for a shape inference pass.
32 class BackEdgeHelper {
33  public:
34   struct BackEdge {
35     const Edge* edge;
36     Node* src;
37     int src_output;
38     Node* dst;
39     int dst_input;
40   };
41 
42   BackEdgeHelper() = default;
43   // Disallows copy and assign.
44   BackEdgeHelper(const BackEdgeHelper& other) = delete;
45   BackEdgeHelper& operator=(const BackEdgeHelper& other) = delete;
46 
47   // Temporarily removes all the back edges in graph.
48   Status Remove(Graph* graph);
49 
50   // Gets the list of removed edges.
51   const std::vector<BackEdge>& RemovedEdges() const;
52 
53   // Replaces the back edges removed by a prior call to Remove.
54   Status Replace();
55 
56  private:
57   Graph* graph_ = nullptr;  // not owned
58   std::vector<BackEdge> back_edges_;
59   // Set once Replace has been called.
60   bool replaced_ = false;
61 };
62 
63 }  // namespace tensorflow
64 
65 #endif  // TENSORFLOW_COMPILER_JIT_SHAPE_INFERENCE_HELPERS_H_
66