1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include <string>
17
18#include "tensorflow/core/framework/allocator_registry.h"
19#include "tensorflow/core/platform/logging.h"
20
21namespace tensorflow {
22
23// static
24AllocatorRegistry* AllocatorRegistry::Global() {
25  static AllocatorRegistry* global_allocator_registry = new AllocatorRegistry;
26  return global_allocator_registry;
27}
28
29Allocator* AllocatorRegistry::GetRegisteredAllocator(const string& name,
30                                                     int priority) {
31  for (auto entry : allocators_) {
32    if (!name.compare(entry.name) && priority == entry.priority) {
33      return entry.allocator;
34    }
35  }
36  return nullptr;
37}
38
39void AllocatorRegistry::Register(const string& name, int priority,
40                                 Allocator* allocator) {
41  CHECK(!name.empty()) << "Need a valid name for Allocator";
42  CHECK_GE(priority, 0) << "Priority needs to be non-negative";
43
44  Allocator* existing = GetRegisteredAllocator(name, priority);
45  if (existing != nullptr) {
46    // A duplicate is if the registration name and priority match
47    // but the Allocator::Name()'s don't match.
48    CHECK_EQ(existing->Name(), allocator->Name())
49        << "Allocator with name: [" << name << "], type [" << existing->Name()
50        << "], priority: [" << priority
51        << "] already registered.  Choose a different name to register "
52        << "an allocator of type " << allocator->Name();
53
54    // The allocator names match, so we can just return.
55    // It should be safe to delete the allocator since the caller
56    // gives up ownership of it.
57    delete allocator;
58    return;
59  }
60
61  AllocatorRegistryEntry tmp_entry;
62  tmp_entry.name = name;
63  tmp_entry.priority = priority;
64  tmp_entry.allocator = allocator;
65
66  allocators_.push_back(tmp_entry);
67  int high_pri = -1;
68  for (auto entry : allocators_) {
69    if (high_pri < entry.priority) {
70      m_curr_allocator_ = entry.allocator;
71      high_pri = entry.priority;
72    }
73  }
74}
75
76Allocator* AllocatorRegistry::GetAllocator() {
77  return CHECK_NOTNULL(m_curr_allocator_);
78}
79
80}  // namespace tensorflow
81