Commit Graph

2758 Commits

Author SHA1 Message Date
Steven Perron
d24a39a7f0
Do not remove control barrier after spv1.3 (#5174)
The control barrier instruction was allowed in a limiteted set of shader types.
Part of the HLSL legalization, we use to remove the instructions when it was is
a shader in which it was not allowed. As of spv1.3 that restriction is not long
there.

This change modifies replaced invalid opc to no longer remove it.

Fixes #4999.
2023-03-27 11:04:40 -04:00
Jeremy Hayes
b4e0850ef7
Ignore NonSemanticInstructions (#5171)
Fix #5163.

Ignore NonSemanticInstructions in DoDeadOutputStoresElimination and
ComputeLiveness.
2023-03-24 10:46:52 -06:00
Spencer Fricke
8e6563b913
spirv-val: Label new Vulkan VUID 07951 (#5154) 2023-03-18 01:01:50 +00:00
Alan Zhao
9743701ed5
Explicitly #include <utility> in spirv_target_env.cpp (#5159)
spirv_target_env.cpp uses std::pair, which is defined in utility.
Right now, this compiles because utility is provided via transitive
includes in other C++ standard library headers provided by the
implementation. However, these transitive includes are not guaranteed to
exist, and won't exist in certain cases (e.g. compiling against LLVM's
libc++ with modules enabled.)
2023-03-15 13:15:29 +01:00
Nathan Gauër
b029037aaa
Revert changes around CHANGES file. (#5143)
* Revert "build: allow update_build to generate fake version (#5098)"

This reverts commit 7823b8ff4a.

* Revert "build: stop parsing CHANGES file. (#5067)"

This reverts commit fcfc3c580c.
2023-03-09 18:24:20 +01:00
Laura Hermanns
bd83b772c3
Fix operand index out of bounds when folding OpCompositeExtract. (#5107)
GetExtractOperandsForElementOfCompositeConstruct() states "Returns the
empty vector if |result_index| is out-of-bounds", but violates that
contract for non-vector result types.
2023-03-03 15:52:49 +00:00
alan-baker
b955c468b1
Add missing header include (#5124)
* Found during an internal build
2023-02-24 13:21:53 -05:00
alan-baker
5d2bc6f064
Fix removal of dependent non-semantic instructions (#5122)
Fixes #5121

* If the non-semantic info instructions depended on other moved
  instructions the def/use manager would get corrupted.
2023-02-24 01:10:35 +00:00
Dave Airlie
956114df28
opt: fix spirv ABI on Linux again. (#5113)
Breaking the ABI for this API isn't worth it when the fix is so simple.
2023-02-15 20:11:30 +00:00
Kévin Petit
f4343515ad
Remove duplicate lists of constant and type opcodes (#5106)
Adding a new type instruction required making the same change in two
places.

Also remove IsCompileTimeConstantInst that was used in a single place
and replace its use by an expression that better conveys the intent.

Change-Id: I49330b74bd34a35db6369c438c053224805c18e0

Signed-off-by: Kevin Petit <kevin.petit@arm.com>
2023-02-15 20:09:55 +00:00
Nathan Gauër
b84c86f718
libspirv.cpp: adds c++ api for spvBinaryParse (#5109)
This commit adds a C++ wrapper above the current spvBinaryParse
function. I tried to match it 1:1, except for 2 things:
 - std::function<>& are used. No more function pointers, allowing
   context capture.
 - spv_result_t replaced with a boolean, to match other C++ apis.

Callbacks still return a spv_result_t because the underlying implem
relies on that. The convertion from spv_result_t to boolean is only done
at the boundary.

Signed-off-by: Nathan Gauër <brioche@google.com>
2023-02-14 14:08:20 -05:00
Caio Oliveira
0ce2bc4ce0
spirv-val: Conditional Branch without an exit is invalid in loop header (#5069)
* Update fuzz tests to not use invalid combinations of LoopMerge + BranchConditional

New IDs were selected to make clear the transformation being done here, instead
of reordering all IDs in between or refactoring the SPIR-V in the test.

* spirv-val: Conditional Branch without an exit is invalid in loop header

From 2.16.2, for CFG:

    Selections must be structured. That is, an OpSelectionMerge
    instruction is required to precede:

    - an OpSwitch instruction

    - an OpBranchConditional instruction that has different True Label
      and False Label operands where neither are declared merge blocks
      or Continue Targets.
2023-02-06 10:31:47 -05:00
Laura Hermanns
cac9a5a3ee
Fix null pointer in FoldInsertWithConstants. (#5093)
* Fix null pointer in FoldInsertWithConstants.

Struct types are not supported in constant folding yet.

* Added 'Test case 16' to fold_test.

Tests OpCompositeInsert not to be folded on a struct type.
2023-02-03 15:03:15 +00:00
Maciej
fd1e650cfe
Validate decoration of structs with RuntimeArray (#5094)
Contributes to https://github.com/KhronosGroup/glslang/issues/2439

* When OpTypeStruct is used in Vulkan env and its last member
  is a RuntimeArray, check if the struct is decorated with
  Block or BufferBlock, as required by VUID-...-04680.
2023-02-03 08:58:51 -05:00
Jeremy Gebben
5890763734
instrument: Clean up generation code (#5090)
-Make more use of InstructionBuilder instruction helper methods
-Use MakeUnique<>() rather than new
-Add InstrumentPass::GenReadFunctionCall() which optimizes function
calls in a loop with constant arguments and no side effects.

This is a prepatory change for future work on the instrumentation
code which will add more generated functions.
2023-02-03 00:39:09 +00:00
Daniel Story
0994ca45b6
Add C interface for Optimizer (#5030) 2023-02-01 13:58:52 +00:00
alan-baker
b230a7c7d1
Validate operand type before operating on it (#5092)
Fixes https://crbug.com/oss-fuzz/52921

* Validate the data operand of OpBitCount before trying to get its
  dimension
2023-01-31 15:40:22 -05:00
Nathan Gauër
fcfc3c580c
build: stop parsing CHANGES file. (#5067)
The CHANGES file was an alternative source of truth that was trying
to duplicate/replace the git history truth.
This allow us to change the way we handle releases so we don't have to make
sure our CHANGES PR are linked to the tag and tested PR, simplifying the
process.
2023-01-30 13:23:41 -05:00
Steven Perron
5db6c38e65
Revert "spirv-val: Initial SPV_EXT_mesh_shader builtins (#5080)" (#5084)
This reverts commit f0b900ed9a.
2023-01-24 19:51:39 +00:00
Nathan Gauër
7f9184a5b2
kokoro: fix dubious ownership (#5082)
Kokoro clones repos with a different user used to run the build steps,
meaning if some git command must be run at build time, they will fail
because of this dubious ownership issue.
Running some git commands makes only sense with history, so changing
checkout depth so we can run them and get the true result.

This is a known Kororo issue.
Fixing this is required to generate the version file using git history.

Signed-off-by: Nathan Gauër <brioche@google.com>

Signed-off-by: Nathan Gauër <brioche@google.com>
2023-01-23 15:32:39 +00:00
Steven Perron
fe087cd5f0
Revert "kokoro: fix dubious ownership (#5078)" (#5081)
This reverts commit 8fbb53dae4.
2023-01-23 14:36:33 +00:00
Spencer Fricke
f0b900ed9a
spirv-val: Initial SPV_EXT_mesh_shader builtins (#5080) 2023-01-23 14:30:45 +00:00
Nathan Gauër
8fbb53dae4
kokoro: fix dubious ownership (#5078)
Kokoro clones repos with a different user used to run the build steps,
meaning if some git command must be run at build time, they will fail
because of this dubious ownership issue.
Running some git commands makes only sense with history, so changing
checkout depth so we can run them and get the true result.

This is a known Kororo issue.
Fixing this is required to generate the version file using git history.

Signed-off-by: Nathan Gauër <brioche@google.com>
2023-01-23 14:22:40 +00:00
Jeremy Gebben
ba4c9fe534
Instrument: Fix bindless checking for BufferDeviceAddress (#5049)
Avoid using OpConstantNull with types that do not allow it.

Update existing tests for slight changes in code generation.

Add new tests based on the Vulkan Validation layer test case
that exposed this problem.
2023-01-16 20:57:37 +00:00
Juan Ramos
1dad991441
cmake: Modernize install(TARGET) usage (#5056) 2023-01-16 10:55:35 -05:00
alan-baker
7e8813bb4c
Validate version 5 of clspv reflection (#5050)
* Validate version 5 of clspv reflection

* Add validation for instructions in versions 2 through 5
* Change the instruction reported for remaining indices on an access
  chain to the access chain itself for clarity

* update spirv-headers
2023-01-11 16:58:53 -05:00
Caio Oliveira
f62e121b0d
spirv-val: Use more specific term 'switch header' in error message (#5048)
* spirv-val: Add tests for OpSwitch directly breaking/continuing outer loop

These are not valid, tests verify the validator catches the issue.
2023-01-09 18:39:02 -05:00
David Neto
bbdd0fefda
Update minimum required CMake to 3.17.2 (#5041)
* Update minimum required CMake to 3.17.2

- For Wasm build, update to emscripten/emsdk:3.1.28 which has 3.22.1
- Move the docker-compose.yml down to the source/wasm directory.

Fixes: #5040

* Fix working directory for invocation of wasm build
2022-12-21 16:22:17 -05:00
David Neto
2937538210
Fix undef behaviour in hex float parsing (#5025)
When the parser saw more significant hex digits than fit in
the target type, it would compute a nonsensical shift amount, resulting
in undefined behaviour.

Now, drop the excess bits, effectively truncating the significand.

Also guard against overflow of the exponent in the extraordinary (and untested)
case where we see more than, for example, 2**(32-4+1) significant hex digits
for a 32-bit float, or 2**(16-4+1) significant hex digits for a 16-bit
float.

Also guard against overflow of the indexing counting the number of
significant bits.  When that would occur silently drop any further
significant bits.  (Untested)

Avoid hex floats in C++ code. It's a C++17 feature.

Fixes: #4724
2022-12-19 15:46:57 -05:00
Jeremy Gebben
025ea891fa
Optimize allocation of spvtools::opt::Instruction::operands_ (#5024)
Reserve space for the entire operand list rather than adding them
one a time.
2022-12-19 13:08:01 -05:00
Greg Fischer
f64a4b64b7
[spirv-opt] Clone names for new struct in EliminateIODeadComponents (#5016) 2022-12-19 10:20:44 -07:00
alan-baker
5a78d798f7
Fix layout validation (#5015)
* Fix layout validation

Fixes #5010

* Unless scalar block layout is enabled, no member can reside at an
  offset between the end of the previous member that is a struct or
  array and the next multiple of that alignment

* Remove a dead if that was introduced

Co-authored-by: David Neto <dneto@google.com>
2022-12-15 21:38:09 -05:00
alan-baker
235182cfee
Fix use of invalid analysis (#5013)
Fixes https://crbug.com/1395415

* Block merging needed to invalid structured cfg analysis
2022-12-12 10:49:59 -05:00
alan-baker
9c6a925c87
Fix infinite loop in validator (#5006)
Fixes https://crbug.com/oss-fuzz/53510

* Fix infinite loop that could occur in structured cfg validation due to
  an invalid cfg
2022-12-06 11:22:33 -05:00
Spencer Fricke
7b8f00f00a
spirv-opt: Fix OpCompositeInsert with Null Constant (#5008)
* spirv-opt: Unify GetConstId function names

* spirv-opt: Fix OpCompositeInsert with Null Constant

* spirv-opt: Improve GetNullCompositeConstant description
2022-12-06 09:00:10 -05:00
Cassandra Beckley
40f5bf59c6
Revert "spirv-val: Multiple interface var with same SC (#4969)" (#5009)
This reverts commit 996d4c021f. This
commit is likely good, but it causes a failure in DXC tests. Will
un-revert once we fix the issue in DXC.
2022-12-05 12:31:01 -08:00
Greg Fischer
00018e58af
Change EliminateDeadInputComponentsPass to EliminateDeadIOComponentsPass (#4997)
To reflect processing of both Input and Output variables.

Also renamed files as needed.
2022-11-25 16:48:13 -07:00
Biswapriyo Nath
9a6f4121f4
Fix missing declaration of std::numeric_limits (#5002)
This fixes the errors:
validate_ray_tracing_reorder.cpp:25:49: error: 'numeric_limits' is not a member of 'std'
2022-11-25 10:54:38 -05:00
alelenv
f33d152400
Add validation support for SPV_NV_shader_invocation_reorder. (#4979)
Co-authored-by: Pankaj Mistry <pmistry@nvidia.com>
2022-11-24 09:50:45 -05:00
Spencer Fricke
597631b693
spirv-opt: Handle null CompositeInsert (#4998)
Fixes #4996
2022-11-24 08:38:12 -05:00
Greg Fischer
81ec2aaa0e
Add option to ADCE to remove output variables from interface. (#4994)
This can cause interface incompatibility and should only be done
if ADCE has been applied to the following shader in the pipeline.
For this reason this capability is not available through the CLI
but rather only non-default through the API. This functionality is
intended as part of a larger cross-shader dead code elimination
sequence.
2022-11-23 10:48:58 -07:00
Greg Fischer
46ca66e699
Add support for tesc, tese and geom to EliminateDead*Components (#4990) 2022-11-18 15:08:18 -07:00
Nathan Gauër
1a7f71afb4
clean: constexpr-ify and unify anon namespace use (#4991)
Constexpr guaranteed no runtime init in addition to const semantics.
Moving all opt/ to constexpr.
Moving all compile-unit statics to anonymous namespaces to uniformize
the method used (anonymous namespace vs static has the same behavior
here AFAIK).

Signed-off-by: Nathan Gauër <brioche@google.com>
2022-11-17 19:02:50 +01:00
Greg Fischer
8ea3ae6be2
Split EliminateDeadInputComponents into safe and unsafe versions. (#4984)
Safe version will only optimize vertex shaders. All other shaders will
succeed without change.

Change --eliminate-dead-input-components to use new safe version.

Unsafe version (allowing non-vertex shaders) currently only available
through API. Should only be used in combination with other optimizations
to keep interfaces consistent. See optimizer.hpp for more details.
2022-11-14 11:44:26 -07:00
Jeremy Gebben
68e8327f29
Instrument: Change output buffer offset definitions (#4961)
Add a flags field at the first offset within this buffer.
Define flags to allow buffer OOB checking to be enabled or
disabled at run time. This is to support VK_EXT_pipeline_robustnes.
2022-11-10 12:35:18 -05:00
Spencer Fricke
996d4c021f
spirv-val: Multiple interface var with same SC (#4969)
* spirv-val: Multiple interface var with same SC

* spirv-val: Use C style headers
2022-11-10 12:32:58 -05:00
Greg Fischer
525bc38062
Add pass to eliminate dead output components (#4982)
This pass eliminates components of output variables that are not stored
to. Currently this just eliminates trailing components of arrays and
structs, all of which are dead.

WARNING: This pass is not designed to be a standalone pass as it can
cause interface incompatibiliies with the following shader in the
pipeline. See the comment in optimizer.hpp for best usage. This pass is
currently available only through the API; it is not available in the CLI.

This commit also fixes a bug in CreateDecoration() which is part of the
system of generating SPIR-V from the Type manager.
2022-11-08 10:45:32 -07:00
Spencer Fricke
54d4e77fa5
spirv-opt: Add const folding for CompositeInsert (#4943)
* spirv-opt: Add const folding pass for CompositeInsert

* spirv-opt: Fix anas stack-use-after-scope
2022-11-08 10:50:42 -05:00
Spencer Fricke
a5e766b2b4
spirv-val: Add VUID label for 07703 (#4980) 2022-11-06 19:05:25 -05:00
alan-baker
d35a78db57
Switch SPIRV-Tools to use spirv.hpp11 internally (#4981)
Fixes #4960

* Switches to using enum classes with an underlying type to avoid
  undefined behaviour
2022-11-04 17:27:10 -04:00
Greg Fischer
c8e1588cfa
Add passes to eliminate dead output stores (#4970)
This adds two passes to accomplish this: one pass to analyze a shader
to determine the input slots that are live. The second pass is run on
the preceding shader to eliminate any stores to output slots that are
not consumed by the following shader.

These passes support vert, tesc, tese, geom, and frag shaders.

These passes are currently only available through the API.

These passes together with dead code elimination, and elimination of
dead input and output components and variables (WIP), will allow users
to do dead code elimination across shader boundaries.
2022-11-02 11:23:25 -06:00
alan-baker
a52de681dd
Prevent eliminating case constructs in block merging (#4976)
Fixes #4918

* Prevent block merging from producing an invalid case construct by
  merging a switch target/default with another construct's merge or
  continue block
* This is to satisfy the structural dominance requirement between the
  switch header and the case constructs
2022-10-28 14:13:20 -04:00
alan-baker
4563d90934
Only validate full layout in Vulkan environments (#4972)
Fixes #4671
Fixes https://crbug.com/oss-fuzz/43265

* Only validate full layout in a vulkan environment
  * Universal validation still checks that the right decorations are
    present, but the values are only considered for vulkan
* One exception is that invalid overlaps are only checked for vulkan
  * This is a pragmatic choice as SPIR-V doesn't define the size of
    types so the amount of universal checking would be quite limited
* Removed redundant check for GLSLShared and GLSLPacked decorations
  * Should never have been validated as part of universal validation

* make conditionals independent
2022-10-28 11:52:28 -04:00
Spencer Fricke
9f3a4afae4
spirv-val: Label new Vulkan OpPtrAccessChain VUs (#4975) 2022-10-27 10:10:27 -04:00
Nathan Gauër
b49a2caa7c
Revert "test" (#4974)
This reverts commit da215f10c9.
2022-10-27 14:17:31 +02:00
Nathan Gauër
da215f10c9 test 2022-10-26 16:42:29 +00:00
alan-baker
7326b967a5
Prevent null pointer from being dereferenced (#4971)
Fixes https://crbug.com/oss-fuzz/48553

* Assign a reflexive dominator if no other dominator can be found using
  forward traversals
  * This prevents a null dereference of a pointer in the sorting of the
    output
2022-10-24 15:16:33 -04:00
Spencer Fricke
0ebf830572
spirv-val: Add OpPtrAccessChain Base checks (#4965) 2022-10-24 12:45:08 -04:00
Spencer Fricke
eb113f0fdf
spirv-val: Improve PR 4831 error message (#4968) 2022-10-20 10:51:43 -04:00
Spencer Fricke
ecd5b9c167
spirv-val: Add remaining Component decoration validation (#4966) 2022-10-17 16:54:39 -04:00
gmitrano-unity
1cecf91701
Support Narrow Types in BitCast Folding Rule (#4941)
* Support Narrow Types in BitCast Folding Rule

This change adds support for narrow types in the BitCastScalarOrVector
folding rule. According to Section 2.2.1 of the SPIR-V spec, types that
are narrower than 32 bits are automatically either sign extended, or
zero extended depending on the type. With that guaranteed, we should
be able to use the first 32-bit word of any narrow type for the folding
logic without performing any special conversions.

In order to reduce code duplication, this change moves the
GetU32BitValue and GetU64BitValue functions from IntConstant to
ScalarConstant. Without this move, we would have needed an identical
version of GetU32BitValue on FloatConstant.

* Add Tests for 16-bit BitCast Folding

This change adds several new test cases to the
IntegerInstructionFoldingTest which trigger the 16-bit BitCast logic.
The logic for half types was also added to the integer case since we
can't easily validate half float types in C++ code. It's easier to
validate them as unsigned integers instead. Pllus this also allows us
to verify the SPIR-V constant sign extension logic too.

* Add 8-Bit Folding Test Cases

This change adds a couple more test cases to the integer instruction
folding test suite in order to ensure that the BitCast logic also
works correctly with the Int8 shader capability.
2022-10-06 10:35:18 -04:00
Kévin Petit
a6e6454ef2
spirv-val: Add SPV_ARM_core_builtins validation (#4958)
Signed-off-by: Kevin Petit <kevin.petit@arm.com>
Change-Id: If1680a823aea9662d44def1ec6fe6ac334c00574

Signed-off-by: Kevin Petit <kevin.petit@arm.com>
2022-10-05 22:47:10 -04:00
Shahbaz Youssefi
07d361b675
spirv-val: Add an option to use friendly names or not (#4951)
The always-friendly messages make it harder to debug when the
disassembly is later generated without friendly names.

Additionally, the friendly-name-mapper is slow.  Disabling it improves
performance of an ANGLE test that creates numerous shaders by ~5%.
2022-09-30 12:22:00 -04:00
Shahbaz Youssefi
3ec6b3698e
spirv-val: Consistently quote ids in messages (#4950)
Half the messages used to output 'id[%name]' and half id[%name].  With
this change, all messages consistently output 'id[%name]'.  Some typos
are also fixed in the process.
2022-09-29 10:03:49 +02:00
Spencer Fricke
49230a2307
spirv-opt: Remove unused folding rule (#4942) 2022-09-23 14:02:01 -04:00
Spencer Fricke
b53d7a8aff
spirv-val: Add initial SPV_EXT_mesh_shader validation (#4924)
* Move TaskEXT check to OpEmitMeshTasksEXT

* Add MeshNV for Execution Model alias
2022-09-23 11:06:46 -04:00
Greg Fischer
265b455c99
Fix CreatDebugInlinedAt to not invoke def_use_mgr (#4939) 2022-09-23 08:45:32 -04:00
Spencer Fricke
ddbee48f85
spirv-opt: Fix stacked CompositeExtract constant folds (#4932)
This was spotted in the Validation Layers where OpSpecConstantOp %x CompositeExtract %y 0 was being folded to a constant, but anything that was using it wasn't recognizing it as a constant, the simple fix was to add a const_mgr->MapInst(new_const_inst); so the next instruction knew it was a const
2022-09-23 08:45:11 -04:00
Steven Perron
f98473ceeb
Remove spvOpcodeTerminatesExecution (#4931)
* Remove `spvOpcodeTerminatesExecution`

This function is the same as `spvOpcodeIsAbort` except for
OpUnreachable.  The names are so close in meaning that it is hard to
distinguish them.  I've removed `spvOpcodeTerminatesExecution` since it
is used in only a single place.  I've special cased OpUnreachable in
that location.

At the same time, I fixed up some comments related to the use of the
TerminatesExecution and IsAbort functions.

Following up on #4930.

* Fix comments
2022-09-21 16:10:58 -04:00
Diego Novillo
21146c1b4b
Fix builtin validator for unimplemented opcodes. (#4940)
This prevents spurious build failures when new opcodeds are added in
SPIRV-Headers.  It moves all the unhandled opcodes to the `default`
case.
2022-09-21 15:52:34 -04:00
Ricardo Garcia
aeb1c64d4a
spirv-val: Make it legal to use arrays of ray queries (#4938)
Private arrays of ray queries are legal to use. Several CTS tests check
they work properly but were being rejected by spirv-val.
2022-09-21 15:27:36 -04:00
Greg Fischer
11d0d16227
Cleanup code for 272e4b3d0 (#4934)
Removed now unused DebugDeclare visibility logic for generating
DebugValue.

Also eliminated the phi sort introduced in 272e4b3. This should have
been removed in the first commit.
2022-09-20 15:27:23 -06:00
David Neto
91c29a197f
spirv-val: Fix comment for checking extended alignments (#4937)
* getBaseAlignment with roundUp true is called the "extended"
  by the Vulka spec.
* roundUp also affects matrix alignment, not just struct and array
2022-09-16 14:51:48 -04:00
Spencer Fricke
0c4ce11b4a
spirv-val: Update VUID from 1.3.228 Vulkan spec (#4936)
Co-authored-by: alan-baker <alanbaker@google.com>
2022-09-16 14:51:36 -04:00
Spencer Fricke
5f4ce362ad
spirv-val: Label VUID 07290 (#4927) 2022-09-16 14:05:40 -04:00
Spencer Fricke
8422d8a44b
spirv-val: Label ShaderRecordBufferKHR VUID (#4926) 2022-09-16 14:05:23 -04:00
Greg Fischer
272e4b3d07
Fix missing and incorrect DebugValues (#4929)
Specificially, fixes DebugValues coming out of
eliminate-local-single-store and eliminate-local-multi-store AKA SSA
rewrite.
2022-09-13 14:41:07 +00:00
Hans-Kristian Arntzen
49deada730
Also consider EmitMeshTasksEXT terminator in spirv-opt. (#4930)
Not sure why this is repeated for validation and optimizer, but ...
2022-09-12 13:24:34 +00:00
Jeremy Hayes
fb27bbf307
Fix DebugInlinedAt Line operand (#4928)
Line instructions may be OpLine or DebugLine. This commit adds support
for DebugLine.
2022-09-09 13:56:35 -04:00
Spencer Fricke
f5b27b6513
spirv-diff: Allow no SpecId (#4904) 2022-09-07 15:14:26 -04:00
Spencer Fricke
59cf5b1346
spirv-val: consider OpEmitMeshTasksEXT a terminator instruction (#4923) 2022-09-07 15:12:07 -04:00
Brad Smith
5f45f793ae
Support building on OpenBSD (#4912) 2022-09-02 19:30:09 +00:00
Steven Perron
529955e03d
Improve time to build dominators (#4916)
Changed a couple small parts of the algorithm to reduce time to build
the dominator trees.  There should be no visible changes.

Add a depth first search algorithm that does not run a function on
backedges.  The check if an edge is a back edge is time consuming, and
pointless if the function run on it is a nop.
2022-09-02 16:27:10 +00:00
Samuel Thibault
8eb8509834
build: cmake: Add support for GNU/Hurd (#4895) 2022-09-02 16:24:12 +00:00
Spencer Fricke
4386afb057
spirv-opt: Remove unused fold spec const code (#4906) 2022-09-02 16:24:02 +00:00
Pankaj Mistry
4c456f7da6
Implement tool changes for SPV_EXT_mesh_shader. (#4915)
- Added validation rule to support EXT_mesh_shader from SPIRV 1.4 onwards
2022-09-01 20:36:15 -04:00
jeremyg-lunarg
33113abf45
Instrument: Add OpNames to generated functions and variables (#4873)
Add name annotations to the generated instrumentation code to
make it easier to understand. Example spirv-cross output:

    vec4 _140;
    if (0u < inst_bindless_direct_read_4(0u, 0u, 1u, uint(_19)))
    {
        _140 = texture(textures[nonuniformEXT(_19)], inUV);
    }
    else
    {
        inst_bindless_stream_write_4(50u, 1u, uint(_19), 0u);
        _140 = vec4(0.0);
    }
2022-09-01 18:32:00 +00:00
Greg Fischer
b5d1040b94
Fix ADCE to mark scope and inlined_at of line instructions as live. (#4910) 2022-08-31 18:10:17 -04:00
Steven Perron
d51dc53d2c
Improve algorithm to reorder blocks in a function (#4911)
* Improve algorithm to reorder blocks in a function

In dead branch elimination, blocks can end up in a the wrong order, so
there is code to reorder the blocks in structured order.  The problem is
that the algorithm to do that is very poor.  It involves many searchs in
the function for the correct position to place the block, as well as
moving many block in the vector.

The solution is to write a specialized function in the function class
that will reorder the blocks in structured order.  After computing the
structured order, reordering the block can be done in linear time, with
very little overhead.
2022-08-31 11:06:15 -04:00
Spencer Fricke
fca39d5cb4
spirv-val: Better message for using OpTypeBool in input/output (#4901) 2022-08-29 12:47:16 -04:00
Spencer Fricke
66bdbacc9c
spirv-val: Use lookup table for Decoration string (#4903) 2022-08-29 11:09:20 -04:00
Spencer Fricke
f76431cbaf
spirv-val: Add SPV_KHR_ray_tracing storage class (#4868)
* Added VUID labels
2022-08-29 11:09:06 -04:00
Greg Fischer
b41e3e1311
Disable DebugInfoMgr during the entire CompactIds pass (#4905)
This is because the DebugInfo manager requires valid SPIR-V
which is not always true during this pass.

Add comment
2022-08-23 12:01:32 -06:00
Spencer Fricke
3c1a14b2b6
spirv-val: SBT Index for OpExecuteCallableKHR (#4900) 2022-08-18 13:42:25 -04:00
Spencer Fricke
0073a1fa36
spirv-val: Remove ImageWrite Texel todo (#4899) 2022-08-17 11:37:05 -04:00
Greg Fischer
71b2aee6c8
Add structs to eliminate dead input components (#4894)
Will eliminate all trailing members of input struct that are not
referenced.
2022-08-16 11:31:04 -04:00
Nathan Gauër
1728c1d40a
spirv-opt: fix copy-propagate-arrays index opti on structs. (#4891)
* spirv-opt: fix copy-propagate-arrays index opti on structs.

As per SPIR-V spec:
OpAccessChain indices must be OpConstant when indexing into a structure.

This optimization tried to remove load cascade. But in some scenario
failed:

```c
cbuffer MyStruct {
    uint my_field;
};

uint main(uint index) {
    const uint my_array[1] = { my_field };
    return my_array[index]
}
```

This is valid as the struct is indexed with a constant index, and then
the array is indexed using a dynamic index.
The optimization would consider the local array to be useless and
generated a load directly into the struct.

* spirv-opt: prevent creation of unused instructions

Copy-propagate-arrays optimization pass would create unused constants,
even if the optimization not completed.
This was caused by the way we handled OpAccessChain squashing: we
only referenced constants, and had to create them upfront.

Fixes #4887
Signed-off-by: Nathan Gauër <brioche@google.com>
2022-08-16 16:05:47 +02:00
Greg Fischer
9abacb34a5
Fix ADCE to not eliminate top level DebugInfo instructions (#4889)
Specifically, DebugSourceContinued, DebugCompilationUnit, and
DebugEntryPoint. These instructions are top-level instructions
which do not or may not have a user except for the tool and so
should not be eliminated.
2022-08-15 15:23:23 -06:00
Cassandra Beckley
3a8a961cff
Fix array copy propagation (#4890)
Array copy propagation was interpreting OpEntryPoint as a store
2022-08-11 09:59:37 -07:00
Steven Perron
0a43a84e02
Fix shuffle feeding shuffle with undef literal (#4883)
When folding a vector shuffle with an undef literal, it is possible that the
literal is adjusted so that it will then be interpreted as an index into
the input operands.  This is fixed by special casing that case, and not
adjusting those operands.

Fixes #4859
2022-08-10 09:04:35 -04:00
Nathan Gauër
0ebcdc4d19
Allow spirv-opt print-all to show pretty IDs (#4888)
Disassembler was called with non-default params, loosing FRIENDLY_NAMES.
This commit changes the call options to allow the spirv-opt to show
friendly names instead of raw-ids. Might be more helpful when reading
the SPIRV-opt output.

Fixes #4882

Signed-off-by: Nathan Gauër <brioche@google.com>
2022-08-09 14:10:36 -04:00
Steven Perron
ed3b9c83b1
Local access chain convert: check for negative indexes (#4884)
An access chain instruction interpretes its index operands as signed.
The composite insert and extract instruction interpret their index
operands as unsigned, so it is not possible to represent a negative
number.

This commit adds a check to the local-access-chain-convert pass to check
for a negative number in the access chain and to not do the conversion.

Fixes #4856
2022-08-09 17:33:04 +00:00
Spencer Fricke
f20e8d05f5
spirv-val: Add SPV_KHR_ray_tracing instructions (#4871) 2022-08-08 14:45:04 -04:00
jeremyg-lunarg
b362d2b7d4
spirv-diff: Fix asserts in ComparePreambleInstructions() (#4872)
These asserts are not valid for string literals, which may
contain several words:
  assert(a_operand.words.size() == 1);
  assert(b_operand.words.size() == 1);

It looks like they only make sense for the default case, which
assumes that both operands contain a single word.

Running a debug version of spirv-diff on any shader containing
a string literal will hit the original asserts.
2022-08-04 16:44:15 +00:00
Spencer Fricke
08c542d344
spirv-val: Label VUID 06997 (#4881) 2022-08-03 10:42:13 -04:00
Pankaj Mistry
54cd5e1963
spirv-opt : SPV_NV_bindless_texture related changes (#4870) 2022-07-29 19:28:27 +00:00
alan-baker
b5d0bf285f
Require ColMajor or RowMajor for matrices (#4878)
Fixes #4875

* Require that matrices in laid out structs have RowMajor or ColMajor
  set as per SPIR-V section 2.16.2 (shader validation)
2022-07-29 15:08:48 -04:00
Jamie Madill
a90ccc2405
Remove default copy constructor in header. (#4879)
A recent libc++ roll in Chrome warned of a deprecated copy. We're
still looking if this is a bug in libc++ or a valid warning, but
removing the redundant line is a safe workaround or fix in either
case.

See discussion in https://crrev.com/c/3791771
2022-07-29 18:26:37 +00:00
alan-baker
4773879b68
Update structure layout validation (#4876)
* Uniform block layout rules for matrices should use extended layouts by
  default
2022-07-29 10:16:54 -04:00
David Neto
8dc0030ecb
spirv-as: Avoid overflow when parsing exponents on hex floats (#4874)
* spirv-as: Avoid overflow when parsing exponents on hex floats

When an exponent is so large that it would overflow the int
type in the parser, saturate the exponent.
This allows extremely large exponents, and saturates
to infinity when the exponent is positive, and zero when the exponent
is negative.

Fixes #4721.

* Avoid unexpected narrowing conversions from arithmetic operations

Co-authored-by: Alastair F. Donaldson <alastair.donaldson@imperial.ac.uk>
2022-07-28 09:40:07 -04:00
Spencer Fricke
cc5fca057e
spirv-val: Fix Vulkan memory scope (#4869) 2022-07-26 15:14:21 -04:00
Alastair Donaldson
388ce0ee64
spirv-as: Avoid recursion when skipping whitespace (#4866)
Excessive whitespace can lead to stack overflow during parsing as each
character of skipped whitespace involves a recursive call. An
iterative solution avoids this.

Fixes #4729.
2022-07-26 10:56:04 -04:00
Spencer Fricke
e4cfa190df
spirv-val: Add SPV_KHR_ray_query (#4848) 2022-07-20 10:12:58 -04:00
Pankaj Mistry
60615b8ec6
Implement SPV_NV_bindless_texture related changes (#4847)
* Add validation for SPV_NV_bindless_texture
2022-07-19 14:41:19 -04:00
Spencer Fricke
93ebf698a0
spirv-val: Add OpConvertUToAccelerationStructureKHR (#4838) 2022-07-15 09:55:33 -04:00
Spencer Fricke
e2cf769302
spirv-val: Label VUID 06925 (#4852) 2022-07-13 10:05:52 -04:00
Greg Fischer
faa8d6a653
Revert "Optimize DefUseManager allocations (#4709)" (#4846)
This reverts commit d18d0d92e5.

This is reverted because it causes a 7X slowdown when legalizing
SPIR-V with NonSemantic.Shader.DebugInfo.100 instructions.
This is due to the creation of very large UseLists for several
heavily used operands for this extension combined with the fact
that the original commit changed the performance of Uselists to O(n).
2022-07-12 13:14:47 -06:00
Greg Fischer
69e1deabc1
Fix small bug traversing users in interface_var_sroa (#4850)
Fix code that is traversing def-use user structure at the same time
that it is changing it. This is dicey at best and error prone at worst.
This was uncovered making a change to the id_to_user representation.
2022-07-08 13:11:22 -04:00
Spencer Fricke
bc5c8760af
spirv-val: Add Vulkan decoration interface (#4831) 2022-07-07 13:03:52 -04:00
alan-baker
05de650371
Use structural reachability in CFG checks (#4849)
Fixes https://crbug.com/oss-fuzz48578

* Adds structural reachability to basic blocks
  * calculated in same manner as reachability, but using structural
    successors
* Change structured CFG validation to use structural reachability
  instead of reachability
* Fix some invalid reducer cases
2022-07-06 17:43:32 -04:00
David Neto
dcee3a5de0
Update validator diagnostics with "structurally dominated" (#4844)
The updated rules in SPIR-V 1.6 Rev2 use structural dominance,
so update the messages to match
2022-07-06 15:10:29 -04:00
Steven Perron
5f4284aa78
Add limit for scalar replacment when fuzzing (#4843)
The fuzzer cretes code with very large array, and scalar replacement
times out.  Adding a limit on the size of the composites that will be
split when fuzzing.

Fixes https://crbug.com/oss-fuzz/48630
2022-07-05 20:12:58 -04:00
Steven Perron
92fe420c8a
Reduce load size does not work for array with spec const size (#4845)
Arrays do not have to have a size that is known at compile time.  It
could be a spec constant.  In these cases, treat the array
as if it is arbitrarily long.  This commit will treat it like it is an
array of size UINT32_MAX.

Fixes https://crbug.com/oss-fuzz/47397.
2022-07-05 16:16:50 -04:00
Steven Perron
d5a3bfcf2f
Avoid undefined behaviour when getting debug opcode (#4842)
If the `instruction` operand in an extended instruction instruction is
too large, it causes undefined behaviour when that value is cast to the
enum for the corresponding set.  This is done with the
NonSemanticDebug100 instruction set.  We need to avoid the undefined
behaviour.

Fixes #4727
2022-07-05 14:14:29 -04:00
Steven Perron
32622ba7c6
DCE: clean up the cfg for all functions that were processed. (#4840)
Which functions are processed is determined by which ones are on the
call tree from the entry points before dead code is removed.  So it is
possible that a function is process because it is called from an entry
point, but the CFG is not cleaned up because the call to the function
was removed.

The fix is to process and cleanup every function in the module.  Since
all of the dead functions would have already been removed in an earlier
step of DCE, it should not make a different in compile time.

Fixes #4731
2022-07-05 12:23:32 -04:00
alan-baker
8ec4a0772b
Fix unreachable loop increment (#4836)
* ANGLE builds with -Werror,-Wunreachable-code-loop-increment which had
  a problem with grabbing the first construct in a loop
  * Change the code to just use begin instead
2022-06-30 13:52:50 -04:00
alan-baker
286e9c1187
Use structural dominance to validate cfg (#4832)
* Structural dominance introduced in SPIR-V 1.6 rev2
* Changes the structured cfg validation to use structural dominance
  * structural dominance is based on a cfg where merge and continue
    declarations are counted as graph edges
* Basic blocks now track structural predecessors and structural
  successors
* Add validation for entry into a loop
* Fixed an issue with inlining a single block loop
  * The continue target needs to be moved to the latch block
* Simplify the calculation of structured exits
  * no longer requires block depth
* Update many invalid tests
2022-06-29 23:32:20 -04:00
Mike
0b824324bc
Fix segfault in SpirvTools::Disassemble when printing (#4833)
When the `SPV_BINARY_TO_TEXT_OPTION_PRINT` option is specified, `spvtext` will not be created (see 37d2396cab/source/disassemble.cpp (L117)), and the attempt to dereference into its members (`spvtext->str` and `spvtext->length`) results in segmentation fault.

This is fixed by first checking if `spvtext` is nulll.

Co-authored-by: Steven Perron <stevenperron@google.com>
2022-06-29 12:05:00 -04:00
Steven Perron
66d88508dd
Build struct order only for the section needed when unrolling. (#4830)
We currently build the structured order for all nodes reachable from the
loop header when unrolling a loop.  However, unrolling only needs the
nodes in the loop and possibly the merge node.

To avoid needless computation, I have implemented a search that will
stop at the merge node.

Fixes #4827
2022-06-29 09:53:26 -04:00
Alastair Donaldson
f2dfa53ae5
Avoid unrolling large loops while fuzzing (#4835)
Uses a preprocessor macro to bail out of unrolling loops with large
iteration counts during fuzzing, to reduce the number of
timeouts/memouts that arise.

Related issue: #4728.
2022-06-29 09:12:09 -04:00
Steven Perron
37d2396cab
Fix SplitLoopHeader to handle single block loop (#4829)
The code in `CFG::SplitLoopHeader` assumes the loop header is not the
latch.  This leads to it not being able to find the latch block.  This
has been fixed, and a test added.

Fixes #4527
2022-06-24 12:33:45 -04:00
Steven Perron
3c9fd7577f
Avoid if-conversion if both predecessors are the same (#4826)
If the predecessor blocks are the same, then there is only 1 value for the
OpPhi.  The simplition pass will simplify it, and it causes problems for
if-conversion.  In these cases, if-conversion can just punt.

Fixes #3554.
2022-06-24 15:28:06 +00:00
PENGUINLIONG
c4ed5157dc
Fixed crash unrolling loops with residual iterations (#4820) 2022-06-23 16:01:44 -04:00
Steven Perron
76fe352190
Fail validation when RelaxedPrecision is applied to a type. (#4823)
* Fail validation when RelaxedPrecision is applied to a type.

Fixes #4723
Fixes #4725

* Fixup invalid test
2022-06-21 19:59:01 +00:00
Steven Perron
845d98d468
Do not check if the binary changed if encoding is different (#4824)
There is an assert that verifies that the binary did not change when the
optimizer said that it did not.  However, if the input binary is in big endian
format, the optimizer will encode the optimized binary in little endian.  This
causes the assert to fail.  Since we do not believe that anybody cares about a
big endien formate, we will disable the assert in that case.

Fixes #4722
2022-06-21 19:58:21 +00:00
Steven Perron
4f321f862a
Avoid undefined divide-by-0 (#4821)
The Reciprocal function expects a divide-by-0 to return nan,and then Reciprocal will return 0.

Since the divide-by-0 is actually undefined, we will identify this case early, and return 0.

No new tests are needed because we already tests folding divide-by-0.

Fixes #4715
2022-06-21 11:37:34 -04:00
manas-kulkarni
fbcb6cf4c8
Ability to fold Constant Vector times Matrix and Matrix times vector instructions (#4818) 2022-06-16 13:54:12 -04:00
Spencer Fricke
bfc611b03e
spirv-val: Label 06807 and 06808 VUID (#4817) 2022-06-15 11:25:16 -04:00
Steven Perron
76ebfb989f
Avoid replacing access chain with OOB access (#4819)
An access chain could have a constant index that is an out of bounds
access.  This is valid spir-v, even if it can cause problems at runtime.
However, it is not valid to have an OpCompositeExtract with an out of
bounds access.  This means we have to stop local-access-chain-convert
from making that change.

Fixes #4605
2022-06-14 13:06:38 -04:00
David Neto
8f7f5024f8
Simplify invocation of snprintf (#4815) 2022-06-10 17:55:45 -04:00
strangewiz
fad68a7551
Fix usage of sprintf. (#4811) 2022-06-08 19:49:46 +00:00
Junda Liu
044ff1aabf
spirv-val: Add support for SPV_AMD_shader_early_and_late_fragment_tests (#4812)
- Update SPIR-V headers.
- Add validator support.
- Add validator tests.
2022-06-08 08:36:32 -04:00
Shahbaz Youssefi
c94501352d
spirv-val: Optimize struct field decoration lookup (#4809)
A std::set is used instead of std::vector, where the elements are
ordered by member index first.  Decorations for fields are now looked up
by going over the range of decorations for the member only, instead of
the whole set.

In an ANGLE test that generates a struct with 4096 members, validation
goes down from ~140ms to ~90ms.  On debug builds, the difference is more
pronounced, going down from ~2.5s to ~600ms.
2022-06-02 11:32:38 -04:00
Nicolas Capens
130a05d2e3
Fold multiply and subtraction into FMA with negation (#4808)
This change adds a folding rule which transforms x * y - a and a - x * y
into FMA(x, y, -a) and FMA(-x, y, a), respectively.

While the SPIR-V instruction count remains the same, target instruction
sets typically feature FMA instruction variants that can negate an
operand. Also this transformation may unlock further optimizations which
eliminate the negation.

(Google bug: b/226145988)
2022-05-31 12:03:56 -04:00
Spencer Fricke
82d91083cb
spirv-val: Add PerVertexKHR (#4807) 2022-05-26 13:11:05 -04:00
Steven Perron
088cb1a5c8
Add more folding for composite instructions (#4802)
* Add move folding for composite instructions

Fold chains of insert into construct

If a chain of OpCompositeInsert instruction write to every element of a
composite object, then we can replace it with an OpCompositeConstruct.

Fold a construct fed by extracts to a single extract

We already fold an OpCompositeConstruct when it is simlpy reconstructing
an object that was decomposed by a series of OpCompositeExtract
instructions.  However, we do not do that if that object is an element
of a larger object.

I have updated the rule, so that if the original object is a an element
of a larger object, then the OpCompositeConstruct is replaced with a
single OpCompositeExtract from the larger object.

Fixes #4371.
2022-05-26 10:29:02 -04:00
stu-s
c267127846
Add SPV_KHR_fragment_shader_barycentric support (#4805)
* Add SPV_KHR_fragment_shader_barycentric support
2022-05-25 09:20:39 -04:00
Steven Perron
f74b85853c
Handle 64-bit integers in local access chain convert (#4798)
* Handle 64-bit integers in local access chain convert

The local access chain convert pass does on run on module that have
64-bit integers, even if they have nothing to to with access chains.
This is very limiting because other passes rely on the access chains
being removed. So this commit will add this functionality to the pass.
2022-05-10 17:02:14 +00:00
Daniele Vettorel
f7a6e3b9d5
Handle chains of OpAccessChain in replacing variable index access for flattened resources. (#4797) 2022-05-10 11:41:43 -04:00
Jaebaek Seo
ad3514b732
spirv-opt: add pass for interface variable scalar replacement (#4779)
Replace shader's stage variables whose types are array or matrix
with scalars/vectors.
For example,
```
Before:
  %foo = OpVariable %_ptr_Output__arr_v2float_uint_4 Output
After:
  %foo = OpVariable %_ptr_Output_v2float Output
  %foo_0 = OpVariable %_ptr_Output_v2float Output
  %foo_1 = OpVariable %_ptr_Output_v2float Output
  %foo_2 = OpVariable %_ptr_Output_v2float Output
```
2022-05-09 14:04:52 -04:00
JiaoluAMD
c11ea09652
spirv-opt : Add FixFuncCallArgumentsPass (#4775)
spirv validation require OpFunctionCall with memory object, usually this
is non issue as all the functions are inlined.
This pass deal with some case for
DontInline function. accesschain input operand would be replaced new
created variable
2022-05-06 10:39:26 -04:00
Daniel Koch
9e377b0f97
spirv-val: Add CullMaskKHR support (#4792)
Co-authored-by: sfricke-samsung <s.fricke@samsung.com>
2022-05-06 07:32:56 -04:00
Kévin Petit
7014be600c
Add support for SPV_KHR_subgroup_rotate (#4786)
- Add assembler/disassembler support
- Add validator support

Signed-off-by: Kevin Petit <kevin.petit@arm.com>
Change-Id: Iffcedd5d5e636a0e128a5906ffe634dd85727de1
2022-05-05 08:58:05 -04:00
JiaoluAMD
2c7fb9707b
Handle dontinline function in spread-volatile-semantics (#4776)
Handle function calls in spread-volatile-semantics
2022-05-04 10:52:58 -04:00
Steven Perron
58dc37ea6a
Add SpvBuiltInCullMaskKHR to a switch (#4790)
Add SpvBuiltInCullMaskKHR to a switch so spirv-tools can compile with
the latest headers.
2022-05-03 14:39:51 -04:00
Steven Perron
1295dca8e2
Reapply "Add folding rule to generate Fma instructions (#4783)" (#4789)
This reverts commit 671f6e633f.

PR #4783 was reverted because it caused OpenCL CTS failures for clvk.
The was in clspv, which was not adding the no contract decoration when
it was required.  This has been fixed in
https://github.com/google/clspv/pull/845.  We can now reapply #4783.
2022-05-03 10:20:23 -04:00
Karol Herbst
edaf51038b
linker: Recalculate interface variables (#4784)
* linker: Recalculate interface variables

By resolving extern symbols Entry Points might access variables they
hadn't declared before.

* test/linker: add test to verify linked spir-vs importing functions validate

Without the fix Validate will complain about:

"ERROR: 9: Interface variable id <5> is used by entry point 'bar' id <1>, but is not listed as an interface\n  %5 = OpVariable %_ptr_Input_v3uint Input\n"
2022-05-03 13:23:02 +00:00
sindney
46492aa45a
spirv-opt: skips if_conversion when dontflatten is set (#4770) 2022-04-28 19:26:02 +00:00
Daniele Vettorel
671f6e633f
Revert "Add folding rule to generate Fma instructions (#4783)" (#4785)
This reverts commit 2b2b0282af.
2022-04-20 10:55:20 -04:00
Steven Perron
2b2b0282af
Add folding rule to generate Fma instructions (#4783)
Adding Fma instruction can speed up the code.  This was requested by
swiftshader, so they do not have to do this analysis themselves.  It can
also help reduce the code size, and the work the ICD compilers have to
do.
2022-04-19 11:25:07 -04:00
Chad Versace
cb96abbf7a
Fix CMake for librt (#4773)
In the installed file
/usr/lib64/cmake/SPIRV-Tools/SPIRV-ToolsTarget.cmake, occurences of
librt in the INTERFACE_LINK_LIBRARIES property are incorrect.  The
property contains the absolute path to librt. In most situations, this
produces no problem. But when building in a sysroot, which is commonly
done when cross-compiling, the absolute path breaks dependent projects.

For example, when building spirv-tools using the Chrome OS SDK, and
targeting the board 'volteer', where the build sysroot is
'/build/volteer', the file includes this line
    INTERFACE_LINK_LIBRARIES "/build/volteer/usr/lib64/librt.so"
when it should instead say
    INTERFACE_LINK_LIBRARIES "rt"

The CMake documentation agrees [1]:
    Note that it is not advisable to populate the
    INTERFACE_LINK_LIBRARIES of a target with absolute paths to
    dependencies. That would hard-code into installed packages the
    library file paths for dependencies as found on the machine the
    package was made on.

[1] https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_LINK_LIBRARIES.html
2022-04-14 09:04:12 -04:00
Steven Perron
92c17edde7
Don't try to unroll loop with step count 0. (#4769)
These loop are infinite loop, so there is no reason to unroll the loop.
Fixes #4711.
2022-04-11 10:21:15 -04:00
Natalie Chouinard
78a0f075ac
Fix gen_build_version on Windows (#4780)
* Fix gen_build_version on Windows

The paths used in the gen_build_version script are causing some failures
in downstream builds. Switch to using the location of the CHANGES file
rather than the ".." parent directory workaround.

* Update other build files
2022-04-07 13:19:05 +00:00
Nico Weber
b0ce31fd2d
Suppress -Wunused-but-set-variable on variable (#4777)
sentinel_count is not used in non-assert builds.

Recent clang improvements to -Wunused-but-set-variable trigger a warning on this.

Fixes #4772.
2022-04-01 17:07:05 +01:00
Shahbaz Youssefi
5760114d77
spirv-diff: Fix OpTypeFunction matching w.r.t operand count (#4771)
The code accidentally expected OpTypeFunction operand count to match.
This is fixed so that OpTypeFunction instructions with different operand
counts are considered not matching.
2022-04-01 09:04:26 -04:00
Shahbaz Youssefi
bd325d2984
spirv-diff: Basic support for OpTypeForwardPointer (#4761)
Currently, the diff tool matches types bottom up, so on every
instruction it expects to know if its operands are already matched or
not.  With cyclical references, it cannot know that.  Type matching
would need significant rework to be able to support such a use case; for
example, it may need to maintain a set of plausable matches between type
pointers that are forward-referenced, and potentially back track when
later the types turn out to be incompatible.

In this change, OpTypeForwardPointer is supported in the more common and
trivial case.  Firstly, forwarded type pointers are only matched if they
have they have the same storage class and point to the same type opcode:

- In the presence of debug info, matching is done only if the names are
  unique in both src and dst.
- In the absence of debug info, matching is done only if there is only
  one possible matching.

Fixes: #4754
2022-03-28 17:01:07 +00:00
sfricke-samsung
0c670ef1d9
spirv-as: Add opcode name when possible (#4757) 2022-03-28 14:46:39 +00:00
Shahbaz Youssefi
40cd21839c
spirv-diff: Use GetSingleWord*Operand (#4768) 2022-03-28 14:42:47 +00:00
Jaebaek Seo
05745cc9d4
Handle shaders without execution model in spread-volatile-semantics (#4766)
spread-volatile-semantics pass spreads Volatile semantics for builtin
variables used by certain execution models based on
VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
SPIR-V"). Therefore, shaders without execution model (e.g., used only
for linkage) are not the target of the pass. This commit lets the pass
just return SuccessWithoutChange in that case.
2022-03-25 17:54:46 +00:00
sfricke-samsung
fa5d424830
spirv-val: Add more Vulkan VUID labels (#4764) 2022-03-25 09:29:19 -04:00
Nikita
a3fbc9331b
Support SPV_KHR_uniform_group_instructions (#4734) 2022-03-25 08:32:50 -04:00
Shahbaz Youssefi
48c8363f0a
spirv-diff: Refactor instruction grouping and matching (#4760)
In preparation for supporting OpTypeForwardPointer, which adds more
usages like this.  This change refactors common code used to group
instructions and match the groups.
2022-03-24 18:04:48 +00:00
sfricke-samsung
90728d2dff
spirv-val: Clean up VariablePointers logic (#4755) 2022-03-24 12:02:29 -04:00
Roy.li
cab0b7715a
Use types have same widths in loop condition. (#4763) 2022-03-24 14:07:22 +00:00
sfricke-samsung
b3c1790632
spirv-val: Add Vulkan 32-bit bit op Base (#4758) 2022-03-23 13:55:42 -04:00
sfricke-samsung
9668d2e4e4
spirv-val: Label and add test for PSB Aligned (#4756) 2022-03-23 11:08:21 -04:00
Greg Fischer
9d1b572884
spirv-opt: (WIP) Eliminate Dead Input Component Pass (#4720)
This adds the --eliminate-dead-input-components pass which currently
removes trailing unused components from input arrays.

Fixes #4532
2022-03-22 20:50:52 -06:00
sfricke-samsung
f8cd51431e
spirv-val: Add better error code for invalid operand (#4753) 2022-03-22 15:37:38 -04:00
Daniel Thornburgh
3820c4f6e2
Qualify std::move. (#4741)
Clang added -Wunqualified-std-cast-call in
https://reviews.llvm.org/D119670, which warns on unqualified std::move
and std::forward calls. This change qualifies these calls to allow the
project to build on HEAD Clang -Werror.
2022-03-22 11:20:11 -04:00
sfricke-samsung
0ab57c2c42
spirv-val: Small Cleanup of validate image (#4752) 2022-03-14 11:08:47 -04:00
sfricke-samsung
7963fa13c7
spirv-val: Add Vulkan Dref not allowed 3D dim VUID (#4751) 2022-03-10 13:08:26 -05:00
sfricke-samsung
5c9d55a59a
spirv-val: Add Vulkan Image VUID 06214 (#4750) 2022-03-10 13:06:48 -05:00
sfricke-samsung
9700708570
spirv-val: Label Vulkan RuntimeArray VUID (#4749) 2022-03-10 13:05:26 -05:00
sfricke-samsung
ca59914c7a
spirv-val: Disallow array of push constants (#4742) 2022-03-10 12:57:20 -05:00
Steven Perron
0741f42738
Reset the id bound on the module in compact ids (#4744)
If the body of the module does not have any ids change, compact ids will
not change the id bound.  This can cause problems because the id bound
could be much higher than the largest id in that is used.  It should be
reset any time it is not the larger id used + 1.

Fixes #4604
2022-03-07 20:33:01 +00:00
Steven Perron
48a36c72e4
Better handling of 0xFFFFFFFF when folding vector shuffle (#4743)
When folding a vector shuffle feeding a vector shuffle, we do not
propagate an 0xFFFFFFFF, which has a special meaning, correctly.  We
adjust the value making it lose it meaning as an undefined value.

Fixes #4581
2022-03-07 19:35:57 +00:00
Steven Perron
4fa1a6f9b4
Generalize assert in ccp (#4735)
CCP does not want to fold an instruction unless it folds to a constant.
There is an asser to check for this.  The question if a spec constant
counts as a constant.  The constant folder considers a spec constant a
constand, but CCP does not.  I've fixed the assert in CCP to match what
the folder does.  It should not require any new changes to CCP.
2022-03-07 19:33:10 +00:00
Steven Perron
920156cf18
Add pass to remove DontInline function control (#4747)
Swift shader needs a way to inline all functions, even those marked as
DontInline.  See https://github.com/KhronosGroup/SPIRV-Tools/pull/4471.
This implements the suggestion I made in the PR.  We add a pass that
will remove the DontInline function control, so that the inlining passes
will inline them.

SwiftShader will still have to modify their code to add this pass before
the other passes are run.
2022-03-07 12:45:17 -05:00
sfricke-samsung
273d2a45ad
spirv-val: Label VUID 06491 (#4745) 2022-03-07 12:30:05 -05:00
Steven Perron
0b8426346d
Don't rebuilt valid analyses. (#4733)
The function `BuildInvalideAnalyses` will be rebuilt for every analysis that
has been requested, but it is not necessary.  It also can cause problems
because if the CFG needs to be rebuilt, so do the dominator trees.

This change will make the functionality match the description of the
function.
2022-03-04 20:16:42 +00:00
sfricke-samsung
d1addc44b2
spirv-val: Label Vulkan VUID 04734 (#4739) 2022-03-04 10:07:24 -05:00
Jeremy Hayes
598bc6744a
spirv-val: Validate DebugTypeMatrix (#4732) 2022-03-04 08:54:05 -05:00
pd-valve
d18d0d92e5
Optimize DefUseManager allocations (#4709)
* Optimize DefUseManager allocations

Saves around 30-35% of compilation time.

For inst->use_ids, use a pool linked list instead of allocating vectors for every instruction.  For inst->uses, use a "PooledLinkedList"' -- a linked list that has shared storage for all nodes.  Neither re-use nodes, instead we do a bulk compaction operation when too much memory is being wasted (tuneable).

Includes separate PooledLinkedList templated datastructure, a very special case construct, but split out to make the code a little easier to understand.
2022-02-15 19:17:30 -05:00
pd-valve
a123632ed9
Optimize Type::HashValue (#4707)
Incrementally compute the hash instead of collecting words

Avoids allocating temporary space in a std::vector and std::u32string, and making three passes over all the hashed data.
Switch to using std::vector to prevent processing duplicates instead of std::unordered_set: avoids an allocation/deletion every call to ComputeHashValue, and ends up faster due to much better cache behaviour and smaller constant-factor when searching the (generally very small) list.

In my test case, made Type::HashValue go from 7.5% of compilation time to .5%
2022-02-15 18:57:39 +00:00
sfricke-samsung
471428a04f
spirv-opt: Add OpExecutionModeId support (#4719)
Needed for Vulkan1.3 adding LocalSizeId support
2022-02-14 14:33:29 +00:00
Natalie Chouinard
72e4475b41
Handle propagation of arrays with decorations (#4717)
When copy propagating, OpDecorate instructions can be copied as is. For
array flattening, they should be ignored.
2022-02-11 16:13:14 -05:00
sfricke-samsung
53078eec1e
Add OpModuleProcessed to debug opcode (#4694) 2022-02-11 19:24:17 +00:00
Shahbaz Youssefi
0ad83f9139
spirv-diff: Match OpSpecConstantComposite correctly (#4704)
OpSpecConstantComposite is not decorated with SpecId, and so is matched
similarly to OpConstantComposite.
2022-02-11 15:29:42 +00:00
pd-valve
940127a77d
avoid unnecessary reallocations in GetOperandConstants (#4708)
reserve capacity since we know the size exactly
2022-02-10 18:31:24 +00:00
pd-valve
44923beb52
Optimize Instruction::Instruction (#4705)
Avoid constructing temporary vector + copying operands multiple times.
Add SmallVector(InputIt first, InputIt last), matching std::vector.
2022-02-10 18:31:07 +00:00
Greg Fischer
ff91f9449b
[spirv-val] Allow 0 Component Count for DebugTypeArray for Shader (#4706)
Rev 7 of NonSemantic.Shader.DebugInfo.100 was updated to allow zero
component count for for DebugTypeArray to represent runtime array.
2022-02-09 17:58:55 -07:00
Shahbaz Youssefi
332475dbc9
spirv-diff: Handle OpSpecConstant array sizes (#4700)
Previously, array sizes were presumed to be OpConstant, which is not
necessarily true.  This change ensures OpSpecConstant array sizes as
matched exactly, instead of taken as OpConstant and matched by value.
2022-02-09 09:06:46 -05:00
Shahbaz Youssefi
9beb54513c
Stabilize the output of spirv-diff (#4698)
* Reimplement LCS used by spirv-diff

Two improvements are made to the LCS algorithm:

- The LCS algorithm is reimplemented to use a std::stack instead of
  being recursive.  This prevents stack overflow in the LCSTest.Large
  test.
- The LCS algorithm uses an NxM table.  Previously, entries of this
  table were {size_t, bool, bool}, which is now packed in 32 bits.  The
  first entry can assume a maximum value of min(N, M), which
  realistically for SPIR-V diff will not be larger than 1 billion
  instructions.  This reduces memory usage of LCS by 75%.

This partially reverts 845f3efb8a and
enables LCS tests.

* Stabilize the output of spirv-diff

std::map is used instead of std::unordered_map to ensure the output of
spirv-diff is identical everywhere.

This partially reverts 845f3efb8a and
enables spirv-diff tests.
2022-02-07 09:37:04 -05:00
Steven Perron
5b371918b9
Have scalar replacement use undef instead of null (#4691)
Scalar replacement generates a null when there value for a member will
not be used.  The null is used to make sure things are
deterministic in case there is an error.

However, some type cannot be null, so we will change that to use undef.
To keep the code simpler we will always use the undef.

Fixes #3996
2022-02-03 15:51:15 +00:00
Shahbaz Youssefi
7fa9e746ef
Introduce spirv-diff (#4611)
spirv-diff is a new tool that produces diff-style output comparing two
SPIR-V modules.  The instructions between the src and dst modules are
matched as best as the tool can, and output is produced (in src
id-space) that shows which instructions are removed in src, added in dst
or modified between them.  The order of instructions are not retained.

Matching instructions between two SPIR-V modules is not trivial, and
thus a number of heuristics are applied in this tool.  In particular,
without debug information, it's hard to match functions as they can be
reordered.  As such, this tool is primarily useful to produce the diff
of two SPIR-V modules derived from the same source.

This tool can be useful in a number of scenarios:

- Compare the SPIR-V before and after modifying a shader
- Compare the SPIR-V produced from a shader before and after compiler
  codegen changes.
- Compare the SPIR-V produced from a shader before and after some
  transformation or optimization.
- Compare the SPIR-V produced from a shader with different compilers.
2022-02-02 10:33:18 -05:00
Steven Perron
b846f8f1dc
Complete handling of RayQueryKHR type (#4690)
The handling of the RayQueryKHR type is not complete in the type
manager.  The tests were not picking this up.  I've added a test to make
sure that the `GenerateAllTypes` function actually does generate all of
the types.  Once it is added there other tests should pick up on the
other parts that were missing.
2022-01-31 15:44:32 +00:00
alan-baker
20b122b2e0
Fix handling of Nontemporal image operand (#4692)
* Nontemporal image operand shouldn't expect a following operand
2022-01-28 21:12:03 -05:00
luzpaz
65ecfd1093
Fix various source comment (doxygen) typos (#4680)
Found via `codespell -q 3 -L fo,lod,parm
2022-01-26 15:13:08 -05:00
Jaebaek Seo
fb9a10cd48
spirv-opt: add pass to Spread Volatile semantics (#4667)
Add a pass to spread Volatile semantics to variables with SMIDNV,
WarpIDNV, SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask,
SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask BuiltIn
decorations or OpLoad for them when the shader model is the ray
generation, closest hit, miss, intersection, or callable shaders. This
pass can be used for VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
SPIR-V").

Handle variables used by multiple entry points:

1. Update error check to make it working regardless of the order of
   entry points.
2. For a variable, if it is used by two entry points E1 and E2 and
   it needs the Volatile semantics for E1 while it does not for E2
  - If VulkanMemoryModel capability is enabled, which means we have to
    set memory operation of load instructions for the variable, we
    update load instructions in E1, but do not update the ones in E2.
  - If VulkanMemoryModel capability is disabled, which means we have
    to add Volatile decoration for the variable, we report an error
    because E1 needs to add Volatile decoration for the variable while
    E2 does not.

For the simplicity of the implementation, we assume that all functions
other than entry point functions are inlined.
2022-01-25 13:14:36 -05:00
alan-baker
6938af7f82
Vulkan 1.3 (#4686)
* Add new environment enum for Vulkan 1,3
* Do not require --allow-localsizeid in Vulkan 1.3 to use LocalSizeId
  execution mode
2022-01-25 10:36:08 -05:00
smikims
e8439c1c9d
Avoid infinite recursion in comparison operators on SmallVector (#4681)
C++20 automatically adds reversed versions of operator overloads for
consideration; in this particular instance this results in infinite
recursion, which has now been pointed out elsewhere as a known issue
when migrating to C++20. Here we just disable one of the overloads in
C++20 mode and let the auto-reversing take care of it for us.
2022-01-25 09:07:40 -05:00
Pierre Moreau
58d8b4e29c
linker: Address conversion error introduced in earlier rework (#4685)
* linker: Address conversion error introduced in earlier rework

Also rework the code slightly to first compute the new ID bound and
validate it, and only then, offset all existing IDs.

This makes those two steps clearer, and avoids potentially overflowing
the IDs within a module (even if that would have been caught later on).

Fixes: c3849565 ("Linker improvements (#4679)")
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4684

* test/linker: Disable IdsLimit tests for now

They are taking too long to run and results in the CI jobs timing out.
2022-01-24 13:40:57 -05:00
Pierre Moreau
c38495656d
Linker improvements (#4679)
* test/linker: Code factorisation and small tweaks

* linker: Do not fail when going over limits

The limits are minima and implementations or APIs might support higher
limits, so just warn the user about it. And only check for the limits
right before emitting the binary, as limits might change earlier when
removing duplicate instructions, function prototypes, etc.
The only check performed right before merging, is making sure the ID
bound will not overflow the 32 bits following the merge.

Also, use the defines for the limits instead of hard-coding them.

* linker: Require a memory model in each input module

The existing code could run into weird situation. For example, if the
first module had no memory model, it would not emit any memory model
(sort of reasonable) and would accept without complains all possible mix
from later modules as it would not verify them.

* linker: Replace hex version with SPV_SPIRV_VERSION_WORD

* linker: Error out when linking together different versions

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4135

* tools/linker: Do not write to disk if linking failed

Also, do not consider warnings as errors.

* tools/linker: Fix formatting in help message

* tools/linker: Further clarify the use of --target-env

Also update the text for the default version to reflect the change made
in 7d768812 ("Basic support for SPIR-V 1.6 (#4663)").
2022-01-22 15:40:19 -05:00
David Neto
8a40f6de57
Add SPIR-V 1.6 support to wasm build (#4674)
* Add SPIR-V 1.6 support to wasm build

* Fix formatting
2022-01-13 13:49:35 -05:00
Pierre Moreau
42dc678913
Remove duplicated "the" from comments (#4666) 2022-01-12 19:04:13 -05:00
Pierre Moreau
05c839ca01
Improvements to disassembly within PassManager (#4677)
* PassManager: Print errors occurring during disassembly

Otherwise one could be greeted by the following text when running
spirv-opt withe the `--print-all` flag:

    ; IR before pass wrap-opkill

    ; IR before pass eliminate-dead-branches

    ; IR before pass merge-return

With this commit, one will instead get:

    error: line 143: Invalid opcode: 400
    warning: line 0: Disassembly failed before pass wrap-opkill

    error: line 143: Invalid opcode: 400
    warning: line 0: Disassembly failed before pass eliminate-dead-branches

    error: line 143: Invalid opcode: 400
    warning: line 0: Disassembly failed before pass merge-return

* PassManager: Use the right target environment when disassembling

Disassembly would fail if features from a newer version of SPIR-V than
1.2 were used.
2022-01-10 10:55:47 -05:00
Steven Perron
b9e0e13d19
Remove misleading comment. (#4676)
The comment in `Array::GetExtraHashWords` is misleading because getting
the hash words is split up between the generic `Type::GetHashWords` and
the type specific `Type::GetExtraHashWords`.  While `IsSameImpl` is
self-contained.  Removing the comment since it is misleading and no
comment is really needed.

Fixes #3248
2022-01-10 09:24:44 -05:00
Alastair Donaldson
75e53b9f68
Avoid uninitialized access to instruction opcode (#4673)
Ensures that instruction's opcode is set to something default when
parsing the module with --preserve-numeric-ids enabled. This avoids
uninitialized accesses and knock-on buffer overflows.

Fixes #4672.
2022-01-04 17:33:33 +00:00
David Neto
df2aad68b9
val: interface struct with builtins must be Block (#4665)
For a shader input/output interface variable of structure type:
If the structure has BuiltIn members, then the structure type
must be Block decorated.

Otherwise, the variable, or the struct members must have locations,
but nothing can have both a location be a BuiltIn.

Implements validation needed to reject the example in
https://github.com/KhronosGroup/SPIRV-Registry/issues/134
2021-12-16 16:48:12 -05:00
David Neto
5d0e3240f0
Patch location validation VUIDs (#4664)
* spirv-val: Add Vulkan Location VUID

* Simplify: interface checking already does all the work

Co-authored-by: sfricke_samsung <s.fricke@samsung.com>
2021-12-16 15:25:23 -05:00
alan-baker
7d768812e2
Basic support for SPIR-V 1.6 (#4663)
* Basic support for SPIR-V 1.6

* Update SPIRV-Headers deps
* Add new environment enum for SPIR-V 1.6
* Make default environment 1.6 for most tools
* Update tests
* Disallow conditional branch with duplicate labels
* Disallow Dim=Buffer with sampled images
* Do not require the non-semantic extension after SPIR-V 1.5
2021-12-15 14:38:28 -05:00
Steven Perron
b7251d4fb7
reflect debug (#4662)
The pass to remove the nonsemantic information and instructions
is used for drivers or tools that may not support them.  Debug
information was only partially handle, which is causing a
problem.  We need to either fully remove debug information or
not remove it all.  Since I can see it being useful to keep the
debug information even when the nonsemantic instructions are
removed, I propose we do not remove debug info.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/4269
2021-12-15 11:06:51 -05:00
Steven Perron
354a46a2a2
Rename strip reflect to strip nonsemantic (#4661)
In https://github.com/KhronosGroup/SPIRV-Tools/pull/3110, the strip reflect
pass was changed to also remove all explicitly nonsemantic instructions.  This
makes it so that the name of the pass no longer reflects what the pass actually
does.  This change renames the pass so that it reflects what the pass actaully does.
2021-12-15 09:55:30 -05:00
Shahbaz Youssefi
4322c4b5a7
Refactor the disassembler code for reuse (#4616)
The upcoming spirv-diff tool also outputs disassembly, although in a
per-instruction basis.  This change refactors the disassembler code to
support such a use case.
2021-12-14 09:46:59 -05:00
Dave Airlie
3156158878
optimizer: restore previous ABI. (#4653)
The change in
commit 4ac8e5e541
Author: Greg Fischer <greg@lunarg.com>
Date:   Wed Sep 15 12:38:34 2021 -0600

    Add preserve_interface mode to aggressive_dead_code_elim (#4520)

Broke the C++ ABI for spirv-tools shared libraries on Linux, for not a great reason.

Restore the previous ABI.
2021-12-09 15:58:53 -05:00
Sebastien Alaiwan
a2260d3b1f
Fix compilation (#4656)
* Delete public accessor, whose only user is one unit-test

The underlying container type becomes invisible from the outside.

* Fix compilation
2021-12-09 12:42:53 -05:00
jiaxin.lai
d240d0db92
fix file encoding (#4654) 2021-12-09 09:43:55 -05:00
Andrei Malashkin
6926c3d9a3
treat google user type as normal semantic google. It's a backport from diligent fork (#4632) 2021-12-09 09:42:40 -05:00
Sebastien Alaiwan
b9e255b366
DefUseManager: rename comparison operators to 'CompareAndPrintDifferences' (#4624)
This make sense, as those are actually debug functions
and shouldn't be used in production code.
2021-12-09 09:41:42 -05:00
Sebastien Alaiwan
f37551d2b6
Use a struct (instead of tuple), with explicit member names. (#4621)
* Cleanup includes.

* Simplify assertion.

* Use a struct with named members for 'UserEntry'
2021-12-09 09:40:29 -05:00
Sebastien Alaiwan
64328e94db
Avoid an extra map lookup (#4623)
Speedup: 5% less time on a real-world compilation batch
(nearly 10k parallel compilations)
(Durations: Before: 156.5s, After: 147.4s)
2021-12-08 14:53:36 -05:00
Marius Hillenbrand
1ed847f438
Fix endianness of string literals (#4622)
* Fix endianness of string literals

To get correct and consistent encoding and decoding of string literals
on big-endian platforms, use spvtools::utils::MakeString and MakeVector
(or wrapper functions) consistently for handling string literals.

- add variant of MakeVector that encodes a string literal into an
  existing vector of words
- add variants of MakeString
- add a wrapper spvDecodeLiteralStringOperand in source/
- fix wrapper Operand::AsString to use MakeString (source/opt)
- remove Operand::AsCString as broken and unused
- add a variant of GetOperandAs for string literals (source/val)
... and apply those wrappers throughout the code.

Fixes  #149

* Extend round trip test for StringLiterals to flip word order

In the encoding/decoding roundtrip tests for string literals, include
a case that flips byte order in words after encoding and then checks for
successful decoding. That is, on a little-endian host flip to big-endian
byte order and then decode, and vice versa.

* BinaryParseTest.InstructionWithStringOperand: also flip byte order

Test binary parsing of string operands both with the host's and with the
reversed byte order.
2021-12-08 12:01:26 -05:00
Shahbaz Youssefi
b162ede0de
Use schema instead of reserved in header description (#4615)
For consistency with SPIR-V disassembly which outputs Schema for this
field.
2021-12-08 11:55:36 -05:00
Alastair Donaldson
1f3f0f185b
Avoid uninitialised read when parsing hex float (#4646)
Ensures that when an attempt to read a floating-point value from an
input stream fails, the recieving variable for the read does not end up
uninitialised.

Fixes OSS-Fuzz:40432
Fixes #4644
2021-12-08 11:09:25 -05:00
Alastair Donaldson
f9bcc82ec7
Exit when ID overflow occurs in a fuzzing build (#4652)
Currently if an ID overflow occurs, spirv-opt (and other users of
IRContext) emits a warning and starts returning 0 when fresh ids are
requested. This tends to lead to crashes - such as null pointer
exceptions. When these arise during fuzzing they lead to auto-reported
bugs.

This change uses an ifdef guard to instead gracefully exit as soon as an
ID overflow occurs when the build is a fuzzing build.

Related issue: #4539.
2021-12-04 07:18:21 +00:00
Diego Novillo
c75a1a46f3
Fix https://github.com/KhronosGroup/SPIRV-Tools/issues/4462 (#4651)
This prevents CCP from making constant -> constant transitions when
evaluating instruction values.  In this case, FClamp is evaluated twice.
On the first evaluation, if computes FClamp(0.5, 0.5, -1) which returns
-1.  On the second evaluation, it computes FClamp(0.5, 0.5, VARYING)
which returns 0.5.

Both fold() computations are correct given the semantics of FClamp() but
this causes a lateral transition in the constant lattice which was not
being considered VARYING by CCP.
2021-12-02 10:40:28 -05:00
Natalie Chouinard
d0a827a9f3
Copy OpDecorateStrings in DescriptorScalarReplacementPass (#4649)
Along with OpDecorate, also clone the OpDecorateString instructions for
variables created in the descriptor scalar replacement pass.

Fixes microsoft/DirectXShaderCompiler#3705
2021-11-29 02:11:22 -05:00
Natalie Chouinard
b023c0da1d
Remove default arguments from lambda (#4648)
Fixes compile failure due to pedantic warning:
`error: default argument specified for lambda parameter [-Werror=pedantic]`
2021-11-26 12:58:43 -05:00
Steven Perron
8c155b364c
Manually fold floating point division by zero (#4637)
See https://github.com/KhronosGroup/SPIRV-Tools/issues/4636 for details.

Fixes #4636.
2021-11-24 14:13:58 -05:00
alan-baker
4b092d2ab8
Allow ADCE to remove dead inputs (#4629)
* https://github.com/KhronosGroup/Vulkan-Docs/issues/666 clearly
  specified that interfaces do not require an input if there is an
  associated output
* ADCE can now remove unused input variables (though they are kept if
  the preserve interfaces option is used)
2021-11-16 15:54:17 -05:00
alan-baker
21e3f681e2
Update SPIRV-Headers (#4628)
* Fix compile
* Fix test
2021-11-10 16:32:09 -05:00
alan-baker
b014238e08
Allow WorkgroupSize on variables for Kernels (#4627)
* Update tests
2021-11-10 15:06:39 -05:00
Greg Fischer
352a411278
Fix handling of OpPhi in convert-relaxed-to-half (#4618)
Fixes #4452
2021-11-09 10:36:50 -07:00
alan-baker
339d4475c1
Improve decoration validation (#4490)
Fixes #4469

* Checks that decorations only usable with structure members are not
  used by OpDecorate or OpDecorateId
* Checks that decorations not allowed on structure members are not used
  with OpMemberDecorate
* Checks decoration targets for most core decorations
* Performs some Vulkan specific validation on deorations
2021-11-05 13:18:19 -04:00
Jaebaek Seo
1589720e10
spirv-opt: create OpDecorate for OpMemberDecorate in desc-sroa (#4617)
The scalar replacement of a resource array/struct variable must create
OpDecorate for elements if OpMemberDecorate instructions decorate
the elements.
2021-11-05 11:05:36 -04:00
Pelle Johnsen
0d0013002a
Add Wasm build (#3752)
* Add wasm build

* Run wasm ci on push

* Add copyright notice to wasm files

* [wasm] Update Emscripten

* [wasm] Change global lambda to regular function

* [wasm] Show detected core count during build

* [wasm] Set JS version from CHANGES, GITHUB_RUN_ID

Also remove custom docker emscripten build with brotli, as not used

* [wasm] Change github actions to use npm-publish

* [wasm] Us docker-compose up for CI

* [wasm] pass GITHUB_RUN_ID to docker

* [wasm] Change GITHUB_RUN_ID to GITHUB_RUN_NUMBER

* [wasm] Fix GITHUB_RUN_NUMBER in docker-compose.yml
2021-11-01 16:45:51 -04:00
Steven Perron
1082de6bb3
Handle overflowing id in merge return (#4606)
If the ids overflow when creating an integer constant in the ir_builder, there will be a nullptr dereference.  This is happening from inside merge return.

We need to propagate the error up, and make sure it is handled appropriately.
2021-11-01 08:45:32 -04:00
Alastair Donaldson
97d4495600
Avoid bitwise and in boolean expression (#4603)
In #3404 a logical && was replaced with a bitwise & to ensure that
both side-effecting arguments were evaluated. However, this leads to
warnings from some compilers (leading to the OSS-Fuzz build breaking,
in particular).

This change reworks the relevant code so that both arguments to the
logical && are evaluated into temporaries.
2021-10-29 15:36:51 -04:00
Ralf Habacker
e3c7098104
In generated cmake config file for SPIRV-Tools only access cmake target, if present (#4590)
Fixes #4582
2021-10-29 14:05:45 -04:00
sfricke-samsung
c194bb2a7f
spirv-val Update LocalSizeId VUID (#4602) 2021-10-29 11:58:02 -04:00