• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2017 The Khronos Group Inc.
2 // Copyright (c) 2017 Valve Corporation
3 // Copyright (c) 2017 LunarG Inc.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 
17 #include "source/opt/local_single_block_elim_pass.h"
18 
19 #include <vector>
20 
21 #include "source/opt/iterator.h"
22 #include "source/util/string_utils.h"
23 
24 namespace spvtools {
25 namespace opt {
26 namespace {
27 
28 const uint32_t kStoreValIdInIdx = 1;
29 
30 }  // anonymous namespace
31 
HasOnlySupportedRefs(uint32_t ptrId)32 bool LocalSingleBlockLoadStoreElimPass::HasOnlySupportedRefs(uint32_t ptrId) {
33   if (supported_ref_ptrs_.find(ptrId) != supported_ref_ptrs_.end()) return true;
34   if (get_def_use_mgr()->WhileEachUser(ptrId, [this](Instruction* user) {
35         auto dbg_op = user->GetCommonDebugOpcode();
36         if (dbg_op == CommonDebugInfoDebugDeclare ||
37             dbg_op == CommonDebugInfoDebugValue) {
38           return true;
39         }
40         SpvOp op = user->opcode();
41         if (IsNonPtrAccessChain(op) || op == SpvOpCopyObject) {
42           if (!HasOnlySupportedRefs(user->result_id())) {
43             return false;
44           }
45         } else if (op != SpvOpStore && op != SpvOpLoad && op != SpvOpName &&
46                    !IsNonTypeDecorate(op)) {
47           return false;
48         }
49         return true;
50       })) {
51     supported_ref_ptrs_.insert(ptrId);
52     return true;
53   }
54   return false;
55 }
56 
LocalSingleBlockLoadStoreElim(Function * func)57 bool LocalSingleBlockLoadStoreElimPass::LocalSingleBlockLoadStoreElim(
58     Function* func) {
59   // Perform local store/load, load/load and store/store elimination
60   // on each block
61   bool modified = false;
62   std::vector<Instruction*> instructions_to_kill;
63   std::unordered_set<Instruction*> instructions_to_save;
64   for (auto bi = func->begin(); bi != func->end(); ++bi) {
65     var2store_.clear();
66     var2load_.clear();
67     auto next = bi->begin();
68     for (auto ii = next; ii != bi->end(); ii = next) {
69       ++next;
70       switch (ii->opcode()) {
71         case SpvOpStore: {
72           // Verify store variable is target type
73           uint32_t varId;
74           Instruction* ptrInst = GetPtr(&*ii, &varId);
75           if (!IsTargetVar(varId)) continue;
76           if (!HasOnlySupportedRefs(varId)) continue;
77           // If a store to the whole variable, remember it for succeeding
78           // loads and stores. Otherwise forget any previous store to that
79           // variable.
80           if (ptrInst->opcode() == SpvOpVariable) {
81             // If a previous store to same variable, mark the store
82             // for deletion if not still used. Don't delete store
83             // if debugging; let ssa-rewrite and DCE handle it
84             auto prev_store = var2store_.find(varId);
85             if (prev_store != var2store_.end() &&
86                 instructions_to_save.count(prev_store->second) == 0 &&
87                 !context()->get_debug_info_mgr()->IsVariableDebugDeclared(
88                     varId)) {
89               instructions_to_kill.push_back(prev_store->second);
90               modified = true;
91             }
92 
93             bool kill_store = false;
94             auto li = var2load_.find(varId);
95             if (li != var2load_.end()) {
96               if (ii->GetSingleWordInOperand(kStoreValIdInIdx) ==
97                   li->second->result_id()) {
98                 // We are storing the same value that already exists in the
99                 // memory location.  The store does nothing.
100                 kill_store = true;
101               }
102             }
103 
104             if (!kill_store) {
105               var2store_[varId] = &*ii;
106               var2load_.erase(varId);
107             } else {
108               instructions_to_kill.push_back(&*ii);
109               modified = true;
110             }
111           } else {
112             assert(IsNonPtrAccessChain(ptrInst->opcode()));
113             var2store_.erase(varId);
114             var2load_.erase(varId);
115           }
116         } break;
117         case SpvOpLoad: {
118           // Verify store variable is target type
119           uint32_t varId;
120           Instruction* ptrInst = GetPtr(&*ii, &varId);
121           if (!IsTargetVar(varId)) continue;
122           if (!HasOnlySupportedRefs(varId)) continue;
123           uint32_t replId = 0;
124           if (ptrInst->opcode() == SpvOpVariable) {
125             // If a load from a variable, look for a previous store or
126             // load from that variable and use its value.
127             auto si = var2store_.find(varId);
128             if (si != var2store_.end()) {
129               replId = si->second->GetSingleWordInOperand(kStoreValIdInIdx);
130             } else {
131               auto li = var2load_.find(varId);
132               if (li != var2load_.end()) {
133                 replId = li->second->result_id();
134               }
135             }
136           } else {
137             // If a partial load of a previously seen store, remember
138             // not to delete the store.
139             auto si = var2store_.find(varId);
140             if (si != var2store_.end()) instructions_to_save.insert(si->second);
141           }
142           if (replId != 0) {
143             // replace load's result id and delete load
144             context()->KillNamesAndDecorates(&*ii);
145             context()->ReplaceAllUsesWith(ii->result_id(), replId);
146             instructions_to_kill.push_back(&*ii);
147             modified = true;
148           } else {
149             if (ptrInst->opcode() == SpvOpVariable)
150               var2load_[varId] = &*ii;  // register load
151           }
152         } break;
153         case SpvOpFunctionCall: {
154           // Conservatively assume all locals are redefined for now.
155           // TODO(): Handle more optimally
156           var2store_.clear();
157           var2load_.clear();
158         } break;
159         default:
160           break;
161       }
162     }
163   }
164 
165   for (Instruction* inst : instructions_to_kill) {
166     context()->KillInst(inst);
167   }
168 
169   return modified;
170 }
171 
Initialize()172 void LocalSingleBlockLoadStoreElimPass::Initialize() {
173   // Initialize Target Type Caches
174   seen_target_vars_.clear();
175   seen_non_target_vars_.clear();
176 
177   // Clear collections
178   supported_ref_ptrs_.clear();
179 
180   // Initialize extensions allowlist
181   InitExtensions();
182 }
183 
AllExtensionsSupported() const184 bool LocalSingleBlockLoadStoreElimPass::AllExtensionsSupported() const {
185   // If any extension not in allowlist, return false
186   for (auto& ei : get_module()->extensions()) {
187     const std::string extName = ei.GetInOperand(0).AsString();
188     if (extensions_allowlist_.find(extName) == extensions_allowlist_.end())
189       return false;
190   }
191   // only allow NonSemantic.Shader.DebugInfo.100, we cannot safely optimise
192   // around unknown extended
193   // instruction sets even if they are non-semantic
194   for (auto& inst : context()->module()->ext_inst_imports()) {
195     assert(inst.opcode() == SpvOpExtInstImport &&
196            "Expecting an import of an extension's instruction set.");
197     const std::string extension_name = inst.GetInOperand(0).AsString();
198     if (spvtools::utils::starts_with(extension_name, "NonSemantic.") &&
199         extension_name != "NonSemantic.Shader.DebugInfo.100") {
200       return false;
201     }
202   }
203   return true;
204 }
205 
ProcessImpl()206 Pass::Status LocalSingleBlockLoadStoreElimPass::ProcessImpl() {
207   // Assumes relaxed logical addressing only (see instruction.h).
208   if (context()->get_feature_mgr()->HasCapability(SpvCapabilityAddresses))
209     return Status::SuccessWithoutChange;
210 
211   // Do not process if module contains OpGroupDecorate. Additional
212   // support required in KillNamesAndDecorates().
213   // TODO(greg-lunarg): Add support for OpGroupDecorate
214   for (auto& ai : get_module()->annotations())
215     if (ai.opcode() == SpvOpGroupDecorate) return Status::SuccessWithoutChange;
216   // If any extensions in the module are not explicitly supported,
217   // return unmodified.
218   if (!AllExtensionsSupported()) return Status::SuccessWithoutChange;
219   // Process all entry point functions
220   ProcessFunction pfn = [this](Function* fp) {
221     return LocalSingleBlockLoadStoreElim(fp);
222   };
223 
224   bool modified = context()->ProcessReachableCallTree(pfn);
225   return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
226 }
227 
228 LocalSingleBlockLoadStoreElimPass::LocalSingleBlockLoadStoreElimPass() =
229     default;
230 
Process()231 Pass::Status LocalSingleBlockLoadStoreElimPass::Process() {
232   Initialize();
233   return ProcessImpl();
234 }
235 
InitExtensions()236 void LocalSingleBlockLoadStoreElimPass::InitExtensions() {
237   extensions_allowlist_.clear();
238   extensions_allowlist_.insert({
239       "SPV_AMD_shader_explicit_vertex_parameter",
240       "SPV_AMD_shader_trinary_minmax",
241       "SPV_AMD_gcn_shader",
242       "SPV_KHR_shader_ballot",
243       "SPV_AMD_shader_ballot",
244       "SPV_AMD_gpu_shader_half_float",
245       "SPV_KHR_shader_draw_parameters",
246       "SPV_KHR_subgroup_vote",
247       "SPV_KHR_8bit_storage",
248       "SPV_KHR_16bit_storage",
249       "SPV_KHR_device_group",
250       "SPV_KHR_multiview",
251       "SPV_NVX_multiview_per_view_attributes",
252       "SPV_NV_viewport_array2",
253       "SPV_NV_stereo_view_rendering",
254       "SPV_NV_sample_mask_override_coverage",
255       "SPV_NV_geometry_shader_passthrough",
256       "SPV_AMD_texture_gather_bias_lod",
257       "SPV_KHR_storage_buffer_storage_class",
258       "SPV_KHR_variable_pointers",
259       "SPV_AMD_gpu_shader_int16",
260       "SPV_KHR_post_depth_coverage",
261       "SPV_KHR_shader_atomic_counter_ops",
262       "SPV_EXT_shader_stencil_export",
263       "SPV_EXT_shader_viewport_index_layer",
264       "SPV_AMD_shader_image_load_store_lod",
265       "SPV_AMD_shader_fragment_mask",
266       "SPV_EXT_fragment_fully_covered",
267       "SPV_AMD_gpu_shader_half_float_fetch",
268       "SPV_GOOGLE_decorate_string",
269       "SPV_GOOGLE_hlsl_functionality1",
270       "SPV_GOOGLE_user_type",
271       "SPV_NV_shader_subgroup_partitioned",
272       "SPV_EXT_demote_to_helper_invocation",
273       "SPV_EXT_descriptor_indexing",
274       "SPV_NV_fragment_shader_barycentric",
275       "SPV_NV_compute_shader_derivatives",
276       "SPV_NV_shader_image_footprint",
277       "SPV_NV_shading_rate",
278       "SPV_NV_mesh_shader",
279       "SPV_NV_ray_tracing",
280       "SPV_KHR_ray_tracing",
281       "SPV_KHR_ray_query",
282       "SPV_EXT_fragment_invocation_density",
283       "SPV_EXT_physical_storage_buffer",
284       "SPV_KHR_terminate_invocation",
285       "SPV_KHR_subgroup_uniform_control_flow",
286       "SPV_KHR_integer_dot_product",
287       "SPV_EXT_shader_image_int64",
288       "SPV_KHR_non_semantic_info",
289   });
290 }
291 
292 }  // namespace opt
293 }  // namespace spvtools
294