blob: fbbd9bc074dc48b833db3cdc074ef04558322034 [file] [log] [blame]
Chris Forbescc5697f2019-01-30 11:54:08 -08001// 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>
Alexis Hetu00e0af12021-11-08 08:57:46 -050022#include <utility>
Chris Forbescc5697f2019-01-30 11:54:08 -080023#include <vector>
24
25#include "libspirv.hpp"
26
27namespace spvtools {
28
29namespace opt {
30class Pass;
Alexis Hetu00e0af12021-11-08 08:57:46 -050031struct DescriptorSetAndBinding;
32} // namespace opt
Chris Forbescc5697f2019-01-30 11:54:08 -080033
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.
39class 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 {
sugoi1b398bf32022-02-18 10:27:28 -050046 struct Impl; // Opaque struct for holding internal data.
Chris Forbescc5697f2019-01-30 11:54:08 -080047
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 //
Ben Claytondc6b76a2020-02-24 14:53:40 +000070 // 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.
Chris Forbescc5697f2019-01-30 11:54:08 -080073 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
Chris Forbescc5697f2019-01-30 11:54:08 -0800106 // 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
Ben Claytondc6b76a2020-02-24 14:53:40 +0000154 // optimized for and validated. Should be called before calling Run().
Chris Forbescc5697f2019-01-30 11:54:08 -0800155 void SetTargetEnv(const spv_target_env env);
156
157 // Optimizes the given SPIR-V module |original_binary| and writes the
Ben Claytondc6b76a2020-02-24 14:53:40 +0000158 // optimized binary into |optimized_binary|. The optimized binary uses
159 // the same SPIR-V version as the original binary.
160 //
Chris Forbescc5697f2019-01-30 11:54:08 -0800161 // 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 //
Ben Claytondc6b76a2020-02-24 14:53:40 +0000167 // 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 //
Chris Forbescc5697f2019-01-30 11:54:08 -0800174 // 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.
Ben Claytondc6b76a2020-02-24 14:53:40 +0000189 //
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.
Chris Forbescc5697f2019-01-30 11:54:08 -0800197 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
Ben Claytonb73b7602019-07-29 13:56:13 +0100216 // Sets the option to validate the module after each pass.
217 Optimizer& SetValidateAfterAll(bool validate);
218
Chris Forbescc5697f2019-01-30 11:54:08 -0800219 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.
226Optimizer::PassToken CreateNullPass();
227
228// Creates a strip-debug-info pass.
229// A strip-debug-info pass removes all debug instructions (as documented in
sugoi1b398bf32022-02-18 10:27:28 -0500230// Section 3.42.2 of the SPIR-V spec) of the SPIR-V module to be optimized.
Chris Forbescc5697f2019-01-30 11:54:08 -0800231Optimizer::PassToken CreateStripDebugInfoPass();
232
sugoi1b398bf32022-02-18 10:27:28 -0500233// [Deprecated] This will create a strip-nonsemantic-info pass. See below.
Chris Forbescc5697f2019-01-30 11:54:08 -0800234Optimizer::PassToken CreateStripReflectInfoPass();
235
sugoi1b398bf32022-02-18 10:27:28 -0500236// Creates a strip-nonsemantic-info pass.
237// A strip-nonsemantic-info pass removes all reflections and explicitly
238// non-semantic instructions.
239Optimizer::PassToken CreateStripNonSemanticInfoPass();
240
Chris Forbescc5697f2019-01-30 11:54:08 -0800241// Creates an eliminate-dead-functions pass.
242// An eliminate-dead-functions pass will remove all functions that are not in
243// the call trees rooted at entry points and exported functions. These
244// functions are not needed because they will never be called.
245Optimizer::PassToken CreateEliminateDeadFunctionsPass();
246
Ben Claytonb73b7602019-07-29 13:56:13 +0100247// Creates an eliminate-dead-members pass.
248// An eliminate-dead-members pass will remove all unused members of structures.
249// This will not affect the data layout of the remaining members.
250Optimizer::PassToken CreateEliminateDeadMembersPass();
251
Chris Forbescc5697f2019-01-30 11:54:08 -0800252// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
253// to the default values in the form of string.
254// A set-spec-constant-default-value pass sets the default values for the
255// spec constants that have SpecId decorations (i.e., those defined by
256// OpSpecConstant{|True|False} instructions).
257Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
258 const std::unordered_map<uint32_t, std::string>& id_value_map);
259
260// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
261// to the default values in the form of bit pattern.
262// A set-spec-constant-default-value pass sets the default values for the
263// spec constants that have SpecId decorations (i.e., those defined by
264// OpSpecConstant{|True|False} instructions).
265Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
266 const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map);
267
268// Creates a flatten-decoration pass.
269// A flatten-decoration pass replaces grouped decorations with equivalent
270// ungrouped decorations. That is, it replaces each OpDecorationGroup
271// instruction and associated OpGroupDecorate and OpGroupMemberDecorate
272// instructions with equivalent OpDecorate and OpMemberDecorate instructions.
273// The pass does not attempt to preserve debug information for instructions
274// it removes.
275Optimizer::PassToken CreateFlattenDecorationPass();
276
277// Creates a freeze-spec-constant-value pass.
278// A freeze-spec-constant pass specializes the value of spec constants to
279// their default values. This pass only processes the spec constants that have
280// SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or
281// OpSpecConstantFalse instructions) and replaces them with their normal
282// counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The
283// corresponding SpecId annotation instructions will also be removed. This
284// pass does not fold the newly added normal constants and does not process
285// other spec constants defined by OpSpecConstantComposite or
286// OpSpecConstantOp.
287Optimizer::PassToken CreateFreezeSpecConstantValuePass();
288
289// Creates a fold-spec-constant-op-and-composite pass.
290// A fold-spec-constant-op-and-composite pass folds spec constants defined by
291// OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants
292// defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or
293// OpConstantComposite instructions. Note that spec constants defined with
294// OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are
295// not handled, as these instructions indicate their value are not determined
296// and can be changed in future. A spec constant is foldable if all of its
297// value(s) can be determined from the module. E.g., an integer spec constant
298// defined with OpSpecConstantOp instruction can be folded if its value won't
sugoi1b398bf32022-02-18 10:27:28 -0500299// change later. This pass will replace the original OpSpecConstantOp
300// instruction with an OpConstant instruction. When folding composite spec
301// constants, new instructions may be inserted to define the components of the
302// composite constant first, then the original spec constants will be replaced
303// by OpConstantComposite instructions.
Chris Forbescc5697f2019-01-30 11:54:08 -0800304//
305// There are some operations not supported yet:
306// OpSConvert, OpFConvert, OpQuantizeToF16 and
307// all the operations under Kernel capability.
308// TODO(qining): Add support for the operations listed above.
309Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass();
310
311// Creates a unify-constant pass.
312// A unify-constant pass de-duplicates the constants. Constants with the exact
313// same value and identical form will be unified and only one constant will
314// be kept for each unique pair of type and value.
315// There are several cases not handled by this pass:
316// 1) Constants defined by OpConstantNull instructions (null constants) and
317// constants defined by OpConstantFalse, OpConstant or OpConstantComposite
318// with value 0 (zero-valued normal constants) are not considered equivalent.
319// So null constants won't be used to replace zero-valued normal constants,
320// vice versa.
321// 2) Whenever there are decorations to the constant's result id id, the
322// constant won't be handled, which means, it won't be used to replace any
323// other constants, neither can other constants replace it.
324// 3) NaN in float point format with different bit patterns are not unified.
325Optimizer::PassToken CreateUnifyConstantPass();
326
327// Creates a eliminate-dead-constant pass.
328// A eliminate-dead-constant pass removes dead constants, including normal
sugoi1b398bf32022-02-18 10:27:28 -0500329// constants defined by OpConstant, OpConstantComposite, OpConstantTrue, or
Chris Forbescc5697f2019-01-30 11:54:08 -0800330// OpConstantFalse and spec constants defined by OpSpecConstant,
331// OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or
332// OpSpecConstantOp.
333Optimizer::PassToken CreateEliminateDeadConstantPass();
334
335// Creates a strength-reduction pass.
336// A strength-reduction pass will look for opportunities to replace an
337// instruction with an equivalent and less expensive one. For example,
338// multiplying by a power of 2 can be replaced by a bit shift.
339Optimizer::PassToken CreateStrengthReductionPass();
340
341// Creates a block merge pass.
342// This pass searches for blocks with a single Branch to a block with no
343// other predecessors and merges the blocks into a single block. Continue
344// blocks and Merge blocks are not candidates for the second block.
345//
346// The pass is most useful after Dead Branch Elimination, which can leave
347// such sequences of blocks. Merging them makes subsequent passes more
348// effective, such as single block local store-load elimination.
349//
350// While this pass reduces the number of occurrences of this sequence, at
351// this time it does not guarantee all such sequences are eliminated.
352//
353// Presence of phi instructions can inhibit this optimization. Handling
354// these is left for future improvements.
355Optimizer::PassToken CreateBlockMergePass();
356
357// Creates an exhaustive inline pass.
358// An exhaustive inline pass attempts to exhaustively inline all function
359// calls in all functions in an entry point call tree. The intent is to enable,
360// albeit through brute force, analysis and optimization across function
361// calls by subsequent optimization passes. As the inlining is exhaustive,
362// there is no attempt to optimize for size or runtime performance. Functions
363// that are not in the call tree of an entry point are not changed.
364Optimizer::PassToken CreateInlineExhaustivePass();
365
366// Creates an opaque inline pass.
367// An opaque inline pass inlines all function calls in all functions in all
368// entry point call trees where the called function contains an opaque type
369// in either its parameter types or return type. An opaque type is currently
370// defined as Image, Sampler or SampledImage. The intent is to enable, albeit
371// through brute force, analysis and optimization across these function calls
372// by subsequent passes in order to remove the storing of opaque types which is
373// not legal in Vulkan. Functions that are not in the call tree of an entry
374// point are not changed.
375Optimizer::PassToken CreateInlineOpaquePass();
376
377// Creates a single-block local variable load/store elimination pass.
378// For every entry point function, do single block memory optimization of
379// function variables referenced only with non-access-chain loads and stores.
380// For each targeted variable load, if previous store to that variable in the
381// block, replace the load's result id with the value id of the store.
382// If previous load within the block, replace the current load's result id
383// with the previous load's result id. In either case, delete the current
384// load. Finally, check if any remaining stores are useless, and delete store
385// and variable if possible.
386//
387// The presence of access chain references and function calls can inhibit
388// the above optimization.
389//
390// Only modules with relaxed logical addressing (see opt/instruction.h) are
391// currently processed.
392//
sugoi1b398bf32022-02-18 10:27:28 -0500393// This pass is most effective if preceded by Inlining and
Chris Forbescc5697f2019-01-30 11:54:08 -0800394// LocalAccessChainConvert. This pass will reduce the work needed to be done
395// by LocalSingleStoreElim and LocalMultiStoreElim.
396//
397// Only functions in the call tree of an entry point are processed.
398Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass();
399
400// Create dead branch elimination pass.
401// For each entry point function, this pass will look for SelectionMerge
402// BranchConditionals with constant condition and convert to a Branch to
403// the indicated label. It will delete resulting dead blocks.
404//
405// For all phi functions in merge block, replace all uses with the id
406// corresponding to the living predecessor.
407//
408// Note that some branches and blocks may be left to avoid creating invalid
409// control flow. Improving this is left to future work.
410//
sugoi1b398bf32022-02-18 10:27:28 -0500411// This pass is most effective when preceded by passes which eliminate
Chris Forbescc5697f2019-01-30 11:54:08 -0800412// local loads and stores, effectively propagating constant values where
413// possible.
414Optimizer::PassToken CreateDeadBranchElimPass();
415
416// Creates an SSA local variable load/store elimination pass.
417// For every entry point function, eliminate all loads and stores of function
418// scope variables only referenced with non-access-chain loads and stores.
419// Eliminate the variables as well.
420//
421// The presence of access chain references and function calls can inhibit
422// the above optimization.
423//
424// Only shader modules with relaxed logical addressing (see opt/instruction.h)
425// are currently processed. Currently modules with any extensions enabled are
426// not processed. This is left for future work.
427//
sugoi1b398bf32022-02-18 10:27:28 -0500428// This pass is most effective if preceded by Inlining and
Chris Forbescc5697f2019-01-30 11:54:08 -0800429// LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
430// will reduce the work that this pass has to do.
431Optimizer::PassToken CreateLocalMultiStoreElimPass();
432
433// Creates a local access chain conversion pass.
434// A local access chain conversion pass identifies all function scope
435// variables which are accessed only with loads, stores and access chains
436// with constant indices. It then converts all loads and stores of such
437// variables into equivalent sequences of loads, stores, extracts and inserts.
438//
439// This pass only processes entry point functions. It currently only converts
440// non-nested, non-ptr access chains. It does not process modules with
441// non-32-bit integer types present. Optional memory access options on loads
442// and stores are ignored as we are only processing function scope variables.
443//
444// This pass unifies access to these variables to a single mode and simplifies
445// subsequent analysis and elimination of these variables along with their
446// loads and stores allowing values to propagate to their points of use where
447// possible.
448Optimizer::PassToken CreateLocalAccessChainConvertPass();
449
450// Creates a local single store elimination pass.
451// For each entry point function, this pass eliminates loads and stores for
452// function scope variable that are stored to only once, where possible. Only
453// whole variable loads and stores are eliminated; access-chain references are
454// not optimized. Replace all loads of such variables with the value that is
455// stored and eliminate any resulting dead code.
456//
457// Currently, the presence of access chains and function calls can inhibit this
458// pass, however the Inlining and LocalAccessChainConvert passes can make it
459// more effective. In additional, many non-load/store memory operations are
460// not supported and will prohibit optimization of a function. Support of
461// these operations are future work.
462//
463// Only shader modules with relaxed logical addressing (see opt/instruction.h)
464// are currently processed.
465//
466// This pass will reduce the work needed to be done by LocalSingleBlockElim
467// and LocalMultiStoreElim and can improve the effectiveness of other passes
468// such as DeadBranchElimination which depend on values for their analysis.
469Optimizer::PassToken CreateLocalSingleStoreElimPass();
470
471// Creates an insert/extract elimination pass.
472// This pass processes each entry point function in the module, searching for
473// extracts on a sequence of inserts. It further searches the sequence for an
474// insert with indices identical to the extract. If such an insert can be
475// found before hitting a conflicting insert, the extract's result id is
476// replaced with the id of the values from the insert.
477//
478// Besides removing extracts this pass enables subsequent dead code elimination
479// passes to delete the inserts. This pass performs best after access chains are
480// converted to inserts and extracts and local loads and stores are eliminated.
481Optimizer::PassToken CreateInsertExtractElimPass();
482
483// Creates a dead insert elimination pass.
484// This pass processes each entry point function in the module, searching for
485// unreferenced inserts into composite types. These are most often unused
486// stores to vector components. They are unused because they are never
487// referenced, or because there is another insert to the same component between
488// the insert and the reference. After removing the inserts, dead code
489// elimination is attempted on the inserted values.
490//
491// This pass performs best after access chains are converted to inserts and
492// extracts and local loads and stores are eliminated. While executing this
493// pass can be advantageous on its own, it is also advantageous to execute
494// this pass after CreateInsertExtractPass() as it will remove any unused
495// inserts created by that pass.
496Optimizer::PassToken CreateDeadInsertElimPass();
497
Chris Forbescc5697f2019-01-30 11:54:08 -0800498// Create aggressive dead code elimination pass
499// This pass eliminates unused code from the module. In addition,
500// it detects and eliminates code which may have spurious uses but which do
501// not contribute to the output of the function. The most common cause of
502// such code sequences is summations in loops whose result is no longer used
503// due to dead code elimination. This optimization has additional compile
504// time cost over standard dead code elimination.
505//
506// This pass only processes entry point functions. It also only processes
507// shaders with relaxed logical addressing (see opt/instruction.h). It
508// currently will not process functions with function calls. Unreachable
509// functions are deleted.
510//
511// This pass will be made more effective by first running passes that remove
512// dead control flow and inlines function calls.
513//
514// This pass can be especially useful after running Local Access Chain
515// Conversion, which tends to cause cycles of dead code to be left after
516// Store/Load elimination passes are completed. These cycles cannot be
517// eliminated with standard dead code elimination.
Alexis Hetu00e0af12021-11-08 08:57:46 -0500518//
519// If |preserve_interface| is true, all non-io variables in the entry point
520// interface are considered live and are not eliminated. This mode is needed
521// by GPU-Assisted validation instrumentation, where a change in the interface
522// is not allowed.
sugoi1b398bf32022-02-18 10:27:28 -0500523Optimizer::PassToken CreateAggressiveDCEPass();
524Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface);
Alexis Hetu00e0af12021-11-08 08:57:46 -0500525
526// Creates a remove-unused-interface-variables pass.
527// Removes variables referenced on the |OpEntryPoint| instruction that are not
528// referenced in the entry point function or any function in its call tree. Note
529// that this could cause the shader interface to no longer match other shader
530// stages.
531Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass();
Chris Forbescc5697f2019-01-30 11:54:08 -0800532
Alexis Hetu7975f152020-11-02 11:08:33 -0500533// Creates an empty pass.
534// This is deprecated and will be removed.
535// TODO(jaebaek): remove this pass after handling glslang's broken unit tests.
536// https://github.com/KhronosGroup/glslang/pull/2440
537Optimizer::PassToken CreatePropagateLineInfoPass();
538
539// Creates an empty pass.
540// This is deprecated and will be removed.
541// TODO(jaebaek): remove this pass after handling glslang's broken unit tests.
542// https://github.com/KhronosGroup/glslang/pull/2440
543Optimizer::PassToken CreateRedundantLineInfoElimPass();
544
Chris Forbescc5697f2019-01-30 11:54:08 -0800545// Creates a compact ids pass.
546// The pass remaps result ids to a compact and gapless range starting from %1.
547Optimizer::PassToken CreateCompactIdsPass();
548
549// Creates a remove duplicate pass.
550// This pass removes various duplicates:
551// * duplicate capabilities;
552// * duplicate extended instruction imports;
553// * duplicate types;
554// * duplicate decorations.
555Optimizer::PassToken CreateRemoveDuplicatesPass();
556
557// Creates a CFG cleanup pass.
558// This pass removes cruft from the control flow graph of functions that are
559// reachable from entry points and exported functions. It currently includes the
560// following functionality:
561//
562// - Removal of unreachable basic blocks.
563Optimizer::PassToken CreateCFGCleanupPass();
564
565// Create dead variable elimination pass.
566// This pass will delete module scope variables, along with their decorations,
567// that are not referenced.
568Optimizer::PassToken CreateDeadVariableEliminationPass();
569
570// create merge return pass.
571// changes functions that have multiple return statements so they have a single
572// return statement.
573//
574// for structured control flow it is assumed that the only unreachable blocks in
575// the function are trivial merge and continue blocks.
576//
577// a trivial merge block contains the label and an opunreachable instructions,
578// nothing else. a trivial continue block contain a label and an opbranch to
579// the header, nothing else.
580//
581// these conditions are guaranteed to be met after running dead-branch
582// elimination.
583Optimizer::PassToken CreateMergeReturnPass();
584
585// Create value numbering pass.
586// This pass will look for instructions in the same basic block that compute the
587// same value, and remove the redundant ones.
588Optimizer::PassToken CreateLocalRedundancyEliminationPass();
589
590// Create LICM pass.
591// This pass will look for invariant instructions inside loops and hoist them to
592// the loops preheader.
593Optimizer::PassToken CreateLoopInvariantCodeMotionPass();
594
595// Creates a loop fission pass.
596// This pass will split all top level loops whose register pressure exceedes the
597// given |threshold|.
598Optimizer::PassToken CreateLoopFissionPass(size_t threshold);
599
600// Creates a loop fusion pass.
601// This pass will look for adjacent loops that are compatible and legal to be
602// fused. The fuse all such loops as long as the register usage for the fused
603// loop stays under the threshold defined by |max_registers_per_loop|.
604Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop);
605
606// Creates a loop peeling pass.
607// This pass will look for conditions inside a loop that are true or false only
608// for the N first or last iteration. For loop with such condition, those N
609// iterations of the loop will be executed outside of the main loop.
610// To limit code size explosion, the loop peeling can only happen if the code
611// size growth for each loop is under |code_growth_threshold|.
612Optimizer::PassToken CreateLoopPeelingPass();
613
614// Creates a loop unswitch pass.
615// This pass will look for loop independent branch conditions and move the
616// condition out of the loop and version the loop based on the taken branch.
617// Works best after LICM and local multi store elimination pass.
618Optimizer::PassToken CreateLoopUnswitchPass();
619
620// Create global value numbering pass.
621// This pass will look for instructions where the same value is computed on all
622// paths leading to the instruction. Those instructions are deleted.
623Optimizer::PassToken CreateRedundancyEliminationPass();
624
625// Create scalar replacement pass.
626// This pass replaces composite function scope variables with variables for each
627// element if those elements are accessed individually. The parameter is a
628// limit on the number of members in the composite variable that the pass will
629// consider replacing.
630Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100);
631
632// Create a private to local pass.
sugoi1b398bf32022-02-18 10:27:28 -0500633// This pass looks for variables declared in the private storage class that are
Chris Forbescc5697f2019-01-30 11:54:08 -0800634// used in only one function. Those variables are moved to the function storage
635// class in the function that they are used.
636Optimizer::PassToken CreatePrivateToLocalPass();
637
638// Creates a conditional constant propagation (CCP) pass.
639// This pass implements the SSA-CCP algorithm in
640//
641// Constant propagation with conditional branches,
642// Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
643//
644// Constant values in expressions and conditional jumps are folded and
645// simplified. This may reduce code size by removing never executed jump targets
646// and computations with constant operands.
647Optimizer::PassToken CreateCCPPass();
648
649// Creates a workaround driver bugs pass. This pass attempts to work around
650// a known driver bug (issue #1209) by identifying the bad code sequences and
651// rewriting them.
652//
653// Current workaround: Avoid OpUnreachable instructions in loops.
654Optimizer::PassToken CreateWorkaround1209Pass();
655
656// Creates a pass that converts if-then-else like assignments into OpSelect.
657Optimizer::PassToken CreateIfConversionPass();
658
659// Creates a pass that will replace instructions that are not valid for the
660// current shader stage by constants. Has no effect on non-shader modules.
661Optimizer::PassToken CreateReplaceInvalidOpcodePass();
662
663// Creates a pass that simplifies instructions using the instruction folder.
664Optimizer::PassToken CreateSimplificationPass();
665
666// Create loop unroller pass.
667// Creates a pass to unroll loops which have the "Unroll" loop control
668// mask set. The loops must meet a specific criteria in order to be unrolled
669// safely this criteria is checked before doing the unroll by the
670// LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria
671// won't be unrolled. See CanPerformUnroll LoopUtils.h for more information.
672Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0);
673
674// Create the SSA rewrite pass.
675// This pass converts load/store operations on function local variables into
676// operations on SSA IDs. This allows SSA optimizers to act on these variables.
677// Only variables that are local to the function and of supported types are
678// processed (see IsSSATargetVar for details).
679Optimizer::PassToken CreateSSARewritePass();
680
Ben Claytond552f632019-11-18 11:18:41 +0000681// Create pass to convert relaxed precision instructions to half precision.
682// This pass converts as many relaxed float32 arithmetic operations to half as
683// possible. It converts any float32 operands to half if needed. It converts
684// any resulting half precision values back to float32 as needed. No variables
685// are changed. No image operations are changed.
686//
Ben Clayton0b54f132020-01-06 13:38:54 +0000687// Best if run after function scope store/load and composite operation
688// eliminations are run. Also best if followed by instruction simplification,
689// redundancy elimination and DCE.
Ben Claytond552f632019-11-18 11:18:41 +0000690Optimizer::PassToken CreateConvertRelaxedToHalfPass();
691
692// Create relax float ops pass.
693// This pass decorates all float32 result instructions with RelaxedPrecision
694// if not already so decorated.
695Optimizer::PassToken CreateRelaxFloatOpsPass();
696
Chris Forbescc5697f2019-01-30 11:54:08 -0800697// Create copy propagate arrays pass.
698// This pass looks to copy propagate memory references for arrays. It looks
699// for specific code patterns to recognize array copies.
700Optimizer::PassToken CreateCopyPropagateArraysPass();
701
702// Create a vector dce pass.
703// This pass looks for components of vectors that are unused, and removes them
704// from the vector. Note this would still leave around lots of dead code that
705// a pass of ADCE will be able to remove.
706Optimizer::PassToken CreateVectorDCEPass();
707
708// Create a pass to reduce the size of loads.
709// This pass looks for loads of structures where only a few of its members are
710// used. It replaces the loads feeding an OpExtract with an OpAccessChain and
Alexis Hetu00e0af12021-11-08 08:57:46 -0500711// a load of the specific elements. The parameter is a threshold to determine
712// whether we have to replace the load or not. If the ratio of the used
713// components of the load is less than the threshold, we replace the load.
714Optimizer::PassToken CreateReduceLoadSizePass(
715 double load_replacement_threshold = 0.9);
Chris Forbescc5697f2019-01-30 11:54:08 -0800716
717// Create a pass to combine chained access chains.
718// This pass looks for access chains fed by other access chains and combines
719// them into a single instruction where possible.
720Optimizer::PassToken CreateCombineAccessChainsPass();
721
722// Create a pass to instrument bindless descriptor checking
723// This pass instruments all bindless references to check that descriptor
Ben Claytonb73b7602019-07-29 13:56:13 +0100724// array indices are inbounds, and if the descriptor indexing extension is
725// enabled, that the descriptor has been initialized. If the reference is
726// invalid, a record is written to the debug output buffer (if space allows)
727// and a null value is returned. This pass is designed to support bindless
728// validation in the Vulkan validation layers.
729//
730// TODO(greg-lunarg): Add support for buffer references. Currently only does
731// checking for image references.
Chris Forbescc5697f2019-01-30 11:54:08 -0800732//
733// Dead code elimination should be run after this pass as the original,
734// potentially invalid code is not removed and could cause undefined behavior,
735// including crashes. It may also be beneficial to run Simplification
736// (ie Constant Propagation), DeadBranchElim and BlockMerge after this pass to
737// optimize instrument code involving the testing of compile-time constants.
738// It is also generally recommended that this pass (and all
739// instrumentation passes) be run after any legalization and optimization
740// passes. This will give better analysis for the instrumentation and avoid
741// potentially de-optimizing the instrument code, for example, inlining
742// the debug record output function throughout the module.
743//
744// The instrumentation will read and write buffers in debug
745// descriptor set |desc_set|. It will write |shader_id| in each output record
746// to identify the shader module which generated the record.
Ben Clayton745997b2021-01-21 22:51:51 +0000747// |desc_length_enable| controls instrumentation of runtime descriptor array
748// references, |desc_init_enable| controls instrumentation of descriptor
749// initialization checking, and |buff_oob_enable| controls instrumentation
750// of storage and uniform buffer bounds checking, all of which require input
751// buffer support. |texbuff_oob_enable| controls instrumentation of texel
752// buffers, which does not require input buffer support.
Ben Claytonb73b7602019-07-29 13:56:13 +0100753Optimizer::PassToken CreateInstBindlessCheckPass(
Ben Clayton745997b2021-01-21 22:51:51 +0000754 uint32_t desc_set, uint32_t shader_id, bool desc_length_enable = false,
755 bool desc_init_enable = false, bool buff_oob_enable = false,
756 bool texbuff_oob_enable = false);
Chris Forbescc5697f2019-01-30 11:54:08 -0800757
Ben Claytond0f684e2019-08-30 22:36:08 +0100758// Create a pass to instrument physical buffer address checking
759// This pass instruments all physical buffer address references to check that
760// all referenced bytes fall in a valid buffer. If the reference is
761// invalid, a record is written to the debug output buffer (if space allows)
762// and a null value is returned. This pass is designed to support buffer
763// address validation in the Vulkan validation layers.
764//
765// Dead code elimination should be run after this pass as the original,
766// potentially invalid code is not removed and could cause undefined behavior,
767// including crashes. Instruction simplification would likely also be
768// beneficial. It is also generally recommended that this pass (and all
769// instrumentation passes) be run after any legalization and optimization
770// passes. This will give better analysis for the instrumentation and avoid
771// potentially de-optimizing the instrument code, for example, inlining
772// the debug record output function throughout the module.
773//
774// The instrumentation will read and write buffers in debug
775// descriptor set |desc_set|. It will write |shader_id| in each output record
776// to identify the shader module which generated the record.
Ben Claytond0f684e2019-08-30 22:36:08 +0100777Optimizer::PassToken CreateInstBuffAddrCheckPass(uint32_t desc_set,
Ben Clayton38e46912020-05-26 15:56:15 +0100778 uint32_t shader_id);
Ben Claytond0f684e2019-08-30 22:36:08 +0100779
Alexis Hetub8a77462020-03-27 07:59:09 -0400780// Create a pass to instrument OpDebugPrintf instructions.
781// This pass replaces all OpDebugPrintf instructions with instructions to write
782// a record containing the string id and the all specified values into a special
783// printf output buffer (if space allows). This pass is designed to support
784// the printf validation in the Vulkan validation layers.
785//
786// The instrumentation will write buffers in debug descriptor set |desc_set|.
787// It will write |shader_id| in each output record to identify the shader
788// module which generated the record.
789Optimizer::PassToken CreateInstDebugPrintfPass(uint32_t desc_set,
790 uint32_t shader_id);
791
Chris Forbescc5697f2019-01-30 11:54:08 -0800792// Create a pass to upgrade to the VulkanKHR memory model.
793// This pass upgrades the Logical GLSL450 memory model to Logical VulkanKHR.
794// Additionally, it modifies memory, image, atomic and barrier operations to
795// conform to that model's requirements.
796Optimizer::PassToken CreateUpgradeMemoryModelPass();
797
798// Create a pass to do code sinking. Code sinking is a transformation
799// where an instruction is moved into a more deeply nested construct.
800Optimizer::PassToken CreateCodeSinkingPass();
801
Ben Claytonb73b7602019-07-29 13:56:13 +0100802// Create a pass to fix incorrect storage classes. In order to make code
803// generation simpler, DXC may generate code where the storage classes do not
804// match up correctly. This pass will fix the errors that it can.
805Optimizer::PassToken CreateFixStorageClassPass();
806
Ben Claytond0f684e2019-08-30 22:36:08 +0100807// Creates a graphics robust access pass.
808//
809// This pass injects code to clamp indexed accesses to buffers and internal
810// arrays, providing guarantees satisfying Vulkan's robustBufferAccess rules.
811//
812// TODO(dneto): Clamps coordinates and sample index for pointer calculations
813// into storage images (OpImageTexelPointer). For an cube array image, it
814// assumes the maximum layer count times 6 is at most 0xffffffff.
815//
816// NOTE: This pass will fail with a message if:
817// - The module is not a Shader module.
818// - The module declares VariablePointers, VariablePointersStorageBuffer, or
819// RuntimeDescriptorArrayEXT capabilities.
820// - The module uses an addressing model other than Logical
821// - Access chain indices are wider than 64 bits.
822// - Access chain index for a struct is not an OpConstant integer or is out
823// of range. (The module is already invalid if that is the case.)
824// - TODO(dneto): The OpImageTexelPointer coordinate component is not 32-bits
825// wide.
Ben Clayton0b54f132020-01-06 13:38:54 +0000826//
827// NOTE: Access chain indices are always treated as signed integers. So
828// if an array has a fixed size of more than 2^31 elements, then elements
829// from 2^31 and above are never accessible with a 32-bit index,
830// signed or unsigned. For this case, this pass will clamp the index
831// between 0 and at 2^31-1, inclusive.
832// Similarly, if an array has more then 2^15 element and is accessed with
833// a 16-bit index, then elements from 2^15 and above are not accessible.
834// In this case, the pass will clamp the index between 0 and 2^15-1
835// inclusive.
Ben Claytond0f684e2019-08-30 22:36:08 +0100836Optimizer::PassToken CreateGraphicsRobustAccessPass();
837
sugoi1b398bf32022-02-18 10:27:28 -0500838// Create a pass to spread Volatile semantics to variables with SMIDNV,
839// WarpIDNV, SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask,
840// SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask BuiltIn
841// decorations or OpLoad for them when the shader model is the ray generation,
842// closest hit, miss, intersection, or callable. This pass can be used for
843// VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
844// VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
845// Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
846// SPIR-V"). When the SPIR-V version is 1.6 or above, the pass also spreads
847// the Volatile semantics to a variable with HelperInvocation BuiltIn decoration
848// in the fragement shader.
849Optimizer::PassToken CreateSpreadVolatileSemanticsPass();
850
Alexis Hetu00e0af12021-11-08 08:57:46 -0500851// Create a pass to replace a descriptor access using variable index.
852// This pass replaces every access using a variable index to array variable
853// |desc| that has a DescriptorSet and Binding decorations with a constant
854// element of the array. In order to replace the access using a variable index
855// with the constant element, it uses a switch statement.
856Optimizer::PassToken CreateReplaceDescArrayAccessUsingVarIndexPass();
857
Ben Claytond0f684e2019-08-30 22:36:08 +0100858// Create descriptor scalar replacement pass.
859// This pass replaces every array variable |desc| that has a DescriptorSet and
860// Binding decorations with a new variable for each element of the array.
861// Suppose |desc| was bound at binding |b|. Then the variable corresponding to
862// |desc[i]| will have binding |b+i|. The descriptor set will be the same. It
863// is assumed that no other variable already has a binding that will used by one
864// of the new variables. If not, the pass will generate invalid Spir-V. All
865// accesses to |desc| must be OpAccessChain instructions with a literal index
866// for the first index.
867Optimizer::PassToken CreateDescriptorScalarReplacementPass();
868
Alexis Hetuc00ee6c2020-07-27 10:48:25 -0400869// Create a pass to replace each OpKill instruction with a function call to a
870// function that has a single OpKill. Also replace each OpTerminateInvocation
871// instruction with a function call to a function that has a single
872// OpTerminateInvocation. This allows more code to be inlined.
Ben Claytond0f684e2019-08-30 22:36:08 +0100873Optimizer::PassToken CreateWrapOpKillPass();
874
875// Replaces the extensions VK_AMD_shader_ballot,VK_AMD_gcn_shader, and
876// VK_AMD_shader_trinary_minmax with equivalent code using core instructions and
877// capabilities.
878Optimizer::PassToken CreateAmdExtToKhrPass();
879
Alexis Hetu00e0af12021-11-08 08:57:46 -0500880// Replaces the internal version of GLSLstd450 InterpolateAt* extended
881// instructions with the externally valid version. The internal version allows
882// an OpLoad of the interpolant for the first argument. This pass removes the
883// OpLoad and replaces it with its pointer. glslang and possibly other
884// frontends will create the internal version for HLSL. This pass will be part
885// of HLSL legalization and should be called after interpolants have been
886// propagated into their final positions.
887Optimizer::PassToken CreateInterpolateFixupPass();
888
Nicolas Capens4111ae92022-03-23 12:23:11 -0400889// Removes unused components from composite input variables. Current
890// implementation just removes trailing unused components from input arrays.
891// The pass performs best after maximizing dead code removal. A subsequent dead
892// code elimination pass would be beneficial in removing newly unused component
893// types.
894Optimizer::PassToken CreateEliminateDeadInputComponentsPass();
895
Alexis Hetu00e0af12021-11-08 08:57:46 -0500896// Creates a convert-to-sampled-image pass to convert images and/or
897// samplers with given pairs of descriptor set and binding to sampled image.
898// If a pair of an image and a sampler have the same pair of descriptor set and
899// binding that is one of the given pairs, they will be converted to a sampled
900// image. In addition, if only an image has the descriptor set and binding that
901// is one of the given pairs, it will be converted to a sampled image as well.
902Optimizer::PassToken CreateConvertToSampledImagePass(
903 const std::vector<opt::DescriptorSetAndBinding>&
904 descriptor_set_binding_pairs);
905
Nicolas Capens9cbc5e22022-03-08 13:03:25 -0500906// Creates a remove-dont-inline pass to remove the |DontInline| function control
907// from every function in the module. This is useful if you want the inliner to
908// inline these functions some reason.
909Optimizer::PassToken CreateRemoveDontInlinePass();
Chris Forbescc5697f2019-01-30 11:54:08 -0800910} // namespace spvtools
911
912#endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_