opt.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. // Copyright (c) 2016 Google Inc.
  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 <algorithm>
  15. #include <cassert>
  16. #include <cstring>
  17. #include <fstream>
  18. #include <iostream>
  19. #include <memory>
  20. #include <sstream>
  21. #include <string>
  22. #include <vector>
  23. #include "source/opt/log.h"
  24. #include "source/spirv_target_env.h"
  25. #include "source/util/string_utils.h"
  26. #include "spirv-tools/libspirv.hpp"
  27. #include "spirv-tools/optimizer.hpp"
  28. #include "tools/io.h"
  29. #include "tools/util/cli_consumer.h"
  30. namespace {
  31. // Status and actions to perform after parsing command-line arguments.
  32. enum OptActions { OPT_CONTINUE, OPT_STOP };
  33. struct OptStatus {
  34. OptActions action;
  35. int code;
  36. };
  37. // Message consumer for this tool. Used to emit diagnostics during
  38. // initialization and setup. Note that |source| and |position| are irrelevant
  39. // here because we are still not processing a SPIR-V input file.
  40. void opt_diagnostic(spv_message_level_t level, const char* /*source*/,
  41. const spv_position_t& /*positon*/, const char* message) {
  42. if (level == SPV_MSG_ERROR) {
  43. fprintf(stderr, "error: ");
  44. }
  45. fprintf(stderr, "%s\n", message);
  46. }
  47. std::string GetListOfPassesAsString(const spvtools::Optimizer& optimizer) {
  48. std::stringstream ss;
  49. for (const auto& name : optimizer.GetPassNames()) {
  50. ss << "\n\t\t" << name;
  51. }
  52. return ss.str();
  53. }
  54. const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_5;
  55. std::string GetLegalizationPasses() {
  56. spvtools::Optimizer optimizer(kDefaultEnvironment);
  57. optimizer.RegisterLegalizationPasses();
  58. return GetListOfPassesAsString(optimizer);
  59. }
  60. std::string GetOptimizationPasses() {
  61. spvtools::Optimizer optimizer(kDefaultEnvironment);
  62. optimizer.RegisterPerformancePasses();
  63. return GetListOfPassesAsString(optimizer);
  64. }
  65. std::string GetSizePasses() {
  66. spvtools::Optimizer optimizer(kDefaultEnvironment);
  67. optimizer.RegisterSizePasses();
  68. return GetListOfPassesAsString(optimizer);
  69. }
  70. void PrintUsage(const char* program) {
  71. std::string target_env_list = spvTargetEnvList(16, 80);
  72. // NOTE: Please maintain flags in lexicographical order.
  73. printf(
  74. R"(%s - Optimize a SPIR-V binary file.
  75. USAGE: %s [options] [<input>] -o <output>
  76. The SPIR-V binary is read from <input>. If no file is specified,
  77. or if <input> is "-", then the binary is read from standard input.
  78. if <output> is "-", then the optimized output is written to
  79. standard output.
  80. NOTE: The optimizer is a work in progress.
  81. Options (in lexicographical order):)",
  82. program, program);
  83. printf(R"(
  84. --amd-ext-to-khr
  85. Replaces the extensions VK_AMD_shader_ballot, VK_AMD_gcn_shader,
  86. and VK_AMD_shader_trinary_minmax with equivalent code using core
  87. instructions and capabilities.)");
  88. printf(R"(
  89. --before-hlsl-legalization
  90. Forwards this option to the validator. See the validator help
  91. for details.)");
  92. printf(R"(
  93. --ccp
  94. Apply the conditional constant propagation transform. This will
  95. propagate constant values throughout the program, and simplify
  96. expressions and conditional jumps with known predicate
  97. values. Performed on entry point call tree functions and
  98. exported functions.)");
  99. printf(R"(
  100. --cfg-cleanup
  101. Cleanup the control flow graph. This will remove any unnecessary
  102. code from the CFG like unreachable code. Performed on entry
  103. point call tree functions and exported functions.)");
  104. printf(R"(
  105. --combine-access-chains
  106. Combines chained access chains to produce a single instruction
  107. where possible.)");
  108. printf(R"(
  109. --compact-ids
  110. Remap result ids to a compact range starting from %%1 and without
  111. any gaps.)");
  112. printf(R"(
  113. --convert-local-access-chains
  114. Convert constant index access chain loads/stores into
  115. equivalent load/stores with inserts and extracts. Performed
  116. on function scope variables referenced only with load, store,
  117. and constant index access chains in entry point call tree
  118. functions.)");
  119. printf(R"(
  120. --convert-relaxed-to-half
  121. Convert all RelaxedPrecision arithmetic operations to half
  122. precision, inserting conversion operations where needed.
  123. Run after function scope variable load and store elimination
  124. for better results. Simplify-instructions, redundancy-elimination
  125. and DCE should be run after this pass to eliminate excess
  126. conversions. This conversion is useful when the target platform
  127. does not support RelaxedPrecision or ignores it. This pass also
  128. removes all RelaxedPrecision decorations.)");
  129. printf(R"(
  130. --copy-propagate-arrays
  131. Does propagation of memory references when an array is a copy of
  132. another. It will only propagate an array if the source is never
  133. written to, and the only store to the target is the copy.)");
  134. printf(R"(
  135. --decompose-initialized-variables
  136. Decomposes initialized variable declarations into a declaration
  137. followed by a store of the initial value. This is done to work
  138. around known issues with some Vulkan drivers for initialize
  139. variables.)");
  140. printf(R"(
  141. --descriptor-scalar-replacement
  142. Replaces every array variable |desc| that has a DescriptorSet
  143. and Binding decorations with a new variable for each element of
  144. the array. Suppose |desc| was bound at binding |b|. Then the
  145. variable corresponding to |desc[i]| will have binding |b+i|.
  146. The descriptor set will be the same. All accesses to |desc|
  147. must be in OpAccessChain instructions with a literal index for
  148. the first index.)");
  149. printf(R"(
  150. --eliminate-dead-branches
  151. Convert conditional branches with constant condition to the
  152. indicated unconditional branch. Delete all resulting dead
  153. code. Performed only on entry point call tree functions.)");
  154. printf(R"(
  155. --eliminate-dead-code-aggressive
  156. Delete instructions which do not contribute to a function's
  157. output. Performed only on entry point call tree functions.)");
  158. printf(R"(
  159. --eliminate-dead-const
  160. Eliminate dead constants.)");
  161. printf(R"(
  162. --eliminate-dead-functions
  163. Deletes functions that cannot be reached from entry points or
  164. exported functions.)");
  165. printf(R"(
  166. --eliminate-dead-inserts
  167. Deletes unreferenced inserts into composites, most notably
  168. unused stores to vector components, that are not removed by
  169. aggressive dead code elimination.)");
  170. printf(R"(
  171. --eliminate-dead-variables
  172. Deletes module scope variables that are not referenced.)");
  173. printf(R"(
  174. --eliminate-insert-extract
  175. DEPRECATED. This pass has been replaced by the simplification
  176. pass, and that pass will be run instead.
  177. See --simplify-instructions.)");
  178. printf(R"(
  179. --eliminate-local-multi-store
  180. Replace stores and loads of function scope variables that are
  181. stored multiple times. Performed on variables referenceed only
  182. with loads and stores. Performed only on entry point call tree
  183. functions.)");
  184. printf(R"(
  185. --eliminate-local-single-block
  186. Perform single-block store/load and load/load elimination.
  187. Performed only on function scope variables in entry point
  188. call tree functions.)");
  189. printf(R"(
  190. --eliminate-local-single-store
  191. Replace stores and loads of function scope variables that are
  192. only stored once. Performed on variables referenceed only with
  193. loads and stores. Performed only on entry point call tree
  194. functions.)");
  195. printf(R"(
  196. --flatten-decorations
  197. Replace decoration groups with repeated OpDecorate and
  198. OpMemberDecorate instructions.)");
  199. printf(R"(
  200. --fold-spec-const-op-composite
  201. Fold the spec constants defined by OpSpecConstantOp or
  202. OpSpecConstantComposite instructions to front-end constants
  203. when possible.)");
  204. printf(R"(
  205. --freeze-spec-const
  206. Freeze the values of specialization constants to their default
  207. values.)");
  208. printf(R"(
  209. --graphics-robust-access
  210. Clamp indices used to access buffers and internal composite
  211. values, providing guarantees that satisfy Vulkan's
  212. robustBufferAccess rules.)");
  213. printf(R"(
  214. --if-conversion
  215. Convert if-then-else like assignments into OpSelect.)");
  216. printf(R"(
  217. --inline-entry-points-exhaustive
  218. Exhaustively inline all function calls in entry point call tree
  219. functions. Currently does not inline calls to functions with
  220. early return in a loop.)");
  221. printf(R"(
  222. --legalize-hlsl
  223. Runs a series of optimizations that attempts to take SPIR-V
  224. generated by an HLSL front-end and generates legal Vulkan SPIR-V.
  225. The optimizations are:
  226. %s
  227. Note this does not guarantee legal code. This option passes the
  228. option --relax-logical-pointer to the validator.)",
  229. GetLegalizationPasses().c_str());
  230. printf(R"(
  231. --local-redundancy-elimination
  232. Looks for instructions in the same basic block that compute the
  233. same value, and deletes the redundant ones.)");
  234. printf(R"(
  235. --loop-fission
  236. Splits any top level loops in which the register pressure has
  237. exceeded a given threshold. The threshold must follow the use of
  238. this flag and must be a positive integer value.)");
  239. printf(R"(
  240. --loop-fusion
  241. Identifies adjacent loops with the same lower and upper bound.
  242. If this is legal, then merge the loops into a single loop.
  243. Includes heuristics to ensure it does not increase number of
  244. registers too much, while reducing the number of loads from
  245. memory. Takes an additional positive integer argument to set
  246. the maximum number of registers.)");
  247. printf(R"(
  248. --loop-invariant-code-motion
  249. Identifies code in loops that has the same value for every
  250. iteration of the loop, and move it to the loop pre-header.)");
  251. printf(R"(
  252. --loop-unroll
  253. Fully unrolls loops marked with the Unroll flag)");
  254. printf(R"(
  255. --loop-unroll-partial
  256. Partially unrolls loops marked with the Unroll flag. Takes an
  257. additional non-0 integer argument to set the unroll factor, or
  258. how many times a loop body should be duplicated)");
  259. printf(R"(
  260. --loop-peeling
  261. Execute few first (respectively last) iterations before
  262. (respectively after) the loop if it can elide some branches.)");
  263. printf(R"(
  264. --loop-peeling-threshold
  265. Takes a non-0 integer argument to set the loop peeling code size
  266. growth threshold. The threshold prevents the loop peeling
  267. from happening if the code size increase created by
  268. the optimization is above the threshold.)");
  269. printf(R"(
  270. --max-id-bound=<n>
  271. Sets the maximum value for the id bound for the module. The
  272. default is the minimum value for this limit, 0x3FFFFF. See
  273. section 2.17 of the Spir-V specification.)");
  274. printf(R"(
  275. --merge-blocks
  276. Join two blocks into a single block if the second has the
  277. first as its only predecessor. Performed only on entry point
  278. call tree functions.)");
  279. printf(R"(
  280. --merge-return
  281. Changes functions that have multiple return statements so they
  282. have a single return statement.
  283. For structured control flow it is assumed that the only
  284. unreachable blocks in the function are trivial merge and continue
  285. blocks.
  286. A trivial merge block contains the label and an OpUnreachable
  287. instructions, nothing else. A trivial continue block contain a
  288. label and an OpBranch to the header, nothing else.
  289. These conditions are guaranteed to be met after running
  290. dead-branch elimination.)");
  291. printf(R"(
  292. --loop-unswitch
  293. Hoists loop-invariant conditionals out of loops by duplicating
  294. the loop on each branch of the conditional and adjusting each
  295. copy of the loop.)");
  296. printf(R"(
  297. -O
  298. Optimize for performance. Apply a sequence of transformations
  299. in an attempt to improve the performance of the generated
  300. code. For this version of the optimizer, this flag is equivalent
  301. to specifying the following optimization code names:
  302. %s)",
  303. GetOptimizationPasses().c_str());
  304. printf(R"(
  305. -Os
  306. Optimize for size. Apply a sequence of transformations in an
  307. attempt to minimize the size of the generated code. For this
  308. version of the optimizer, this flag is equivalent to specifying
  309. the following optimization code names:
  310. %s
  311. NOTE: The specific transformations done by -O and -Os change
  312. from release to release.)",
  313. GetSizePasses().c_str());
  314. printf(R"(
  315. -Oconfig=<file>
  316. Apply the sequence of transformations indicated in <file>.
  317. This file contains a sequence of strings separated by whitespace
  318. (tabs, newlines or blanks). Each string is one of the flags
  319. accepted by spirv-opt. Optimizations will be applied in the
  320. sequence they appear in the file. This is equivalent to
  321. specifying all the flags on the command line. For example,
  322. given the file opts.cfg with the content:
  323. --inline-entry-points-exhaustive
  324. --eliminate-dead-code-aggressive
  325. The following two invocations to spirv-opt are equivalent:
  326. $ spirv-opt -Oconfig=opts.cfg program.spv
  327. $ spirv-opt --inline-entry-points-exhaustive \
  328. --eliminate-dead-code-aggressive program.spv
  329. Lines starting with the character '#' in the configuration
  330. file indicate a comment and will be ignored.
  331. The -O, -Os, and -Oconfig flags act as macros. Using one of them
  332. is equivalent to explicitly inserting the underlying flags at
  333. that position in the command line. For example, the invocation
  334. 'spirv-opt --merge-blocks -O ...' applies the transformation
  335. --merge-blocks followed by all the transformations implied by
  336. -O.)");
  337. printf(R"(
  338. --preserve-bindings
  339. Ensure that the optimizer preserves all bindings declared within
  340. the module, even when those bindings are unused.)");
  341. printf(R"(
  342. --preserve-spec-constants
  343. Ensure that the optimizer preserves all specialization constants declared
  344. within the module, even when those constants are unused.)");
  345. printf(R"(
  346. --print-all
  347. Print SPIR-V assembly to standard error output before each pass
  348. and after the last pass.)");
  349. printf(R"(
  350. --private-to-local
  351. Change the scope of private variables that are used in a single
  352. function to that function.)");
  353. printf(R"(
  354. --reduce-load-size
  355. Replaces loads of composite objects where not every component is
  356. used by loads of just the elements that are used.)");
  357. printf(R"(
  358. --redundancy-elimination
  359. Looks for instructions in the same function that compute the
  360. same value, and deletes the redundant ones.)");
  361. printf(R"(
  362. --relax-block-layout
  363. Forwards this option to the validator. See the validator help
  364. for details.)");
  365. printf(R"(
  366. --relax-float-ops
  367. Decorate all float operations with RelaxedPrecision if not already
  368. so decorated. This does not decorate types or variables.)");
  369. printf(R"(
  370. --relax-logical-pointer
  371. Forwards this option to the validator. See the validator help
  372. for details.)");
  373. printf(R"(
  374. --relax-struct-store
  375. Forwards this option to the validator. See the validator help
  376. for details.)");
  377. printf(R"(
  378. --remove-duplicates
  379. Removes duplicate types, decorations, capabilities and extension
  380. instructions.)");
  381. printf(R"(
  382. --replace-invalid-opcode
  383. Replaces instructions whose opcode is valid for shader modules,
  384. but not for the current shader stage. To have an effect, all
  385. entry points must have the same execution model.)");
  386. printf(R"(
  387. --ssa-rewrite
  388. Replace loads and stores to function local variables with
  389. operations on SSA IDs.)");
  390. printf(R"(
  391. --scalar-block-layout
  392. Forwards this option to the validator. See the validator help
  393. for details.)");
  394. printf(R"(
  395. --scalar-replacement[=<n>]
  396. Replace aggregate function scope variables that are only accessed
  397. via their elements with new function variables representing each
  398. element. <n> is a limit on the size of the aggregates that will
  399. be replaced. 0 means there is no limit. The default value is
  400. 100.)");
  401. printf(R"(
  402. --set-spec-const-default-value "<spec id>:<default value> ..."
  403. Set the default values of the specialization constants with
  404. <spec id>:<default value> pairs specified in a double-quoted
  405. string. <spec id>:<default value> pairs must be separated by
  406. blank spaces, and in each pair, spec id and default value must
  407. be separated with colon ':' without any blank spaces in between.
  408. e.g.: --set-spec-const-default-value "1:100 2:400")");
  409. printf(R"(
  410. --simplify-instructions
  411. Will simplify all instructions in the function as much as
  412. possible.)");
  413. printf(R"(
  414. --skip-block-layout
  415. Forwards this option to the validator. See the validator help
  416. for details.)");
  417. printf(R"(
  418. --skip-validation
  419. Will not validate the SPIR-V before optimizing. If the SPIR-V
  420. is invalid, the optimizer may fail or generate incorrect code.
  421. This options should be used rarely, and with caution.)");
  422. printf(R"(
  423. --strength-reduction
  424. Replaces instructions with equivalent and less expensive ones.)");
  425. printf(R"(
  426. --strip-atomic-counter-memory
  427. Removes AtomicCountMemory bit from memory semantics values.)");
  428. printf(R"(
  429. --strip-debug
  430. Remove all debug instructions.)");
  431. printf(R"(
  432. --strip-reflect
  433. Remove all reflection information. For now, this covers
  434. reflection information defined by SPV_GOOGLE_hlsl_functionality1
  435. and SPV_KHR_non_semantic_info)");
  436. printf(R"(
  437. --target-env=<env>
  438. Set the target environment. Without this flag the target
  439. environment defaults to spv1.5. <env> must be one of
  440. {%s})",
  441. target_env_list.c_str());
  442. printf(R"(
  443. --time-report
  444. Print the resource utilization of each pass (e.g., CPU time,
  445. RSS) to standard error output. Currently it supports only Unix
  446. systems. This option is the same as -ftime-report in GCC. It
  447. prints CPU/WALL/USR/SYS time (and RSS if possible), but note that
  448. USR/SYS time are returned by getrusage() and can have a small
  449. error.)");
  450. printf(R"(
  451. --upgrade-memory-model
  452. Upgrades the Logical GLSL450 memory model to Logical VulkanKHR.
  453. Transforms memory, image, atomic and barrier operations to conform
  454. to that model's requirements.)");
  455. printf(R"(
  456. --vector-dce
  457. This pass looks for components of vectors that are unused, and
  458. removes them from the vector. Note this would still leave around
  459. lots of dead code that a pass of ADCE will be able to remove.)");
  460. printf(R"(
  461. --workaround-1209
  462. Rewrites instructions for which there are known driver bugs to
  463. avoid triggering those bugs.
  464. Current workarounds: Avoid OpUnreachable in loops.)");
  465. printf(R"(
  466. --workgroup-scalar-block-layout
  467. Forwards this option to the validator. See the validator help
  468. for details.)");
  469. printf(R"(
  470. --wrap-opkill
  471. Replaces all OpKill instructions in functions that can be called
  472. from a continue construct with a function call to a function
  473. whose only instruction is an OpKill. This is done to enable
  474. inlining on these functions.
  475. )");
  476. printf(R"(
  477. --unify-const
  478. Remove the duplicated constants.)");
  479. printf(R"(
  480. --validate-after-all
  481. Validate the module after each pass is performed.)");
  482. printf(R"(
  483. -h, --help
  484. Print this help.)");
  485. printf(R"(
  486. --version
  487. Display optimizer version information.
  488. )");
  489. }
  490. // Reads command-line flags the file specified in |oconfig_flag|. This string
  491. // is assumed to have the form "-Oconfig=FILENAME". This function parses the
  492. // string and extracts the file name after the '=' sign.
  493. //
  494. // Flags found in |FILENAME| are pushed at the end of the vector |file_flags|.
  495. //
  496. // This function returns true on success, false on failure.
  497. bool ReadFlagsFromFile(const char* oconfig_flag,
  498. std::vector<std::string>* file_flags) {
  499. const char* fname = strchr(oconfig_flag, '=');
  500. if (fname == nullptr || fname[0] != '=') {
  501. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Invalid -Oconfig flag %s",
  502. oconfig_flag);
  503. return false;
  504. }
  505. fname++;
  506. std::ifstream input_file;
  507. input_file.open(fname);
  508. if (input_file.fail()) {
  509. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Could not open file '%s'",
  510. fname);
  511. return false;
  512. }
  513. std::string line;
  514. while (std::getline(input_file, line)) {
  515. // Ignore empty lines and lines starting with the comment marker '#'.
  516. if (line.length() == 0 || line[0] == '#') {
  517. continue;
  518. }
  519. // Tokenize the line. Add all found tokens to the list of found flags. This
  520. // mimics the way the shell will parse whitespace on the command line. NOTE:
  521. // This does not support quoting and it is not intended to.
  522. std::istringstream iss(line);
  523. while (!iss.eof()) {
  524. std::string flag;
  525. iss >> flag;
  526. file_flags->push_back(flag);
  527. }
  528. }
  529. return true;
  530. }
  531. OptStatus ParseFlags(int argc, const char** argv,
  532. spvtools::Optimizer* optimizer, const char** in_file,
  533. const char** out_file,
  534. spvtools::ValidatorOptions* validator_options,
  535. spvtools::OptimizerOptions* optimizer_options);
  536. // Parses and handles the -Oconfig flag. |prog_name| contains the name of
  537. // the spirv-opt binary (used to build a new argv vector for the recursive
  538. // invocation to ParseFlags). |opt_flag| contains the -Oconfig=FILENAME flag.
  539. // |optimizer|, |in_file|, |out_file|, |validator_options|, and
  540. // |optimizer_options| are as in ParseFlags.
  541. //
  542. // This returns the same OptStatus instance returned by ParseFlags.
  543. OptStatus ParseOconfigFlag(const char* prog_name, const char* opt_flag,
  544. spvtools::Optimizer* optimizer, const char** in_file,
  545. const char** out_file,
  546. spvtools::ValidatorOptions* validator_options,
  547. spvtools::OptimizerOptions* optimizer_options) {
  548. std::vector<std::string> flags;
  549. flags.push_back(prog_name);
  550. std::vector<std::string> file_flags;
  551. if (!ReadFlagsFromFile(opt_flag, &file_flags)) {
  552. spvtools::Error(opt_diagnostic, nullptr, {},
  553. "Could not read optimizer flags from configuration file");
  554. return {OPT_STOP, 1};
  555. }
  556. flags.insert(flags.end(), file_flags.begin(), file_flags.end());
  557. const char** new_argv = new const char*[flags.size()];
  558. for (size_t i = 0; i < flags.size(); i++) {
  559. if (flags[i].find("-Oconfig=") != std::string::npos) {
  560. spvtools::Error(
  561. opt_diagnostic, nullptr, {},
  562. "Flag -Oconfig= may not be used inside the configuration file");
  563. return {OPT_STOP, 1};
  564. }
  565. new_argv[i] = flags[i].c_str();
  566. }
  567. auto ret_val =
  568. ParseFlags(static_cast<int>(flags.size()), new_argv, optimizer, in_file,
  569. out_file, validator_options, optimizer_options);
  570. delete[] new_argv;
  571. return ret_val;
  572. }
  573. // Canonicalize the flag in |argv[argi]| of the form '--pass arg' into
  574. // '--pass=arg'. The optimizer only accepts arguments to pass names that use the
  575. // form '--pass_name=arg'. Since spirv-opt also accepts the other form, this
  576. // function makes the necessary conversion.
  577. //
  578. // Pass flags that require additional arguments should be handled here. Note
  579. // that additional arguments should be given as a single string. If the flag
  580. // requires more than one argument, the pass creator in
  581. // Optimizer::GetPassFromFlag() should parse it accordingly (e.g., see the
  582. // handler for --set-spec-const-default-value).
  583. //
  584. // If the argument requests one of the passes that need an additional argument,
  585. // |argi| is modified to point past the current argument, and the string
  586. // "argv[argi]=argv[argi + 1]" is returned. Otherwise, |argi| is unmodified and
  587. // the string "|argv[argi]|" is returned.
  588. std::string CanonicalizeFlag(const char** argv, int argc, int* argi) {
  589. const char* cur_arg = argv[*argi];
  590. const char* next_arg = (*argi + 1 < argc) ? argv[*argi + 1] : nullptr;
  591. std::ostringstream canonical_arg;
  592. canonical_arg << cur_arg;
  593. // NOTE: DO NOT ADD NEW FLAGS HERE.
  594. //
  595. // These flags are supported for backwards compatibility. When adding new
  596. // passes that need extra arguments in its command-line flag, please make them
  597. // use the syntax "--pass_name[=pass_arg].
  598. if (0 == strcmp(cur_arg, "--set-spec-const-default-value") ||
  599. 0 == strcmp(cur_arg, "--loop-fission") ||
  600. 0 == strcmp(cur_arg, "--loop-fusion") ||
  601. 0 == strcmp(cur_arg, "--loop-unroll-partial") ||
  602. 0 == strcmp(cur_arg, "--loop-peeling-threshold")) {
  603. if (next_arg) {
  604. canonical_arg << "=" << next_arg;
  605. ++(*argi);
  606. }
  607. }
  608. return canonical_arg.str();
  609. }
  610. // Parses command-line flags. |argc| contains the number of command-line flags.
  611. // |argv| points to an array of strings holding the flags. |optimizer| is the
  612. // Optimizer instance used to optimize the program.
  613. //
  614. // On return, this function stores the name of the input program in |in_file|.
  615. // The name of the output file in |out_file|. The return value indicates whether
  616. // optimization should continue and a status code indicating an error or
  617. // success.
  618. OptStatus ParseFlags(int argc, const char** argv,
  619. spvtools::Optimizer* optimizer, const char** in_file,
  620. const char** out_file,
  621. spvtools::ValidatorOptions* validator_options,
  622. spvtools::OptimizerOptions* optimizer_options) {
  623. std::vector<std::string> pass_flags;
  624. for (int argi = 1; argi < argc; ++argi) {
  625. const char* cur_arg = argv[argi];
  626. if ('-' == cur_arg[0]) {
  627. if (0 == strcmp(cur_arg, "--version")) {
  628. spvtools::Logf(opt_diagnostic, SPV_MSG_INFO, nullptr, {}, "%s\n",
  629. spvSoftwareVersionDetailsString());
  630. return {OPT_STOP, 0};
  631. } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) {
  632. PrintUsage(argv[0]);
  633. return {OPT_STOP, 0};
  634. } else if (0 == strcmp(cur_arg, "-o")) {
  635. if (!*out_file && argi + 1 < argc) {
  636. *out_file = argv[++argi];
  637. } else {
  638. PrintUsage(argv[0]);
  639. return {OPT_STOP, 1};
  640. }
  641. } else if ('\0' == cur_arg[1]) {
  642. // Setting a filename of "-" to indicate stdin.
  643. if (!*in_file) {
  644. *in_file = cur_arg;
  645. } else {
  646. spvtools::Error(opt_diagnostic, nullptr, {},
  647. "More than one input file specified");
  648. return {OPT_STOP, 1};
  649. }
  650. } else if (0 == strncmp(cur_arg, "-Oconfig=", sizeof("-Oconfig=") - 1)) {
  651. OptStatus status =
  652. ParseOconfigFlag(argv[0], cur_arg, optimizer, in_file, out_file,
  653. validator_options, optimizer_options);
  654. if (status.action != OPT_CONTINUE) {
  655. return status;
  656. }
  657. } else if (0 == strcmp(cur_arg, "--skip-validation")) {
  658. optimizer_options->set_run_validator(false);
  659. } else if (0 == strcmp(cur_arg, "--print-all")) {
  660. optimizer->SetPrintAll(&std::cerr);
  661. } else if (0 == strcmp(cur_arg, "--preserve-bindings")) {
  662. optimizer_options->set_preserve_bindings(true);
  663. } else if (0 == strcmp(cur_arg, "--preserve-spec-constants")) {
  664. optimizer_options->set_preserve_spec_constants(true);
  665. } else if (0 == strcmp(cur_arg, "--time-report")) {
  666. optimizer->SetTimeReport(&std::cerr);
  667. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  668. validator_options->SetRelaxStructStore(true);
  669. } else if (0 == strncmp(cur_arg, "--max-id-bound=",
  670. sizeof("--max-id-bound=") - 1)) {
  671. auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  672. // Will not allow values in the range [2^31,2^32).
  673. uint32_t max_id_bound =
  674. static_cast<uint32_t>(atoi(split_flag.second.c_str()));
  675. // That SPIR-V mandates the minimum value for max id bound but
  676. // implementations may allow higher minimum bounds.
  677. if (max_id_bound < kDefaultMaxIdBound) {
  678. spvtools::Error(opt_diagnostic, nullptr, {},
  679. "The max id bound must be at least 0x3FFFFF");
  680. return {OPT_STOP, 1};
  681. }
  682. optimizer_options->set_max_id_bound(max_id_bound);
  683. validator_options->SetUniversalLimit(spv_validator_limit_max_id_bound,
  684. max_id_bound);
  685. } else if (0 == strncmp(cur_arg,
  686. "--target-env=", sizeof("--target-env=") - 1)) {
  687. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  688. const auto target_env_str = split_flag.second.c_str();
  689. spv_target_env target_env;
  690. if (!spvParseTargetEnv(target_env_str, &target_env)) {
  691. spvtools::Error(opt_diagnostic, nullptr, {},
  692. "Invalid value passed to --target-env");
  693. return {OPT_STOP, 1};
  694. }
  695. optimizer->SetTargetEnv(target_env);
  696. } else if (0 == strcmp(cur_arg, "--validate-after-all")) {
  697. optimizer->SetValidateAfterAll(true);
  698. } else if (0 == strcmp(cur_arg, "--before-hlsl-legalization")) {
  699. validator_options->SetBeforeHlslLegalization(true);
  700. } else if (0 == strcmp(cur_arg, "--relax-logical-pointer")) {
  701. validator_options->SetRelaxLogicalPointer(true);
  702. } else if (0 == strcmp(cur_arg, "--relax-block-layout")) {
  703. validator_options->SetRelaxBlockLayout(true);
  704. } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) {
  705. validator_options->SetScalarBlockLayout(true);
  706. } else if (0 == strcmp(cur_arg, "--workgroup-scalar-block-layout")) {
  707. validator_options->SetWorkgroupScalarBlockLayout(true);
  708. } else if (0 == strcmp(cur_arg, "--skip-block-layout")) {
  709. validator_options->SetSkipBlockLayout(true);
  710. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  711. validator_options->SetRelaxStructStore(true);
  712. } else {
  713. // Some passes used to accept the form '--pass arg', canonicalize them
  714. // to '--pass=arg'.
  715. pass_flags.push_back(CanonicalizeFlag(argv, argc, &argi));
  716. // If we were requested to legalize SPIR-V generated from the HLSL
  717. // front-end, skip validation.
  718. if (0 == strcmp(cur_arg, "--legalize-hlsl")) {
  719. validator_options->SetBeforeHlslLegalization(true);
  720. }
  721. }
  722. } else {
  723. if (!*in_file) {
  724. *in_file = cur_arg;
  725. } else {
  726. spvtools::Error(opt_diagnostic, nullptr, {},
  727. "More than one input file specified");
  728. return {OPT_STOP, 1};
  729. }
  730. }
  731. }
  732. if (!optimizer->RegisterPassesFromFlags(pass_flags)) {
  733. return {OPT_STOP, 1};
  734. }
  735. return {OPT_CONTINUE, 0};
  736. }
  737. } // namespace
  738. int main(int argc, const char** argv) {
  739. const char* in_file = nullptr;
  740. const char* out_file = nullptr;
  741. spv_target_env target_env = kDefaultEnvironment;
  742. spvtools::Optimizer optimizer(target_env);
  743. optimizer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer);
  744. spvtools::ValidatorOptions validator_options;
  745. spvtools::OptimizerOptions optimizer_options;
  746. OptStatus status = ParseFlags(argc, argv, &optimizer, &in_file, &out_file,
  747. &validator_options, &optimizer_options);
  748. optimizer_options.set_validator_options(validator_options);
  749. if (status.action == OPT_STOP) {
  750. return status.code;
  751. }
  752. if (out_file == nullptr) {
  753. spvtools::Error(opt_diagnostic, nullptr, {}, "-o required");
  754. return 1;
  755. }
  756. std::vector<uint32_t> binary;
  757. if (!ReadFile<uint32_t>(in_file, "rb", &binary)) {
  758. return 1;
  759. }
  760. // By using the same vector as input and output, we save time in the case
  761. // that there was no change.
  762. bool ok =
  763. optimizer.Run(binary.data(), binary.size(), &binary, optimizer_options);
  764. if (!WriteFile<uint32_t>(out_file, "wb", binary.data(), binary.size())) {
  765. return 1;
  766. }
  767. return ok ? 0 : 1;
  768. }