xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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/tools/kernel_gen/tf_jit_cache.h"
17 
18 #include <functional>
19 #include <string>
20 #include <utility>
21 
22 namespace mlir {
23 namespace kernel_gen {
24 namespace tf_framework {
25 
Create(JITCache ** dst)26 tensorflow::Status JITCache::Create(JITCache** dst) {
27   *dst = new JITCache;
28   return ::tensorflow::OkStatus();
29 }
30 
DebugString() const31 std::string JITCache::DebugString() const { return "JIT cache"; }
32 
LookupOrCompile(const std::string code,std::function<llvm::Expected<std::unique_ptr<ExecutionEngine>> ()> compile_callback)33 ExecutionEngine* JITCache::LookupOrCompile(
34     const std::string code,
35     std::function<llvm::Expected<std::unique_ptr<ExecutionEngine>>()>
36         compile_callback) {
37   // Check if we already have a compiled module in the cache.
38   {
39     tensorflow::mutex_lock lock(mu_);
40     if (execution_engine_by_key_.contains(code))
41       return execution_engine_by_key_[code].get();
42   }
43 
44   // Otherwise, compile the module now.
45   llvm::Expected<std::unique_ptr<ExecutionEngine>> engine = compile_callback();
46   if (!engine) return nullptr;
47 
48   // Insert the compiled module into our cache and return a raw pointer.
49   {
50     tensorflow::mutex_lock lock(mu_);
51     // Check again whether we already have a compiled module in the cache. It
52     // may have been added during the time we ran compile_callback().
53     return execution_engine_by_key_.try_emplace(code, std::move(engine.get()))
54         .first->second.get();
55   }
56 }
57 
Size()58 size_t JITCache::Size() {
59   tensorflow::mutex_lock lock(mu_);
60   return execution_engine_by_key_.size();
61 }
62 
63 }  // namespace tf_framework
64 }  // namespace kernel_gen
65 }  // namespace mlir
66