1 /* Copyright 2019 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_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 17 #define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 18 19 #include <cstddef> 20 #include <cstdint> 21 #include <memory> 22 23 #include "llvm/ADT/DenseMap.h" 24 #include "mlir/IR/BuiltinOps.h" // from @llvm-project 25 #include "mlir/Pass/Pass.h" // from @llvm-project 26 27 namespace mlir { 28 namespace TF { 29 namespace detail { 30 31 // This template defines an aggregate analysis base class, which analyzes a 32 // module but the analysis info is stored per function. 33 template <typename InfoT> 34 class PerFunctionAggregateAnalysis { 35 public: 36 using Info = InfoT; 37 38 // Returns the analysis info for the given function. GetAnalysisForFunc(FuncOp func)39 const Info& GetAnalysisForFunc(FuncOp func) const { 40 auto it = info_map_.find(func); 41 assert(it != info_map_.end()); 42 return it->second; 43 } 44 45 protected: 46 llvm::SmallDenseMap<FuncOp, InfoT, 8> info_map_; 47 }; 48 49 } // namespace detail 50 51 // Base CRTP class to help write passes that are consumes a per-function 52 // aggregate analysis and operate on all non-extern functions (similar to a 53 // FunctionPass, but with no concurrency between functions). The derived classes 54 // need to provide a runOnFunction() method that accepts the function and the 55 // analysis information for that function. 56 template <typename DerivedT, typename AnalysisT> 57 class PerFunctionAggregateAnalysisConsumerPass 58 : public PassWrapper< 59 PerFunctionAggregateAnalysisConsumerPass<DerivedT, AnalysisT>, 60 OperationPass<ModuleOp>> { runOnOperation()61 void runOnOperation() override { 62 ModuleOp op = this->getOperation(); 63 DerivedT& derived = *static_cast<DerivedT*>(this); 64 auto& analysis = this->template getAnalysis<AnalysisT>(); 65 66 for (auto func : op.getOps<FuncOp>()) 67 if (!func.isExternal()) 68 derived.runOnFunction(func, analysis.GetAnalysisForFunc(func)); 69 } 70 }; 71 72 } // namespace TF 73 } // namespace mlir 74 75 #endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 76