platform/upstream/SPIRV-Tools.git
6 years agoADCE: Fix combinator initialization
GregF [Fri, 2 Feb 2018 23:57:39 +0000 (16:57 -0700)]
ADCE: Fix combinator initialization

The combinator initialization was only looking at the capabilities
in the shader and not the inferred capabilities. Geometry and tessellation
shaders were not setting the Shader capability which is inferred. So the
combinator set was not initialized correctly causing problems for ADCE.

6 years agoVS2013: LoopDescriptor LoopContainerType can't contain unique_ptr
David Neto [Mon, 5 Feb 2018 15:56:45 +0000 (07:56 -0800)]
VS2013: LoopDescriptor LoopContainerType can't contain unique_ptr

The loop descriptor must explicitly manage the storage for contained
Loop objects.

Fixes #1262

6 years agoAdd barrier instructions validation pass
Andrey Tuganov [Wed, 31 Jan 2018 21:29:54 +0000 (16:29 -0500)]
Add barrier instructions validation pass

6 years agoAvoid vector copies in range-for loops in opt/types.cpp
David Neto [Fri, 2 Feb 2018 15:28:52 +0000 (10:28 -0500)]
Avoid vector copies in range-for loops in opt/types.cpp

Also be more explicit about iterated types in other range-for loops.

6 years agoDisambiguate between const and nonconst ForEachSuccessorLabel
David Neto [Fri, 2 Feb 2018 22:17:42 +0000 (14:17 -0800)]
Disambiguate between const and nonconst ForEachSuccessorLabel

This helps VisualStudio 2013 compile the code.

Contributes to #1262

6 years agoAdd general folding infrastructure.
Steven Perron [Wed, 24 Jan 2018 18:26:33 +0000 (13:26 -0500)]
Add general folding infrastructure.

Create the folding engine that will

1) attempt to fold an instruction.
2) iterates on the folding so small folding rules can be easily combined.
3) insert new instructions when needed.

I've added the minimum number of rules needed to test the features above.

6 years agoStart v2018.1-dev
David Neto [Fri, 2 Feb 2018 16:27:07 +0000 (11:27 -0500)]
Start v2018.1-dev

6 years agoFinalize v2018.0
David Neto [Fri, 2 Feb 2018 16:25:58 +0000 (11:25 -0500)]
Finalize v2018.0

6 years agoUpdate CHANGES
David Neto [Fri, 2 Feb 2018 16:23:33 +0000 (11:23 -0500)]
Update CHANGES

6 years agoReordering performance passes ordering to produce better opts
Alan Baker [Wed, 31 Jan 2018 15:40:33 +0000 (10:40 -0500)]
Reordering performance passes ordering to produce better opts

* Moved initial insert/extract passes later to cover more opportunities
* Added an extra set of passes to clean up opportunities exposed later
in the pipeline

6 years agoAdd LoopUtils class to gather some loop transformation support.
Victor Lomuller [Fri, 26 Jan 2018 12:07:10 +0000 (12:07 +0000)]
Add LoopUtils class to gather some loop transformation support.

This patch adds LoopUtils class to handle some loop related transformations. For now it has 2 transformations that simplifies other transformations such as loop unroll or unswitch:
 - Dedicate exit blocks: this ensure that all exit basic block
   (out-of-loop basic blocks that have a predecessor in the loop)
   have all their predecessors in the loop;
 - Loop Closed SSA (LCSSA): this ensure that all definitions in a loop are used inside the loop
   or in a phi instruction in an exit basic block.

It also adds the following capabilities:
 - Loop::IsLCSSA to test if the loop is in a LCSSA form
 - Loop::GetOrCreatePreHeaderBlock that can build a loop preheader if required;
 - New methods to allow on the fly updates of the loop descriptors.
 - New methods to allow on the fly updates of the CFG analysis.
 - Instruction::SetOperand to allow expression of the index relative to Instruction::NumOperands (to be compatible with the index returned by DefUseManager::ForEachUse)

6 years agoAdd pass to reaplce invalid opcodes
Steven Perron [Tue, 30 Jan 2018 16:24:03 +0000 (11:24 -0500)]
Add pass to reaplce invalid opcodes

Creates a pass that will remove instructions that are invalid for the
current shader stage.  For the instruction to be considered for replacement

1) The opcode must be valid for a shader modules.
2) The opcode must be invalid for the current shader stage.
3) All entry points to the module must be for the same shader stage.
4) The function containing the instruction must be reachable from an entry point.

Fixes #1247.

6 years agoAdded OpenCL ExtInst validation rules
Andrey Tuganov [Tue, 9 Jan 2018 15:58:22 +0000 (10:58 -0500)]
Added OpenCL ExtInst validation rules

6 years agoAdd adjacency validation pass
Jeremy Hayes [Thu, 25 Jan 2018 23:32:01 +0000 (16:32 -0700)]
Add adjacency validation pass

Validate OpPhi predecessors.
Validate OpLoopMerge successors.
Validate OpSelectionMerge successors.
Fix collateral damage to existing tests.
Remove ValidateIdWithMessage.OpSampledImageUsedInOpPhiBad.

6 years agoFixed harmless uninit var warning
Andrey Tuganov [Wed, 31 Jan 2018 21:59:55 +0000 (16:59 -0500)]
Fixed harmless uninit var warning

6 years agoUse SPIR-V headers from "unified1" directory
David Neto [Tue, 23 Jan 2018 09:50:54 +0000 (17:50 +0800)]
Use SPIR-V headers from "unified1" directory

6 years agoRemove constexpr from Analysis operators
Alan Baker [Tue, 30 Jan 2018 21:43:55 +0000 (16:43 -0500)]
Remove constexpr from Analysis operators

* Had to remove templating from InstructionBuilder as a result
 * now preserved analyses are specified as a constructor argument
* updated tests and uses
* changed static_assert to a runtime assert
 * this should probably get further changes in the future

6 years agoOpt: Add ScalarReplacement to RegisterSizePasses
GregF [Wed, 31 Jan 2018 01:13:30 +0000 (18:13 -0700)]
Opt: Add ScalarReplacement to RegisterSizePasses

6 years agoAdd memory semantics checks to validate atomics
Andrey Tuganov [Thu, 25 Jan 2018 18:39:43 +0000 (13:39 -0500)]
Add memory semantics checks to validate atomics

6 years agoUpdate CHANGES
David Neto [Tue, 30 Jan 2018 22:47:00 +0000 (17:47 -0500)]
Update CHANGES

6 years agoPrevent unnecessary changes to the IR in dead branch elim
Alan Baker [Tue, 30 Jan 2018 20:00:27 +0000 (15:00 -0500)]
Prevent unnecessary changes to the IR in dead branch elim

* When handling unreachable merges and continues, do not optimize to the
same IR
 * pass did not check whether the unreachable blocks were in the
 optimized form before transforming them
* added a test to catch this issue

6 years agoImproved error message in val capabilities
Andrey Tuganov [Fri, 26 Jan 2018 16:29:15 +0000 (11:29 -0500)]
Improved error message in val capabilities

6 years agoEnhancements to block merging
Alan Baker [Thu, 25 Jan 2018 22:40:06 +0000 (14:40 -0800)]
Enhancements to block merging

* Should handle all possibilities
 * Stricter checks for what is disallowed:
  * header and header
  * merge and merge
 * Allow header and merge blocks to be merged
  * Erases the structured control declaration if merging header and
    merge blocks together.

6 years agoFix dereference of possibly nullptr
Alan Baker [Tue, 30 Jan 2018 15:15:43 +0000 (10:15 -0500)]
Fix dereference of possibly nullptr

* If the dead branch elim is performed on a module without structured
control flow, the OpSelectionMerge may not be present
 * Add a check for pointer validity before dereferencing
* Added a test to catch the bug

6 years agoInsertExtractElim: Split out DeadInsertElim as separate pass
GregF [Sat, 27 Jan 2018 00:05:33 +0000 (17:05 -0700)]
InsertExtractElim: Split out DeadInsertElim as separate pass

6 years agoFixes in CCP for #1228
Alan Baker [Thu, 25 Jan 2018 18:45:21 +0000 (10:45 -0800)]
Fixes in CCP for #1228

* Forces traversal of phis if the def has changed to varying
* Mark a phi as varying if all incoming values are varying
* added a test to catch the bug

6 years agoAdd LoopDescriptor as an IRContext analysis.
Victor Lomuller [Thu, 25 Jan 2018 10:33:06 +0000 (10:33 +0000)]
Add LoopDescriptor as an IRContext analysis.

Move some function definitions from header to source to avoid circular definition.

6 years agoDeadInsertElim: Detect and DCE dead Inserts
Greg Fischer [Thu, 11 Jan 2018 23:23:58 +0000 (16:23 -0700)]
DeadInsertElim: Detect and DCE dead Inserts

This adds Dead Insert Elimination to the end of the
--eliminate-insert-extract pass. See the new tests for examples of code
that will benefit.

Essentially, this removes OpCompositeInsert instructions which are not
used, either because there is no instruction which uses the value at the
index it is inserted, or because a subsequent insert intercepts any such
use.

This code has been seen to remove significant amounts of dead code from
real-life HLSL shaders being ported to Vulkan. In fact, it is needed to
remove dead texture samples which cause Vulkan validation layer errors
(unbound textures and samplers) if not removed . Such DCE is thus
required for fxc equivalence and legalization.

This analysis operates across "chains" of Inserts which can also contain
Phi instructions.

6 years agoInitial implementation of if conversion
Alan Baker [Tue, 16 Jan 2018 16:15:06 +0000 (11:15 -0500)]
Initial implementation of if conversion

* Handles simple cases only
* Identifies phis in blocks with two predecessors and attempts to
convert the phi to an select
 * does not perform code motion currently so the converted values must
 dominate the join point (e.g. can't be defined in the branches)
 * limited for now to two predecessors, but can be extended to handle
 more cases
* Adding if conversion to -O and -Os

6 years agoValidator: restricted some atomic ops for shaders
Andrey Tuganov [Wed, 24 Jan 2018 17:48:55 +0000 (12:48 -0500)]
Validator: restricted some atomic ops for shaders

Ban floating point case for OpAtomicLoad, OpAtomicExchange,
OpAtomicCompareExchange. In graphics (Shader) environments, these
instructions only operate on scalar integers. Ban the floating point
case. OpenCL supports atomic_float.

6 years agoAdded Vulkan-specifc checks to image validation
Andrey Tuganov [Tue, 23 Jan 2018 20:02:27 +0000 (15:02 -0500)]
Added Vulkan-specifc checks to image validation

Implemented Vulkan-specific rules:
- OpTypeImage must declare a scalar 32-bit float or 32-bit integer type
for the “Sampled Type”.
- OpSampledImage must only consume an “Image” operand whose type has its
“Sampled” operand set to 1.

6 years agoUse id_map in Fold*ToConstant
Steven Perron [Mon, 22 Jan 2018 19:48:43 +0000 (14:48 -0500)]
Use id_map in Fold*ToConstant

The folding routines are suppose to use the id_map provided to map the
ids in the instruction.  The ones I just added are missing it.

6 years agoAdd generic folding function and use in CCP
Steven Perron [Tue, 9 Jan 2018 17:45:46 +0000 (12:45 -0500)]
Add generic folding function and use in CCP

The current folding routines have a very cumbersome interface, make them
harder to use, and not a obvious how to extend.

This change is to create a new interface for the folding routines, and
show how it can be used by calling it from CCP.

This does not make a significant change to the behaviour of CCP.  In
general it should produce the same code as before; however it is
possible that an instruction that takes 32-bit integers as inputs and
the result is not a 32-bit integer or bool will not be folded as before.

It seems like andriod has a problem with INT32_MAX and the like.  I'll
explicitly define those if the are not already defined.

6 years agoFixes infinite loop in ADCE
Alan Baker [Thu, 18 Jan 2018 20:44:00 +0000 (15:44 -0500)]
Fixes infinite loop in ADCE

* Addresses how breaks are indentified to prevent infinite loops when
back to back loop share a merge and header
* Added test to catch the bug

6 years agoIntroduce an instruction builder helper class.
Victor Lomuller [Thu, 18 Jan 2018 17:14:58 +0000 (17:14 +0000)]
Introduce an instruction builder helper class.

The class factorize the instruction building process.
Def-use manager analysis can be updated on the fly to maintain coherency.
To be updated to take into account more analysis.

6 years agoSimplifying code for adding instructions to worklist
Alan Baker [Thu, 18 Jan 2018 19:15:54 +0000 (14:15 -0500)]
Simplifying code for adding instructions to worklist

* AddToWorklist can now be called unconditionally
 * It will only add instructions that have not already been marked as
 live
 * Fixes a case where a merge was not added to the worklist because the
 branch was already marked as live
* Added two similar tests that fail without the fix

6 years agoCreate a pass to work around a driver bug related to OpUnreachable.
Steven Perron [Wed, 17 Jan 2018 19:57:37 +0000 (14:57 -0500)]
Create a pass to work around a driver bug related to OpUnreachable.

We have come across a driver bug where and OpUnreachable inside a loop
is causing the shader to go into an infinite loop.  This commit will try
to avoid this bug by turning OpUnreachable instructions that are
contained in a loop into branches to the loop merge block.

This is not added to "-O" and "-Os" because it should only be used if
the driver being targeted has this problem.

Fixes #1209.

6 years agoAdding testcase for #1210
Alan Baker [Thu, 18 Jan 2018 16:02:57 +0000 (11:02 -0500)]
Adding testcase for #1210

6 years agoCFG: force the creation of a predecessor entry for all basic block.
Victor Lomuller [Thu, 18 Jan 2018 08:51:12 +0000 (08:51 +0000)]
CFG: force the creation of a predecessor entry for all basic block.

This ensure that all basic blocks in a function have a valid entry the CFG object.

The entry block has no predecessors but remains a valid basic block
for which we might want to query the number of predecessors.
Some unreachable basic blocks may not have predecessors as well.

6 years agospirv-dis: Add --color option to force color disassembly
David Neto [Wed, 17 Jan 2018 15:57:20 +0000 (10:57 -0500)]
spirv-dis: Add --color option to force color disassembly

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

6 years agoFixing missing early exit from break identification
Alan Baker [Wed, 17 Jan 2018 19:09:24 +0000 (14:09 -0500)]
Fixing missing early exit from break identification

6 years agoAdding support for switch removal in ADCE
Alan Baker [Mon, 15 Jan 2018 18:25:45 +0000 (13:25 -0500)]
Adding support for switch removal in ADCE

* Updated code to handle switches
* Enabled disabled test and added a couple new ones

6 years agoCapturing value table by reference in local redundancy elim
Alan Baker [Tue, 16 Jan 2018 21:27:13 +0000 (16:27 -0500)]
Capturing value table by reference in local redundancy elim

6 years agoUpdate CHANGES
David Neto [Wed, 17 Jan 2018 03:52:39 +0000 (22:52 -0500)]
Update CHANGES

6 years agoFixes missing increment in common uniform elim
Alan Baker [Tue, 16 Jan 2018 19:47:35 +0000 (14:47 -0500)]
Fixes missing increment in common uniform elim

* Addresses #1203
* Increments inIdx in IsConstantIndexAccessChain
 * added test to catch the bug

6 years agoSkip SpecConstants in CCP.
Steven Perron [Sat, 13 Jan 2018 05:28:40 +0000 (00:28 -0500)]
Skip SpecConstants in CCP.

At the moment specialization constants look like constants to ccp.  This
causes a problem because they are handled differently by the constant
manager.

I choose to simply skip over them, and not try to add them to the value
table.  We can do specialization before ccp if we want to be able to
propagate these values.

Fixes #1199.

6 years agoUpdate CHANGES
David Neto [Fri, 12 Jan 2018 23:52:42 +0000 (18:52 -0500)]
Update CHANGES

6 years agoAdd MatrixConstant
Greg Fischer [Fri, 12 Jan 2018 22:52:45 +0000 (15:52 -0700)]
Add MatrixConstant

6 years agoRemove redundant passes from legalization passes
Steven Perron [Fri, 12 Jan 2018 20:15:57 +0000 (15:15 -0500)]
Remove redundant passes from legalization passes

With work that Alan has done, some passes have become redundant.  ADCE
now removed unused variables.  Dead branch elimination removes
unreachable blocks.  This means we can remove CFG Cleanup and dead
variable elimination.

6 years agoAdding early exit versions of several ForEach* methods
Alan Baker [Fri, 12 Jan 2018 20:05:53 +0000 (15:05 -0500)]
Adding early exit versions of several ForEach* methods

* Looked through code for instances where code would benefit from early
exit
 * Added a corresponding WhileEach* method and updated the code

6 years agoMove initialization of the const mgr to the constructor.
Steven Perron [Fri, 12 Jan 2018 16:23:57 +0000 (11:23 -0500)]
Move initialization of the const mgr to the constructor.

The current code expects the users of the constant manager to initialize
it with all of the constants in the module.  The problem is that you do
not want to redo the work multiple times.  So I decided to move that
code to the constructor of the constant manager.  This way it will
always be initialized on first use.

I also removed an assert that expects all constant instructions to be
successfully mapped.  This is because not all OpConstant* instruction
can map to a constant, and neither do the OpSpecConstant* instructions.

The real problem is that an OpConstantComposite can contain a member
that is OpUndef.  I tried to treat OpUndef like OpConstantNull, but this
failed because an OpSpecConstantComposite with an OpUndef cannot be
changed to an OpConstantComposite.  Since I feel this case will not be
common, I decided to not complicate the code.

Fixes #1193.

6 years agoStart v2018.0-dev
David Neto [Fri, 12 Jan 2018 18:33:43 +0000 (13:33 -0500)]
Start v2018.0-dev

6 years agoFinalize v2017.3
David Neto [Fri, 12 Jan 2018 18:32:04 +0000 (13:32 -0500)]
Finalize v2017.3

6 years agoAdding ostream operators for IR structures
Alan Baker [Wed, 10 Jan 2018 19:23:47 +0000 (14:23 -0500)]
Adding ostream operators for IR structures

* Added for Instruction, BasicBlock, Function and Module
* Uses new disassembly functionality that can disassemble individual
instructions
 * For debug use only (no caching is done)
 * Each output converts module to binary, parses and outputs an
 individual instruction
* Added a test for whole module output
* Disabling Microsoft checked iterator warnings
* Updated check_copyright.py to accept 2018

6 years agoMaintain instruction to block mapping in phi insertion
Alan Baker [Thu, 11 Jan 2018 20:05:39 +0000 (15:05 -0500)]
Maintain instruction to block mapping in phi insertion

* Changed MemPass::InsertPhiInstructions to set basic blocks for new
phis
* Local SSA elim now maintains instr to block mapping
 * Added a test and confirmed it fails without the updated phis
* IRContext::set_instr_block no longer builds the map if the analysis is
invalid
* Added instruction to block mapping verification to
IRContext::IsConsistent()

6 years agoInsertExtractElim: Optimize through VectorShuffle, Mix
Greg Fischer [Fri, 29 Dec 2017 23:44:43 +0000 (16:44 -0700)]
InsertExtractElim: Optimize through VectorShuffle, Mix

This improves Extract replacement to continue through VectorShuffle.
It will also handle Mix with 0.0 or 1.0 in the a-value of the desired
component.

To facilitate optimization of VectorShuffle, the algorithm was refactored
to pass around the indices of the extract in a vector rather than pass the
extract instruction itself. This allows the indices to be modified as the
algorithm progresses.

6 years agoAdd generic folding function and use in CCP
Steven Perron [Tue, 9 Jan 2018 17:45:46 +0000 (12:45 -0500)]
Add generic folding function and use in CCP

The current folding routines have a very cumbersome interface, make them
harder to use, and not a obvious how to extend.

This change is to create a new interface for the folding routines, and
show how it can be used by calling it from CCP.

This does not make a significant change to the behaviour of CCP.  In
general it should produce the same code as before; however it is
possible that an instruction that takes 32-bit integers as inputs and
the result is not a 32-bit integer or bool will not be folded as before.

6 years agoAdding additional functionality to ADCE.
Alan Baker [Mon, 18 Dec 2017 17:13:10 +0000 (12:13 -0500)]
Adding additional functionality to ADCE.

Modified ADCE to remove dead globals.
* Entry point and execution mode instructions are marked as alive
* Reachable functions and their parameters are marked as alive
* Instruction deletion now deferred until the end of the pass
* Eliminated dead insts set, added IsDead to calculate that value
instead
* Ported applicable dead variable elimination tests
* Ported dead constant elim tests

Added dead function elimination to ADCE
* ported dead function elim tests

Added handling of decoration groups in ADCE
* Uses a custom sorter to traverse decorations in a specific order
* Simplifies necessary checks

Updated -O and -Os pass lists.

6 years agoFix validation rules for GLSL pack/unpack 2x32
Andrey Tuganov [Tue, 9 Jan 2018 16:08:44 +0000 (11:08 -0500)]
Fix validation rules for GLSL pack/unpack 2x32

6 years agoRewriting dead branch elimination.
Alan Baker [Thu, 4 Jan 2018 22:04:03 +0000 (17:04 -0500)]
Rewriting dead branch elimination.

Pass now paints live blocks and fixes constant branches and switches as
it goes. No longer requires structured control flow. It also removes
unreachable blocks as a side effect. It fixes the IR (phis) before doing
any code removal (other than terminator changes).

Added several unit tests for updated/new functionality.

Does not remove dead edge from a phi node:
* Checks that incoming edges are live in order to retain them
* Added BasicBlock::IsSuccessor
* added test

Fixing phi updates in the presence of extra backedge blocks

* Added tests to catch bug

Reworked how phis are updated

* Instead of creating a new Phi and RAUW'ing the old phi with it, I now
replace the phi operands, but maintain the def/use manager correctly.

For unreachable merge:

* When considering unreachable continue blocks the code now properly
checks whether the incoming edge will continue to be live.

Major refactoring for review

* Broke into 4 major functions
 * marking live blocks
 * marking structured targets
 * fixing phis
 * deleting blocks

6 years agoFix constant propagation of induction variables.
Diego Novillo [Mon, 8 Jan 2018 16:56:57 +0000 (11:56 -0500)]
Fix constant propagation of induction variables.

This fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1143.
When an instruction transitions from constant to bottom (varying) in the
lattice, we were telling the propagator that the instruction was
varying, but never updating the actual value in the values table.

This led to incorrect value substitutions at the end of propagation.

The patch also re-enables CCP in -O and -Os.

6 years agoFix method comment for BasicBlock::MegeBlockIdIfAny
David Neto [Mon, 8 Jan 2018 15:42:02 +0000 (10:42 -0500)]
Fix method comment for BasicBlock::MegeBlockIdIfAny

Fixes #1177

6 years agoAllow relaxing validation of pointers in logical addressing mode
Lei Zhang [Sun, 7 Jan 2018 15:50:01 +0000 (10:50 -0500)]
Allow relaxing validation of pointers in logical addressing mode

In HLSL structured buffer legalization, pointer to pointer types
are emitted to indicate a structured buffer variable should be
treated as an alias of some other variable. We need an option to
relax the check of pointer types in logical addressing mode to
catch other validation errors.

6 years agoAdd loop descriptors and some required dominator tree extensions.
Victor Lomuller [Thu, 21 Dec 2017 14:47:25 +0000 (14:47 +0000)]
Add loop descriptors and some required dominator tree extensions.

Add post-order tree iterator.

Add DominatorTreeNode extensions:
 - Add begin/end methods to do pre-order and post-order tree traversal from a given DominatorTreeNode

Add DominatorTree extensions:
  - Add begin/end methods to do pre-order and post-order tree traversal
  - Tree traversal ignore by default the pseudo entry block
  - Retrieve a DominatorTreeNode from a basic block

Add loop descriptor:
  - Add a LoopDescriptor class to register all loops in a given function.
  - Add a Loop class to describe a loop:
    - Loop parent
    - Nested loops
    - Loop depth
    - Loop header, merge, continue and preheader
    - Basic blocks that belong to the loop

Correct a bug that forced dominator tree to be constantly rebuilt.

6 years agoAnalyzeInstUse: Reuse the instruction lookup
David Neto [Fri, 5 Jan 2018 23:08:31 +0000 (18:08 -0500)]
AnalyzeInstUse: Reuse the instruction lookup

6 years agoRemove CCP from size and performance recipes, pending bugfixes
David Neto [Fri, 5 Jan 2018 18:21:36 +0000 (13:21 -0500)]
Remove CCP from size and performance recipes, pending bugfixes

Currently CCP is incorrectly optimizing loops.
See https://github.com/KhronosGroup/SPIRV-Tools/issues/1143

6 years agoLinker code cleanups
Pierre Moreau [Wed, 3 Jan 2018 00:54:55 +0000 (01:54 +0100)]
Linker code cleanups

Turn `Linker::Link()` into free functions

  As very little information was kept in the Linker class, we can get rid
  of the whole class and have the `Link()` as free functions instead; the
  environment target as well as the consumer are passed along through an
  `spv_context` object.
  The resulting linked_binary is passed as a pointer rather than a
  reference to follow the Google C++ Style guidelines.

  Addresses remaining comments from
  https://github.com/KhronosGroup/SPIRV-Tools/pull/693 about the SPIR-V
  linker.

Fix variable naming in the linker

  Some of the variables were using mixed case, which did not follow the
  Google C++ Style guidelines.

Linker: Use EXPECT_EQ when possible and update some test

* Replace occurrences of ASSERT_EQ by EXPECT_EQ when possible;
* Reformulated some of the error messages;
* Added the symbol name in the error message when there is a type or
  decoration mismatch between the imported and exported declarations.

Opt: List all duplicates removed by RemoveDuplicatePass in the header

Opt: Make the const version of GetLabelInst() return a pointer

  For consistency with the non-const version, as well as other similar
  functions.

Opt: Rename function_end to EndInst()

  As pointed out by dneto0 the previous name was quite confusing and could
  be mistaken with a function returning an end iterator.
  Also change the return type of the const version to a pointer rather
  than a reference, for consistency.

Opt: Add performance comment to RemoveDuplicateTypes and decorations

  This comment was requested during the review of
  https://github.com/KhronosGroup/SPIRV-Tools/pull/693.

Opt: Add comments and fix variable naming in RemoveDuplicatePass

* Add missing comments to private functions;
* Rename variables that were using mixed case;
* Add TODO for moving AreTypesEqual out.

Linker: Remove commented out code and add TODOs

Linker: Merged together strings that were too much splitted

Implement a C++ RAII wrapper around spv_context

6 years agoAllow getting the base pointer of an image load/store.
Steven Perron [Thu, 4 Jan 2018 16:37:19 +0000 (11:37 -0500)]
Allow getting the base pointer of an image load/store.

In value numbering, we treat loads and stores of images, ie OpImageLoad,
as a memory operation where it is interested in the "base address" of
the instruction.  In those cases, it is an image instruction.

The problem is that `Instruction::GetBaseAddress()` does not account for
the image instructions, so the assert at the end to make sure it found
a valid base address for its addressing mode fails.

The solution is to look at the load/store instruction to determine how
the assertion should be done.

Fixes #1160.

6 years agoFix infinite simulation cycles in SSA propagator.
Diego Novillo [Fri, 5 Jan 2018 14:34:18 +0000 (09:34 -0500)]
Fix infinite simulation cycles in SSA propagator.

This fixes https://github.com/KhronosGroup/SPIRV-Tools/issues/1159.  I
had missed a nuance in the original algorithm.  When simulating Phi
instructions, the SSA edges out of a Phi instruction should never be
added to the list of edges to simulate.

Phi instructions can be in SSA def-use cycles with other Phi
instructions.  This was causing the propagator to fall into an infinite
loop when the same def-use edge kept being added to the queue.

The original algorithm in the paper specifically separates the visit of
a Phi instruction vs the visit of a regular instruction.  This fix makes
the implementation match the original algorithm.

6 years agoIgnore clang-format-diff.py from copyrights check
Pierre Moreau [Thu, 4 Jan 2018 22:16:39 +0000 (23:16 +0100)]
Ignore clang-format-diff.py from copyrights check

Having that script locally, for example to run check_code_format.sh
before sending a pull request, would cause the copyright notices check
to fail.

6 years agodead branch elim: Track killed backedges
David Neto [Thu, 4 Jan 2018 23:52:38 +0000 (18:52 -0500)]
dead branch elim: Track killed backedges

When deleting branches and blocks, also remove them from
the backedges set, in case they were there.

This prevents us from keeping stale pointers to deleted Instruction
objects.  That memory could be used later by another instruction,
incorrectly signaling that something has a backedge reference, and
the dead branch eliminator could end up deleting live blocks.

Adds accessor method ir::BasicBlock::terminator

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

6 years agoAdd --print-all optimizer option
David Neto [Thu, 4 Jan 2018 17:59:50 +0000 (12:59 -0500)]
Add --print-all optimizer option

Adds optimizer API to write disassembly to a given output stream
before each pass, and after the last pass.

Adds spirv-opt --print-all option to write disassembly to stderr
before each pass, and after the last pass.

6 years agoOpt: Make DecorationManager::HaveTheSameDecorations symmetric
Pierre Moreau [Sun, 24 Dec 2017 10:15:14 +0000 (11:15 +0100)]
Opt: Make DecorationManager::HaveTheSameDecorations symmetric

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

Also: Add SpvOpDecorateId to IsAnnotationInst()

6 years agoValidator checks out of bounds composite access
Andrey Tuganov [Tue, 2 Jan 2018 21:02:55 +0000 (16:02 -0500)]
Validator checks out of bounds composite access

1. Added OpCompositeExtract/Insert out of bounds checks where possible
(everything except RuntimeArray)
2. Moved validation of OpCompositeExtract/Insert from validate_id.cpp to
validate_composites.cpp.

6 years agoAddress review comments from https://github.com/KhronosGroup/SPIRV-Tools/pull/985.
Diego Novillo [Thu, 4 Jan 2018 18:20:18 +0000 (13:20 -0500)]
Address review comments from https://github.com/KhronosGroup/SPIRV-Tools/pull/985.

6 years agoUpdate legalization passes
Steven Perron [Wed, 3 Jan 2018 19:03:07 +0000 (14:03 -0500)]
Update legalization passes

I've a few passes the legalization passes.  The first is to add the
more specialized load-store removal passes to help improve the compile
time, as was suggested in #1118.

I've also added dead branch elimination while we wait for the behaviour
of dead branch elimination to be folded into CFG cleanup.

I did not add CCP because it seems like most of the constant propagation
what is needed is already being done by the load-store removal passes,
which call `ReplaceAllUsesWith`.  We can reconsider this if needed.

6 years agoReplace calls to `ToNop` by `KillInst`.
Steven Perron [Wed, 3 Jan 2018 18:23:57 +0000 (13:23 -0500)]
Replace calls to `ToNop` by `KillInst`.

Calling `ToNop` leaves around instructions that are pointless.  In
general it is better to remove the instruction completely.  That way
other optimizations will not need to look at them.

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

6 years agoHandle execution termination instructions when building edges.
Diego Novillo [Wed, 3 Jan 2018 20:25:03 +0000 (15:25 -0500)]
Handle execution termination instructions when building edges.

This fixes issue https://github.com/KhronosGroup/SPIRV-Tools/issues/1153.

When building CFG edges, edges out of a OpKill and OpUnreachable
instruction should be directed to the CFG's pseudo exit block.

6 years agoDo not insert Phi nodes in CCP propagator.
Diego Novillo [Wed, 3 Jan 2018 17:38:21 +0000 (12:38 -0500)]
Do not insert Phi nodes in CCP propagator.

In CCP we should not need to insert Phi nodes because CCP never looks at
loads/stores.  This required adjusting two tests that relied on Phi
instructions being inserted.  I changed the tests to have the Phi
instructions pre-inserted.

I also added a new test to make sure that CCP does not try to look
through stores and loads.

Finally, given that CCP does not handle loads/stores, it's better to run
mem2reg before it.  I've changed the -O/-Os schedules to run local
multi-store elimination before CCP.

Although this is just an efficiency fix for CCP, it is
also working around a bug in Phi insertion.  When Phi instructions are
inserted, they are never associated a basic block.  This causes a
segfault when the propagator tries to lookup CFG edges when analyzing
Phi instructions.

6 years agoAdd ExtInst validation pass (GLSL only for now)
Andrey Tuganov [Wed, 13 Dec 2017 16:56:09 +0000 (11:56 -0500)]
Add ExtInst validation pass (GLSL only for now)

Validates all GLSL.std.450 extended instructions.

6 years agoTest: Fix linux/gcc defined-but-not-used warnings/errors
GregF [Thu, 28 Dec 2017 00:12:04 +0000 (17:12 -0700)]
Test: Fix linux/gcc defined-but-not-used warnings/errors

6 years agoutils/generate_grammar_tables.py: use spaces for indentation
Leo Izen [Thu, 28 Dec 2017 16:13:06 +0000 (11:13 -0500)]
utils/generate_grammar_tables.py: use spaces for indentation

One part of this file had indented using tabs. This causes newer
versions of python to complain. This changes the indentation to
consistently use four spaces throughout the file, to be consistent
with the rest of the file and the rest of the project.

6 years agoFix https://github.com/KhronosGroup/SPIRV-Tools/issues/1130
Diego Novillo [Fri, 22 Dec 2017 17:38:02 +0000 (12:38 -0500)]
Fix https://github.com/KhronosGroup/SPIRV-Tools/issues/1130

This addresses review feedback for the CCP implementation (which fixes
https://github.com/KhronosGroup/SPIRV-Tools/issues/889).

This adds more protection around the folding of instructions that would
not be supported by the folder.

6 years agoDisallow Dim=SubpassData for OpImageSparseRead
Andrey Tuganov [Thu, 21 Dec 2017 20:24:27 +0000 (15:24 -0500)]
Disallow Dim=SubpassData for OpImageSparseRead

6 years agoAdd asm, dis support for DebugInfo extended instruction set
David Neto [Sun, 3 Dec 2017 17:30:08 +0000 (12:30 -0500)]
Add asm, dis support for DebugInfo extended instruction set

Add grammar file for DebugInfo extended instruction set
- Each new operand enum kind in extinst.debuginfo.grammar.json maps
  to a new value in spv_operand_type_t.
- Add new concrete enum operand types for DebugInfo

Generate a C header for the DebugInfo extended instruction set

Add table lookup of DebugInfo extended instrutions

Handle the debug info operand types in binary parser,
disassembler, and assembler.

Add DebugInfo round trip tests for assembler, disassembler

Android.mk: Support DebugInfo extended instruction set

The extinst.debuginfo.grammar.json file is currently part of
SPIRV-Tools source.

It contributes operand type enums, so it has to be processed
along with the core grammar files.

We also generate a C header DebugInfo.h.

Add necessary grammar file processing to Android.mk.

6 years agoCONTRIBUTING: If you fixed a bug, say so
David Neto [Thu, 21 Dec 2017 16:25:31 +0000 (11:25 -0500)]
CONTRIBUTING: If you fixed a bug, say so

6 years agoImplement SSA CCP (SSA Conditional Constant Propagation).
Diego Novillo [Tue, 5 Dec 2017 16:39:25 +0000 (11:39 -0500)]
Implement SSA CCP (SSA Conditional Constant Propagation).

This implements the conditional constant propagation pass proposed in

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

The main logic resides in CCPPass::VisitInstruction.  Instruction that
may produce a constant value are evaluated with the constant folder. If
they produce a new constant, the instruction is considered interesting.
Otherwise, it's considered varying (for unfoldable instructions) or
just not interesting (when not enough operands have a constant value).

The other main piece of logic is in CCPPass::VisitBranch.  This
evaluates the selector of the branch.  When it's found to be a known
value, it computes the destination basic block and sets it.  This tells
the propagator which branches to follow.

The patch required extensions to the constant manager as well. Instead
of hashing the Constant pointers, this patch changes the constant pool
to hash the contents of the Constant.  This allows the lookups to be
done using the actual values of the Constant, preventing duplicate
definitions.

6 years agoStore all enabled capabilities in the feature manger.
Steven Perron [Tue, 19 Dec 2017 19:18:13 +0000 (14:18 -0500)]
Store all enabled capabilities in the feature manger.

In order to keep track of all of the implicit capabilities as well as
the explicit ones, we will add them all to the feature manager.  That is
the object that needs to be queried when checking if a capability is
enabled.

The name of the "HasCapability" function in the module was changed to
make it more obvious that it does not check for implied capabilities.

Keep an spv_context and AssemblyGrammar in IRContext

6 years agoUpdate CHANGES
David Neto [Thu, 21 Dec 2017 15:42:46 +0000 (10:42 -0500)]
Update CHANGES

6 years agoFixing bugs in type manager memory management
Alan Baker [Mon, 18 Dec 2017 22:02:19 +0000 (17:02 -0500)]
Fixing bugs in type manager memory management

* changed the way duplicate types are removed to stop copying
instructions
* Reworked RemoveDuplicatesPass::AreTypesSame to use type manager and
type equality
* Reworked TypeManager memory management to store a pool of unique
pointers of types
 * removed unique pointers from id map
 * fixed instances where free'd memory could be accessed

6 years agoUpdate the legalization passes.
Steven Perron [Tue, 19 Dec 2017 20:08:54 +0000 (15:08 -0500)]
Update the legalization passes.

Changes the set of optimizations done for legalization.  While doing
this, I added documentation to explain why we want each optimization.

A new option "--legalize-hlsl" is added so the legalization passes can
be easily run from the command line.
The legalize option implies skip-validation.

6 years agoMake a string parameter const ref
David Neto [Tue, 19 Dec 2017 18:52:23 +0000 (13:52 -0500)]
Make a string parameter const ref

6 years agoFix CHANGES: there is no OpImageSparseWrite
David Neto [Tue, 19 Dec 2017 23:30:10 +0000 (18:30 -0500)]
Fix CHANGES: there is no OpImageSparseWrite

6 years agoUpdate CHANGES for recent changes
David Neto [Tue, 19 Dec 2017 22:50:01 +0000 (17:50 -0500)]
Update CHANGES for recent changes

6 years agoOpt: Fix implementation and comment of AreDecorationsTheSame
Pierre Moreau [Wed, 29 Nov 2017 23:29:34 +0000 (00:29 +0100)]
Opt: Fix implementation and comment of AreDecorationsTheSame
Target should not be ignored when comparing decorations in RemoveDuplicates
Opt: Remove unused code in RemoveDuplicateDecorations

6 years agoAllow pointers to pointers in logical addressing mode.
Steven Perron [Mon, 11 Dec 2017 18:10:24 +0000 (13:10 -0500)]
Allow pointers to pointers in logical addressing mode.

A few optimizations are updates to handle code that is suppose to be
using the logical addressing mode, but still has variables that contain
pointers as long as the pointer are to opaque objects.  This is called
"relaxed logical addressing".

|Instruction::GetBaseAddress| will check that pointers that are use meet
the relaxed logical addressing rules.  Optimization that now handle
relaxed logical addressing instead of logical addressing are:

 - aggressive dead-code elimination
 - local access chain convert
 - local store elimination passes.

6 years agoConvert private variables to function scope.
Steven Perron [Mon, 11 Dec 2017 18:10:24 +0000 (13:10 -0500)]
Convert private variables to function scope.

When a private variable is used in a single function, it can be
converted to a function scope variable in that function.  This adds a
pass that does that.  The pass can be enabled using the option
`--private-to-local`.

This transformation allows other transformations to act on these
variables.

Also moved `FindPointerToType` from the inline class to the type manager.

6 years agoMore validation on primitive instructions
David Neto [Fri, 15 Dec 2017 18:19:09 +0000 (13:19 -0500)]
More validation on primitive instructions

- Test validation success for OpEmitVertex OpEndPrimitive
- Test missing capabilities for primitive instructions
- Primitive instructions require Geometry execution model

6 years agovalidate & test of literal's upper bits
Jesus Carabano [Wed, 18 Oct 2017 09:00:02 +0000 (12:00 +0300)]
validate & test of literal's upper bits

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

6 years agoOpt: Remove commented out duplicated type_id function
Pierre Moreau [Wed, 29 Nov 2017 23:26:20 +0000 (00:26 +0100)]
Opt: Remove commented out duplicated type_id function

This code was wrongly added by #693.