tvm
scope_stack.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
24 #ifndef TVM_IR_SCOPE_STACK_H_
25 #define TVM_IR_SCOPE_STACK_H_
26 
27 #include <tvm/ffi/error.h>
28 
29 #include <deque>
30 #include <type_traits>
31 
32 namespace tvm {
33 
54 template <typename T>
55 class ScopeStack {
56  public:
58  ScopeStack() { stack_.emplace_back(); }
59 
61  size_t size() const { return stack_.size(); }
62 
64  bool empty() const { return stack_.empty(); }
65 
74  T& Current() {
75  TVM_FFI_ICHECK(!stack_.empty());
76  return stack_.back();
77  }
78 
80  const T& Current() const {
81  TVM_FFI_ICHECK(!stack_.empty());
82  return stack_.back();
83  }
84 
93  template <typename F>
94  auto WithNewScope(F&& body) -> decltype(body()) {
95  stack_.emplace_back();
96  struct Guard {
97  std::deque<T>* stack;
98  ~Guard() noexcept(false) { stack->pop_back(); }
99  } guard{&stack_};
100  if constexpr (std::is_void_v<decltype(body())>) {
101  body();
102  } else {
103  return body();
104  }
105  }
106 
107  private:
118  std::deque<T> stack_;
119 };
120 
121 } // namespace tvm
122 
123 #endif // TVM_IR_SCOPE_STACK_H_
A scope stack for maintaining hierarchical state during IR visiting.
Definition: scope_stack.h:55
ScopeStack()
Construct with one initial scope level.
Definition: scope_stack.h:58
bool empty() const
Return true if no scopes are active.
Definition: scope_stack.h:64
auto WithNewScope(F &&body) -> decltype(body())
Execute body within a new scope.
Definition: scope_stack.h:94
size_t size() const
Return the number of active scopes.
Definition: scope_stack.h:61
const T & Current() const
Const access to the current (innermost) scope element.
Definition: scope_stack.h:80
T & Current()
Access the current (innermost) scope element.
Definition: scope_stack.h:74
Tensor stack(const ffi::Array< Tensor > &inputs, int axis=0, std::string name="T_stack", std::string tag=kInjective)
Join a sequence of tensors along a new axis.
Definition: transform.h:541
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition: analyzer.h:37