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