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 #include "tensorflow/lite/delegates/gpu/gl/compiler/compiled_node.h"
17 
18 #include "absl/container/flat_hash_set.h"
19 #include "absl/strings/str_cat.h"
20 #include "tensorflow/lite/delegates/gpu/common/status.h"
21 #include "tensorflow/lite/delegates/gpu/gl/compiler/rename.h"
22 
23 namespace tflite {
24 namespace gpu {
25 namespace gl {
26 
MergeCode(CompiledNodeAttributes * attr,CompiledNodeAttributes * merged_attr)27 absl::Status MergeCode(CompiledNodeAttributes* attr,
28                        CompiledNodeAttributes* merged_attr) {
29   // build a map of known names.
30   absl::flat_hash_set<std::string> known_names;
31   for (const auto& parameter : merged_attr->code.parameters) {
32     known_names.insert(parameter.name);
33   }
34   for (const auto& object : merged_attr->code.objects) {
35     known_names.insert(object.first);
36   }
37 
38   // Rewrite parameters with unique names.
39   int index =
40       merged_attr->code.parameters.size() + merged_attr->code.objects.size();
41   RETURN_IF_ERROR(Rename(
42       [&](absl::string_view name) -> std::string {
43         std::string n(name.begin(), name.end());
44         // if a name is unique, then keep it as is. Otherwise append a unique
45         // index.
46         if (known_names.find(n) == known_names.end()) {
47           return n;
48         }
49         return absl::StrCat(n, index++);
50       },
51       &attr->code));
52   std::move(attr->code.objects.begin(), attr->code.objects.end(),
53             std::back_inserter(merged_attr->code.objects));
54   std::move(attr->code.parameters.begin(), attr->code.parameters.end(),
55             std::back_inserter(merged_attr->code.parameters));
56   std::move(attr->node_indices.begin(), attr->node_indices.end(),
57             std::back_inserter(merged_attr->node_indices));
58   return absl::OkStatus();
59 }
60 
61 }  // namespace gl
62 }  // namespace gpu
63 }  // namespace tflite
64