Caffe2 - C++ API
A deep learning, cross platform ML framework
final_returns.h
1 #pragma once
2 #include <functional>
3 #include <memory>
4 #include <string>
5 
6 #include <torch/csrc/WindowsTorchApiMacro.h>
7 #include <torch/csrc/jit/script/error_report.h>
8 #include <torch/csrc/jit/script/tree_views.h>
9 
10 namespace torch {
11 namespace jit {
12 namespace script {
13 
14 // This is an AST-to-AST transform that ensures that all return statements
15 // are at the end of the natural control-flow of the program.
16 //
17 // Since the return is at the end of the function, it is equivalent
18 // to simply assigning the returned value to to a special `$return` variable
19 // that is universally set to be the output of the function.
20 //
21 // This transform is only intended to support a subset of control-flow
22 // structures to make the transformation both easy to do _and_ easy to
23 // explain to users of TorchScript. The second constraint is important: if
24 // it is unclear what is allowed users will get the impression that the
25 // subset is difficult to use.
26 //
27 // if <cond>:
28 // <true>
29 // else:
30 // <false>
31 // <rest>
32 //
33 // In particular we allow:
34 // 1. If statements where neither <true> nor <false> branch returns.
35 // 2. If statements where both <true> and <false> always return.
36 // 3. An 'early return' if statement where <true> always returns <false> is
37 // empty, and <rest> always returns.
38 //
39 // We do not allow returns from loops in any case.
40 //
41 // This pass handles the following cases as follows:
42 //
43 // 1. Neither branch returns so we can just leave the branches as is
44 // 2. Both branches return, so we recursively transform the program such that
45 // <true> and <false>'s final action is to return. We then delete <rest>
46 // because the code is dead. The remaining program preserves the inductive
47 // property that its last action is to return since both branches end in a
48 // return.
49 // 3. In this case we know that <true> and <rest> always returns, and <false> is
50 // empty.
51 // We transform the graph to:
52 // if <cond>:
53 // <true>
54 // else:
55 // <rest>
56 // Now it is another instance of case (2).
57 
58 TORCH_API List<Stmt> moveAllReturnsToEnd(const List<Stmt>& stmts);
59 
60 } // namespace script
61 } // namespace jit
62 } // namespace torch
Definition: jit_type.h:17