opt.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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& /*position*/, 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_6;
  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. --convert-to-sampled-image "<descriptor set>:<binding> ..."
  131. convert images and/or samplers with the given pairs of descriptor
  132. set and binding to sampled images. If a pair of an image and a
  133. sampler have the same pair of descriptor set and binding that is
  134. one of the given pairs, they will be converted to a sampled
  135. image. In addition, if only an image or a sampler has the
  136. descriptor set and binding that is one of the given pairs, it
  137. will be converted to a sampled image.)");
  138. printf(R"(
  139. --copy-propagate-arrays
  140. Does propagation of memory references when an array is a copy of
  141. another. It will only propagate an array if the source is never
  142. written to, and the only store to the target is the copy.)");
  143. printf(R"(
  144. --replace-desc-array-access-using-var-index
  145. Replaces accesses to descriptor arrays based on a variable index
  146. with a switch that has a case for every possible value of the
  147. index.)");
  148. printf(R"(
  149. --spread-volatile-semantics
  150. Spread Volatile semantics to variables with SMIDNV, WarpIDNV,
  151. SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask,
  152. SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask
  153. BuiltIn decorations or OpLoad for them when the shader model is
  154. ray generation, closest hit, miss, intersection, or callable.
  155. For the SPIR-V version is 1.6 or above, it also spreads Volatile
  156. semantics to a variable with HelperInvocation BuiltIn decoration
  157. in the fragement shader.)");
  158. printf(R"(
  159. --descriptor-scalar-replacement
  160. Replaces every array variable |desc| that has a DescriptorSet
  161. and Binding decorations with a new variable for each element of
  162. the array. Suppose |desc| was bound at binding |b|. Then the
  163. variable corresponding to |desc[i]| will have binding |b+i|.
  164. The descriptor set will be the same. All accesses to |desc|
  165. must be in OpAccessChain instructions with a literal index for
  166. the first index.)");
  167. printf(R"(
  168. --descriptor-composite-scalar-replacement
  169. Same as descriptor-scalar-replacement, but only impacts composite/structs.
  170. For details, see --descriptor-scalar-replacement help.)");
  171. printf(R"(
  172. --descriptor-array-scalar-replacement
  173. Same as descriptor-scalar-replacement, but only impacts arrays.
  174. For details, see --descriptor-scalar-replacement help.)");
  175. printf(R"(
  176. --eliminate-dead-branches
  177. Convert conditional branches with constant condition to the
  178. indicated unconditional branch. Delete all resulting dead
  179. code. Performed only on entry point call tree functions.)");
  180. printf(R"(
  181. --eliminate-dead-code-aggressive
  182. Delete instructions which do not contribute to a function's
  183. output. Performed only on entry point call tree functions.)");
  184. printf(R"(
  185. --eliminate-dead-const
  186. Eliminate dead constants.)");
  187. printf(R"(
  188. --eliminate-dead-functions
  189. Deletes functions that cannot be reached from entry points or
  190. exported functions.)");
  191. printf(R"(
  192. --eliminate-dead-inserts
  193. Deletes unreferenced inserts into composites, most notably
  194. unused stores to vector components, that are not removed by
  195. aggressive dead code elimination.)");
  196. printf(R"(
  197. --eliminate-dead-input-components
  198. Deletes unused components from input variables. Currently
  199. deletes trailing unused elements from input arrays.)");
  200. printf(R"(
  201. --eliminate-dead-variables
  202. Deletes module scope variables that are not referenced.)");
  203. printf(R"(
  204. --eliminate-insert-extract
  205. DEPRECATED. This pass has been replaced by the simplification
  206. pass, and that pass will be run instead.
  207. See --simplify-instructions.)");
  208. printf(R"(
  209. --eliminate-local-multi-store
  210. Replace stores and loads of function scope variables that are
  211. stored multiple times. Performed on variables referenceed only
  212. with loads and stores. Performed only on entry point call tree
  213. functions.)");
  214. printf(R"(
  215. --eliminate-local-single-block
  216. Perform single-block store/load and load/load elimination.
  217. Performed only on function scope variables in entry point
  218. call tree functions.)");
  219. printf(R"(
  220. --eliminate-local-single-store
  221. Replace stores and loads of function scope variables that are
  222. only stored once. Performed on variables referenceed only with
  223. loads and stores. Performed only on entry point call tree
  224. functions.)");
  225. printf(R"(
  226. --fix-func-call-param
  227. fix non memory argument for the function call, replace
  228. accesschain pointer argument with a variable.)");
  229. printf(R"(
  230. --flatten-decorations
  231. Replace decoration groups with repeated OpDecorate and
  232. OpMemberDecorate instructions.)");
  233. printf(R"(
  234. --fold-spec-const-op-composite
  235. Fold the spec constants defined by OpSpecConstantOp or
  236. OpSpecConstantComposite instructions to front-end constants
  237. when possible.)");
  238. printf(R"(
  239. --freeze-spec-const
  240. Freeze the values of specialization constants to their default
  241. values.)");
  242. printf(R"(
  243. --graphics-robust-access
  244. Clamp indices used to access buffers and internal composite
  245. values, providing guarantees that satisfy Vulkan's
  246. robustBufferAccess rules.)");
  247. printf(R"(
  248. --if-conversion
  249. Convert if-then-else like assignments into OpSelect.)");
  250. printf(R"(
  251. --inline-entry-points-exhaustive
  252. Exhaustively inline all function calls in entry point call tree
  253. functions. Currently does not inline calls to functions with
  254. early return in a loop.)");
  255. printf(R"(
  256. --legalize-hlsl
  257. Runs a series of optimizations that attempts to take SPIR-V
  258. generated by an HLSL front-end and generates legal Vulkan SPIR-V.
  259. The optimizations are:
  260. %s
  261. Note this does not guarantee legal code. This option passes the
  262. option --relax-logical-pointer to the validator.)",
  263. GetLegalizationPasses().c_str());
  264. printf(R"(
  265. --local-redundancy-elimination
  266. Looks for instructions in the same basic block that compute the
  267. same value, and deletes the redundant ones.)");
  268. printf(R"(
  269. --loop-fission
  270. Splits any top level loops in which the register pressure has
  271. exceeded a given threshold. The threshold must follow the use of
  272. this flag and must be a positive integer value.)");
  273. printf(R"(
  274. --loop-fusion
  275. Identifies adjacent loops with the same lower and upper bound.
  276. If this is legal, then merge the loops into a single loop.
  277. Includes heuristics to ensure it does not increase number of
  278. registers too much, while reducing the number of loads from
  279. memory. Takes an additional positive integer argument to set
  280. the maximum number of registers.)");
  281. printf(R"(
  282. --loop-invariant-code-motion
  283. Identifies code in loops that has the same value for every
  284. iteration of the loop, and move it to the loop pre-header.)");
  285. printf(R"(
  286. --loop-unroll
  287. Fully unrolls loops marked with the Unroll flag)");
  288. printf(R"(
  289. --loop-unroll-partial
  290. Partially unrolls loops marked with the Unroll flag. Takes an
  291. additional non-0 integer argument to set the unroll factor, or
  292. how many times a loop body should be duplicated)");
  293. printf(R"(
  294. --loop-peeling
  295. Execute few first (respectively last) iterations before
  296. (respectively after) the loop if it can elide some branches.)");
  297. printf(R"(
  298. --loop-peeling-threshold
  299. Takes a non-0 integer argument to set the loop peeling code size
  300. growth threshold. The threshold prevents the loop peeling
  301. from happening if the code size increase created by
  302. the optimization is above the threshold.)");
  303. printf(R"(
  304. --max-id-bound=<n>
  305. Sets the maximum value for the id bound for the module. The
  306. default is the minimum value for this limit, 0x3FFFFF. See
  307. section 2.17 of the Spir-V specification.)");
  308. printf(R"(
  309. --merge-blocks
  310. Join two blocks into a single block if the second has the
  311. first as its only predecessor. Performed only on entry point
  312. call tree functions.)");
  313. printf(R"(
  314. --merge-return
  315. Changes functions that have multiple return statements so they
  316. have a single return statement.
  317. For structured control flow it is assumed that the only
  318. unreachable blocks in the function are trivial merge and continue
  319. blocks.
  320. A trivial merge block contains the label and an OpUnreachable
  321. instructions, nothing else. A trivial continue block contain a
  322. label and an OpBranch to the header, nothing else.
  323. These conditions are guaranteed to be met after running
  324. dead-branch elimination.)");
  325. printf(R"(
  326. --modify-maximal-reconvergence=[add|remove]
  327. Add or remove the MaximallyReconvergesKHR execution mode to all
  328. entry points in the module.
  329. Note: when adding the execution mode, no attempt is made to
  330. determine if any ray tracing repack instructions are used.)");
  331. printf(R"(
  332. --loop-unswitch
  333. Hoists loop-invariant conditionals out of loops by duplicating
  334. the loop on each branch of the conditional and adjusting each
  335. copy of the loop.)");
  336. printf(R"(
  337. -O
  338. Optimize for performance. Apply a sequence of transformations
  339. in an attempt to improve the performance of the generated
  340. code. For this version of the optimizer, this flag is equivalent
  341. to specifying the following optimization code names:
  342. %s)",
  343. GetOptimizationPasses().c_str());
  344. printf(R"(
  345. -Os
  346. Optimize for size. Apply a sequence of transformations in an
  347. attempt to minimize the size of the generated code. For this
  348. version of the optimizer, this flag is equivalent to specifying
  349. the following optimization code names:
  350. %s
  351. NOTE: The specific transformations done by -O and -Os change
  352. from release to release.)",
  353. GetSizePasses().c_str());
  354. printf(R"(
  355. -Oconfig=<file>
  356. Apply the sequence of transformations indicated in <file>.
  357. This file contains a sequence of strings separated by whitespace
  358. (tabs, newlines or blanks). Each string is one of the flags
  359. accepted by spirv-opt. Optimizations will be applied in the
  360. sequence they appear in the file. This is equivalent to
  361. specifying all the flags on the command line. For example,
  362. given the file opts.cfg with the content:
  363. --inline-entry-points-exhaustive
  364. --eliminate-dead-code-aggressive
  365. The following two invocations to spirv-opt are equivalent:
  366. $ spirv-opt -Oconfig=opts.cfg program.spv
  367. $ spirv-opt --inline-entry-points-exhaustive \
  368. --eliminate-dead-code-aggressive program.spv
  369. Lines starting with the character '#' in the configuration
  370. file indicate a comment and will be ignored.
  371. The -O, -Os, and -Oconfig flags act as macros. Using one of them
  372. is equivalent to explicitly inserting the underlying flags at
  373. that position in the command line. For example, the invocation
  374. 'spirv-opt --merge-blocks -O ...' applies the transformation
  375. --merge-blocks followed by all the transformations implied by
  376. -O.)");
  377. printf(R"(
  378. --preserve-bindings
  379. Ensure that the optimizer preserves all bindings declared within
  380. the module, even when those bindings are unused.)");
  381. printf(R"(
  382. --preserve-interface
  383. Ensure that input and output variables are not removed from the
  384. shader, even if they are unused. Note that this option applies to
  385. all passes that will be run regardless of the order of the flags.)");
  386. printf(R"(
  387. --preserve-spec-constants
  388. Ensure that the optimizer preserves all specialization constants declared
  389. within the module, even when those constants are unused.)");
  390. printf(R"(
  391. --print-all
  392. Print SPIR-V assembly to standard error output before each pass
  393. and after the last pass.)");
  394. printf(R"(
  395. --private-to-local
  396. Change the scope of private variables that are used in a single
  397. function to that function.)");
  398. printf(R"(
  399. --reduce-load-size[=<threshold>]
  400. Replaces loads of composite objects where not every component is
  401. used by loads of just the elements that are used. If the ratio
  402. of the used components of the load is less than the <threshold>,
  403. we replace the load. <threshold> is a double type number. If
  404. it is bigger than 1.0, we always replaces the load.)");
  405. printf(R"(
  406. --redundancy-elimination
  407. Looks for instructions in the same function that compute the
  408. same value, and deletes the redundant ones.)");
  409. printf(R"(
  410. --relax-block-layout
  411. Forwards this option to the validator. See the validator help
  412. for details.)");
  413. printf(R"(
  414. --relax-float-ops
  415. Decorate all float operations with RelaxedPrecision if not already
  416. so decorated. This does not decorate types or variables.)");
  417. printf(R"(
  418. --relax-logical-pointer
  419. Forwards this option to the validator. See the validator help
  420. for details.)");
  421. printf(R"(
  422. --relax-struct-store
  423. Forwards this option to the validator. See the validator help
  424. for details.)");
  425. printf(R"(
  426. --remove-duplicates
  427. Removes duplicate types, decorations, capabilities and extension
  428. instructions.)");
  429. printf(R"(
  430. --remove-unused-interface-variables
  431. Removes variables referenced on the |OpEntryPoint| instruction
  432. that are not referenced in the entry point function or any function
  433. in its call tree. Note that this could cause the shader interface
  434. to no longer match other shader stages.)");
  435. printf(R"(
  436. --replace-invalid-opcode
  437. Replaces instructions whose opcode is valid for shader modules,
  438. but not for the current shader stage. To have an effect, all
  439. entry points must have the same execution model.)");
  440. printf(R"(
  441. --resolve-binding-conflicts
  442. Renumber bindings to avoid conflicts.
  443. When an image and sampler share the same desriptor set and binding,
  444. increment the binding number of the sampler. Recursively ripple
  445. to higher-numbered bindings until all conflicts resolved resolved.)");
  446. printf(R"(
  447. --ssa-rewrite
  448. Replace loads and stores to function local variables with
  449. operations on SSA IDs.)");
  450. printf(R"(
  451. --scalar-block-layout
  452. Forwards this option to the validator. See the validator help
  453. for details.)");
  454. printf(R"(
  455. --scalar-replacement[=<n>]
  456. Replace aggregate function scope variables that are only accessed
  457. via their elements with new function variables representing each
  458. element. <n> is a limit on the size of the aggregates that will
  459. be replaced. 0 means there is no limit. The default value is
  460. 100.)");
  461. printf(R"(
  462. --set-spec-const-default-value "<spec id>:<default value> ..."
  463. Set the default values of the specialization constants with
  464. <spec id>:<default value> pairs specified in a double-quoted
  465. string. <spec id>:<default value> pairs must be separated by
  466. blank spaces, and in each pair, spec id and default value must
  467. be separated with colon ':' without any blank spaces in between.
  468. e.g.: --set-spec-const-default-value "1:100 2:400")");
  469. printf(R"(
  470. --simplify-instructions
  471. Will simplify all instructions in the function as much as
  472. possible.)");
  473. printf(R"(
  474. --skip-block-layout
  475. Forwards this option to the validator. See the validator help
  476. for details.)");
  477. printf(R"(
  478. --skip-validation
  479. Will not validate the SPIR-V before optimizing. If the SPIR-V
  480. is invalid, the optimizer may fail or generate incorrect code.
  481. This options should be used rarely, and with caution.)");
  482. printf(R"(
  483. --split-combined-image-sampler
  484. Replace combined image sampler variables and parameters into
  485. pairs of images and samplers. New variables have the same
  486. bindings as the original variable.)");
  487. printf(R"(
  488. --strength-reduction
  489. Replaces instructions with equivalent and less expensive ones.)");
  490. printf(R"(
  491. --strip-debug
  492. Remove all debug instructions.)");
  493. printf(R"(
  494. --strip-nonsemantic
  495. Remove all reflection and nonsemantic information.)");
  496. printf(R"(
  497. --strip-reflect
  498. DEPRECATED. Remove all reflection information. For now, this
  499. covers reflection information defined by
  500. SPV_GOOGLE_hlsl_functionality1 and SPV_KHR_non_semantic_info)");
  501. printf(R"(
  502. --struct-packing=name:rule
  503. Re-assign layout offsets to a given struct according to
  504. its packing rules.)");
  505. printf(R"(
  506. --switch-descriptorset=<from>:<to>
  507. Switch any DescriptoSet decorations using the value <from> to
  508. the new value <to>.)");
  509. printf(R"(
  510. --target-env=<env>
  511. Set the target environment. Without this flag the target
  512. environment defaults to spv1.5. <env> must be one of
  513. {%s})",
  514. target_env_list.c_str());
  515. printf(R"(
  516. --time-report
  517. Print the resource utilization of each pass (e.g., CPU time,
  518. RSS) to standard error output. Currently it supports only Unix
  519. systems. This option is the same as -ftime-report in GCC. It
  520. prints CPU/WALL/USR/SYS time (and RSS if possible), but note that
  521. USR/SYS time are returned by getrusage() and can have a small
  522. error.)");
  523. printf(R"(
  524. --trim-capabilities
  525. Remove unnecessary capabilities and extensions declared within the
  526. module.)");
  527. printf(R"(
  528. --upgrade-memory-model
  529. Upgrades the Logical GLSL450 memory model to Logical VulkanKHR.
  530. Transforms memory, image, atomic and barrier operations to conform
  531. to that model's requirements.)");
  532. printf(R"(
  533. --vector-dce
  534. This pass looks for components of vectors that are unused, and
  535. removes them from the vector. Note this would still leave around
  536. lots of dead code that a pass of ADCE will be able to remove.)");
  537. printf(R"(
  538. --workaround-1209
  539. Rewrites instructions for which there are known driver bugs to
  540. avoid triggering those bugs.
  541. Current workarounds: Avoid OpUnreachable in loops.)");
  542. printf(R"(
  543. --workgroup-scalar-block-layout
  544. Forwards this option to the validator. See the validator help
  545. for details.)");
  546. printf(R"(
  547. --wrap-opkill
  548. Replaces all OpKill instructions in functions that can be called
  549. from a continue construct with a function call to a function
  550. whose only instruction is an OpKill. This is done to enable
  551. inlining on these functions.
  552. )");
  553. printf(R"(
  554. --unify-const
  555. Remove the duplicated constants.)");
  556. printf(R"(
  557. --validate-after-all
  558. Validate the module after each pass is performed.)");
  559. printf(R"(
  560. -h, --help
  561. Print this help.)");
  562. printf(R"(
  563. --version
  564. Display optimizer version information.
  565. )");
  566. }
  567. // Reads command-line flags the file specified in |oconfig_flag|. This string
  568. // is assumed to have the form "-Oconfig=FILENAME". This function parses the
  569. // string and extracts the file name after the '=' sign.
  570. //
  571. // Flags found in |FILENAME| are pushed at the end of the vector |file_flags|.
  572. //
  573. // This function returns true on success, false on failure.
  574. bool ReadFlagsFromFile(const char* oconfig_flag,
  575. std::vector<std::string>* file_flags) {
  576. const char* fname = strchr(oconfig_flag, '=');
  577. if (fname == nullptr || fname[0] != '=') {
  578. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Invalid -Oconfig flag %s",
  579. oconfig_flag);
  580. return false;
  581. }
  582. fname++;
  583. std::ifstream input_file;
  584. input_file.open(fname);
  585. if (input_file.fail()) {
  586. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Could not open file '%s'",
  587. fname);
  588. return false;
  589. }
  590. std::string line;
  591. while (std::getline(input_file, line)) {
  592. // Ignore empty lines and lines starting with the comment marker '#'.
  593. if (line.length() == 0 || line[0] == '#') {
  594. continue;
  595. }
  596. // Tokenize the line. Add all found tokens to the list of found flags. This
  597. // mimics the way the shell will parse whitespace on the command line. NOTE:
  598. // This does not support quoting and it is not intended to.
  599. std::istringstream iss(line);
  600. while (!iss.eof()) {
  601. std::string flag;
  602. iss >> flag;
  603. file_flags->push_back(flag);
  604. }
  605. }
  606. return true;
  607. }
  608. OptStatus ParseFlags(int argc, const char** argv,
  609. spvtools::Optimizer* optimizer, const char** in_file,
  610. const char** out_file,
  611. spvtools::ValidatorOptions* validator_options,
  612. spvtools::OptimizerOptions* optimizer_options);
  613. // Parses and handles the -Oconfig flag. |prog_name| contains the name of
  614. // the spirv-opt binary (used to build a new argv vector for the recursive
  615. // invocation to ParseFlags). |opt_flag| contains the -Oconfig=FILENAME flag.
  616. // |optimizer|, |in_file|, |out_file|, |validator_options|, and
  617. // |optimizer_options| are as in ParseFlags.
  618. //
  619. // This returns the same OptStatus instance returned by ParseFlags.
  620. OptStatus ParseOconfigFlag(const char* prog_name, const char* opt_flag,
  621. spvtools::Optimizer* optimizer, const char** in_file,
  622. const char** out_file,
  623. spvtools::ValidatorOptions* validator_options,
  624. spvtools::OptimizerOptions* optimizer_options) {
  625. std::vector<std::string> flags;
  626. flags.push_back(prog_name);
  627. std::vector<std::string> file_flags;
  628. if (!ReadFlagsFromFile(opt_flag, &file_flags)) {
  629. spvtools::Error(opt_diagnostic, nullptr, {},
  630. "Could not read optimizer flags from configuration file");
  631. return {OPT_STOP, 1};
  632. }
  633. flags.insert(flags.end(), file_flags.begin(), file_flags.end());
  634. const char** new_argv = new const char*[flags.size()];
  635. for (size_t i = 0; i < flags.size(); i++) {
  636. if (flags[i].find("-Oconfig=") != std::string::npos) {
  637. spvtools::Error(
  638. opt_diagnostic, nullptr, {},
  639. "Flag -Oconfig= may not be used inside the configuration file");
  640. return {OPT_STOP, 1};
  641. }
  642. new_argv[i] = flags[i].c_str();
  643. }
  644. auto ret_val =
  645. ParseFlags(static_cast<int>(flags.size()), new_argv, optimizer, in_file,
  646. out_file, validator_options, optimizer_options);
  647. delete[] new_argv;
  648. return ret_val;
  649. }
  650. // Canonicalize the flag in |argv[argi]| of the form '--pass arg' into
  651. // '--pass=arg'. The optimizer only accepts arguments to pass names that use the
  652. // form '--pass_name=arg'. Since spirv-opt also accepts the other form, this
  653. // function makes the necessary conversion.
  654. //
  655. // Pass flags that require additional arguments should be handled here. Note
  656. // that additional arguments should be given as a single string. If the flag
  657. // requires more than one argument, the pass creator in
  658. // Optimizer::GetPassFromFlag() should parse it accordingly (e.g., see the
  659. // handler for --set-spec-const-default-value).
  660. //
  661. // If the argument requests one of the passes that need an additional argument,
  662. // |argi| is modified to point past the current argument, and the string
  663. // "argv[argi]=argv[argi + 1]" is returned. Otherwise, |argi| is unmodified and
  664. // the string "|argv[argi]|" is returned.
  665. std::string CanonicalizeFlag(const char** argv, int argc, int* argi) {
  666. const char* cur_arg = argv[*argi];
  667. const char* next_arg = (*argi + 1 < argc) ? argv[*argi + 1] : nullptr;
  668. std::ostringstream canonical_arg;
  669. canonical_arg << cur_arg;
  670. // NOTE: DO NOT ADD NEW FLAGS HERE.
  671. //
  672. // These flags are supported for backwards compatibility. When adding new
  673. // passes that need extra arguments in its command-line flag, please make them
  674. // use the syntax "--pass_name[=pass_arg].
  675. if (0 == strcmp(cur_arg, "--set-spec-const-default-value") ||
  676. 0 == strcmp(cur_arg, "--loop-fission") ||
  677. 0 == strcmp(cur_arg, "--loop-fusion") ||
  678. 0 == strcmp(cur_arg, "--loop-unroll-partial") ||
  679. 0 == strcmp(cur_arg, "--loop-peeling-threshold")) {
  680. if (next_arg) {
  681. canonical_arg << "=" << next_arg;
  682. ++(*argi);
  683. }
  684. }
  685. return canonical_arg.str();
  686. }
  687. // Parses command-line flags. |argc| contains the number of command-line flags.
  688. // |argv| points to an array of strings holding the flags. |optimizer| is the
  689. // Optimizer instance used to optimize the program.
  690. //
  691. // On return, this function stores the name of the input program in |in_file|.
  692. // The name of the output file in |out_file|. The return value indicates whether
  693. // optimization should continue and a status code indicating an error or
  694. // success.
  695. OptStatus ParseFlags(int argc, const char** argv,
  696. spvtools::Optimizer* optimizer, const char** in_file,
  697. const char** out_file,
  698. spvtools::ValidatorOptions* validator_options,
  699. spvtools::OptimizerOptions* optimizer_options) {
  700. std::vector<std::string> pass_flags;
  701. bool preserve_interface = true;
  702. for (int argi = 1; argi < argc; ++argi) {
  703. const char* cur_arg = argv[argi];
  704. if ('-' == cur_arg[0]) {
  705. if (0 == strcmp(cur_arg, "--version")) {
  706. spvtools::Logf(opt_diagnostic, SPV_MSG_INFO, nullptr, {}, "%s\n",
  707. spvSoftwareVersionDetailsString());
  708. return {OPT_STOP, 0};
  709. } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) {
  710. PrintUsage(argv[0]);
  711. return {OPT_STOP, 0};
  712. } else if (0 == strcmp(cur_arg, "-o")) {
  713. if (!*out_file && argi + 1 < argc) {
  714. *out_file = argv[++argi];
  715. } else {
  716. PrintUsage(argv[0]);
  717. return {OPT_STOP, 1};
  718. }
  719. } else if ('\0' == cur_arg[1]) {
  720. // Setting a filename of "-" to indicate stdin.
  721. if (!*in_file) {
  722. *in_file = cur_arg;
  723. } else {
  724. spvtools::Error(opt_diagnostic, nullptr, {},
  725. "More than one input file specified");
  726. return {OPT_STOP, 1};
  727. }
  728. } else if (0 == strncmp(cur_arg, "-Oconfig=", sizeof("-Oconfig=") - 1)) {
  729. OptStatus status =
  730. ParseOconfigFlag(argv[0], cur_arg, optimizer, in_file, out_file,
  731. validator_options, optimizer_options);
  732. if (status.action != OPT_CONTINUE) {
  733. return status;
  734. }
  735. } else if (0 == strcmp(cur_arg, "--skip-validation")) {
  736. optimizer_options->set_run_validator(false);
  737. } else if (0 == strcmp(cur_arg, "--print-all")) {
  738. optimizer->SetPrintAll(&std::cerr);
  739. } else if (0 == strcmp(cur_arg, "--preserve-bindings")) {
  740. optimizer_options->set_preserve_bindings(true);
  741. } else if (0 == strcmp(cur_arg, "--preserve-spec-constants")) {
  742. optimizer_options->set_preserve_spec_constants(true);
  743. } else if (0 == strcmp(cur_arg, "--time-report")) {
  744. optimizer->SetTimeReport(&std::cerr);
  745. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  746. validator_options->SetRelaxStructStore(true);
  747. } else if (0 == strncmp(cur_arg, "--max-id-bound=",
  748. sizeof("--max-id-bound=") - 1)) {
  749. auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  750. // Will not allow values in the range [2^31,2^32).
  751. uint32_t max_id_bound =
  752. static_cast<uint32_t>(atoi(split_flag.second.c_str()));
  753. // That SPIR-V mandates the minimum value for max id bound but
  754. // implementations may allow higher minimum bounds.
  755. if (max_id_bound < kDefaultMaxIdBound) {
  756. spvtools::Error(opt_diagnostic, nullptr, {},
  757. "The max id bound must be at least 0x3FFFFF");
  758. return {OPT_STOP, 1};
  759. }
  760. optimizer_options->set_max_id_bound(max_id_bound);
  761. validator_options->SetUniversalLimit(spv_validator_limit_max_id_bound,
  762. max_id_bound);
  763. } else if (0 == strncmp(cur_arg,
  764. "--target-env=", sizeof("--target-env=") - 1)) {
  765. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  766. const auto target_env_str = split_flag.second.c_str();
  767. spv_target_env target_env;
  768. if (!spvParseTargetEnv(target_env_str, &target_env)) {
  769. spvtools::Error(opt_diagnostic, nullptr, {},
  770. "Invalid value passed to --target-env");
  771. return {OPT_STOP, 1};
  772. }
  773. optimizer->SetTargetEnv(target_env);
  774. } else if (0 == strcmp(cur_arg, "--validate-after-all")) {
  775. optimizer->SetValidateAfterAll(true);
  776. } else if (0 == strcmp(cur_arg, "--before-hlsl-legalization")) {
  777. validator_options->SetBeforeHlslLegalization(true);
  778. } else if (0 == strcmp(cur_arg, "--relax-logical-pointer")) {
  779. validator_options->SetRelaxLogicalPointer(true);
  780. } else if (0 == strcmp(cur_arg, "--relax-block-layout")) {
  781. validator_options->SetRelaxBlockLayout(true);
  782. } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) {
  783. validator_options->SetScalarBlockLayout(true);
  784. } else if (0 == strcmp(cur_arg, "--workgroup-scalar-block-layout")) {
  785. validator_options->SetWorkgroupScalarBlockLayout(true);
  786. } else if (0 == strcmp(cur_arg, "--skip-block-layout")) {
  787. validator_options->SetSkipBlockLayout(true);
  788. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  789. validator_options->SetRelaxStructStore(true);
  790. } else if (0 == strcmp(cur_arg, "--preserve-interface")) {
  791. preserve_interface = true;
  792. } else {
  793. // Some passes used to accept the form '--pass arg', canonicalize them
  794. // to '--pass=arg'.
  795. pass_flags.push_back(CanonicalizeFlag(argv, argc, &argi));
  796. // If we were requested to legalize SPIR-V generated from the HLSL
  797. // front-end, skip validation.
  798. if (0 == strcmp(cur_arg, "--legalize-hlsl")) {
  799. validator_options->SetBeforeHlslLegalization(true);
  800. }
  801. }
  802. } else {
  803. if (!*in_file) {
  804. *in_file = cur_arg;
  805. } else {
  806. spvtools::Error(opt_diagnostic, nullptr, {},
  807. "More than one input file specified");
  808. return {OPT_STOP, 1};
  809. }
  810. }
  811. }
  812. if (!optimizer->RegisterPassesFromFlags(pass_flags, preserve_interface)) {
  813. return {OPT_STOP, 1};
  814. }
  815. return {OPT_CONTINUE, 0};
  816. }
  817. } // namespace
  818. int main(int argc, const char** argv) {
  819. const char* in_file = nullptr;
  820. const char* out_file = nullptr;
  821. spv_target_env target_env = kDefaultEnvironment;
  822. spvtools::Optimizer optimizer(target_env);
  823. optimizer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer);
  824. spvtools::ValidatorOptions validator_options;
  825. spvtools::OptimizerOptions optimizer_options;
  826. OptStatus status = ParseFlags(argc, argv, &optimizer, &in_file, &out_file,
  827. &validator_options, &optimizer_options);
  828. optimizer_options.set_validator_options(validator_options);
  829. if (status.action == OPT_STOP) {
  830. return status.code;
  831. }
  832. if (out_file == nullptr) {
  833. spvtools::Error(opt_diagnostic, nullptr, {}, "-o required");
  834. return 1;
  835. }
  836. std::vector<uint32_t> binary;
  837. if (!ReadBinaryFile(in_file, &binary)) {
  838. return 1;
  839. }
  840. // By using the same vector as input and output, we save time in the case
  841. // that there was no change.
  842. bool ok =
  843. optimizer.Run(binary.data(), binary.size(), &binary, optimizer_options);
  844. if (!WriteFile<uint32_t>(out_file, "wb", binary.data(), binary.size())) {
  845. return 1;
  846. }
  847. return ok ? 0 : 1;
  848. }