Commit Graph

861 Commits

Author SHA1 Message Date
Diego Novillo
74327845aa Generic value propagation engine.
This class implements a generic value propagation algorithm based on the
conditional constant propagation algorithm proposed in

     Constant propagation with conditional branches,
     Wegman and Zadeck, ACM TOPLAS 13(2):181-210.

The implementation is based on

     A Propagation Engine for GCC
     Diego Novillo, GCC Summit 2005
     http://ols.fedoraproject.org/GCC/Reprints-2005/novillo-Reprint.pdf

The purpose of this implementation is to act as a common framework for any
transformation that needs to propagate values from statements producing new
values to statements using those values.
2017-11-27 23:32:06 -05:00
Diego Novillo
83228137e1 Re-format source tree - NFC.
Re-formatted the source tree with the command:

$ /usr/bin/clang-format -style=file -i \
    $(find include source tools test utils -name '*.cpp' -or -name '*.h')

This required a fix to source/val/decoration.h.  It was not including
spirv.h, which broke builds when the #include headers were re-ordered by
clang-format.
2017-11-27 14:31:49 -05:00
Andrey Tuganov
d8b2013ecf Derivative opcodes require Fragment exec model
Added validator check that all derivative opcodes require Fragment
execution model.
2017-11-27 12:05:25 -05:00
Andrey Tuganov
c170afd93b Relaxed OpImageWrite texel type check 2017-11-24 14:31:08 -05:00
Andrey Tuganov
f84f266977 Relaxed OpImageRead validation rules
Removed the check that result type of OpImageRead should be a vector4.
Will reenable/adapt once the spec is clarified on what the right
dimension should be.
2017-11-24 10:12:24 -05:00
Andrey Tuganov
3e08a3f718 Add validation checks for Execution Model
Currently checks that these instructions are called from entry points
with Fragment execution model.
OpImageImplicit*
OpImageQueryLod
OpKill
2017-11-23 23:38:03 -05:00
Alan Baker
746bfd210a Adding new def -> use mapping container
Replaced representation of uses

* Changed uses from unordered_map<uint32_t, UseList> to
set<pairInstruction*, Instruction*>>
* Replaced GetUses with ForEachUser and ForEachUse functions
* updated passes to use new functions
* partially updated tests
* lots of cleanup still todo

Adding an unique id to Instruction generated by IRContext

Each instruction is given an unique id that can be used for ordering
purposes. The ids are generated via the IRContext.

Major changes:
* Instructions now contain a uint32_t for unique id and a cached context
pointer
 * Most constructors have been modified to take a context as input
 * unfortunately I cannot remove the default and copy constructors, but
 developers should avoid these
* Added accessors to parents of basic block and function
* Removed the copy constructors for BasicBlock and Function and replaced
them with Clone functions
* Reworked BuildModule to return an IRContext owning the built module
 * Since all instructions require a context, the context now becomes the
basic unit for IR
* Added a constructor to context to create an owned module internally
* Replaced uses of Instruction's copy constructor with Clone whereever I
found them
* Reworked the linker functionality to perform clones into a different
context instead of moves
* Updated many tests to be consistent with the above changes
 * Still need to add new tests to cover added functionality
* Added comparison operators to Instruction

Adding tests for Instruction, IRContext and IR loading

Fixed some header comments for BuildModule

Fixes to get tests passing again

* Reordered two linker steps to avoid use/def problems
* Fixed def/use manager uses in merge return pass
* Added early return for GetAnnotations
* Changed uses of Instruction::ToNop in passes to IRContext::KillInst

Simplifying the uses for some contexts in passes
2017-11-23 16:40:02 -05:00
Lei Zhang
b02c9a5802 Allow derived access chain without uses in access chain conversion 2017-11-23 16:00:28 -05:00
Andrey Tuganov
ab892f7bd6 Add derivatives validation pass
Checks operands of instructions in opcode range from OpDPdx to
OpFwidthCoarse.
2017-11-23 14:17:10 -05:00
David Neto
c2999273d9 Move SetContextMessageConsumer into libspirv namespace
Avoid polluting the global namespace.
2017-11-23 13:56:12 -05:00
Steven Perron
28c415500d Create a local value numbering pass
Creates a pass that removes redundant instructions within the same basic
block.  This will be implemented using a hash based value numbering
algorithm.

Added a number of functions that check for the Vulkan descriptor types.
These are used to determine if we are variables are read-only or not.

Implemented a function to check if loads and variables are read-only.
Implemented kernel specific and shader specific versions.

A big change is that the Combinator analysis in ADCE is factored out
into the IRContext as an analysis. This was done because it is being
reused in the value number table.
2017-11-23 11:45:09 -05:00
Andrey Tuganov
f407ae2b50 Validator pass for image instructions
Includes validation rules for OpImageXXX and ImageOperand.

Doesn't include OpTypeImage and OpImageSparseXXX.

Disabled an invalid test.
2017-11-22 14:34:15 -05:00
GregF
e28edd458b Optimize loads/stores on nested structs
Also fix LocalAccessChainConvert test: nested structs now convert

Add InsertExtractElim test for nested struct
2017-11-21 17:56:03 -05:00
Andrey Tuganov
250a235a8d Add new compression algorithm and models
Add new "short descriptor" algorithm to MARK-V codec.

Add three shader compression models:
lite - fast, poor compression
mid - balanced
max - best compression
2017-11-21 17:32:58 -05:00
Alan Baker
a771713e42 Adding an unique id to Instruction generated by IRContext
Each instruction is given an unique id that can be used for ordering
purposes. The ids are generated via the IRContext.

Major changes:
* Instructions now contain a uint32_t for unique id and a cached context
pointer
 * Most constructors have been modified to take a context as input
 * unfortunately I cannot remove the default and copy constructors, but
 developers should avoid these
* Added accessors to parents of basic block and function
* Removed the copy constructors for BasicBlock and Function and replaced
them with Clone functions
* Reworked BuildModule to return an IRContext owning the built module
 * Since all instructions require a context, the context now becomes the
basic unit for IR
* Added a constructor to context to create an owned module internally
* Replaced uses of Instruction's copy constructor with Clone whereever I
found them
* Reworked the linker functionality to perform clones into a different
context instead of moves
* Updated many tests to be consistent with the above changes
 * Still need to add new tests to cover added functionality
* Added comparison operators to Instruction
* Added an internal option to LinkerOptions to verify merged ids are
unique
* Added a test for the linker to verify merged ids are unique

* Updated MergeReturnPass to supply a context
* Updated DecorationManager to supply a context for cloned decorations

* Reworked several portions of the def use tests in anticipation of next
set of changes
2017-11-20 17:49:10 -05:00
Lei Zhang
4019bcfd57 Fix hard-coded header path
If SPIRV-Tools is used as an external project and have
googletest being kept in the same directory as it, we
won't have gmock-matchers.h in external/. This will
result in a compilation error.

Use gmock.h instead.
2017-11-17 19:54:55 -05:00
Steven Perron
eb4653a67f Add the decoration manager to the IRContext.
To make the decoration manger available everywhere, and to reduce the
number of times it needs to be build, I add one the IRContext.

As the same time, I move code that modifies decoration instruction into
the IRContext from mempass and the decoration manager.  This will make
it easier to keep everything up to date.

This should take care of issue #928.
2017-11-15 12:48:03 -05:00
Alan Baker
a92d69b43d Initial implementation of merge return pass.
Works with current DefUseManager infrastructure.

Added merge return to the standard opts.

Added validation to passes.

Disabled pass for shader capabilty.
2017-11-15 10:27:04 -05:00
Diego Novillo
98281ed411 Add analysis to compute mappings between instructions and basic blocks.
This analysis builds a map from instructions to the basic block that
contains them.  It is accessed via get_instr_block().  Once built, it is kept
up-to-date by the IRContext, as long as instructions are removed via
KillInst.

I have not yet marked passes that preserve this analysis. I will do it
in a separate change.

Other changes:

- Add documentation about analysis values requirement to be powers of 2.
- Force a re-build of the def-use manager in tests.
- Fix AllPreserveFirstOnlyAfterPassWithChange to use the
  DummyPassPreservesFirst pass.
- Fix sentinel value for IRContext::Analysis enum.

- Fix logic for checking if the instr<->block mapping is valid in KillInst.
2017-11-13 13:21:48 -05:00
Daniel Schürmann
a76d0977ac Fix decorations of inlined functions.
Fixes issue #728.  Currently the inliner is not generating decorations for
inlined code which corresponds to function code which has decorations. An
example of decorations that are relevant: RelaxedPrecision, NoContraction.

The solution is to replicate the decoration during inlining.
2017-11-13 12:49:25 -05:00
David Neto
76555bd4ba Tests: Add optional dependency on Effcee stateful matcher
Add Effcee as an optional dependency for use in tests.  In future it will
be a required dependency.

Effcee is a stateful pattern matcher that has much of the functionality
of LLVM's FileCheck, except in library form.  Effcee makes it much easier
to write tests for optimization passes.

Demonstrate its use in a test for the strength-reduction pass.

Update README.md with example commands of how to get sources.

Update Appveyor and Travis-CI build rules.

Also: Include test libraries if not SPIRV_SKIP_TESTS
- SPIRV_SKIP_TESTS is implied by SPIRV_SKIP_EXECUTABLES
2017-11-13 11:34:21 -05:00
Steven Perron
f32d11f74b Add the IRContext (part 2): Add def-use manager
This change will move the instances of the def-use manager to the
IRContext.  This allows it to persists across optimization, and does
not have to be rebuilt multiple times.

Added test to ensure that the IRContext is validating and invalidating
the analyses correctly.
2017-11-08 13:35:34 -05:00
GregF
ac04b2faea Opt: Fix HasLoads to not report decoration as load. 2017-11-07 17:39:58 -05:00
Nuno Subtil
2dddb8193b Validate storage class of target pointer for OpStore 2017-11-02 13:44:11 -04:00
Steven Perron
476cae6f7d Add the IRContext (part 1)
This is the first part of adding the IRContext.  This class is meant to
hold the extra data that is build on top of the module that it
owns.

The first part will simply create the IRContext class and get it passed
to the passes in place of the module.  For now it does not have any
functionality of its own, but it acts more as a wrapper for the module.

The functions that I added to the IRContext are those that either
traverse the headers or add to them.  I did this because we may decide
to have other ways of dealing with these sections (for example adding a
type pool, or use the decoration manager).

I also added the function that add to the header because the IRContext
needs to know when an instruction is added to update other data
structures appropriately.

Note that there is still lots of work that needs to be done.  There are
still many places that change the module, and do not inform the context.
That will be the next step.
2017-10-31 13:46:05 -04:00
Nuno Subtil
d861ceffd4 Add validation for OpBranchConditional 2017-10-31 12:05:20 -04:00
GregF
94bec26afe ADCE: Dead if elimination
Mark structured conditional branches live only if one or more instructions
in their associated construct is marked live. After closure, replace dead
structured conditional branches with a branch to its merge and remove
dead blocks.

ADCE: Dead If Elim: Remove duplicate StructuredOrder code

Also generalize ComputeStructuredOrder so that the caller can specify the
root block for the order. Phi insertion uses pseudo_entry_block and adce and
dead branch elim use the first block of the function.

ADCE: Dead If Elim: Pull redundant code out of InsertPhiInstructions

ADCE: Dead If Elim: Encapsulate CFG Cleanup Initialization

ADCE: Dead If Elim: Remove redundant code from ADCE initialization

ADCE: Dead If: Use CFGCleanup to eliminate newly dead blocks

Moved bulk of CFG Cleanup code into MemPass.
2017-10-31 11:51:30 -04:00
Steven Perron
716138ee14 Add option to relax validation of store types.
There are a number of users of spriv-opt that are hitting errors
because of stores with different types.  In general, this is wrong, but,
in these cases, the types are the exact same except for decorations.

The options is "--relax-store-struct", and it can be used with the
validator or the optimizer.

We assume that if layout information is missing it is consistent.  For
example if one struct has a offset of one of its members, and the other
one does not, we will still consider them as being layout compatible.
The problem will be if both struct has and offset decoration for
corresponding members, and the offset are different.
2017-10-28 18:48:21 -04:00
Steven Perron
94dc66b74d Change the sections in the module to use the InstructionList class.
This change will replace a number of the
std::vector<std::unique_ptr<Instruction>> member of the module to
InstructionList.  This is for consistency and to make it easier to
delete instructions that are no longer needed.
2017-10-25 15:52:06 -04:00
Lei Zhang
063dbea0f1 Turn all function static non-POD variables into global POD variables
Function static non-POD data causes problems with DLL lifetime.
This pull request turns all static info tables into strict POD
tables. Specifically, the capabilities/extensions field of
opcode/operand/extended-instruction table are turned into two
fields, one for the count and the other a pointer to an array of
capabilities/extensions. CapabilitySet/EnumSet are not used in
the static table anymore, but they are still used for checking
inclusion by constructing on the fly, which should be cheap for
the majority cases.

Also moves all these tables into the global namespace to avoid
C++11 function static thread-safe initialization overhead.
2017-10-25 15:44:19 -04:00
Józef Kucia
90862fe4b1 Validate SpvOpVectorShuffle 2017-10-24 11:45:03 -04:00
Jesus Carabano
13e6598947 restrict opcodes targeting OpDecorationGroup 2017-10-24 11:39:08 -04:00
Daniel Schürmann
97990dc907 Fixed --eliminate-common-uniform so that it does not eliminate loads of volatile variables. 2017-10-24 11:17:33 -04:00
Andrey Tuganov
cfd95f3d5a Refactored compression debugger
Markv codec now receives two optional callbacks:
LogConsumer for internal codec logging
DebugConsumer for testing if encoding->decoding produces the original
results.
2017-10-23 22:12:40 -04:00
Steven Perron
5834719fc1 Add pass to remove dead variables at the module level.
There does not seem to be any pass that remove global variables.  I
think we could use one.  This pass will look specifically for global
variables that are not referenced and are not exported.  Any decoration
associated with the variable will also be removed.  However, this could
cause types or constants to become unreferenced.  They will not be
removed.  Another pass will have to be called to remove those.
2017-10-23 13:57:05 -04:00
David Neto
2436794736 Optimizer: OpModuleProcessed is in its own layout section
This is a recent decision from the SPIR WG.  The spec update
has not yet been published.
Khronos SPIR-V internal issue 199
2017-10-23 10:46:37 -04:00
Andrey Tuganov
39e25fd8ab Add validation pass for conversion instructions
The pass checks correctness of operands of instruction in opcode range
OpConvertFToU - OpBitset.

Disabled invalid tests

Disabled UConvert validation until Vulkan CTS can catch up.

Add validate_conversion to Android.mk

Also remove duplicate entry in CMakeLists.txt.
2017-10-20 13:51:24 -04:00
Steven Perron
bb7802b18c Change BasicBlock to use InstructionList to hold instructions.
This is the first step in replacing the std::vector of Instruction
pointers to using and intrusive linked list.

To this end, we created the InstructionList class.  It inherites from
the IntrusiveList class, but add the extra concept of ownership.  An
InstructionList owns the instruction that are in it.  This is to be
consistent with the current ownership rules where the vector owns the
instruction that are in it.

The other larger change is that the inst_ member of the BasicBlock class
was changed to using the InstructionList class.

Added test for the InsertBefore functions, and making sure that the
InstructionList destructor will delete the elements that it contains.

I've also add extra comments to explain ownership a little better.
2017-10-20 12:37:44 -04:00
David Neto
8ec62deb23 The reviewed cfg_cleanup optimize pass 2017-10-19 15:28:09 -04:00
Diego Novillo
c75704ec08 CFG cleanup pass - Remove unreachable blocks.
- Adds a new pass CFGCleanupPass.  This serves as an umbrella pass to
  remove unnecessary cruft from a CFG.
- Currently, the only cleanup operation done is the removal of
  unreachable basic blocks.
- Adds unit tests.
- Adds a flag to spirvopt to execute the pass (--cfg-cleanup).
2017-10-19 15:16:29 -04:00
GregF
1a9061a2be ADCE: Treat privates like locals in entry point with no calls
This is needed for ongoing legalization of HLSL. It allows removal
of accesses to textures/buffers that are not used.
2017-10-13 15:39:14 -04:00
David Neto
941a234132 Validator: Test OpReturnValue type check
The check already existed.  I added a test for it.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/876
2017-10-13 15:19:13 -04:00
Andrey Tuganov
8de8dd8c8c Reenable validate type unique pass
Vulkan CTS patch fixing the instances of non-unique type declaration in
autogenerated code has recently been submitted.
2017-10-12 15:46:06 -04:00
Andrey Tuganov
2401fc0a72 Refactored MARK-V API
- switched from C to C++
- moved MARK-V model creation from backend to frontend
- The same MARK-V model object can be used to encode/decode multiple
files
- Added MARK-V model factory (currently only one option)
- Added --validate option to spirv-markv (run validation while
encoding/decoding)
2017-10-12 15:40:40 -04:00
Andrey Tuganov
b54997e6eb Validator checks OpReturn called from void func
Added check into validate_cfg which checks that OpReturn is not called
from functions which are supposed to return a value.
2017-10-12 15:32:32 -04:00
Steven Perron
720beb161a Generic intrusive linked list class.
This commit is the initial implementation of the intrusive linked list
class.  It includes the implementation in the header files, and unit
test.

The iterators are circular: incrementing end() gives begin() and
decrementing begin() gives end().  Also made it valid to
decrement end().

Expliticly defines move constructor and move assignment
- Visual Studio 2013 does not implicitly generate the move constructor or
  move assignments.  So they need to be explicit, otherwise it will try to
  use the copy constructor, which we explicitly deleted.
- Can't use "= default" either.
  Seems like VS2013 does not support explicitly using the default move
  constructors and move assignments, so I wrote them out.
2017-10-12 12:40:18 -04:00
GregF
63064bd9eb DeadBranchElim: Add dead case elimination
Expands dead branch elimination to eliminate dead switch cases. It also
changes dbe to eliminate orphaned merge blocks and recursively eliminate
any blocks thereby orphaned.
2017-10-12 11:44:05 -04:00
Pierre Moreau
86627f7b3f Implement Linker (module combiner)
Add extra iterators for ir::Module's sections
Add extra getters to ir::Function
Add a const version of BasicBlock::GetLabelInst()

Use the max of all inputs' version as version

Split debug in debug1 and debug2
- Debug1 instructions have to be placed before debug2 instructions.

Error out if different addressing or memory models are found

Exit early if no binaries were given

Error out if entry points are redeclared

Implement copy ctors for Function and BasicBlock
- Visual Studio ends up generating copy constructors that call deleted
  functions while compiling the linker code, while GCC and clang do not.
  So explicitly write those functions to avoid Visual Studio messing up.

Move removing duplicate capabilities to its own pass

Add functions running on all IDs present in an instruction

Remove duplicate SpvOpExtInstImport

Give default options value for link functions

Remove linkage capability if not making a library

Check types before allowing to link

Detect if two types/variables/functions have different decorations

Remove decorations of imported variables/functions and their types

Add a DecorationManager

Add a method for removing all decorations of id

Add methods for removing operands from instructions

Error out if one of the modules has a non-zero schema

Update README.md to talk about the linker

Do not freak out if an imported built-in variable has no export
2017-10-06 18:33:53 -04:00
GregF
da04f5640e AggressiveDCE: Fix to not treat parameter memory refs as local
This fixes a bug that incorrectly deletes stores to parameters, which
can be used to return values from functions.
2017-10-05 10:59:45 -04:00
Pierre Moreau
c87e9671ab Compact-ids pass should update the header ID bound 2017-10-03 11:24:28 -04:00
David Neto
169266e9b8 DiagnosticStream move ctor moves output duties to new object
- Take over contents of the expiring message stream
- Prevent the expiring object from emitting anything during destruction
2017-10-03 11:23:54 -04:00
David Neto
77feb8dd03 Compact-ids pass should update instruction's result_id member
Also update the result type field.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/827
2017-09-27 08:31:05 -04:00
Andrey Tuganov
64d5e5214f Add bitwise operations validator pass
The pass checks correctness of operand types of all bitwise instructions
(opcode range from SpvOpShiftRightLogical to SpvOpBitCount).
2017-09-26 14:22:37 -04:00
Andrey Tuganov
dcf42433a6 Add remaining opcodes to arithmetics validation
Add validation rules for:
- OpIAddCarry
- OpISubBorrow
- OpUMulExtended
- OpSMulExtended

Includes some refactoring of old code.
2017-09-26 11:47:34 -04:00
Steven Perron
e43c91046b Create the dead function elimination pass
Creates a pass called eliminate dead functions that looks for functions
that could never be called, and deletes them from the module.

To support this change a new function was added to the Pass class to
traverse the call trees from diffent starting points.

Includes a test to ensure that annotations are removed when deleting a
dead function.  They were not, so fixed that up as well.

Did some cleanup of the assembly for the test in pass_test.cpp.  Trying
to make them smaller and easier to read.
2017-09-26 11:18:06 -04:00
Andrey Tuganov
c25b5bea35 Add SPIRV_SPIRV_COMPRESSION option to cmake
The option is off by default.
cmake -DSPIRV_BUILD_COMPRESSION=ON ..
enables the compression lib, executable, and test build.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/834
2017-09-25 14:37:08 -04:00
Andrey Tuganov
3f5e1a91ae Validator: fix logicals pass for OpSelect pointers
OpSelect works with pointers also when capability
VariablePointersStorageBuffer is declared (before worked only with
capability VariablePointers).
2017-09-21 16:12:14 -04:00
David Neto
33b879c105 elim-multi-store: only patch loop header phis that we created
There can already be OpPhi instructions in a loop header that
are unrelated to the optimization.  We should not be patching those.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/826
2017-09-21 10:01:30 -04:00
Andrey Tuganov
cf85ad1429 Add validate logicals pass to the validator
New pass checks operands of all instructions listed under
3.32.15. Relational and Logical Instructions
2017-09-20 10:37:12 -04:00
Andrey Tuganov
4e3cc2f57f Refactored validate_aritmetics.cpp
Improved error messages and readability.
2017-09-20 10:30:54 -04:00
Steven Perron
e4c7d8e748 Add strength reduction; for now replace multiply by power of 2
Create a new optimization pass, strength reduction, which will replace
integer multiplication by a constant power of 2 with an equivalent bit
shift.  More changes could be added later.

- Does not duplicate constants

- Adds vector |Concat| utility function to a common test header.
2017-09-18 17:01:36 -04:00
David Neto
a91cecfefc Recognize SPV_AMD_shader_fragment_mask 2017-09-14 10:37:18 -04:00
Andrey Tuganov
c6dfc11880 Add new checks to validate arithmetics pass
New operations:
- OpDot
- OpVectorTimesScalar
- OpMatrixTimesScalar
- OpVectorTimesMatrix
- OpMatrixTimesVector
- OpMatrixTimesMatrix
- OpOuterProduct
2017-09-08 11:08:41 -04:00
David Neto
c843ef8ab5 validator: OpModuleProcessed allowed in layout section 7c
Recent spec fix from SPIR Working group:
  Allow OpModuleProcessed after debug names, but before any
  annotation instructions.
2017-09-07 17:45:51 -04:00
Andrey Tuganov
b36acbec0e Update MARK-V to version 1.01
Includes:
- Multi-sequence move-to-front
- Coding by id descriptor
- Statistical coding of non-id words
- Joint coding of opcode and num_operands

Removed explicit form Huffman codec constructor
- The standard use case for it is to be constructed from initializer list.

Using serialization for Huffman codecs
2017-09-06 16:03:16 -04:00
David Neto
25ddfec08e Inliner: Fix LoopMerge when inline into loop header of multi block loop
This adapts the fix for the single-block loop.  Split the loop like
before.  But when we move the OpLoopMerge back to the loop header,
redirect the continue target only when the original loop was a single
block loop.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/800
2017-09-05 19:46:24 -04:00
Andrey Tuganov
82df4bbd68 Add validation pass for arithmetic operations
The pass checks if arithmetic operations (such as OpFMul) receive
correct operands.
2017-09-05 12:21:53 -04:00
David Neto
0d3b8329a4 Make enums for all currently published extensions
Use the list from the SPIR-V registry page.  Also, capture it as
a string so it's much easier to update via copy-paste.

The validator will accept modules that declare these known
extensions.  However, we might not know about new tokens or
instructions declared in them.  For that we need grammar updates
applied to SPIRV-Headers.
2017-09-02 15:10:52 -04:00
David Neto
860c4197b0 Inliner: Remap callee entry block id to single-trip loop header
Otherwise cloned phis can be invalid.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/790
2017-09-01 15:56:14 -04:00
David Neto
efff5fabfa Inline: Fix single-block loop caller cases
If the caller block is a single-block loop and inlining will
replace the caller block by several blocks, then:
- The original OpLoopMerge instruction will end up in the *last*
  such block.  That's the wrong place to put it.
- Move it back to the end of the first block.
- Update its Continue Target ID to point to the last block

We also have to take care of cases where the inlined code
begins with a structured header block.  In this case
we need to ensure the restored OpLoopMerge does not appear
in the same block as the merge instruction from the callee's
first block.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/787
2017-09-01 15:47:17 -04:00
David Neto
e6279cde7a Update tests for new preferred name as ShaderViewportIndexLayerEXT
This reacts to a recent update to SPIRV-Headers
2017-09-01 10:29:57 -04:00
Andrey Tuganov
725284c2ef Extension allows multiple same OpTypePointer types
SPV_KHR_variable_pointers allows OpTypePointer to declare multiple
pointer identical types.

https://github.com/KhronosGroup/SPIRV-Tools/issues/781
2017-09-01 10:14:15 -04:00
GregF
7c3de19ce7 DeadBranchElim: Fix dead block detection to ignore backedges
- DeadBranchElim: Make sure to mark orphan'd merge blocks and continue
targets as live.
- Add test with loop in dead branch
- Add test that orphan'd merge block is handled.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/776
2017-08-30 13:37:46 -04:00
GregF
a699d1ade7 Inline: Fix remapping of non-label forward references in callee phi 2017-08-29 18:35:05 -06:00
Andrey Tuganov
d41a52415a Fix encode zero bits on word boundary bug
Bit stream writer was manifesting incorrect behaviour when the following
two conditions were met:
- writer was on 64-bit word boundary
- WriteBits was invoked with num_bits=0 (can happen when a Huffman codec has only one
value)

The bug was causing very rare sporadic corruption which was detected by
tests after a random experimental change in MARK-V model.
2017-08-28 13:36:39 -04:00
David Neto
851ff8395a Updated capabilites for SampleMask
SPIRV-Headers recently fixed the capability dependency
for SampleMask.  It depends on Shader, not SampleRateShading
2017-08-24 10:00:39 -04:00
GregF
429ca05b3f Opt: Create InlineOpaquePass
Only inline calls to functions with opaque params or return

TODO: Handle parameter type or return type where the opqaue
type is buried within an array.
2017-08-18 18:04:30 -04:00
GregF
c8c86a0d36 Opt: Have "size" passes process full entry point call tree.
Includes code to deal correctly with OpFunctionParameter. This
is needed by opaque propagation which may not exhaustively inline
entry point functions.

Adds ProcessEntryPointCallTree: a method to do work on the
functions in the entry point call trees in a deterministic order.
2017-08-18 10:16:01 -04:00
Andrey Tuganov
17d941af4f Huffman codec can serialize to text
Refactored the Huffman codec implementation and added ability to
serialize to C++-like text format. This would reduce the time-complexity
if loading hard-coded codecs.
2017-08-15 23:57:21 -04:00
GregF
1d477b9898 Opt: Add opaque tests 2017-08-15 15:54:41 -06:00
Andrey Tuganov
78cf86150e Add id descriptor feature to SPIR-V
Id descriptors are computed as a recursive hash of all instructions used
to define an id. Descriptors are invarint of actual id values and
the similar code in different files would produce the same descriptors.

Multiple ids can have the same descriptor. For example
%1 = OpConstant %u32 1
%2 = OpConstant %u32 1
would produce two ids with the same descriptor. But
%3 = OpConstant %s32 1
%4 = OpConstant %u32 2
would have descriptors different from %1 and %2.

Descriptors will be used as handles of move-to-front sequences in SPIR-V
compression.
2017-08-10 18:44:52 -04:00
GregF
b0310a4156 ADCE: Add support for function calls
ADCE will now generate correct code in the presence of function calls.
This is needed for opaque type optimization needed by glslang. Currently
all function calls are marked as live. TODO: mark calls live only if they
write a non-local.
2017-08-10 17:30:05 -04:00
David Neto
2a1014be9c Inliner: callee can have early return that isn't multi-return
Avoid generating an invalid OpLabel.
Create the continue target for the single-trip loop only if
you actually created the header for the single-trip loop.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/755
2017-08-10 11:43:44 -04:00
GregF
e28bd39997 Inline: Split out InlineExhaustivePass from InlinePass 2017-08-04 17:56:46 -04:00
GregF
f4b29f3bf7 Add CommonUniformElim pass
- UniformElim: Only process reachable blocks

- UniformElim: Don't reuse loads of samplers and images across blocks.
  Added a second phase which only reuses loads within a block for samplers
  and images.

- UniformElim: Upgrade CopyObject skipping in GetPtr

- UniformElim: Add extensions whitelist
  Currently disallowing SPV_KHR_variable_pointers because it doesn't
  handle extended pointer forms.

- UniformElim: Do not process shaders with GroupDecorate

- UniformElim: Bail on shaders with non-32-bit ints.

- UniformElim: Document support for only single index and add TODO.
2017-08-03 11:34:58 -04:00
GregF
c1b46eedbd Add MemPass, move all shared functions to it. 2017-08-02 14:24:02 -04:00
Andrey Tuganov
30bee67439 Add multi-sequence move-to-front implementation
Add MultiMoveToFront class which supports multiple move-to-front
sequences and allows to promote value in all sequences at once.

Added caching for last accessed sequence handle and last accessed value
in each sequence.
2017-08-02 14:07:24 -04:00
GregF
7954740d54 Opt: Delete names and decorations of dead instructions 2017-07-26 18:36:41 -04:00
Lei Zhang
9f6efc76c8 Opt: HasOnlySupportedRefs should consider OpCopyObject
This fixes test failure after merging the previous pull request.
2017-07-25 23:22:09 -04:00
GregF
1182415581 Add extension whitelists to size-reduction passes.
Currently only SPV_KHR_variable_pointers is disallowed in passes which
do pointer analysis. Positive and negative tests of the general extensions
mechanism were added to aggressive_dce but cover all passes.
2017-07-25 19:14:02 -04:00
GregF
adb237f3bd Fix handling of CopyObject in GetPtr and its call sites 2017-07-21 18:08:01 -04:00
GregF
9de4e69856 Add AggressiveDCEPass
Create aggressive dead code elimination pass
This pass eliminates unused code from functions. In addition,
it detects and eliminates code which may have spurious uses but which do
not contribute to the output of the function. The most common cause of
such code sequences is summations in loops whose result is no longer used
due to dead code elimination. This optimization has additional compile
time cost over standard dead code elimination.

This pass only processes entry point functions. It also only processes
shaders with logical addressing. It currently will not process functions
with function calls. It currently only supports the GLSL.std.450 extended
instruction set. It currently does not support any extensions.

This pass will be made more effective by first running passes that remove
dead control flow and inlines function calls.

This pass can be especially useful after running Local Access Chain
Conversion, which tends to cause cycles of dead code to be left after
Store/Load elimination passes are completed. These cycles cannot be
eliminated with standard dead code elimination.

Additionally: This transform uses a whitelist of instructions that it
knows do have side effects, (a.k.a. combinators).  It assumes other
instructions have side effects: it will not remove them, and assumes
they have side effects via their ID operands.
2017-07-10 11:30:25 -04:00
GregF
cc8bad3a5b Add LocalMultiStoreElim pass
A SSA local variable load/store elimination pass.
For every entry point function, eliminate all loads and stores of function
scope variables only referenced with non-access-chain loads and stores.
Eliminate the variables as well.

The presence of access chain references and function calls can inhibit
the above optimization.

Only shader modules with logical addressing are currently processed.
Currently modules with any extensions enabled are not processed. This
is left for future work.

This pass is most effective if preceeded by Inlining and
LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
will reduce the work that this pass has to do.
2017-07-07 17:54:21 -04:00
GregF
52e247f221 DeadBranchElim: Add DeadBranchElimPass 2017-07-07 15:16:25 -04:00
David Neto
35a0695844 Include memory and semantics IDs when iterating over inbound IDs
Fixes Instruction::ForEachInId so it covers
SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID and SPV_OPERAND_TYPE_SCOPE_ID.
Future proof a bit by using the common spvIsIdType routine.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/697
2017-07-05 10:36:57 -04:00
Andrey Tuganov
abc6f5a672 MARK-V decoder supports extended instructions 2017-07-04 16:31:19 -04:00
Chris Forbes
78338d5ba9 Convert pattern stack from deque to vector, and share it
Also move various vector::reserve calls to State ctor
Negligible perf benefit, but more tidy.
2017-07-04 12:02:26 -04:00
Andrey Tuganov
e842c17eb5 Added fixed width encoding to bit_stream
Fixed width encoding is intended to be used for small unsigned integers
when the upper bound is known both to the encoder and the decoder
(for example move-to-front rank).
2017-07-04 11:57:13 -04:00
Andrey Tuganov
73e8dac5b9 Added compression tool tools/spirv-markv. Work in progress.
Command line application is located at tools/spirv-markv
API at include/spirv-tools/markv.h

At the moment only very basic compression is implemented, mostly varint.
Scope of supported SPIR-V opcodes is also limited.

Using a simple move-to-front implementation instead of encoding mapped
ids.

Work in progress:
- Does not cover all of SPIR-V
- Does not promise compatibility of compression/decompression across
  different versions of the code.
2017-06-30 12:22:48 -04:00
Andrey Tuganov
8d3882a408 Added log(n) move-to-front implementation
The implementation is based on AVL and order statistic tree.

It accepts all kinds of values and the implementation
doesn't expect the behaviour to be consistent with id coding.

Intended by SPIR-V compression algorithms.
2017-06-29 16:16:18 -04:00
Andrey Tuganov
40a2829611 Added Huffman codec to utils
Attached ids to Huffman nodes for deterministic internal node
comparison.
2017-06-29 14:51:01 -04:00
GregF
ad1d0351a0 BlockMerge: Add BlockMergePass
Also, add BasicBlock::tail()
2017-06-27 11:31:33 -04:00
Rex Xu
5fbbadca4e Add support for SPV AMD extensions 2017-06-21 15:08:07 -04:00
GregF
6136bf9e0b mem2reg: Add InsertExtractElimPass 2017-06-21 08:13:15 -04:00
GregF
0c5722fc01 mem2reg: Add LocalSingleStoreElimPass
Eliminate function scope variables with one store, if possible.
2017-06-19 10:43:02 -04:00
GregF
7c8da66bc2 mem2reg: Add pass to eliminate local loads and stores in single block. 2017-06-12 17:03:47 -04:00
GregF
aa7e687ef0 Mem2Reg: Add Local Access Chain Convert pass
- Supports OpAccessChain and OpInBoundsAccessChain
- Does not process modules with non-32-bit integer types.
2017-06-04 12:49:27 -04:00
Andrey Tuganov
20fe946666 Added extension SPV_VALIDATOR_ignore_type_decl_unique
If extension is present in the module, validator will ignore the "type
declaration must be unique" rule.
2017-05-25 11:36:48 -04:00
David Neto
dbc2049aa3 Add SPIR-V 1.2 support, for OpenCL 2.2 2017-05-15 17:10:07 -04:00
David Neto
eb720b2ad1 Fix size_t conversion error on MinGW 2017-05-15 11:55:22 -04:00
Greg Fischer
bba812f4e4 Inline: Inline early return function if no returns in loop. 2017-05-12 17:18:00 -04:00
Andrey Tuganov
3eb716cae4 Added bit stream utils
Also added generalized zigzag coding.
- Due to signed integers being mostly non-negative, improved zigzag coding
  to favor positive values.
2017-05-12 17:08:33 -04:00
Andrey Tuganov
f5facf842f Stats analyzer aggregates OpConstant usage 2017-05-09 11:50:15 -04:00
Andrey Tuganov
b4cf371936 Stats analyzer uses validator
Stats analyzer calls validator to check the instruction and update
validator state.

Fixed unit tests (validator was failing).
2017-05-09 11:17:23 -04:00
Mike Lothain
3f90058d2f Update set_spec_const_default_value_test.cpp
Work around warning of dangling else
2017-05-08 10:41:48 -04:00
Andrey Tuganov
87a3f651e2 Added Markov chain analysis to stats
Added data structure to SpirvStats which is used to collect statistics
on opcodes following other opcodes.

Added a simple analysis print-out to spirv-stats.
2017-04-26 02:31:13 -04:00
GregF
a107d349e3 Inline: Do not inline functions with multiple returns (for now) 2017-04-25 16:50:57 -06:00
qining
144f59e451 Add bit pattern interface for setting default value for spec constants 2017-04-21 11:22:47 -04:00
Andrey Tuganov
1e309af80a Added --compact-ids to /tools/opt
The pass remaps ids to a compact set which starts with %1 and
has no gaps.
2017-04-20 10:54:39 -04:00
Andrey Tuganov
b173d1c3cd Added option --preserve-numeric-ids to tools/spirv-as
Added options to tools::Assemble
2017-04-13 14:13:33 -04:00
Andrey Tuganov
4f216402ba Added statistical analysis tool (tool/stats)
Currently analyzes percentages of the following:
- version (how many 1.0 or 1.1)
- generator
- extension
- capability
- opcode prevalence
2017-04-10 17:15:04 -04:00
David Neto
72debb8fd4 Test source language HLSL 2017-04-07 09:54:38 -04:00
David Neto
bf68c81426 Support SPV_KHR_storage_buffer_storage_class
Includes interaction with SPV_KHR_variable_pointers

TODO: Update capabilitly dependency tests for new capabilities.
2017-04-07 09:54:38 -04:00
Ehsan Nasiri
23af06c3a3 Validator support for Variable Pointer extension.
If the variable_pointer extension is used:

* OpLoad's pointer argument may be the result of any of the following:
 * OpSelect
 * OpPhi
 * OpFunctionCall
 * OpPtrAccessChain
 * OpCopyObject
 * OpLoad
 * OpConstantNull

* Return value of a function may be a pointer.

* It is valid to use a pointer as the return value of a function.

* OpStore should allow a variable pointer argument.
2017-04-07 09:49:48 -04:00
David Neto
4895ace29b Update cap tests for SPV_KHR_16bit_storage 2017-04-07 09:49:48 -04:00
David Neto
4087e89bc6 Test asm,dis support for SPV_KHR_variable_pointers 2017-04-07 09:49:48 -04:00
David Neto
11a867f412 Add FlattenDecoration transform
Add --flatten-decorations to spirv-opt

Flattens decoration groups.  That is, replace OpDecorationGroup
and its uses in OpGroupDecorate and OpGroupMemberDecorate with
ordinary OpDecorate and OpMemberDecorate instructions.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/602
2017-04-06 11:19:56 -04:00
Lei Zhang
5c3c054c1f Group targets into folders
This plays nicer with IDEs.
2017-04-06 09:44:33 -04:00
David Neto
afc60bbebf Fix optimizer on when to write the binary
The spvtools::Optimizer::Run method should also write the output binary
if optimization succeeds without changes but the output binary vector
does not have exactly the same contents as the input binary.
We have to check both the base pointer of the storage and the size of
the vector

Added a test for this too.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/611
2017-04-03 15:48:50 -04:00
David Neto
ceb1d4f2fd Avoid inlining calls to external functions
External functions don't have bodies to inline anyway.
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/605
2017-03-31 10:36:58 -04:00
David Neto
2410e00851 Add low priority test suggestions for inliner 2017-03-29 18:02:40 -04:00
Greg Fischer
04fcc66743 Add exhaustive function call inlining to spirv-opt
Inlining is done for all functions designated as entry points.

Add optional validation to test fixture method SinglePassRunAndCheck.
2017-03-29 18:02:40 -04:00
David Neto
7fe8a57a5b Support SPV_AMD_gcn_shader
Supported in assembler, disassembler, and binary parser.

The validator does not check SPV_AMD_gcn_shader validation rules
beyond parsing the extension.

Adds generic support for generating instruction tables for vendor
extensions.

Adds generic support for extensions the validator should recognize
(but not check) but which aren't derived from the SPIR-V core
grammar file.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/594
2017-03-23 16:32:35 -04:00
David Neto
fa834dea40 Fix validator message for bad logical pointer
Affects OpLoad and OpStore validation.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/588
2017-03-23 15:50:45 -04:00
David Neto
ddd40f855b Update capability tests for SPV_KHR_16bit_storage rev 7
The SPIR-V core grammar file in a recent SPIRV-Headers
applied the fix from Rev 7 of SPV_KHR_16bit_storage:
FPRoundingMode enums are now enabled by the capabilities
introduced by that extension.

Update the SPIRV-Tools tests accordingly.
2017-03-23 15:46:08 -04:00
David Neto
0066a363d6 Add SpirvTools::Validate that takes an options object
Add spvtools::ValidatorOptions RAII wrapper around
a spv_validator_options value.
2017-03-17 12:48:51 -04:00
Andrey Tuganov
971ede33b2 Validator dissallows unsupported Vulkan capability
If environment is SPV_ENV_VULKAN_1_0, disallow OpCapability operands
which are not supported by Vulkan 1.0.

See https://github.com/KhronosGroup/SPIRV-Tools/issues/572
2017-03-17 10:28:35 -04:00
Andrey Tuganov
c804c125c5 Autogenererating enum-string mappings from grammar
Autogenerating the following code:
- extension enum
- extension-to-string
- string-to-extension
- capability-to-string

Capability mapping table will not compile if incomplete.
TODO: Use "spirv-latest-version.h" instead of 1.1.

Added function to generate capability tables for tests.
2017-03-16 15:29:17 -04:00
Andrey Tuganov
b011633171 Validator checks if operands require extension
If required extension is not found, returning new error
SPV_ERROR_MISSING_EXTENSION.
2017-03-14 13:39:43 -04:00
Andrey Tuganov
1fb8c37b57 Refactored enum_set
- removed forgotten file enum_set.cpp
- added IsEmpty and HasAnyOf
- hidden unsafe functions Add(uint32_t), Contains(uint32_t)
- added new tests
2017-03-10 13:38:32 -05:00
Andrey Tuganov
1c43cb8550 Validator parses and registers OpExtension
Known extensions are saved in validation state. Unknown extension
produce a dignostic message, but do not fail the validation.

Moved extension definitions to their own file.
2017-03-09 15:28:33 -05:00
David Neto
42037205a8 Test SPV_KHR_multiview in assembler, disassembler 2017-03-08 17:11:22 -05:00
David Neto
7327f63c34 Test SPV_KHR_device_group in assembler, disassembler 2017-03-08 17:11:22 -05:00
David Neto
83b334e549 Test SPV_KHR_16bit_storage in assembler, disassembler 2017-03-08 17:11:22 -05:00
David Neto
0004f721e3 Test SPV_KHR_subgroup_vote support in assembler, disassembler 2017-03-08 17:11:22 -05:00
Andrey Tuganov
9696393c5b Fix nullptr dereferencing in val_fixtures.cpp 2017-03-08 15:41:46 -05:00
David Neto
892b009959 Change Ids in tests to avoid confusion
The assembler assigns ID numbers sequentially, so it's confusing
to have a %1 in the source assembly when it isn't the first mentioned
ID.  Rewrite the ID names to avoid this situation in a few cases.
2017-03-07 09:51:32 -05:00
Aliya Pazylbekova
edb52647bd Validate that SpecId decoration target is a OpSpecConstant instruction
on a scalar

Fixes: https://github.com/KhronosGroup/SPIRV-Tools/issues/275
2017-03-07 09:51:16 -05:00
Andrey Tuganov
11fbe5dc1f Validator: unique type check allows runtime arrays
OpTypeRuntimeArray is an aggregate and therefore can have duplicate
declarations.
2017-03-02 17:24:29 -05:00
Ehsan Nasiri
2046e24498 Fixes issue #489.
From the SPIR-V Spec 2.16.1:

A function declaration (an OpFunction with no basic blocks), must have
a Linkage Attributes Decoration with the Import Linkage Type.

A function definition (an OpFunction with basic blocks) cannot be
decorated with the Import Linkage Type.
2017-03-02 10:06:29 -05:00
Lei Zhang
40be4bdd34 Allow using FPRoundingMode when see VK_KHR_16bit_storage
According to the extension, FPRoundingMode should be allowed to
use without requiring Kernel capability when VK_KHR_16bit_storage
is enabled.
2017-03-01 18:25:28 -05:00
Andrey Tuganov
94d94e1f4a Validator: downgraded dupl type decl to warning
Validator check for uniqueness of type declarations
(commit 0e9c24fdd1)
was causing failures in vulkancts tests.

Downgrading from error to warning.
2017-03-01 17:50:26 -05:00
Andrey Tuganov
0e9c24fdd1 Issue 559: check type declaration uniqueness
Adds PassTypeUnique to the validator.
Disallows repeated declarations of all types except for aggregates.
2017-02-28 22:27:08 -05:00
Ehsan Nasiri
da4ae05638 Add command line options struct for the validator
The limit for the number of struct members is parameterized using
command line options.

Add --max-struct-depth command line option.
Add --max-switch-branches command line option.
Add --max-function-args command line option.
Add --max-control-flow-nesting-depth option.
Add --max-access-chain-indexes option.
2017-02-28 12:00:06 -05:00
David Neto
af7125dfb0 Validation of type decls for SPV_KHR_16bit_storage
Allow declaration of 16bit int or 16bit float in
the presence of capabilities from SPV_KHR_16bit_storage
2017-02-27 13:12:59 -05:00
Adam Van Ymeren
c0949703b1 Fixes issue #548
Add validation checks for the reserved OpImageSparseSampleProj* opcodes.
2017-02-16 16:32:33 -05:00
David Neto
dadd5161bb Check strict domination of merge block
If a merge block is reachable, then it must be *strictly* dominated
by its header.  Until now we've allowed the header and the merge
block to be the same.

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

Also: Use dominates and postdominates methods on BasicBlock to
improve readability.
2017-02-10 12:26:10 -05:00
Ehsan Nasiri
f2867d7485 The Signedness in OpTypeInt must always be 0.
When Kernel capability is used, The Signedness in OpTypeInt must always
be 0. Fixes issue #492.
2017-02-10 12:21:16 -05:00
Ehsan Nasiri
affbc31849 Making the unit tests more robust.
It is best to check the error messages of unit tests that fail
validation. This will ensure that a validation failure is due to what we
expect and not due to some secondary reason.

Updating SPIR-V Validator unit tests with error message checks.
2017-01-29 22:50:37 -05:00
Ehsan Nasiri
cb009b3862 Fixes issue #497.
The Linkage Attributes Decoration cannot be applied to functions
targeted by an OpEntryPoint instruction.
2017-01-19 16:34:47 -05:00
Ehsan Nasiri
9c71c572e5 Check BuiltIn Decoration rules.
When applied to a structure-type member, all members of that structure
type must also be decorated with BuiltIn. (No allowed mixing of built-in
variables and non-built-in variables within a single structure.)

When applied to a structure-type member, that structure type cannot be
contained as a member of another structure type.

There is at most one object per Storage Class that can contain a
structure type containing members decorated with BuiltIn, consumed per
entry-point.
2017-01-19 16:01:06 -05:00
Ehsan Nasiri
3a7df2cf1b Fixes issue #532.
It is acceptable for OpAccessChain, OpInBoundsAccessChain,
OpPtrAccessChain, OpInBoundsPtrAccessChain, OpCompositeInsert, and
OpCompositeExtract to not take any indexes as arguments. In such cases,
no indexing will be done on the Base pointer/composite.
2017-01-19 11:03:04 -05:00
Ehsan Nasiri
eb7d2534df Fixes issue #493.
Check function call operands and return type agree with the called
function type.

The validation code exists. I have fixed the unit tests.
2017-01-18 17:04:00 -05:00
Ehsan Nasiri
d75bf5ef03 Validation for decoration rules. Fixes issue #499.
Added a new file where all the decoration validation can be performed.

In this change the SPIRV Spec Section 2.16.1 is implemented:
"It is illegal to initialize an imported variable. This means
that a module-scope OpVariable with initialization value cannot be
marked with the Import Linkage Type."

Also added unit tests.
2017-01-18 16:29:14 -05:00
Ehsan Nasiri
fcf7df069d Adding decoration class and tests.
* Added the decoration class as well as the code that registers the
decorations for each <id> and also decorations for struct members.

* Added unit tests for decorations in ValidationState as well as
decoration id tests.
2017-01-16 16:52:08 -05:00
Ehsan Nasiri
1c11c8690f Validation of OpEntryPoint usage.
According to the SPIRV Spec (2.16.1):
* There is at least one OpEntryPoint instruction, unless the Linkage
capability is being used.

* No function can be targeted by both an OpEntryPoint instruction and an
OpFunctionCall instruction.

Also updated unit tests to includ OpEntryPoint.
2017-01-13 16:15:11 -05:00
Ehsan Nasiri
68e36ec7e9 Introducing a new flow for running the Validator.
We are adding a new API which can be called to run the SPIR-V validator,
and retrieve the ValidationState_t object. This is very useful for
unit testing.

I have also added basic unit tests that demonstrate usage of this flow
and ease of use to verify correctness.
2017-01-13 16:07:03 -05:00
David Neto
545a6c1dc3 Provide friendly names for true and false 2017-01-11 16:33:45 -05:00
Ehsan Nasiri
d1868b9361 Validation for Composite Extract and Insert.
The validity of each command is checked based on the descripton in
SPIR-V Spec Section 3.32.12 (Composite Instructions).

Also checked that the number of indexes passed to these commands does
not exceed the limit described in 2.17 (Universal Limits).

Also added unit tests for each one.
2017-01-06 17:14:38 -05:00
Ehsan Nasiri
109ce225c9 Fixes bug #517.
entry_block_to_construct_ maps an entry block to its construct. The key
in this map (the entry block) is not unique, and therefore the entry for
the continue construct gets overwritten when the selection construct is
discovered.

Since a given block may be the entry block of different types of
constructs, the (basic_block, construct_type) pair should be able to
uniquely identify the construct.

Adds test:
- In this test, a basic block is the entry block of a continue construct
  as well as the entry block of a selection construct.
  It can be shown that this unit test would crash without the fix in this
  PR and passes with the fix in this PR.
2017-01-06 14:23:17 -05:00
Ehsan Nasiri
ff272a9820 Adding validation code for PtrAccessChain.
Validation for OpPtrAccessChain is similar to OpAccessChain with the
following difference: OpPtrAccessChain takes an extra argument (word 4)
which is the Element <id> argument.

Validation for OpInBoundsPtrAccessChain is also similar to OpPtrAccessChain.

Also added tests for all access chain instructions:
Modified the existing parameterized tests to accommodate OpPtrAccessChain and
OpInBoundsPtrAccessChain.

Also fixed a typo in previous commits.
2017-01-03 16:36:35 -05:00
Ehsan Nasiri
c656c23ad3 Refactoring unit tests using TEST_P.
Using parameterized unit tests to avoid duplicate code that runs the
tests of OpAccessChain and OpInBoundsAccessChain.

This is also a steppingstone to adding tests for OpPtrAccessChain and
OpInBoundsPtrAccessChain.
2017-01-03 14:58:48 -05:00
Ehsan Nasiri
6993fc413d Validation code for control flow nesting depth.
According to Section 2.17 (Universal Limits) of the SPIR-V Spec, the
control flow nesting depth may not be larger than 1023.

This is checked only when we are required to have structured
control flow.  Otherwise it's not clear how to compute control
flow nesting depth.
2016-12-23 14:14:50 -05:00
David Neto
37422e9dba Support building under CYGWIN
- Parse CHANGES file with Universal Python line endings in case
  the source tree was checked out with Windows line endings.
- Use our own clone of strnlen_s which might not be available
  everywhere.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/508
2016-12-21 10:34:23 -05:00
David Neto
5a0b5ca4a7 Get vendor tool info from the SPIR-V registry file
Update old tests to use officially registered vendor names;
this affected "Codeplay".
2016-12-09 14:01:43 -05:00
Ehsan Nasiri
d004cd46db Adding validation for OpInBoundsAccessChain.
The validation for this instruction is similar to OpAccessChain.

Include a test for testing a struct with (valid) depth of 255.
2016-12-08 15:11:30 -05:00
Ehsan Nasiri
4fb79b54f2 Validation for struct nesting depth.
According to sectin 2.17 in SPIR-V Spec, the structure nesting depth may
not be larger than 255. This is interpreted as structures nested in
structures. The code does not look into arrays or follow pointers to see
if it reaches a structure downstream.

Use memoization to avoid exponential runtime.
2016-12-07 16:15:56 -05:00
David Neto
d5b0cd34c9 An OpVariable initializer can be a module-scope variable
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/482
2016-12-07 16:04:51 -05:00
Ehsan Nasiri
aadf696fce Fixing bug in OpAccessChain validation code.
The validation code for OpAccessChain was missing OpTypeRuntimeArray as
a possible type that can be indexed into.

This was caught by running the validator on VKCTS.

Also adding unit tests for it.
2016-12-06 09:55:39 -05:00
Ehsan Nasiri
1f6123fa5f Add a test that exercises wrong usage of result id
Result <id> resulting from an instruction within a function may not be
used outside that function.
2016-12-06 09:50:08 -05:00
Ehsan Nasiri
bab1aad856 Adding validation code for OpAccessChain.
* Result Type must be an OpTypePointer. Its Type operand must be the
type reached by walking the Base’s type hierarchy down to the last
provided index in Indexes, and its Storage Class operand must be the
same as the Storage Class of Base.

* Base must be a pointer, pointing to the base of a composite object.

* Indexes walk the type hierarchy to the desired depth, potentially down
to scalar granularity. The first index in Indexes will select the
top-level member/element/component/element of the base composite. All
composite constituents use zero-based numbering, as described by their
OpType... instruction. The second index will apply similarly to that
result, and so on. Once any non-composite type is reached, there must
be no remaining (unused) indexes. Each of the Indexes must:
- be a scalar integer type,
- be an OpConstant when indexing into a structure.

* Check for the case where no indexes are passed to OpAccessChain.

Minor improvements based on code review.
2016-12-02 13:50:41 -05:00
Ehsan Nasiri
4b26d514ef Validate the number of global and local variables.
According to the Universal Limits section of the SPIR-V Spec (2.17), the
number of global variables may not exceed 65,535 and the number of local
variables may not exceed 524,287.

Also added unit tests for each one.
2016-12-01 16:04:13 -05:00
Ehsan Nasiri
490617133e Validate the number of arguments in OpTypeFunction
According to the SPIR-V spec (section 2.17: Universal Limits), the
OpTypeFunction instruction may not take more than 255 arguments for the
function. Also added unit tests for it.
2016-12-01 15:49:31 -05:00
Ehsan Nasiri
3c8bc80e3a Adding validation code for OpSwitch limits
The number of (literal, label) pairs passed to OpSwitch may not exceed
16,383. Added code to validate this and added unit tests for it.

Also fixed a typo in another validor error message.
2016-11-30 15:36:05 -05:00
Ehsan Nasiri
bef80716d7 Validation for number of Struct members.
The number of members in a struct may not exceed 16,383.
Also Adding unit tests for Struct size limit check.
2016-11-30 15:29:37 -05:00
Ehsan Nasiri
bd5b0bfca1 Checks that result IDs are within the ID bound specified in the SPIR-V header
This is described in Section 2.17 of the SPIR-V Spec.

* Updated existing unit test 'SemanticsIdIsAnIdNotALiteral' to pass by
manipulating the ID bound in its binary header.

* Fixed boundary check in the code.

* Added unit test to check the case that the largest ID is equal to the
ID bound.
2016-11-28 11:44:10 -05:00
Ehsan Nasiri
f72189c249 Validation for OpSampledImage instruction.
This change implements the validation for usages of OpSampledImage
instruction as described in the Data Rules section of the Universal
Validation Rules of the SPIR-V Spec.
2016-11-24 09:29:10 -05:00
Ehsan Nasiri
6fa6a3f647 Adding validation for OpSpecConstantComposite.
SpecConstantComposite may specialize to a vector, matrix, array, or
struct. In each case, the number of components and type of components
that are being specialized to must match the expected result type.

Removed use of macros in these tests.
Now using the spvValidateBase class. Using CompileSuccessfully(), and
ValidateInstructions() to compile to binary and run the validator. Also
using getDiagnosticString() to check the proper error message string.
All the heavy lifting is done in ValidateBase class.
2016-11-19 15:47:28 -05:00
Ehsan Nasiri
8c414eb579 Adding validation code for OpTypeStruct.
According to the Data Rules section of 2.16.1. Universal Validation
Rules of the SPIR-V Spec:

Forward reference operands in an OpTypeStruct
* must be later declared with OpTypePointer
* the type pointed to must be an OpTypeStruct
* had an earlier OpTypeForwardPointer forward reference to the same <id>
2016-11-16 16:41:56 -05:00
David Neto
c935253c91 Make friendly number-based names for OpConstant
For example:
  %int_42 = OpConstant %int 42
  %int_n42 = OpConstant %int -42
  %float_3_14 = OpConstant %float 3.14
2016-11-15 14:05:03 -05:00
David Neto
4f750c0dcc Extract EmitNumericLiteral from disassembler
Test with disassembly of numeric literals.
2016-11-15 14:05:03 -05:00
Ehsan Nasiri
d0620061c7 Adding validation code for more data rules.
These rules are under "Data Rules" in 2.16.1 (Universal Validation
Rules) part of the SPIR-V 1.1 Specification document:

* Scalar floating-point types can be parameterized only as 32 bit, plus
any additional sizes enabled by capabilities.

* Scalar integer types can be parameterized only as 32 bit, plus any
additional sizes enabled by capabilities.

* Vector types can only be parameterized with numerical types or the
OpTypeBool type.

* Matrix types can only be parameterized with floating-point types.

* Matrix types can only be parameterized as having only 2, 3, or 4
columns.

* Specialization constants (see Specialization) are limited to integers,
Booleans, floating-point numbers, and vectors of these.
2016-11-15 13:38:39 -05:00
Lei Zhang
38036a7203 Rename validation source files to comply with Google style guide. 2016-11-08 17:19:56 -08:00
Lei Zhang
2881fe958f Rename validation tests to comply with Google style guide. 2016-11-08 17:19:11 -08:00
Ehsan Nasiri
6c899a52f9 Adding validation for vector data rule.
Number of components in a vector can be 2 or 3 or 4. If Vector16
capability is used, 8 and 16 components are also allowed.
Also added unit tests for vector data rule.
2016-11-08 17:48:30 -05:00
Lei Zhang
4f57e140bf Renaming test files to comply with Google style guide.
Also posfixing test files with `_test' to make it more clear.
2016-11-07 14:41:51 -05:00
David Neto
ee6c877b53 Test SPV_KHR_shader_draw_parameters support
In assembler, disassembler, parser.
2016-10-12 10:47:28 -04:00
Lei Zhang
c1d5e660ee Add begin() and end() for TypeManager. 2016-09-30 16:56:42 -04:00
David Neto
f0a96c91f8 Remove unnecessary #include
This will make it easier to port these tests to different contexts.
2016-09-29 16:44:18 -04:00
Lei Zhang
f9cb7c282c Avoid appending EOL in StringifyMessage().
EOL should be appended when outputing to streams by the tool.
2016-09-23 15:13:24 -04:00
Lei Zhang
069b0a7339 Fix operand class test coverage table.
* Fix a missing column.
* Convert line endings.

This will make the table beautiful and searchable on Github.
2016-09-23 11:58:25 -04:00
Umar Arshad
a6ef1ea29e Fix forward reference issues with forword pointer
* Allows OpTypeForwardPointer to reference IDs not yet declared in
  the module
* Allows OpTypeStruct to reference IDs not yet declared in
  the module

Possible Issue: OpTypeStruct should only allow forward references
if the ID is a pointer that is referenced by a forward pointer. Need
Type support in Validator which is currently a work in progress.
2016-09-22 16:54:02 -04:00
Lei Zhang
1ca817a38e Use nullptr as the default message consumer to ignore all messages.
There is no difference between the previous IgnoreMessage() function
and a null std::function, from functionality's perspective.
The user can set nullptr as the MessageConsumer, so need to guard
against nullptr before calling the consumer anyway. It's better
we use it internally so that it may expose problems by us instead
of the user.
2016-09-21 17:23:03 -04:00
Lei Zhang
6effeaa7f1 Change some asserts to normal errors in IrLoader. 2016-09-21 17:22:00 -04:00
Lei Zhang
5edf054926 Add more Assemble(), Disassemble() and Validate() overloads. 2016-09-21 14:42:04 -04:00
Lei Zhang
620f05e679 Publish the C++ interface. 2016-09-21 14:41:47 -04:00
Lei Zhang
92411caa3b Rename SpvTools to SpirvTools. 2016-09-21 14:28:33 -04:00
Lei Zhang
6849a3cefd Use C style names for MessageLevel. 2016-09-21 12:44:37 -04:00
Lei Zhang
80eb0793c9 Change to use enum instead of enum class for MessageLevel.
This allows us to create C interface with MessageLevel later.
2016-09-21 11:30:41 -04:00
Lei Zhang
f18e1f293b Add a C++ interface to the optimization functionalities. 2016-09-20 16:52:05 -04:00
Lei Zhang
1bc0b275dd Allow changing MessageConsumer in Pass & PassManager.
Default-constructed Pass/PassManager will have a MessageConsumer
which ignores all messages. SetMessageConsumer() should be called
to supply a meaningful MessageConsumer.
2016-09-20 16:48:00 -04:00
Lei Zhang
2cbb2cce3e Change interface of Pass::Process() to return possible failures. 2016-09-20 16:40:17 -04:00
David Neto
12b5777912 Provide friendly names for shader ballot BuiltIns 2016-09-19 17:31:25 -04:00
Lei Zhang
3590279a73 Set the default source name as "input". 2016-09-19 10:20:22 -04:00
David Neto
9382035a22 Add basic support for SPV_KHR_shader_ballot
Requires use of SPIRV-Headers that has support
for SPV_KHR_shader_ballot.

Adds assembler, disassembler, binary parser support.

Adds general support for allowing an operand to be
only enabled by a set of extensions.

TODO: Validator support for extension checking.
2016-09-16 16:38:36 -04:00
Lei Zhang
8654caa565 Prepare the C++ interface for publication.
* Use PIMPL idiom in the C++ interface.
* Clean up interface for assembling and disassembling.
* Add validation into C++ interface.
* Add more tests for the C++ interface.
2016-09-16 16:37:27 -04:00
Lei Zhang
b54686d017 Move functions for building modules outside of the C++ interface. 2016-09-16 14:02:47 -04:00
Lei Zhang
869440ebd4 Let SPIRV_ASSERT() exit the program if the assertion fails. 2016-09-16 13:14:57 -04:00
Lei Zhang
114af21994 Add MessageConsumer to PassManager, Pass, and analysis interfaces.
Also convert some uses of assert() in optimization code to use
SPIRV_ASSERT(), SPIRV_UNIMPLEMENTED(), or SPIRV_UNREACHABLE()
accordingly.
2016-09-16 13:14:57 -04:00
Lei Zhang
bfd7cd6d6e Add utility macros for logging messages.
Add the following macros for logging purpose:
* SPIRV_ASSERT
* SPIRV_DEBUG
* SPIRV_UNIMPLEMENTED
* SPIRV_UNREACHABLE

The last two is always turned on, while the first two can only
be turned on in debug build.
2016-09-16 09:56:34 -04:00
Lei Zhang
755f97f534 Add a callback mechanism for communicating messages to callers.
Every time an event happens in the library that the user should be
aware of, the callback will be invoked.

The existing diagnostic mechanism is hijacked internally by a
callback that creates an diagnostic object each time an event
happens.
2016-09-15 12:35:48 -04:00
David Neto
e0dd033414 Make friendly names for built-in variables.
Handles only OpDecorate

Does not handle:
- decorations on struct members
- decoration via OpGroupDecorate
2016-09-14 15:25:24 -04:00
David Neto
1f3fb506e8 Fix validator: OpUndef can be member of a constant composite
This was enabled in SPIR-V 1.0 Rev 7

Fixes: https://github.com/KhronosGroup/SPIRV-Tools/issues/414
2016-09-14 15:21:09 -04:00
David Neto
4e2ed04d6e Clarify: Ok to pass null diagnostic to spvBinaryParse
It's a valid use case: I might mostly trust my binaries and I don't
care to to collect detailed diagnostic feedback.
2016-09-14 15:19:10 -04:00
David Neto
5c9080eea8 Fix validator SSA check: Phi can use its own value sometimes
Defer removal of a Phi's result id from the undefined-forward-reference
set until after you've scanned the arguments.  The reordering is only
significant for Phi.

Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/415
2016-09-14 15:15:28 -04:00
qining
66f5b4bfc5 Build "spec id->default val str" mapping from string
Add function `ParseDefaultValuesString()` to build the spec id->default
value string mapping required by `SetSpecConstantDefaultValuePass`.
2016-09-14 12:26:34 -04:00
qining
5ac63523d7 Guard against nullptr in number parsing utilities
ParseNumber(): Returns false if the given string is a nullptr.
ParseAndEncodeXXXX(): Returns kInvalidText and populate error message:
  "The given text is a nullptr", if the givne string is a nullptr.
2016-09-13 12:12:31 -04:00
qining
abf57933ea Set default values for spec const decorated by SpecId
The pass instance is constructed with a map from spec id (uint32_t) to
default values in string format. The default value strings will be
parsed to numbers according to the target spec constant type.

If the Spec Id decoration is found to be applied on multiple different
target ids, that decoration instruction (OpDecorate or OpGroupDecorate)
will be skipped. But other decoration instrucitons may still be
processed.
2016-09-12 23:21:42 -04:00
qining
049f80f3b9 Add IsSigned() to opt::Analysis::Integer. 2016-09-08 19:32:20 -04:00
qining
1773b95737 Pull out the number parsing logic
Pull out the number parsing logic from
AssemblyContext::binaryEncodeNumericLiteral() to utilities.

The new utility function: `ParseAndEncodeNumber()` now accepts:
  * number text to parse
  * number type
  * a emit function, which is a function which will be called with each
    parsed uint32 word.
  * a pointer to std::string to be overwritten with error messages.
    (pass nullptr if expect no error message)
and returns:
  * an enum result type to indicate the status

Type/Structs moved to utility:
  * template<typename T> class ClampToZeroIfUnsignedType

New type:
* enum EncodeNumberStatus: success or error code
* NumberType: hold the number type information for the number to be parsed.
 * several helper functions are also added for NumberType.

Functions moved to utility:
  * Helpers:
    * template<typename T> checkRangeAndIfHexThenSignExtend() -> CheckRangeAndIfHex....()
  * Interfaces:
    * template<typename T> parseNumber() -> ParseNumber()
    * binaryEncodeIntegerLiteral() -> ParseAndEncodeIntegerNumber()
    * binaryEncodeFloatingPointLiteral() -> ParseAndEncodeFloatingPointNumber()
    * binaryEncodeNumericLiteral() -> ParseAndEncodeNumber()

Tests added/moved to test/ParseNumber.cpp, including tests for:
* ParseNumber(): This is moved from TextToBinary.cpp to ParseNumber.cpp
* ParseAndEncodeIntegerNumber(): New added
* ParseAndEncodeFloatingPointNumber(): New added
* ParseAndEncodeNumber(): New added

Note that the error messages are kept almost the same as before, but
they may be inappropriate for an utility function. Those will be fixed
in another CL.
2016-09-08 18:42:54 -04:00
Lei Zhang
a35919c008 Merge diagnostic tests and single them out in a separate binary. 2016-09-08 17:26:53 -04:00
Lei Zhang
219f0cc13c Create separate binaries for validation tests. 2016-09-07 17:43:15 -04:00
Lei Zhang
ef600df16e Prefix test binaries with test_, rename UnitSPIRV, update README. 2016-09-07 17:26:18 -04:00
David Neto
9fc8658ef3 Relicense SPIRV-Tools under Apache 2.0
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/383

Finalize v2016.4
2016-09-02 10:00:29 -04:00
David Neto
0e001b70e4 Fix Google copyright lines 2016-09-02 10:00:29 -04:00
Lei Zhang
2ad3b74fa3 Tests for preserving line debug insts even killing its affecting targets. 2016-09-01 11:51:09 -04:00
qining
eb60e2945a Unify constants pass
De-duplicate constants and unifies the uses of constants for a SPIR-V
module. If two constants are defined exactly the same, only one of them
will be kept and all the uses of the removed constant will be redirected
to the kept one.

This pass handles normal constants (defined with
OpConstant{|True|False|Composite}), some spec constants (those defined
with OpSpecConstant{Op|Composite}) and null constants (defined with
OpConstantNull).

There are several cases not handled by this pass:

  1) If there are decorations for the result id of a constant defining
  instruction, that instruction will not be processed. This means the
  instruction won't be used to replace other instructions and other
  instructions won't be used to replace it either.

  2) This pass does not unify null constants (defined with
  OpConstantNull instruction) with their equivalent zero-valued normal
  constants (defined with OpConstant{|False|Composite} with zero as the
  operand values or component values).
2016-09-01 11:46:05 -04:00
David Neto
909d7f9bf5 Refactor CapabilitySet into templated class EnumSet 2016-09-01 09:32:22 -04:00
qining
2ce67252c8 Add forwarding so that passes' ctor can have args.
Also removed the default argument value of `skip_nop` for function
`SinglePassRunAndCheck()` and `SinglePassRunAndDisassemble()`. This is
required to support variadic arguments.
2016-08-31 15:27:55 -04:00
David Neto
273920c554 Handle capabilities larger than value 63
Use libspirv::CapabilitySet instead of a 64-bit mask.

Remove dead function spvOpcodeRequiresCapability and its tests.

The JSON grammar parser is simplified since it just writes the
list of capabilities as a braced list, and takes advantage of
the CapabilitySet intializer-list constructor.
2016-08-30 15:41:39 -04:00
David Neto
47f2a1414b Add libspirv::CapabilitySet
It's optimized for the common case, where capabilities have value
at most 63.
2016-08-30 15:41:39 -04:00
qining
76982706f9 Get annotation instructions of a given id. 2016-08-30 15:08:24 -04:00
qining
ecb5692389 Add AppendNames() interface for AssemblyBuilder 2016-08-29 17:18:31 -04:00
qining
380f36eae1 Fold spec constants to normal constants (values fixed)
For the spec constants defined by OpSpecConstantOp and
OpSpecContantComposite, if all of their operands are constants with
determined values (normal constants whose values are fixed), calculate
the correct values of the spec constants and re-define them as normal
constants.

In short, this pass replaces all the spec constants defined by
OpSpecContantOp and OpSpecConstantComposite with normal constants when
possible. So far not all valid operations of OpSpecConstantOp are
supported, we have several constriction here:

1) Only 32-bit integer and boolean (both scalar and vector) are
supported for any arithmetic operations. Integers in other width (like
64-bit) are not supported.
2) OpSConvert, OpFConvert, OpQuantizeToF16, and all the
operations under Kernel capability, are not supported.
3) OpCompositeInsert is not supported.

Note that this pass does not unify normal constants. This means it is
possible to have new generatd constants defining the same values.
2016-08-29 08:58:53 -04:00
David Neto
1d59aa0777 Pass manager recomputes Id bound automatically.
Fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/371
in the sense that the id bound is correct after all the passes
have been run.  But it might be inconsistent between passes.
2016-08-27 13:19:18 -04:00
David Neto
d7b6362ed7 Add Module::ComputeIdBound
When IDs change, something should use this utility method
and Module::SetIdBound before writing out the binary.
2016-08-26 16:27:12 -04:00
Lei Zhang
0a175eb0d6 Add tests for decoration_empty(). 2016-08-26 14:05:04 -04:00
David Neto
58e1a1e3be Test ir::Instruction::GetOperand and GetInOperand 2016-08-26 10:59:25 -04:00
David Neto
cc60caba1d IrLoader gracefully handles incomplete blocks and functions
This lets us write smaller test cases with the IrLoader, avoiding
boilerplate for function begin/end, and basic block begin/end.

Also ForEachInst is more forgiving of cases where a basic block
doesn't have a label, and when a function doesn't have a defining
or end instruction.
2016-08-26 10:15:15 -04:00
David Neto
53013cc816 Add Instruction begin and end mutable iterators
Refactored the instuction test.
2016-08-25 17:48:58 -04:00