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