optimizer.hpp 50 KB

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