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 #include "tensorflow/contrib/lite/kernels/gemm_support.h" 16 17 #include "tensorflow/contrib/lite/kernels/op_macros.h" 18 19 namespace tflite { 20 namespace gemm_support { 21 22 struct RefCountedGemmContext { 23 gemmlowp::GemmContext* gemm_context_ = nullptr; 24 int num_references_ = 0; 25 }; 26 IncrementUsageCounter(TfLiteContext * context)27void IncrementUsageCounter(TfLiteContext* context) { 28 auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context); 29 if (ptr == nullptr) { 30 ptr = new RefCountedGemmContext; 31 ptr->gemm_context_ = new gemmlowp::GemmContext(); 32 ptr->num_references_ = 0; 33 context->gemm_context = ptr; 34 } 35 ptr->num_references_++; 36 } 37 DecrementUsageCounter(TfLiteContext * context)38void DecrementUsageCounter(TfLiteContext* context) { 39 auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context); 40 if (ptr == nullptr) { 41 TF_LITE_FATAL( 42 "Call to DecrementUsageCounter() not preceded by " 43 "IncrementUsageCounter()"); 44 } 45 if (--ptr->num_references_ == 0) { 46 delete ptr->gemm_context_; 47 delete ptr; 48 context->gemm_context = nullptr; 49 } 50 } 51 GetFromContext(TfLiteContext * context)52gemmlowp::GemmContext* GetFromContext(TfLiteContext* context) { 53 auto* ptr = reinterpret_cast<RefCountedGemmContext*>(context->gemm_context); 54 if (ptr == nullptr) { 55 TF_LITE_FATAL( 56 "Call to GetFromContext() not preceded by IncrementUsageCounter()"); 57 } 58 return ptr->gemm_context_; 59 } 60 SetMaxNumThreads(TfLiteContext * context,int num_threads)61void SetMaxNumThreads(TfLiteContext* context, int num_threads) { 62 IncrementUsageCounter(context); 63 GetFromContext(context)->set_max_num_threads(num_threads); 64 DecrementUsageCounter(context); 65 } 66 67 } // namespace gemm_support 68 } // namespace tflite 69