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 #ifndef INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 16 #define INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 17 18 #include <memory> 19 #include <ostream> 20 #include <string> 21 #include <unordered_map> 22 #include <utility> 23 #include <vector> 24 25 #include "libspirv.hpp" 26 27 namespace spvtools { 28 29 namespace opt { 30 class Pass; 31 struct DescriptorSetAndBinding; 32 } // namespace opt 33 34 // C++ interface for SPIR-V optimization functionalities. It wraps the context 35 // (including target environment and the corresponding SPIR-V grammar) and 36 // provides methods for registering optimization passes and optimizing. 37 // 38 // Instances of this class provides basic thread-safety guarantee. 39 class Optimizer { 40 public: 41 // The token for an optimization pass. It is returned via one of the 42 // Create*Pass() standalone functions at the end of this header file and 43 // consumed by the RegisterPass() method. Tokens are one-time objects that 44 // only support move; copying is not allowed. 45 struct PassToken { 46 struct Impl; // Opaque struct for holding inernal data. 47 48 PassToken(std::unique_ptr<Impl>); 49 50 // Tokens for built-in passes should be created using Create*Pass functions 51 // below; for out-of-tree passes, use this constructor instead. 52 // Note that this API isn't guaranteed to be stable and may change without 53 // preserving source or binary compatibility in the future. 54 PassToken(std::unique_ptr<opt::Pass>&& pass); 55 56 // Tokens can only be moved. Copying is disabled. 57 PassToken(const PassToken&) = delete; 58 PassToken(PassToken&&); 59 PassToken& operator=(const PassToken&) = delete; 60 PassToken& operator=(PassToken&&); 61 62 ~PassToken(); 63 64 std::unique_ptr<Impl> impl_; // Unique pointer to internal data. 65 }; 66 67 // Constructs an instance with the given target |env|, which is used to decode 68 // the binaries to be optimized later. 69 // 70 // The instance will have an empty message consumer, which ignores all 71 // messages from the library. Use SetMessageConsumer() to supply a consumer 72 // if messages are of concern. 73 explicit Optimizer(spv_target_env env); 74 75 // Disables copy/move constructor/assignment operations. 76 Optimizer(const Optimizer&) = delete; 77 Optimizer(Optimizer&&) = delete; 78 Optimizer& operator=(const Optimizer&) = delete; 79 Optimizer& operator=(Optimizer&&) = delete; 80 81 // Destructs this instance. 82 ~Optimizer(); 83 84 // Sets the message consumer to the given |consumer|. The |consumer| will be 85 // invoked once for each message communicated from the library. 86 void SetMessageConsumer(MessageConsumer consumer); 87 88 // Returns a reference to the registered message consumer. 89 const MessageConsumer& consumer() const; 90 91 // Registers the given |pass| to this optimizer. Passes will be run in the 92 // exact order of registration. The token passed in will be consumed by this 93 // method. 94 Optimizer& RegisterPass(PassToken&& pass); 95 96 // Registers passes that attempt to improve performance of generated code. 97 // This sequence of passes is subject to constant review and will change 98 // from time to time. 99 Optimizer& RegisterPerformancePasses(); 100 101 // Registers passes that attempt to improve the size of generated code. 102 // This sequence of passes is subject to constant review and will change 103 // from time to time. 104 Optimizer& RegisterSizePasses(); 105 106 // Registers passes that attempt to legalize the generated code. 107 // 108 // Note: this recipe is specially designed for legalizing SPIR-V. It should be 109 // used by compilers after translating HLSL source code literally. It should 110 // *not* be used by general workloads for performance or size improvement. 111 // 112 // This sequence of passes is subject to constant review and will change 113 // from time to time. 114 Optimizer& RegisterLegalizationPasses(); 115 116 // Register passes specified in the list of |flags|. Each flag must be a 117 // string of a form accepted by Optimizer::FlagHasValidForm(). 118 // 119 // If the list of flags contains an invalid entry, it returns false and an 120 // error message is emitted to the MessageConsumer object (use 121 // Optimizer::SetMessageConsumer to define a message consumer, if needed). 122 // 123 // If all the passes are registered successfully, it returns true. 124 bool RegisterPassesFromFlags(const std::vector<std::string>& flags); 125 126 // Registers the optimization pass associated with |flag|. This only accepts 127 // |flag| values of the form "--pass_name[=pass_args]". If no such pass 128 // exists, it returns false. Otherwise, the pass is registered and it returns 129 // true. 130 // 131 // The following flags have special meaning: 132 // 133 // -O: Registers all performance optimization passes 134 // (Optimizer::RegisterPerformancePasses) 135 // 136 // -Os: Registers all size optimization passes 137 // (Optimizer::RegisterSizePasses). 138 // 139 // --legalize-hlsl: Registers all passes that legalize SPIR-V generated by an 140 // HLSL front-end. 141 bool RegisterPassFromFlag(const std::string& flag); 142 143 // Validates that |flag| has a valid format. Strings accepted: 144 // 145 // --pass_name[=pass_args] 146 // -O 147 // -Os 148 // 149 // If |flag| takes one of the forms above, it returns true. Otherwise, it 150 // returns false. 151 bool FlagHasValidForm(const std::string& flag) const; 152 153 // Allows changing, after creation time, the target environment to be 154 // optimized for and validated. Should be called before calling Run(). 155 void SetTargetEnv(const spv_target_env env); 156 157 // Optimizes the given SPIR-V module |original_binary| and writes the 158 // optimized binary into |optimized_binary|. The optimized binary uses 159 // the same SPIR-V version as the original binary. 160 // 161 // Returns true on successful optimization, whether or not the module is 162 // modified. Returns false if |original_binary| fails to validate or if errors 163 // occur when processing |original_binary| using any of the registered passes. 164 // In that case, no further passes are executed and the contents in 165 // |optimized_binary| may be invalid. 166 // 167 // By default, the binary is validated before any transforms are performed, 168 // and optionally after each transform. Validation uses SPIR-V spec rules 169 // for the SPIR-V version named in the binary's header (at word offset 1). 170 // Additionally, if the target environment is a client API (such as 171 // Vulkan 1.1), then validate for that client API version, to the extent 172 // that it is verifiable from data in the binary itself. 173 // 174 // It's allowed to alias |original_binary| to the start of |optimized_binary|. 175 bool Run(const uint32_t* original_binary, size_t original_binary_size, 176 std::vector<uint32_t>* optimized_binary) const; 177 178 // DEPRECATED: Same as above, except passes |options| to the validator when 179 // trying to validate the binary. If |skip_validation| is true, then the 180 // caller is guaranteeing that |original_binary| is valid, and the validator 181 // will not be run. The |max_id_bound| is the limit on the max id in the 182 // module. 183 bool Run(const uint32_t* original_binary, const size_t original_binary_size, 184 std::vector<uint32_t>* optimized_binary, 185 const ValidatorOptions& options, bool skip_validation) const; 186 187 // Same as above, except it takes an options object. See the documentation 188 // for |OptimizerOptions| to see which options can be set. 189 // 190 // By default, the binary is validated before any transforms are performed, 191 // and optionally after each transform. Validation uses SPIR-V spec rules 192 // for the SPIR-V version named in the binary's header (at word offset 1). 193 // Additionally, if the target environment is a client API (such as 194 // Vulkan 1.1), then validate for that client API version, to the extent 195 // that it is verifiable from data in the binary itself, or from the 196 // validator options set on the optimizer options. 197 bool Run(const uint32_t* original_binary, const size_t original_binary_size, 198 std::vector<uint32_t>* optimized_binary, 199 const spv_optimizer_options opt_options) const; 200 201 // Returns a vector of strings with all the pass names added to this 202 // optimizer's pass manager. These strings are valid until the associated 203 // pass manager is destroyed. 204 std::vector<const char*> GetPassNames() const; 205 206 // Sets the option to print the disassembly before each pass and after the 207 // last pass. If |out| is null, then no output is generated. Otherwise, 208 // output is sent to the |out| output stream. 209 Optimizer& SetPrintAll(std::ostream* out); 210 211 // Sets the option to print the resource utilization of each pass. If |out| 212 // is null, then no output is generated. Otherwise, output is sent to the 213 // |out| output stream. 214 Optimizer& SetTimeReport(std::ostream* out); 215 216 // Sets the option to validate the module after each pass. 217 Optimizer& SetValidateAfterAll(bool validate); 218 219 private: 220 struct Impl; // Opaque struct for holding internal data. 221 std::unique_ptr<Impl> impl_; // Unique pointer to internal data. 222 }; 223 224 // Creates a null pass. 225 // A null pass does nothing to the SPIR-V module to be optimized. 226 Optimizer::PassToken CreateNullPass(); 227 228 // Creates a strip-debug-info pass. 229 // A strip-debug-info pass removes all debug instructions (as documented in 230 // Section 3.32.2 of the SPIR-V spec) of the SPIR-V module to be optimized. 231 Optimizer::PassToken CreateStripDebugInfoPass(); 232 233 // Creates a strip-reflect-info pass. 234 // A strip-reflect-info pass removes all reflections instructions. 235 // For now, this is limited to removing decorations defined in 236 // SPV_GOOGLE_hlsl_functionality1. The coverage may expand in 237 // the future. 238 Optimizer::PassToken CreateStripReflectInfoPass(); 239 240 // Creates an eliminate-dead-functions pass. 241 // An eliminate-dead-functions pass will remove all functions that are not in 242 // the call trees rooted at entry points and exported functions. These 243 // functions are not needed because they will never be called. 244 Optimizer::PassToken CreateEliminateDeadFunctionsPass(); 245 246 // Creates an eliminate-dead-members pass. 247 // An eliminate-dead-members pass will remove all unused members of structures. 248 // This will not affect the data layout of the remaining members. 249 Optimizer::PassToken CreateEliminateDeadMembersPass(); 250 251 // Creates a set-spec-constant-default-value pass from a mapping from spec-ids 252 // to the default values in the form of string. 253 // A set-spec-constant-default-value pass sets the default values for the 254 // spec constants that have SpecId decorations (i.e., those defined by 255 // OpSpecConstant{|True|False} instructions). 256 Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( 257 const std::unordered_map<uint32_t, std::string>& id_value_map); 258 259 // Creates a set-spec-constant-default-value pass from a mapping from spec-ids 260 // to the default values in the form of bit pattern. 261 // A set-spec-constant-default-value pass sets the default values for the 262 // spec constants that have SpecId decorations (i.e., those defined by 263 // OpSpecConstant{|True|False} instructions). 264 Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( 265 const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map); 266 267 // Creates a flatten-decoration pass. 268 // A flatten-decoration pass replaces grouped decorations with equivalent 269 // ungrouped decorations. That is, it replaces each OpDecorationGroup 270 // instruction and associated OpGroupDecorate and OpGroupMemberDecorate 271 // instructions with equivalent OpDecorate and OpMemberDecorate instructions. 272 // The pass does not attempt to preserve debug information for instructions 273 // it removes. 274 Optimizer::PassToken CreateFlattenDecorationPass(); 275 276 // Creates a freeze-spec-constant-value pass. 277 // A freeze-spec-constant pass specializes the value of spec constants to 278 // their default values. This pass only processes the spec constants that have 279 // SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or 280 // OpSpecConstantFalse instructions) and replaces them with their normal 281 // counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The 282 // corresponding SpecId annotation instructions will also be removed. This 283 // pass does not fold the newly added normal constants and does not process 284 // other spec constants defined by OpSpecConstantComposite or 285 // OpSpecConstantOp. 286 Optimizer::PassToken CreateFreezeSpecConstantValuePass(); 287 288 // Creates a fold-spec-constant-op-and-composite pass. 289 // A fold-spec-constant-op-and-composite pass folds spec constants defined by 290 // OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants 291 // defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or 292 // OpConstantComposite instructions. Note that spec constants defined with 293 // OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are 294 // not handled, as these instructions indicate their value are not determined 295 // and can be changed in future. A spec constant is foldable if all of its 296 // value(s) can be determined from the module. E.g., an integer spec constant 297 // defined with OpSpecConstantOp instruction can be folded if its value won't 298 // change later. This pass will replace the original OpSpecContantOp instruction 299 // with an OpConstant instruction. When folding composite spec constants, 300 // new instructions may be inserted to define the components of the composite 301 // constant first, then the original spec constants will be replaced by 302 // OpConstantComposite instructions. 303 // 304 // There are some operations not supported yet: 305 // OpSConvert, OpFConvert, OpQuantizeToF16 and 306 // all the operations under Kernel capability. 307 // TODO(qining): Add support for the operations listed above. 308 Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass(); 309 310 // Creates a unify-constant pass. 311 // A unify-constant pass de-duplicates the constants. Constants with the exact 312 // same value and identical form will be unified and only one constant will 313 // be kept for each unique pair of type and value. 314 // There are several cases not handled by this pass: 315 // 1) Constants defined by OpConstantNull instructions (null constants) and 316 // constants defined by OpConstantFalse, OpConstant or OpConstantComposite 317 // with value 0 (zero-valued normal constants) are not considered equivalent. 318 // So null constants won't be used to replace zero-valued normal constants, 319 // vice versa. 320 // 2) Whenever there are decorations to the constant's result id id, the 321 // constant won't be handled, which means, it won't be used to replace any 322 // other constants, neither can other constants replace it. 323 // 3) NaN in float point format with different bit patterns are not unified. 324 Optimizer::PassToken CreateUnifyConstantPass(); 325 326 // Creates a eliminate-dead-constant pass. 327 // A eliminate-dead-constant pass removes dead constants, including normal 328 // contants defined by OpConstant, OpConstantComposite, OpConstantTrue, or 329 // OpConstantFalse and spec constants defined by OpSpecConstant, 330 // OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or 331 // OpSpecConstantOp. 332 Optimizer::PassToken CreateEliminateDeadConstantPass(); 333 334 // Creates a strength-reduction pass. 335 // A strength-reduction pass will look for opportunities to replace an 336 // instruction with an equivalent and less expensive one. For example, 337 // multiplying by a power of 2 can be replaced by a bit shift. 338 Optimizer::PassToken CreateStrengthReductionPass(); 339 340 // Creates a block merge pass. 341 // This pass searches for blocks with a single Branch to a block with no 342 // other predecessors and merges the blocks into a single block. Continue 343 // blocks and Merge blocks are not candidates for the second block. 344 // 345 // The pass is most useful after Dead Branch Elimination, which can leave 346 // such sequences of blocks. Merging them makes subsequent passes more 347 // effective, such as single block local store-load elimination. 348 // 349 // While this pass reduces the number of occurrences of this sequence, at 350 // this time it does not guarantee all such sequences are eliminated. 351 // 352 // Presence of phi instructions can inhibit this optimization. Handling 353 // these is left for future improvements. 354 Optimizer::PassToken CreateBlockMergePass(); 355 356 // Creates an exhaustive inline pass. 357 // An exhaustive inline pass attempts to exhaustively inline all function 358 // calls in all functions in an entry point call tree. The intent is to enable, 359 // albeit through brute force, analysis and optimization across function 360 // calls by subsequent optimization passes. As the inlining is exhaustive, 361 // there is no attempt to optimize for size or runtime performance. Functions 362 // that are not in the call tree of an entry point are not changed. 363 Optimizer::PassToken CreateInlineExhaustivePass(); 364 365 // Creates an opaque inline pass. 366 // An opaque inline pass inlines all function calls in all functions in all 367 // entry point call trees where the called function contains an opaque type 368 // in either its parameter types or return type. An opaque type is currently 369 // defined as Image, Sampler or SampledImage. The intent is to enable, albeit 370 // through brute force, analysis and optimization across these function calls 371 // by subsequent passes in order to remove the storing of opaque types which is 372 // not legal in Vulkan. Functions that are not in the call tree of an entry 373 // point are not changed. 374 Optimizer::PassToken CreateInlineOpaquePass(); 375 376 // Creates a single-block local variable load/store elimination pass. 377 // For every entry point function, do single block memory optimization of 378 // function variables referenced only with non-access-chain loads and stores. 379 // For each targeted variable load, if previous store to that variable in the 380 // block, replace the load's result id with the value id of the store. 381 // If previous load within the block, replace the current load's result id 382 // with the previous load's result id. In either case, delete the current 383 // load. Finally, check if any remaining stores are useless, and delete store 384 // and variable if possible. 385 // 386 // The presence of access chain references and function calls can inhibit 387 // the above optimization. 388 // 389 // Only modules with relaxed logical addressing (see opt/instruction.h) are 390 // currently processed. 391 // 392 // This pass is most effective if preceeded by Inlining and 393 // LocalAccessChainConvert. This pass will reduce the work needed to be done 394 // by LocalSingleStoreElim and LocalMultiStoreElim. 395 // 396 // Only functions in the call tree of an entry point are processed. 397 Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass(); 398 399 // Create dead branch elimination pass. 400 // For each entry point function, this pass will look for SelectionMerge 401 // BranchConditionals with constant condition and convert to a Branch to 402 // the indicated label. It will delete resulting dead blocks. 403 // 404 // For all phi functions in merge block, replace all uses with the id 405 // corresponding to the living predecessor. 406 // 407 // Note that some branches and blocks may be left to avoid creating invalid 408 // control flow. Improving this is left to future work. 409 // 410 // This pass is most effective when preceeded by passes which eliminate 411 // local loads and stores, effectively propagating constant values where 412 // possible. 413 Optimizer::PassToken CreateDeadBranchElimPass(); 414 415 // Creates an SSA local variable load/store elimination pass. 416 // For every entry point function, eliminate all loads and stores of function 417 // scope variables only referenced with non-access-chain loads and stores. 418 // Eliminate the variables as well. 419 // 420 // The presence of access chain references and function calls can inhibit 421 // the above optimization. 422 // 423 // Only shader modules with relaxed logical addressing (see opt/instruction.h) 424 // are currently processed. Currently modules with any extensions enabled are 425 // not processed. This is left for future work. 426 // 427 // This pass is most effective if preceeded by Inlining and 428 // LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim 429 // will reduce the work that this pass has to do. 430 Optimizer::PassToken CreateLocalMultiStoreElimPass(); 431 432 // Creates a local access chain conversion pass. 433 // A local access chain conversion pass identifies all function scope 434 // variables which are accessed only with loads, stores and access chains 435 // with constant indices. It then converts all loads and stores of such 436 // variables into equivalent sequences of loads, stores, extracts and inserts. 437 // 438 // This pass only processes entry point functions. It currently only converts 439 // non-nested, non-ptr access chains. It does not process modules with 440 // non-32-bit integer types present. Optional memory access options on loads 441 // and stores are ignored as we are only processing function scope variables. 442 // 443 // This pass unifies access to these variables to a single mode and simplifies 444 // subsequent analysis and elimination of these variables along with their 445 // loads and stores allowing values to propagate to their points of use where 446 // possible. 447 Optimizer::PassToken CreateLocalAccessChainConvertPass(); 448 449 // Creates a local single store elimination pass. 450 // For each entry point function, this pass eliminates loads and stores for 451 // function scope variable that are stored to only once, where possible. Only 452 // whole variable loads and stores are eliminated; access-chain references are 453 // not optimized. Replace all loads of such variables with the value that is 454 // stored and eliminate any resulting dead code. 455 // 456 // Currently, the presence of access chains and function calls can inhibit this 457 // pass, however the Inlining and LocalAccessChainConvert passes can make it 458 // more effective. In additional, many non-load/store memory operations are 459 // not supported and will prohibit optimization of a function. Support of 460 // these operations are future work. 461 // 462 // Only shader modules with relaxed logical addressing (see opt/instruction.h) 463 // are currently processed. 464 // 465 // This pass will reduce the work needed to be done by LocalSingleBlockElim 466 // and LocalMultiStoreElim and can improve the effectiveness of other passes 467 // such as DeadBranchElimination which depend on values for their analysis. 468 Optimizer::PassToken CreateLocalSingleStoreElimPass(); 469 470 // Creates an insert/extract elimination pass. 471 // This pass processes each entry point function in the module, searching for 472 // extracts on a sequence of inserts. It further searches the sequence for an 473 // insert with indices identical to the extract. If such an insert can be 474 // found before hitting a conflicting insert, the extract's result id is 475 // replaced with the id of the values from the insert. 476 // 477 // Besides removing extracts this pass enables subsequent dead code elimination 478 // passes to delete the inserts. This pass performs best after access chains are 479 // converted to inserts and extracts and local loads and stores are eliminated. 480 Optimizer::PassToken CreateInsertExtractElimPass(); 481 482 // Creates a dead insert elimination pass. 483 // This pass processes each entry point function in the module, searching for 484 // unreferenced inserts into composite types. These are most often unused 485 // stores to vector components. They are unused because they are never 486 // referenced, or because there is another insert to the same component between 487 // the insert and the reference. After removing the inserts, dead code 488 // elimination is attempted on the inserted values. 489 // 490 // This pass performs best after access chains are converted to inserts and 491 // extracts and local loads and stores are eliminated. While executing this 492 // pass can be advantageous on its own, it is also advantageous to execute 493 // this pass after CreateInsertExtractPass() as it will remove any unused 494 // inserts created by that pass. 495 Optimizer::PassToken CreateDeadInsertElimPass(); 496 497 // Create aggressive dead code elimination pass 498 // This pass eliminates unused code from the module. In addition, 499 // it detects and eliminates code which may have spurious uses but which do 500 // not contribute to the output of the function. The most common cause of 501 // such code sequences is summations in loops whose result is no longer used 502 // due to dead code elimination. This optimization has additional compile 503 // time cost over standard dead code elimination. 504 // 505 // This pass only processes entry point functions. It also only processes 506 // shaders with relaxed logical addressing (see opt/instruction.h). It 507 // currently will not process functions with function calls. Unreachable 508 // functions are deleted. 509 // 510 // This pass will be made more effective by first running passes that remove 511 // dead control flow and inlines function calls. 512 // 513 // This pass can be especially useful after running Local Access Chain 514 // Conversion, which tends to cause cycles of dead code to be left after 515 // Store/Load elimination passes are completed. These cycles cannot be 516 // eliminated with standard dead code elimination. 517 // 518 // If |preserve_interface| is true, all non-io variables in the entry point 519 // interface are considered live and are not eliminated. This mode is needed 520 // by GPU-Assisted validation instrumentation, where a change in the interface 521 // is not allowed. 522 Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface = false); 523 524 // Creates a remove-unused-interface-variables pass. 525 // Removes variables referenced on the |OpEntryPoint| instruction that are not 526 // referenced in the entry point function or any function in its call tree. Note 527 // that this could cause the shader interface to no longer match other shader 528 // stages. 529 Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass(); 530 531 // Creates an empty pass. 532 // This is deprecated and will be removed. 533 // TODO(jaebaek): remove this pass after handling glslang's broken unit tests. 534 // https://github.com/KhronosGroup/glslang/pull/2440 535 Optimizer::PassToken CreatePropagateLineInfoPass(); 536 537 // Creates an empty pass. 538 // This is deprecated and will be removed. 539 // TODO(jaebaek): remove this pass after handling glslang's broken unit tests. 540 // https://github.com/KhronosGroup/glslang/pull/2440 541 Optimizer::PassToken CreateRedundantLineInfoElimPass(); 542 543 // Creates a compact ids pass. 544 // The pass remaps result ids to a compact and gapless range starting from %1. 545 Optimizer::PassToken CreateCompactIdsPass(); 546 547 // Creates a remove duplicate pass. 548 // This pass removes various duplicates: 549 // * duplicate capabilities; 550 // * duplicate extended instruction imports; 551 // * duplicate types; 552 // * duplicate decorations. 553 Optimizer::PassToken CreateRemoveDuplicatesPass(); 554 555 // Creates a CFG cleanup pass. 556 // This pass removes cruft from the control flow graph of functions that are 557 // reachable from entry points and exported functions. It currently includes the 558 // following functionality: 559 // 560 // - Removal of unreachable basic blocks. 561 Optimizer::PassToken CreateCFGCleanupPass(); 562 563 // Create dead variable elimination pass. 564 // This pass will delete module scope variables, along with their decorations, 565 // that are not referenced. 566 Optimizer::PassToken CreateDeadVariableEliminationPass(); 567 568 // create merge return pass. 569 // changes functions that have multiple return statements so they have a single 570 // return statement. 571 // 572 // for structured control flow it is assumed that the only unreachable blocks in 573 // the function are trivial merge and continue blocks. 574 // 575 // a trivial merge block contains the label and an opunreachable instructions, 576 // nothing else. a trivial continue block contain a label and an opbranch to 577 // the header, nothing else. 578 // 579 // these conditions are guaranteed to be met after running dead-branch 580 // elimination. 581 Optimizer::PassToken CreateMergeReturnPass(); 582 583 // Create value numbering pass. 584 // This pass will look for instructions in the same basic block that compute the 585 // same value, and remove the redundant ones. 586 Optimizer::PassToken CreateLocalRedundancyEliminationPass(); 587 588 // Create LICM pass. 589 // This pass will look for invariant instructions inside loops and hoist them to 590 // the loops preheader. 591 Optimizer::PassToken CreateLoopInvariantCodeMotionPass(); 592 593 // Creates a loop fission pass. 594 // This pass will split all top level loops whose register pressure exceedes the 595 // given |threshold|. 596 Optimizer::PassToken CreateLoopFissionPass(size_t threshold); 597 598 // Creates a loop fusion pass. 599 // This pass will look for adjacent loops that are compatible and legal to be 600 // fused. The fuse all such loops as long as the register usage for the fused 601 // loop stays under the threshold defined by |max_registers_per_loop|. 602 Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop); 603 604 // Creates a loop peeling pass. 605 // This pass will look for conditions inside a loop that are true or false only 606 // for the N first or last iteration. For loop with such condition, those N 607 // iterations of the loop will be executed outside of the main loop. 608 // To limit code size explosion, the loop peeling can only happen if the code 609 // size growth for each loop is under |code_growth_threshold|. 610 Optimizer::PassToken CreateLoopPeelingPass(); 611 612 // Creates a loop unswitch pass. 613 // This pass will look for loop independent branch conditions and move the 614 // condition out of the loop and version the loop based on the taken branch. 615 // Works best after LICM and local multi store elimination pass. 616 Optimizer::PassToken CreateLoopUnswitchPass(); 617 618 // Create global value numbering pass. 619 // This pass will look for instructions where the same value is computed on all 620 // paths leading to the instruction. Those instructions are deleted. 621 Optimizer::PassToken CreateRedundancyEliminationPass(); 622 623 // Create scalar replacement pass. 624 // This pass replaces composite function scope variables with variables for each 625 // element if those elements are accessed individually. The parameter is a 626 // limit on the number of members in the composite variable that the pass will 627 // consider replacing. 628 Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100); 629 630 // Create a private to local pass. 631 // This pass looks for variables delcared in the private storage class that are 632 // used in only one function. Those variables are moved to the function storage 633 // class in the function that they are used. 634 Optimizer::PassToken CreatePrivateToLocalPass(); 635 636 // Creates a conditional constant propagation (CCP) pass. 637 // This pass implements the SSA-CCP algorithm in 638 // 639 // Constant propagation with conditional branches, 640 // Wegman and Zadeck, ACM TOPLAS 13(2):181-210. 641 // 642 // Constant values in expressions and conditional jumps are folded and 643 // simplified. This may reduce code size by removing never executed jump targets 644 // and computations with constant operands. 645 Optimizer::PassToken CreateCCPPass(); 646 647 // Creates a workaround driver bugs pass. This pass attempts to work around 648 // a known driver bug (issue #1209) by identifying the bad code sequences and 649 // rewriting them. 650 // 651 // Current workaround: Avoid OpUnreachable instructions in loops. 652 Optimizer::PassToken CreateWorkaround1209Pass(); 653 654 // Creates a pass that converts if-then-else like assignments into OpSelect. 655 Optimizer::PassToken CreateIfConversionPass(); 656 657 // Creates a pass that will replace instructions that are not valid for the 658 // current shader stage by constants. Has no effect on non-shader modules. 659 Optimizer::PassToken CreateReplaceInvalidOpcodePass(); 660 661 // Creates a pass that simplifies instructions using the instruction folder. 662 Optimizer::PassToken CreateSimplificationPass(); 663 664 // Create loop unroller pass. 665 // Creates a pass to unroll loops which have the "Unroll" loop control 666 // mask set. The loops must meet a specific criteria in order to be unrolled 667 // safely this criteria is checked before doing the unroll by the 668 // LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria 669 // won't be unrolled. See CanPerformUnroll LoopUtils.h for more information. 670 Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0); 671 672 // Create the SSA rewrite pass. 673 // This pass converts load/store operations on function local variables into 674 // operations on SSA IDs. This allows SSA optimizers to act on these variables. 675 // Only variables that are local to the function and of supported types are 676 // processed (see IsSSATargetVar for details). 677 Optimizer::PassToken CreateSSARewritePass(); 678 679 // Create pass to convert relaxed precision instructions to half precision. 680 // This pass converts as many relaxed float32 arithmetic operations to half as 681 // possible. It converts any float32 operands to half if needed. It converts 682 // any resulting half precision values back to float32 as needed. No variables 683 // are changed. No image operations are changed. 684 // 685 // Best if run after function scope store/load and composite operation 686 // eliminations are run. Also best if followed by instruction simplification, 687 // redundancy elimination and DCE. 688 Optimizer::PassToken CreateConvertRelaxedToHalfPass(); 689 690 // Create relax float ops pass. 691 // This pass decorates all float32 result instructions with RelaxedPrecision 692 // if not already so decorated. 693 Optimizer::PassToken CreateRelaxFloatOpsPass(); 694 695 // Create copy propagate arrays pass. 696 // This pass looks to copy propagate memory references for arrays. It looks 697 // for specific code patterns to recognize array copies. 698 Optimizer::PassToken CreateCopyPropagateArraysPass(); 699 700 // Create a vector dce pass. 701 // This pass looks for components of vectors that are unused, and removes them 702 // from the vector. Note this would still leave around lots of dead code that 703 // a pass of ADCE will be able to remove. 704 Optimizer::PassToken CreateVectorDCEPass(); 705 706 // Create a pass to reduce the size of loads. 707 // This pass looks for loads of structures where only a few of its members are 708 // used. It replaces the loads feeding an OpExtract with an OpAccessChain and 709 // a load of the specific elements. The parameter is a threshold to determine 710 // whether we have to replace the load or not. If the ratio of the used 711 // components of the load is less than the threshold, we replace the load. 712 Optimizer::PassToken CreateReduceLoadSizePass( 713 double load_replacement_threshold = 0.9); 714 715 // Create a pass to combine chained access chains. 716 // This pass looks for access chains fed by other access chains and combines 717 // them into a single instruction where possible. 718 Optimizer::PassToken CreateCombineAccessChainsPass(); 719 720 // Create a pass to instrument bindless descriptor checking 721 // This pass instruments all bindless references to check that descriptor 722 // array indices are inbounds, and if the descriptor indexing extension is 723 // enabled, that the descriptor has been initialized. If the reference is 724 // invalid, a record is written to the debug output buffer (if space allows) 725 // and a null value is returned. This pass is designed to support bindless 726 // validation in the Vulkan validation layers. 727 // 728 // TODO(greg-lunarg): Add support for buffer references. Currently only does 729 // checking for image references. 730 // 731 // Dead code elimination should be run after this pass as the original, 732 // potentially invalid code is not removed and could cause undefined behavior, 733 // including crashes. It may also be beneficial to run Simplification 734 // (ie Constant Propagation), DeadBranchElim and BlockMerge after this pass to 735 // optimize instrument code involving the testing of compile-time constants. 736 // It is also generally recommended that this pass (and all 737 // instrumentation passes) be run after any legalization and optimization 738 // passes. This will give better analysis for the instrumentation and avoid 739 // potentially de-optimizing the instrument code, for example, inlining 740 // the debug record output function throughout the module. 741 // 742 // The instrumentation will read and write buffers in debug 743 // descriptor set |desc_set|. It will write |shader_id| in each output record 744 // to identify the shader module which generated the record. 745 // |desc_length_enable| controls instrumentation of runtime descriptor array 746 // references, |desc_init_enable| controls instrumentation of descriptor 747 // initialization checking, and |buff_oob_enable| controls instrumentation 748 // of storage and uniform buffer bounds checking, all of which require input 749 // buffer support. |texbuff_oob_enable| controls instrumentation of texel 750 // buffers, which does not require input buffer support. 751 Optimizer::PassToken CreateInstBindlessCheckPass( 752 uint32_t desc_set, uint32_t shader_id, bool desc_length_enable = false, 753 bool desc_init_enable = false, bool buff_oob_enable = false, 754 bool texbuff_oob_enable = false); 755 756 // Create a pass to instrument physical buffer address checking 757 // This pass instruments all physical buffer address references to check that 758 // all referenced bytes fall in a valid buffer. If the reference is 759 // invalid, a record is written to the debug output buffer (if space allows) 760 // and a null value is returned. This pass is designed to support buffer 761 // address validation in the Vulkan validation layers. 762 // 763 // Dead code elimination should be run after this pass as the original, 764 // potentially invalid code is not removed and could cause undefined behavior, 765 // including crashes. Instruction simplification would likely also be 766 // beneficial. It is also generally recommended that this pass (and all 767 // instrumentation passes) be run after any legalization and optimization 768 // passes. This will give better analysis for the instrumentation and avoid 769 // potentially de-optimizing the instrument code, for example, inlining 770 // the debug record output function throughout the module. 771 // 772 // The instrumentation will read and write buffers in debug 773 // descriptor set |desc_set|. It will write |shader_id| in each output record 774 // to identify the shader module which generated the record. 775 Optimizer::PassToken CreateInstBuffAddrCheckPass(uint32_t desc_set, 776 uint32_t shader_id); 777 778 // Create a pass to instrument OpDebugPrintf instructions. 779 // This pass replaces all OpDebugPrintf instructions with instructions to write 780 // a record containing the string id and the all specified values into a special 781 // printf output buffer (if space allows). This pass is designed to support 782 // the printf validation in the Vulkan validation layers. 783 // 784 // The instrumentation will write buffers in debug descriptor set |desc_set|. 785 // It will write |shader_id| in each output record to identify the shader 786 // module which generated the record. 787 Optimizer::PassToken CreateInstDebugPrintfPass(uint32_t desc_set, 788 uint32_t shader_id); 789 790 // Create a pass to upgrade to the VulkanKHR memory model. 791 // This pass upgrades the Logical GLSL450 memory model to Logical VulkanKHR. 792 // Additionally, it modifies memory, image, atomic and barrier operations to 793 // conform to that model's requirements. 794 Optimizer::PassToken CreateUpgradeMemoryModelPass(); 795 796 // Create a pass to do code sinking. Code sinking is a transformation 797 // where an instruction is moved into a more deeply nested construct. 798 Optimizer::PassToken CreateCodeSinkingPass(); 799 800 // Create a pass to fix incorrect storage classes. In order to make code 801 // generation simpler, DXC may generate code where the storage classes do not 802 // match up correctly. This pass will fix the errors that it can. 803 Optimizer::PassToken CreateFixStorageClassPass(); 804 805 // Creates a graphics robust access pass. 806 // 807 // This pass injects code to clamp indexed accesses to buffers and internal 808 // arrays, providing guarantees satisfying Vulkan's robustBufferAccess rules. 809 // 810 // TODO(dneto): Clamps coordinates and sample index for pointer calculations 811 // into storage images (OpImageTexelPointer). For an cube array image, it 812 // assumes the maximum layer count times 6 is at most 0xffffffff. 813 // 814 // NOTE: This pass will fail with a message if: 815 // - The module is not a Shader module. 816 // - The module declares VariablePointers, VariablePointersStorageBuffer, or 817 // RuntimeDescriptorArrayEXT capabilities. 818 // - The module uses an addressing model other than Logical 819 // - Access chain indices are wider than 64 bits. 820 // - Access chain index for a struct is not an OpConstant integer or is out 821 // of range. (The module is already invalid if that is the case.) 822 // - TODO(dneto): The OpImageTexelPointer coordinate component is not 32-bits 823 // wide. 824 // 825 // NOTE: Access chain indices are always treated as signed integers. So 826 // if an array has a fixed size of more than 2^31 elements, then elements 827 // from 2^31 and above are never accessible with a 32-bit index, 828 // signed or unsigned. For this case, this pass will clamp the index 829 // between 0 and at 2^31-1, inclusive. 830 // Similarly, if an array has more then 2^15 element and is accessed with 831 // a 16-bit index, then elements from 2^15 and above are not accessible. 832 // In this case, the pass will clamp the index between 0 and 2^15-1 833 // inclusive. 834 Optimizer::PassToken CreateGraphicsRobustAccessPass(); 835 836 // Create a pass to replace a descriptor access using variable index. 837 // This pass replaces every access using a variable index to array variable 838 // |desc| that has a DescriptorSet and Binding decorations with a constant 839 // element of the array. In order to replace the access using a variable index 840 // with the constant element, it uses a switch statement. 841 Optimizer::PassToken CreateReplaceDescArrayAccessUsingVarIndexPass(); 842 843 // Create descriptor scalar replacement pass. 844 // This pass replaces every array variable |desc| that has a DescriptorSet and 845 // Binding decorations with a new variable for each element of the array. 846 // Suppose |desc| was bound at binding |b|. Then the variable corresponding to 847 // |desc[i]| will have binding |b+i|. The descriptor set will be the same. It 848 // is assumed that no other variable already has a binding that will used by one 849 // of the new variables. If not, the pass will generate invalid Spir-V. All 850 // accesses to |desc| must be OpAccessChain instructions with a literal index 851 // for the first index. 852 Optimizer::PassToken CreateDescriptorScalarReplacementPass(); 853 854 // Create a pass to replace each OpKill instruction with a function call to a 855 // function that has a single OpKill. Also replace each OpTerminateInvocation 856 // instruction with a function call to a function that has a single 857 // OpTerminateInvocation. This allows more code to be inlined. 858 Optimizer::PassToken CreateWrapOpKillPass(); 859 860 // Replaces the extensions VK_AMD_shader_ballot,VK_AMD_gcn_shader, and 861 // VK_AMD_shader_trinary_minmax with equivalent code using core instructions and 862 // capabilities. 863 Optimizer::PassToken CreateAmdExtToKhrPass(); 864 865 // Replaces the internal version of GLSLstd450 InterpolateAt* extended 866 // instructions with the externally valid version. The internal version allows 867 // an OpLoad of the interpolant for the first argument. This pass removes the 868 // OpLoad and replaces it with its pointer. glslang and possibly other 869 // frontends will create the internal version for HLSL. This pass will be part 870 // of HLSL legalization and should be called after interpolants have been 871 // propagated into their final positions. 872 Optimizer::PassToken CreateInterpolateFixupPass(); 873 874 // Creates a convert-to-sampled-image pass to convert images and/or 875 // samplers with given pairs of descriptor set and binding to sampled image. 876 // If a pair of an image and a sampler have the same pair of descriptor set and 877 // binding that is one of the given pairs, they will be converted to a sampled 878 // image. In addition, if only an image has the descriptor set and binding that 879 // is one of the given pairs, it will be converted to a sampled image as well. 880 Optimizer::PassToken CreateConvertToSampledImagePass( 881 const std::vector<opt::DescriptorSetAndBinding>& 882 descriptor_set_binding_pairs); 883 884 } // namespace spvtools 885 886 #endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 887