1 // Copyright (c) 2017 Pierre Moreau
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 "spirv-tools/linker.hpp"
16 
17 #include <cassert>
18 #include <cstring>
19 #include <iostream>
20 #include <vector>
21 
22 #include "source/spirv_target_env.h"
23 #include "source/table.h"
24 #include "spirv-tools/libspirv.hpp"
25 #include "tools/io.h"
26 #include "tools/util/flags.h"
27 
28 namespace {
29 
30 constexpr auto kDefaultEnvironment = "spv1.6";
31 
print_usage(const char * program)32 void print_usage(const char* program) {
33   std::string target_env_list = spvTargetEnvList(16, 80);
34   // NOTE: Please maintain flags in lexicographical order.
35   printf(
36       R"(%s - Link SPIR-V binary files together.
37 
38 USAGE: %s [options] [-o <output>] <input>...
39 
40 The SPIR-V binaries are read from the different <input>(s).
41 The SPIR-V resulting linked binary module is written to the file "out.spv"
42 unless the -o option is used; if <output> is "-", it is written to the standard
43 output.
44 
45 NOTE: The linker is a work in progress.
46 
47 Options (in lexicographical order):
48   --allow-partial-linkage
49                Allow partial linkage by accepting imported symbols to be
50                unresolved.
51   --create-library
52                Link the binaries into a library, keeping all exported symbols.
53   -h, --help
54                Print this help.
55   --target-env <env>
56                Set the environment used for interpreting the inputs. Without
57                this option the environment defaults to spv1.6. <env> must be
58                one of {%s}.
59                NOTE: The SPIR-V version used by the linked binary module
60                depends only on the version of the inputs, and is not affected
61                by this option.
62   --use-highest-version
63                Upgrade the output SPIR-V version to the highest of the input
64                files, instead of requiring all of them to have the same
65                version.
66                NOTE: If one of the older input files uses an instruction that
67                is deprecated in the highest SPIR-V version, the output will
68                be invalid.
69   --verify-ids
70                Verify that IDs in the resulting modules are truly unique.
71   --version
72                Display linker version information.
73 )",
74       program, program, target_env_list.c_str());
75 }
76 
77 }  // namespace
78 
79 // clang-format off
80 FLAG_SHORT_bool(  h,                     /* default_value= */ false,               /* required= */ false);
81 FLAG_LONG_bool(   help,                  /* default_value= */ false,               /* required= */false);
82 FLAG_LONG_bool(   version,               /* default_value= */ false,               /* required= */ false);
83 FLAG_LONG_bool(   verify_ids,            /* default_value= */ false,               /* required= */ false);
84 FLAG_LONG_bool(   create_library,        /* default_value= */ false,               /* required= */ false);
85 FLAG_LONG_bool(   allow_partial_linkage, /* default_value= */ false,               /* required= */ false);
86 FLAG_SHORT_string(o,                     /* default_value= */ "",                  /* required= */ false);
87 FLAG_LONG_string( target_env,            /* default_value= */ kDefaultEnvironment, /* required= */ false);
88 FLAG_LONG_bool(   use_highest_version,   /* default_value= */ false,               /* required= */ false);
89 // clang-format on
90 
main(int,const char * argv[])91 int main(int, const char* argv[]) {
92   if (!flags::Parse(argv)) {
93     return 1;
94   }
95 
96   if (flags::h.value() || flags::help.value()) {
97     print_usage(argv[0]);
98     return 0;
99   }
100 
101   if (flags::version.value()) {
102     spv_target_env target_env;
103     bool success = spvParseTargetEnv(kDefaultEnvironment, &target_env);
104     assert(success && "Default environment should always parse.");
105     if (!success) {
106       fprintf(stderr,
107               "error: invalid default target environment. Please report this "
108               "issue.");
109       return 1;
110     }
111     printf("%s\n", spvSoftwareVersionDetailsString());
112     printf("Target: %s\n", spvTargetEnvDescription(target_env));
113     return 0;
114   }
115 
116   spv_target_env target_env;
117   if (!spvParseTargetEnv(flags::target_env.value().c_str(), &target_env)) {
118     fprintf(stderr, "error: Unrecognized target env: %s\n",
119             flags::target_env.value().c_str());
120     return 1;
121   }
122 
123   const std::string outFile =
124       flags::o.value().empty() ? "out.spv" : flags::o.value();
125   const std::vector<std::string>& inFiles = flags::positional_arguments;
126 
127   spvtools::LinkerOptions options;
128   options.SetAllowPartialLinkage(flags::allow_partial_linkage.value());
129   options.SetCreateLibrary(flags::create_library.value());
130   options.SetVerifyIds(flags::verify_ids.value());
131   options.SetUseHighestVersion(flags::use_highest_version.value());
132 
133   if (inFiles.empty()) {
134     fprintf(stderr, "error: No input file specified\n");
135     return 1;
136   }
137 
138   std::vector<std::vector<uint32_t>> contents(inFiles.size());
139   for (size_t i = 0u; i < inFiles.size(); ++i) {
140     if (!ReadBinaryFile<uint32_t>(inFiles[i].c_str(), &contents[i])) return 1;
141   }
142 
143   const spvtools::MessageConsumer consumer = [](spv_message_level_t level,
144                                                 const char*,
145                                                 const spv_position_t& position,
146                                                 const char* message) {
147     switch (level) {
148       case SPV_MSG_FATAL:
149       case SPV_MSG_INTERNAL_ERROR:
150       case SPV_MSG_ERROR:
151         std::cerr << "error: " << position.index << ": " << message
152                   << std::endl;
153         break;
154       case SPV_MSG_WARNING:
155         std::cout << "warning: " << position.index << ": " << message
156                   << std::endl;
157         break;
158       case SPV_MSG_INFO:
159         std::cout << "info: " << position.index << ": " << message << std::endl;
160         break;
161       default:
162         break;
163     }
164   };
165   spvtools::Context context(target_env);
166   context.SetMessageConsumer(consumer);
167 
168   std::vector<uint32_t> linkingResult;
169   spv_result_t status = Link(context, contents, &linkingResult, options);
170   if (status != SPV_SUCCESS && status != SPV_WARNING) return 1;
171 
172   if (!WriteFile<uint32_t>(outFile.c_str(), "wb", linkingResult.data(),
173                            linkingResult.size()))
174     return 1;
175 
176   return 0;
177 }
178