1// Copyright (c) 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef SOURCE_OPT_GRAPHICS_ROBUST_ACCESS_PASS_H_
16#define SOURCE_OPT_GRAPHICS_ROBUST_ACCESS_PASS_H_
17
18#include <map>
19#include <unordered_map>
20
21#include "constants.h"
22#include "def_use_manager.h"
23#include "instruction.h"
24#include "module.h"
25#include "pass.h"
26#include "source/diagnostic.h"
27#include "type_manager.h"
28
29namespace spvtools {
30namespace opt {
31
32// See optimizer.hpp for documentation.
33class GraphicsRobustAccessPass : public Pass {
34 public:
35  GraphicsRobustAccessPass();
36  const char* name() const override { return "graphics-robust-access"; }
37  Status Process() override;
38
39  IRContext::Analysis GetPreservedAnalyses() override {
40    return IRContext::kAnalysisDefUse |
41           IRContext::kAnalysisInstrToBlockMapping |
42           IRContext::kAnalysisConstants | IRContext::kAnalysisTypes |
43           IRContext::kAnalysisIdToFuncMapping;
44  }
45
46 private:
47  // Records failure for the current module, and returns a stream
48  // that can be used to provide user error information to the message
49  // consumer.
50  spvtools::DiagnosticStream Fail();
51
52  // Returns SPV_SUCCESS if this pass can correctly process the module,
53  // as far as we can tell from capabilities and the memory model.
54  // Otherwise logs a message and returns a failure code.
55  spv_result_t IsCompatibleModule();
56
57  // Transform the current module, if possible. Failure and modification
58  // status is recorded in the |_| member. On failure, error information is
59  // posted to the message consumer.  The return value has no significance.
60  spv_result_t ProcessCurrentModule();
61
62  // Process the given function.  Updates the state value |_|.  Returns true
63  // if the module was modified.  This can log a failure.
64  bool ProcessAFunction(opt::Function*);
65
66  // Clamps indices in the OpAccessChain or OpInBoundsAccessChain instruction
67  // |access_chain|. Inserts instructions before the given instruction.  Updates
68  // analyses and records that the module is modified.  This can log a failure.
69  void ClampIndicesForAccessChain(Instruction* access_chain);
70
71  // Returns the id of the instruction importing the "GLSL.std.450" extended
72  // instruction set. If it does not yet exist, the import instruction is
73  // created and inserted into the module, and updates |_.modified| and
74  // |_.glsl_insts_id|.
75  uint32_t GetGlslInsts();
76
77  // Returns an instruction which is constant with the given value of the given
78  // type. Ignores any value bits beyond the width of the type.
79  Instruction* GetValueForType(uint64_t value, const analysis::Integer* type);
80
81  // Converts an integer value to an unsigned wider integer type, using either
82  // sign extension or zero extension.  The new instruction is inserted
83  // immediately before |before_inst|, and is analyzed for definitions and uses.
84  // Returns the newly inserted instruction.  Assumes the |value| is an integer
85  // scalar of a narrower type than |bit_width| bits.
86  Instruction* WidenInteger(bool sign_extend, uint32_t bit_width,
87                            Instruction* value, Instruction* before_inst);
88
89  // Returns a new instruction that invokes the UMin GLSL.std.450 extended
90  // instruction with the two given operands.  That is, the result of the
91  // instruction is:
92  //  - |x| if |x| is unsigned-less than |y|
93  //  - |y| otherwise
94  // We assume that |x| and |y| are scalar integer types with the same
95  // width.  The instruction is inserted before |where|.
96  opt::Instruction* MakeUMinInst(const analysis::TypeManager& tm,
97                                 Instruction* x, Instruction* y,
98                                 Instruction* where);
99
100  // Returns a new instruction that invokes the SClamp GLSL.std.450 extended
101  // instruction with the three given operands.  That is, the result of the
102  // instruction is:
103  //  - |min| if |x| is signed-less than |min|
104  //  - |max| if |x| is signed-more than |max|
105  //  - |x| otherwise.
106  // We assume that |min| is signed-less-or-equal to |max|, and that the
107  // operands all have the same scalar integer type.  The instruction is
108  // inserted before |where|.
109  opt::Instruction* MakeSClampInst(const analysis::TypeManager& tm,
110                                   Instruction* x, Instruction* min,
111                                   Instruction* max, Instruction* where);
112
113  // Returns a new instruction which evaluates to the length the runtime array
114  // referenced by the access chain at the specified index.  The instruction is
115  // inserted before the access chain instruction.  Returns a null pointer in
116  // some cases if assumptions are violated (rather than asserting out).
117  opt::Instruction* MakeRuntimeArrayLengthInst(Instruction* access_chain,
118                                               uint32_t operand_index);
119
120  // Clamps the coordinate for an OpImageTexelPointer so it stays within
121  // the bounds of the size of the image.  Updates analyses and records that
122  // the module is modified.  Returns a status code to indicate success
123  // or failure.  If assumptions are not met, returns an error status code
124  // and emits a diagnostic.
125  spv_result_t ClampCoordinateForImageTexelPointer(
126      opt::Instruction* image_texel_pointer);
127
128  // Gets the instruction that defines the given id.
129  opt::Instruction* GetDef(uint32_t id) {
130    return context()->get_def_use_mgr()->GetDef(id);
131  }
132
133  // Returns a new instruction inserted before |where_inst|, and created from
134  // the remaining arguments. Registers the definitions and uses of the new
135  // instruction and also records its block.
136  opt::Instruction* InsertInst(opt::Instruction* where_inst, spv::Op opcode,
137                               uint32_t type_id, uint32_t result_id,
138                               const Instruction::OperandList& operands);
139
140  // State required for the current module.
141  struct PerModuleState {
142    // This pass modified the module.
143    bool modified = false;
144    // True if there is an error processing the current module, e.g. if
145    // preconditions are not met.
146    bool failed = false;
147    // The id of the GLSL.std.450 extended instruction set.  Zero if it does
148    // not exist.
149    uint32_t glsl_insts_id = 0;
150  } module_status_;
151};
152
153}  // namespace opt
154}  // namespace spvtools
155
156#endif  // SOURCE_OPT_GRAPHICS_ROBUST_ACCESS_PASS_H_
157