blob: 5d2e306e2d76214b33e56e8b61ad4ed3bbb904a9 [file] [log] [blame]
Lei Zhangf18e1f22016-09-12 14:11:46 -04001// 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 SPIRV_TOOLS_OPTIMIZER_HPP_
16#define SPIRV_TOOLS_OPTIMIZER_HPP_
17
18#include <memory>
19#include <string>
20#include <unordered_map>
21#include <vector>
22
23#include "libspirv.hpp"
Lei Zhangf18e1f22016-09-12 14:11:46 -040024
25namespace spvtools {
26
27// C++ interface for SPIR-V optimization functionalities. It wraps the context
28// (including target environment and the corresponding SPIR-V grammar) and
29// provides methods for registering optimization passes and optimizing.
30//
31// Instances of this class provides basic thread-safety guarantee.
32class Optimizer {
33 public:
34 // The token for an optimization pass. It is returned via one of the
35 // Create*Pass() standalone functions at the end of this header file and
36 // consumed by the RegisterPass() method. Tokens are one-time objects that
37 // only support move; copying is not allowed.
38 struct PassToken {
39 struct Impl; // Opaque struct for holding inernal data.
40
41 PassToken(std::unique_ptr<Impl>);
42
43 // Tokens can only be moved. Copying is disabled.
44 PassToken(const PassToken&) = delete;
45 PassToken(PassToken&&);
46 PassToken& operator=(const PassToken&) = delete;
47 PassToken& operator=(PassToken&&);
48
49 ~PassToken();
50
51 std::unique_ptr<Impl> impl_; // Unique pointer to internal data.
52 };
53
54 // Constructs an instance with the given target |env|, which is used to decode
55 // the binaries to be optimized later.
56 //
57 // The constructed instance will have an empty message consumer, which just
58 // ignores all messages from the library. Use SetMessageConsumer() to supply
59 // one if messages are of concern.
60 explicit Optimizer(spv_target_env env);
61
62 // Disables copy/move constructor/assignment operations.
63 Optimizer(const Optimizer&) = delete;
64 Optimizer(Optimizer&&) = delete;
65 Optimizer& operator=(const Optimizer&) = delete;
66 Optimizer& operator=(Optimizer&&) = delete;
67
68 // Destructs this instance.
69 ~Optimizer();
70
71 // Sets the message consumer to the given |consumer|. The |consumer| will be
72 // invoked once for each message communicated from the library.
73 void SetMessageConsumer(MessageConsumer consumer);
74
75 // Registers the given |pass| to this optimizer. Passes will be run in the
76 // exact order of registration. The token passed in will be consumed by this
77 // method.
78 Optimizer& RegisterPass(PassToken&& pass);
79
Diego Novilloc90d7302017-08-30 14:19:22 -040080 // Registers passes that attempt to improve performance of generated code.
81 // This sequence of passes is subject to constant review and will change
82 // from time to time.
83 Optimizer& RegisterPerformancePasses();
84
85 // Registers passes that attempt to improve the size of generated code.
86 // This sequence of passes is subject to constant review and will change
87 // from time to time.
88 Optimizer& RegisterSizePasses();
89
Lei Zhangaec60b82017-11-17 16:50:43 -050090 // Registers passes that attempt to legalize the generated code.
91 //
92 // Note: this recipe is specially for legalizing SPIR-V. It should be used
93 // by compilers after translating HLSL source code literally. It should
94 // *not* be used by general workloads for performance or size improvement.
95 //
96 // This sequence of passes is subject to constant review and will change
97 // from time to time.
98 Optimizer& RegisterLegalizationPasses();
99
Lei Zhangf18e1f22016-09-12 14:11:46 -0400100 // Optimizes the given SPIR-V module |original_binary| and writes the
101 // optimized binary into |optimized_binary|.
102 // Returns true on successful optimization, whether or not the module is
103 // modified. Returns false if errors occur when processing |original_binary|
104 // using any of the registered passes. In that case, no further passes are
Diego Novilloc90d7302017-08-30 14:19:22 -0400105 // executed and the contents in |optimized_binary| may be invalid.
Lei Zhangf18e1f22016-09-12 14:11:46 -0400106 //
107 // It's allowed to alias |original_binary| to the start of |optimized_binary|.
108 bool Run(const uint32_t* original_binary, size_t original_binary_size,
109 std::vector<uint32_t>* optimized_binary) const;
110
Diego Novilloc90d7302017-08-30 14:19:22 -0400111 // Returns a vector of strings with all the pass names added to this
112 // optimizer's pass manager. These strings are valid until the associated
113 // pass manager is destroyed.
Steven Perron58347192017-10-20 12:17:41 -0400114 std::vector<const char*> GetPassNames() const;
Diego Novilloc90d7302017-08-30 14:19:22 -0400115
Lei Zhangf18e1f22016-09-12 14:11:46 -0400116 private:
117 struct Impl; // Opaque struct for holding internal data.
118 std::unique_ptr<Impl> impl_; // Unique pointer to internal data.
119};
120
121// Creates a null pass.
122// A null pass does nothing to the SPIR-V module to be optimized.
123Optimizer::PassToken CreateNullPass();
124
125// Creates a strip-debug-info pass.
126// A strip-debug-info pass removes all debug instructions (as documented in
127// Section 3.32.2 of the SPIR-V spec) of the SPIR-V module to be optimized.
128Optimizer::PassToken CreateStripDebugInfoPass();
129
Steven Perrone43c9102017-09-19 10:12:13 -0400130// Creates an eliminate-dead-functions pass.
Steven Perron58347192017-10-20 12:17:41 -0400131// An eliminate-dead-functions pass will remove all functions that are not in
132// the call trees rooted at entry points and exported functions. These
133// functions are not needed because they will never be called.
Steven Perrone43c9102017-09-19 10:12:13 -0400134Optimizer::PassToken CreateEliminateDeadFunctionsPass();
135
qining144f59e2017-04-19 18:10:59 -0400136// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
137// to the default values in the form of string.
Lei Zhangf18e1f22016-09-12 14:11:46 -0400138// A set-spec-constant-default-value pass sets the default values for the
139// spec constants that have SpecId decorations (i.e., those defined by
140// OpSpecConstant{|True|False} instructions).
141Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
142 const std::unordered_map<uint32_t, std::string>& id_value_map);
143
qining144f59e2017-04-19 18:10:59 -0400144// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
145// to the default values in the form of bit pattern.
146// A set-spec-constant-default-value pass sets the default values for the
147// spec constants that have SpecId decorations (i.e., those defined by
148// OpSpecConstant{|True|False} instructions).
149Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
150 const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map);
151
David Neto11a867f2017-04-01 16:10:16 -0400152// Creates a flatten-decoration pass.
153// A flatten-decoration pass replaces grouped decorations with equivalent
154// ungrouped decorations. That is, it replaces each OpDecorationGroup
155// instruction and associated OpGroupDecorate and OpGroupMemberDecorate
156// instructions with equivalent OpDecorate and OpMemberDecorate instructions.
157// The pass does not attempt to preserve debug information for instructions
158// it removes.
159Optimizer::PassToken CreateFlattenDecorationPass();
160
Lei Zhangf18e1f22016-09-12 14:11:46 -0400161// Creates a freeze-spec-constant-value pass.
162// A freeze-spec-constant pass specializes the value of spec constants to
163// their default values. This pass only processes the spec constants that have
164// SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or
165// OpSpecConstantFalse instructions) and replaces them with their normal
166// counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The
167// corresponding SpecId annotation instructions will also be removed. This
168// pass does not fold the newly added normal constants and does not process
169// other spec constants defined by OpSpecConstantComposite or
170// OpSpecConstantOp.
171Optimizer::PassToken CreateFreezeSpecConstantValuePass();
172
173// Creates a fold-spec-constant-op-and-composite pass.
174// A fold-spec-constant-op-and-composite pass folds spec constants defined by
175// OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants
176// defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or
177// OpConstantComposite instructions. Note that spec constants defined with
178// OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are
179// not handled, as these instructions indicate their value are not determined
180// and can be changed in future. A spec constant is foldable if all of its
181// value(s) can be determined from the module. E.g., an integer spec constant
182// defined with OpSpecConstantOp instruction can be folded if its value won't
183// change later. This pass will replace the original OpSpecContantOp instruction
184// with an OpConstant instruction. When folding composite spec constants,
185// new instructions may be inserted to define the components of the composite
186// constant first, then the original spec constants will be replaced by
187// OpConstantComposite instructions.
188//
189// There are some operations not supported yet:
190// OpSConvert, OpFConvert, OpQuantizeToF16 and
191// all the operations under Kernel capability.
192// TODO(qining): Add support for the operations listed above.
193Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass();
194
195// Creates a unify-constant pass.
196// A unify-constant pass de-duplicates the constants. Constants with the exact
197// same value and identical form will be unified and only one constant will
198// be kept for each unique pair of type and value.
199// There are several cases not handled by this pass:
200// 1) Constants defined by OpConstantNull instructions (null constants) and
201// constants defined by OpConstantFalse, OpConstant or OpConstantComposite
202// with value 0 (zero-valued normal constants) are not considered equivalent.
203// So null constants won't be used to replace zero-valued normal constants,
204// vice versa.
205// 2) Whenever there are decorations to the constant's result id id, the
206// constant won't be handled, which means, it won't be used to replace any
207// other constants, neither can other constants replace it.
208// 3) NaN in float point format with different bit patterns are not unified.
209Optimizer::PassToken CreateUnifyConstantPass();
210
211// Creates a eliminate-dead-constant pass.
212// A eliminate-dead-constant pass removes dead constants, including normal
213// contants defined by OpConstant, OpConstantComposite, OpConstantTrue, or
214// OpConstantFalse and spec constants defined by OpSpecConstant,
215// OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or
216// OpSpecConstantOp.
217Optimizer::PassToken CreateEliminateDeadConstantPass();
218
Steven Perrone4c7d8e2017-09-08 12:08:03 -0400219// Creates a strength-reduction pass.
220// A strength-reduction pass will look for opportunities to replace an
221// instruction with an equivalent and less expensive one. For example,
222// multiplying by a power of 2 can be replaced by a bit shift.
223Optimizer::PassToken CreateStrengthReductionPass();
224
GregFad1d0352017-06-07 15:28:53 -0600225// Creates a block merge pass.
226// This pass searches for blocks with a single Branch to a block with no
227// other predecessors and merges the blocks into a single block. Continue
228// blocks and Merge blocks are not candidates for the second block.
229//
230// The pass is most useful after Dead Branch Elimination, which can leave
231// such sequences of blocks. Merging them makes subsequent passes more
232// effective, such as single block local store-load elimination.
233//
234// While this pass reduces the number of occurrences of this sequence, at
235// this time it does not guarantee all such sequences are eliminated.
236//
237// Presence of phi instructions can inhibit this optimization. Handling
Steven Perrone43c9102017-09-19 10:12:13 -0400238// these is left for future improvements.
GregFad1d0352017-06-07 15:28:53 -0600239Optimizer::PassToken CreateBlockMergePass();
240
GregF429ca052017-08-15 17:58:28 -0600241// Creates an exhaustive inline pass.
242// An exhaustive inline pass attempts to exhaustively inline all function
243// calls in all functions in an entry point call tree. The intent is to enable,
244// albeit through brute force, analysis and optimization across function
245// calls by subsequent optimization passes. As the inlining is exhaustive,
246// there is no attempt to optimize for size or runtime performance. Functions
247// that are not in the call tree of an entry point are not changed.
GregFe28bd392017-08-01 17:20:13 -0600248Optimizer::PassToken CreateInlineExhaustivePass();
Steven Perrone43c9102017-09-19 10:12:13 -0400249
GregF429ca052017-08-15 17:58:28 -0600250// Creates an opaque inline pass.
251// An opaque inline pass inlines all function calls in all functions in all
252// entry point call trees where the called function contains an opaque type
253// in either its parameter types or return type. An opaque type is currently
254// defined as Image, Sampler or SampledImage. The intent is to enable, albeit
255// through brute force, analysis and optimization across these function calls
256// by subsequent passes in order to remove the storing of opaque types which is
257// not legal in Vulkan. Functions that are not in the call tree of an entry
258// point are not changed.
259Optimizer::PassToken CreateInlineOpaquePass();
Steven Perrone43c9102017-09-19 10:12:13 -0400260
GregF7c8da662017-05-18 14:51:55 -0600261// Creates a single-block local variable load/store elimination pass.
Steven Perrone43c9102017-09-19 10:12:13 -0400262// For every entry point function, do single block memory optimization of
GregF7c8da662017-05-18 14:51:55 -0600263// function variables referenced only with non-access-chain loads and stores.
264// For each targeted variable load, if previous store to that variable in the
265// block, replace the load's result id with the value id of the store.
266// If previous load within the block, replace the current load's result id
267// with the previous load's result id. In either case, delete the current
268// load. Finally, check if any remaining stores are useless, and delete store
269// and variable if possible.
270//
271// The presence of access chain references and function calls can inhibit
272// the above optimization.
273//
Steven Perron79a00642017-12-11 13:10:24 -0500274// Only modules with relaxed logical addressing (see opt/instruction.h) are
275// currently processed.
GregF7c8da662017-05-18 14:51:55 -0600276//
Steven Perrone43c9102017-09-19 10:12:13 -0400277// This pass is most effective if preceeded by Inlining and
GregF7c8da662017-05-18 14:51:55 -0600278// LocalAccessChainConvert. This pass will reduce the work needed to be done
GregFcc8bad32017-06-16 15:37:31 -0600279// by LocalSingleStoreElim and LocalMultiStoreElim.
GregF429ca052017-08-15 17:58:28 -0600280//
281// Only functions in the call tree of an entry point are processed.
GregF7c8da662017-05-18 14:51:55 -0600282Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass();
Greg Fischer04fcc662016-11-10 10:11:50 -0700283
GregF52e247f2017-06-02 13:23:20 -0600284// Create dead branch elimination pass.
285// For each entry point function, this pass will look for SelectionMerge
286// BranchConditionals with constant condition and convert to a Branch to
287// the indicated label. It will delete resulting dead blocks.
288//
Andrey Tuganov4b1577a2017-10-05 16:26:09 -0400289// For all phi functions in merge block, replace all uses with the id
290// corresponding to the living predecessor.
291//
GregF52e247f2017-06-02 13:23:20 -0600292// This pass only works on shaders (guaranteed to have structured control
293// flow). Note that some such branches and blocks may be left to avoid
294// creating invalid control flow. Improving this is left to future work.
295//
296// This pass is most effective when preceeded by passes which eliminate
297// local loads and stores, effectively propagating constant values where
298// possible.
299Optimizer::PassToken CreateDeadBranchElimPass();
300
GregFcc8bad32017-06-16 15:37:31 -0600301// Creates an SSA local variable load/store elimination pass.
302// For every entry point function, eliminate all loads and stores of function
303// scope variables only referenced with non-access-chain loads and stores.
Steven Perrone43c9102017-09-19 10:12:13 -0400304// Eliminate the variables as well.
GregFcc8bad32017-06-16 15:37:31 -0600305//
306// The presence of access chain references and function calls can inhibit
307// the above optimization.
308//
Steven Perron79a00642017-12-11 13:10:24 -0500309// Only shader modules with relaxed logical addressing (see opt/instruction.h)
310// are currently processed. Currently modules with any extensions enabled are
311// not processed. This is left for future work.
GregFcc8bad32017-06-16 15:37:31 -0600312//
Steven Perrone43c9102017-09-19 10:12:13 -0400313// This pass is most effective if preceeded by Inlining and
GregFcc8bad32017-06-16 15:37:31 -0600314// LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
315// will reduce the work that this pass has to do.
316Optimizer::PassToken CreateLocalMultiStoreElimPass();
317
GregFaa7e6872017-05-12 17:27:21 -0600318// Creates a local access chain conversion pass.
319// A local access chain conversion pass identifies all function scope
320// variables which are accessed only with loads, stores and access chains
321// with constant indices. It then converts all loads and stores of such
322// variables into equivalent sequences of loads, stores, extracts and inserts.
323//
324// This pass only processes entry point functions. It currently only converts
325// non-nested, non-ptr access chains. It does not process modules with
326// non-32-bit integer types present. Optional memory access options on loads
327// and stores are ignored as we are only processing function scope variables.
328//
329// This pass unifies access to these variables to a single mode and simplifies
330// subsequent analysis and elimination of these variables along with their
331// loads and stores allowing values to propagate to their points of use where
332// possible.
333Optimizer::PassToken CreateLocalAccessChainConvertPass();
334
GregF0c5722f2017-05-19 17:31:28 -0600335// Creates a local single store elimination pass.
Steven Perrone43c9102017-09-19 10:12:13 -0400336// For each entry point function, this pass eliminates loads and stores for
GregF0c5722f2017-05-19 17:31:28 -0600337// function scope variable that are stored to only once, where possible. Only
338// whole variable loads and stores are eliminated; access-chain references are
339// not optimized. Replace all loads of such variables with the value that is
340// stored and eliminate any resulting dead code.
341//
342// Currently, the presence of access chains and function calls can inhibit this
343// pass, however the Inlining and LocalAccessChainConvert passes can make it
344// more effective. In additional, many non-load/store memory operations are
345// not supported and will prohibit optimization of a function. Support of
346// these operations are future work.
347//
Steven Perron79a00642017-12-11 13:10:24 -0500348// Only shader modules with relaxed logical addressing (see opt/instruction.h)
349// are currently processed.
350//
GregF0c5722f2017-05-19 17:31:28 -0600351// This pass will reduce the work needed to be done by LocalSingleBlockElim
GregFcc8bad32017-06-16 15:37:31 -0600352// and LocalMultiStoreElim and can improve the effectiveness of other passes
353// such as DeadBranchElimination which depend on values for their analysis.
GregF0c5722f2017-05-19 17:31:28 -0600354Optimizer::PassToken CreateLocalSingleStoreElimPass();
355
GregF6136bf92017-05-26 10:33:11 -0600356// Creates an insert/extract elimination pass.
357// This pass processes each entry point function in the module, searching for
358// extracts on a sequence of inserts. It further searches the sequence for an
359// insert with indices identical to the extract. If such an insert can be
360// found before hitting a conflicting insert, the extract's result id is
361// replaced with the id of the values from the insert.
362//
363// Besides removing extracts this pass enables subsequent dead code elimination
364// passes to delete the inserts. This pass performs best after access chains are
365// converted to inserts and extracts and local loads and stores are eliminated.
366Optimizer::PassToken CreateInsertExtractElimPass();
367
GregFf4b29f32017-07-03 17:23:04 -0600368// Creates a pass to consolidate uniform references.
369// For each entry point function in the module, first change all constant index
Steven Perrone43c9102017-09-19 10:12:13 -0400370// access chain loads into equivalent composite extracts. Then consolidate
GregFf4b29f32017-07-03 17:23:04 -0600371// identical uniform loads into one uniform load. Finally, consolidate
372// identical uniform extracts into one uniform extract. This may require
373// moving a load or extract to a point which dominates all uses.
374//
375// This pass requires a module to have structured control flow ie shader
376// capability. It also requires logical addressing ie Addresses capability
377// is not enabled. It also currently does not support any extensions.
378//
379// This pass currently only optimizes loads with a single index.
380Optimizer::PassToken CreateCommonUniformElimPass();
381
GregF9de4e692017-06-08 10:37:21 -0600382// Create aggressive dead code elimination pass
383// This pass eliminates unused code from functions. In addition,
384// it detects and eliminates code which may have spurious uses but which do
385// not contribute to the output of the function. The most common cause of
386// such code sequences is summations in loops whose result is no longer used
387// due to dead code elimination. This optimization has additional compile
388// time cost over standard dead code elimination.
389//
390// This pass only processes entry point functions. It also only processes
Steven Perron79a00642017-12-11 13:10:24 -0500391// shaders with relaxed logical addressing (see opt/instruction.h). It currently
392// will not process functions with function calls.
GregF9de4e692017-06-08 10:37:21 -0600393//
394// This pass will be made more effective by first running passes that remove
395// dead control flow and inlines function calls.
396//
397// This pass can be especially useful after running Local Access Chain
398// Conversion, which tends to cause cycles of dead code to be left after
399// Store/Load elimination passes are completed. These cycles cannot be
400// eliminated with standard dead code elimination.
401Optimizer::PassToken CreateAggressiveDCEPass();
402
Andrey Tuganov1e309af2017-04-11 15:11:04 -0400403// Creates a compact ids pass.
404// The pass remaps result ids to a compact and gapless range starting from %1.
405Optimizer::PassToken CreateCompactIdsPass();
406
Pierre Moreau86627f72017-07-13 02:16:51 +0200407// Creates a remove duplicate capabilities pass.
408Optimizer::PassToken CreateRemoveDuplicatesPass();
409
Diego Novilloc75704e2017-09-06 08:56:41 -0400410// Creates a CFG cleanup pass.
411// This pass removes cruft from the control flow graph of functions that are
412// reachable from entry points and exported functions. It currently includes the
413// following functionality:
414//
415// - Removal of unreachable basic blocks.
416Optimizer::PassToken CreateCFGCleanupPass();
417
Steven Perron58347192017-10-20 12:17:41 -0400418// Create dead variable elimination pass.
419// This pass will delete module scope variables, along with their decorations,
420// that are not referenced.
421Optimizer::PassToken CreateDeadVariableEliminationPass();
422
Alan Bakera92d69b2017-11-08 16:22:10 -0500423// Create merge return pass.
424// This pass replaces all returns with unconditional branches to a new block
425// containing a return. If necessary, this new block will contain a PHI node to
426// select the correct return value.
427//
428// This pass does not consider unreachable code, nor does it perform any other
429// optimizations.
430//
431// This pass does not currently support structured control flow. It bails out if
432// the shader capability is detected.
433Optimizer::PassToken CreateMergeReturnPass();
434
Steven Perron28c41552017-11-10 20:26:55 -0500435// Create value numbering pass.
436// This pass will look for instructions in the same basic block that compute the
437// same value, and remove the redundant ones.
438Optimizer::PassToken CreateLocalRedundancyEliminationPass();
Steven Perron5d602ab2017-12-04 12:29:51 -0500439
440// Create global value numbering pass.
441// This pass will look for instructions where the same value is computed on all
442// paths leading to the instruction. Those instructions are deleted.
443Optimizer::PassToken CreateRedundancyEliminationPass();
Alan Baker867451f2017-11-30 17:03:06 -0500444
445// Create scalar replacement pass.
446// This pass replaces composite function scope variables with variables for each
447// element if those elements are accessed individually.
448Optimizer::PassToken CreateScalarReplacementPass();
Steven Perronb86eb682017-12-11 13:10:24 -0500449
450// Create a private to local pass.
451// This pass looks for variables delcared in the private storage class that are
452// used in only one function. Those variables are moved to the function storage
453// class in the function that they are used.
454Optimizer::PassToken CreatePrivateToLocalPass();
Lei Zhangf18e1f22016-09-12 14:11:46 -0400455} // namespace spvtools
456
457#endif // SPIRV_TOOLS_OPTIMIZER_HPP_