reduce.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Copyright (c) 2018 Google LLC
  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. #include <cassert>
  15. #include <cerrno>
  16. #include <cstring>
  17. #include <functional>
  18. #include <sstream>
  19. #include "source/opt/build_module.h"
  20. #include "source/opt/ir_context.h"
  21. #include "source/opt/log.h"
  22. #include "source/reduce/reducer.h"
  23. #include "source/spirv_reducer_options.h"
  24. #include "source/util/string_utils.h"
  25. #include "tools/io.h"
  26. #include "tools/util/cli_consumer.h"
  27. namespace {
  28. // Check that the std::system function can actually be used.
  29. bool CheckExecuteCommand() {
  30. int res = std::system(nullptr);
  31. return res != 0;
  32. }
  33. // Execute a command using the shell.
  34. // Returns true if and only if the command's exit status was 0.
  35. bool ExecuteCommand(const std::string& command) {
  36. errno = 0;
  37. int status = std::system(command.c_str());
  38. assert(errno == 0 && "failed to execute command");
  39. // The result returned by 'system' is implementation-defined, but is
  40. // usually the case that the returned value is 0 when the command's exit
  41. // code was 0. We are assuming that here, and that's all we depend on.
  42. return status == 0;
  43. }
  44. // Status and actions to perform after parsing command-line arguments.
  45. enum ReduceActions { REDUCE_CONTINUE, REDUCE_STOP };
  46. struct ReduceStatus {
  47. ReduceActions action;
  48. int code;
  49. };
  50. void PrintUsage(const char* program) {
  51. // NOTE: Please maintain flags in lexicographical order.
  52. printf(
  53. R"(%s - Reduce a SPIR-V binary file with respect to a user-provided
  54. interestingness test.
  55. USAGE: %s [options] <input.spv> -o <output.spv> -- <interestingness_test> [args...]
  56. The SPIR-V binary is read from <input.spv>. The reduced SPIR-V binary is
  57. written to <output.spv>.
  58. Whether a binary is interesting is determined by <interestingness_test>, which
  59. should be the path to a script. The "--" characters are optional but denote
  60. that all arguments that follow are positional arguments and thus will be
  61. forwarded to the interestingness test, and not parsed by %s.
  62. * The script must be executable.
  63. * The script should take the path to a SPIR-V binary file (.spv) as an
  64. argument, and exit with code 0 if and only if the binary file is
  65. interesting. The binary will be passed to the script as an argument after
  66. any other provided arguments [args...].
  67. * Example: an interestingness test for reducing a SPIR-V binary file that
  68. causes tool "foo" to exit with error code 1 and print "Fatal error: bar" to
  69. standard error should:
  70. - invoke "foo" on the binary passed as the script argument;
  71. - capture the return code and standard error from "bar";
  72. - exit with code 0 if and only if the return code of "foo" was 1 and the
  73. standard error from "bar" contained "Fatal error: bar".
  74. * The reducer does not place a time limit on how long the interestingness test
  75. takes to run, so it is advisable to use per-command timeouts inside the
  76. script when invoking SPIR-V-processing tools (such as "foo" in the above
  77. example).
  78. NOTE: The reducer is a work in progress.
  79. Options (in lexicographical order):
  80. --fail-on-validation-error
  81. Stop reduction with an error if any reduction step produces a
  82. SPIR-V module that fails to validate.
  83. -h, --help
  84. Print this help.
  85. --step-limit=
  86. 32-bit unsigned integer specifying maximum number of steps the
  87. reducer will take before giving up.
  88. --target-function=
  89. 32-bit unsigned integer specifying the id of a function in the
  90. input module. The reducer will restrict attention to this
  91. function, and will not make changes to other functions or to
  92. instructions outside of functions, except that some global
  93. instructions may be added in support of reducing the target
  94. function. If 0 is specified (the default) then all functions are
  95. reduced.
  96. --temp-file-prefix=
  97. Specifies a temporary file prefix that will be used to output
  98. temporary shader files during reduction. A number and .spv
  99. extension will be added. The default is "temp_", which will
  100. cause files like "temp_0001.spv" to be output to the current
  101. directory.
  102. --version
  103. Display reducer version information.
  104. Supported validator options are as follows. See `spirv-val --help` for details.
  105. --before-hlsl-legalization
  106. --relax-block-layout
  107. --relax-logical-pointer
  108. --relax-struct-store
  109. --scalar-block-layout
  110. --skip-block-layout
  111. )",
  112. program, program, program);
  113. }
  114. // Message consumer for this tool. Used to emit diagnostics during
  115. // initialization and setup. Note that |source| and |position| are irrelevant
  116. // here because we are still not processing a SPIR-V input file.
  117. void ReduceDiagnostic(spv_message_level_t level, const char* /*source*/,
  118. const spv_position_t& /*position*/, const char* message) {
  119. if (level == SPV_MSG_ERROR) {
  120. fprintf(stderr, "error: ");
  121. }
  122. fprintf(stderr, "%s\n", message);
  123. }
  124. ReduceStatus ParseFlags(int argc, const char** argv,
  125. std::string* in_binary_file,
  126. std::string* out_binary_file,
  127. std::vector<std::string>* interestingness_test,
  128. std::string* temp_file_prefix,
  129. spvtools::ReducerOptions* reducer_options,
  130. spvtools::ValidatorOptions* validator_options) {
  131. uint32_t positional_arg_index = 0;
  132. bool only_positional_arguments_remain = false;
  133. for (int argi = 1; argi < argc; ++argi) {
  134. const char* cur_arg = argv[argi];
  135. if ('-' == cur_arg[0] && !only_positional_arguments_remain) {
  136. if (0 == strcmp(cur_arg, "--version")) {
  137. spvtools::Logf(ReduceDiagnostic, SPV_MSG_INFO, nullptr, {}, "%s\n",
  138. spvSoftwareVersionDetailsString());
  139. return {REDUCE_STOP, 0};
  140. } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) {
  141. PrintUsage(argv[0]);
  142. return {REDUCE_STOP, 0};
  143. } else if (0 == strcmp(cur_arg, "-o")) {
  144. if (out_binary_file->empty() && argi + 1 < argc) {
  145. *out_binary_file = std::string(argv[++argi]);
  146. } else {
  147. PrintUsage(argv[0]);
  148. return {REDUCE_STOP, 1};
  149. }
  150. } else if (0 == strncmp(cur_arg,
  151. "--step-limit=", sizeof("--step-limit=") - 1)) {
  152. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  153. char* end = nullptr;
  154. errno = 0;
  155. const auto step_limit =
  156. static_cast<uint32_t>(strtol(split_flag.second.c_str(), &end, 10));
  157. assert(end != split_flag.second.c_str() && errno == 0);
  158. reducer_options->set_step_limit(step_limit);
  159. } else if (0 == strncmp(cur_arg, "--target-function=",
  160. sizeof("--target-function=") - 1)) {
  161. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  162. char* end = nullptr;
  163. errno = 0;
  164. const auto target_function =
  165. static_cast<uint32_t>(strtol(split_flag.second.c_str(), &end, 10));
  166. assert(end != split_flag.second.c_str() && errno == 0);
  167. reducer_options->set_target_function(target_function);
  168. } else if (0 == strcmp(cur_arg, "--fail-on-validation-error")) {
  169. reducer_options->set_fail_on_validation_error(true);
  170. } else if (0 == strcmp(cur_arg, "--before-hlsl-legalization")) {
  171. validator_options->SetBeforeHlslLegalization(true);
  172. } else if (0 == strcmp(cur_arg, "--relax-logical-pointer")) {
  173. validator_options->SetRelaxLogicalPointer(true);
  174. } else if (0 == strcmp(cur_arg, "--relax-block-layout")) {
  175. validator_options->SetRelaxBlockLayout(true);
  176. } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) {
  177. validator_options->SetScalarBlockLayout(true);
  178. } else if (0 == strcmp(cur_arg, "--skip-block-layout")) {
  179. validator_options->SetSkipBlockLayout(true);
  180. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  181. validator_options->SetRelaxStructStore(true);
  182. } else if (0 == strncmp(cur_arg, "--temp-file-prefix=",
  183. sizeof("--temp-file-prefix=") - 1)) {
  184. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  185. *temp_file_prefix = std::string(split_flag.second);
  186. } else if (0 == strcmp(cur_arg, "--")) {
  187. only_positional_arguments_remain = true;
  188. } else {
  189. std::stringstream ss;
  190. ss << "Unrecognized argument: " << cur_arg << std::endl;
  191. spvtools::Error(ReduceDiagnostic, nullptr, {}, ss.str().c_str());
  192. PrintUsage(argv[0]);
  193. return {REDUCE_STOP, 1};
  194. }
  195. } else if (positional_arg_index == 0) {
  196. // Binary input file name
  197. assert(in_binary_file->empty());
  198. *in_binary_file = std::string(cur_arg);
  199. positional_arg_index++;
  200. } else {
  201. interestingness_test->push_back(std::string(cur_arg));
  202. }
  203. }
  204. if (in_binary_file->empty()) {
  205. spvtools::Error(ReduceDiagnostic, nullptr, {}, "No input file specified");
  206. return {REDUCE_STOP, 1};
  207. }
  208. if (out_binary_file->empty()) {
  209. spvtools::Error(ReduceDiagnostic, nullptr, {}, "-o required");
  210. return {REDUCE_STOP, 1};
  211. }
  212. if (interestingness_test->empty()) {
  213. spvtools::Error(ReduceDiagnostic, nullptr, {},
  214. "No interestingness test specified");
  215. return {REDUCE_STOP, 1};
  216. }
  217. return {REDUCE_CONTINUE, 0};
  218. }
  219. } // namespace
  220. // Dumps |binary| to file |filename|. Useful for interactive debugging.
  221. void DumpShader(const std::vector<uint32_t>& binary, const char* filename) {
  222. auto write_file_succeeded =
  223. WriteFile(filename, "wb", &binary[0], binary.size());
  224. if (!write_file_succeeded) {
  225. std::cerr << "Failed to dump shader" << std::endl;
  226. }
  227. }
  228. // Dumps the SPIRV-V module in |context| to file |filename|. Useful for
  229. // interactive debugging.
  230. void DumpShader(spvtools::opt::IRContext* context, const char* filename) {
  231. std::vector<uint32_t> binary;
  232. context->module()->ToBinary(&binary, false);
  233. DumpShader(binary, filename);
  234. }
  235. const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_6;
  236. int main(int argc, const char** argv) {
  237. std::string in_binary_file;
  238. std::string out_binary_file;
  239. std::vector<std::string> interestingness_test;
  240. std::string temp_file_prefix = "temp_";
  241. spv_target_env target_env = kDefaultEnvironment;
  242. spvtools::ReducerOptions reducer_options;
  243. spvtools::ValidatorOptions validator_options;
  244. ReduceStatus status = ParseFlags(
  245. argc, argv, &in_binary_file, &out_binary_file, &interestingness_test,
  246. &temp_file_prefix, &reducer_options, &validator_options);
  247. if (status.action == REDUCE_STOP) {
  248. return status.code;
  249. }
  250. if (!CheckExecuteCommand()) {
  251. std::cerr << "could not find shell interpreter for executing a command"
  252. << std::endl;
  253. return 2;
  254. }
  255. spvtools::reduce::Reducer reducer(target_env);
  256. std::stringstream joined;
  257. joined << interestingness_test[0];
  258. for (size_t i = 1, size = interestingness_test.size(); i < size; ++i) {
  259. joined << " " << interestingness_test[i];
  260. }
  261. std::string interestingness_command_joined = joined.str();
  262. reducer.SetInterestingnessFunction(
  263. [interestingness_command_joined, temp_file_prefix](
  264. std::vector<uint32_t> binary, uint32_t reductions_applied) -> bool {
  265. std::stringstream ss;
  266. ss << temp_file_prefix << std::setw(4) << std::setfill('0')
  267. << reductions_applied << ".spv";
  268. const auto spv_file = ss.str();
  269. const std::string command =
  270. interestingness_command_joined + " " + spv_file;
  271. auto write_file_succeeded =
  272. WriteFile(spv_file.c_str(), "wb", &binary[0], binary.size());
  273. (void)(write_file_succeeded);
  274. assert(write_file_succeeded);
  275. return ExecuteCommand(command);
  276. });
  277. reducer.AddDefaultReductionPasses();
  278. reducer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer);
  279. std::vector<uint32_t> binary_in;
  280. if (!ReadBinaryFile<uint32_t>(in_binary_file.c_str(), &binary_in)) {
  281. return 1;
  282. }
  283. const uint32_t target_function = (*reducer_options).target_function;
  284. if (target_function) {
  285. // A target function was specified; check that it exists.
  286. std::unique_ptr<spvtools::opt::IRContext> context = spvtools::BuildModule(
  287. kDefaultEnvironment, spvtools::utils::CLIMessageConsumer,
  288. binary_in.data(), binary_in.size());
  289. bool found_target_function = false;
  290. for (auto& function : *context->module()) {
  291. if (function.result_id() == target_function) {
  292. found_target_function = true;
  293. break;
  294. }
  295. }
  296. if (!found_target_function) {
  297. std::stringstream strstr;
  298. strstr << "Target function with id " << target_function
  299. << " was requested, but not found in the module; stopping.";
  300. spvtools::utils::CLIMessageConsumer(SPV_MSG_ERROR, nullptr, {},
  301. strstr.str().c_str());
  302. return 1;
  303. }
  304. }
  305. std::vector<uint32_t> binary_out;
  306. const auto reduction_status = reducer.Run(std::move(binary_in), &binary_out,
  307. reducer_options, validator_options);
  308. // Always try to write the output file, even if the reduction failed.
  309. if (!WriteFile<uint32_t>(out_binary_file.c_str(), "wb", binary_out.data(),
  310. binary_out.size())) {
  311. return 1;
  312. }
  313. // These are the only successful statuses.
  314. switch (reduction_status) {
  315. case spvtools::reduce::Reducer::ReductionResultStatus::kComplete:
  316. case spvtools::reduce::Reducer::ReductionResultStatus::kReachedStepLimit:
  317. return 0;
  318. default:
  319. break;
  320. }
  321. return 1;
  322. }