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 // This pass injects code in a graphics shader to implement guarantees
16 // satisfying Vulkan's robustBufferAccess rules. Robust access rules permit
17 // an out-of-bounds access to be redirected to an access of the same type
18 // (load, store, etc.) but within the same root object.
19 //
20 // We assume baseline functionality in Vulkan, i.e. the module uses
21 // logical addressing mode, without VK_KHR_variable_pointers.
22 //
23 // - Logical addressing mode implies:
24 // - Each root pointer (a pointer that exists other than by the
25 // execution of a shader instruction) is the result of an OpVariable.
26 //
27 // - Instructions that result in pointers are:
28 // OpVariable
29 // OpAccessChain
30 // OpInBoundsAccessChain
31 // OpFunctionParameter
32 // OpImageTexelPointer
33 // OpCopyObject
34 //
35 // - Instructions that use a pointer are:
36 // OpLoad
37 // OpStore
38 // OpAccessChain
39 // OpInBoundsAccessChain
40 // OpFunctionCall
41 // OpImageTexelPointer
42 // OpCopyMemory
43 // OpCopyObject
44 // all OpAtomic* instructions
45 //
46 // We classify pointer-users into:
47 // - Accesses:
48 // - OpLoad
49 // - OpStore
50 // - OpAtomic*
51 // - OpCopyMemory
52 //
53 // - Address calculations:
54 // - OpAccessChain
55 // - OpInBoundsAccessChain
56 //
57 // - Pass-through:
58 // - OpFunctionCall
59 // - OpFunctionParameter
60 // - OpCopyObject
61 //
62 // The strategy is:
63 //
64 // - Handle only logical addressing mode. In particular, don't handle a module
65 // if it uses one of the variable-pointers capabilities.
66 //
67 // - Don't handle modules using capability RuntimeDescriptorArrayEXT. So the
68 // only runtime arrays are those that are the last member in a
69 // Block-decorated struct. This allows us to feasibly/easily compute the
70 // length of the runtime array. See below.
71 //
72 // - The memory locations accessed by OpLoad, OpStore, OpCopyMemory, and
73 // OpAtomic* are determined by their pointer parameter or parameters.
74 // Pointers are always (correctly) typed and so the address and number of
75 // consecutive locations are fully determined by the pointer.
76 //
77 // - A pointer value originates as one of few cases:
78 //
79 // - OpVariable for an interface object or an array of them: image,
80 // buffer (UBO or SSBO), sampler, sampled-image, push-constant, input
81 // variable, output variable. The execution environment is responsible for
82 // allocating the correct amount of storage for these, and for ensuring
83 // each resource bound to such a variable is big enough to contain the
84 // SPIR-V pointee type of the variable.
85 //
86 // - OpVariable for a non-interface object. These are variables in
87 // Workgroup, Private, and Function storage classes. The compiler ensures
88 // the underlying allocation is big enough to store the entire SPIR-V
89 // pointee type of the variable.
90 //
91 // - An OpFunctionParameter. This always maps to a pointer parameter to an
92 // OpFunctionCall.
93 //
94 // - In logical addressing mode, these are severely limited:
95 // "Any pointer operand to an OpFunctionCall must be:
96 // - a memory object declaration, or
97 // - a pointer to an element in an array that is a memory object
98 // declaration, where the element type is OpTypeSampler or OpTypeImage"
99 //
100 // - This has an important simplifying consequence:
101 //
102 // - When looking for a pointer to the structure containing a runtime
103 // array, you begin with a pointer to the runtime array and trace
104 // backward in the function. You never have to trace back beyond
105 // your function call boundary. So you can't take a partial access
106 // chain into an SSBO, then pass that pointer into a function. So
107 // we don't resort to using fat pointers to compute array length.
108 // We can trace back to a pointer to the containing structure,
109 // and use that in an OpArrayLength instruction. (The structure type
110 // gives us the member index of the runtime array.)
111 //
112 // - Otherwise, the pointer type fully encodes the range of valid
113 // addresses. In particular, the type of a pointer to an aggregate
114 // value fully encodes the range of indices when indexing into
115 // that aggregate.
116 //
117 // - The pointer is the result of an access chain instruction. We clamp
118 // indices contributing to address calculations. As noted above, the
119 // valid ranges are either bound by the length of a runtime array, or
120 // by the type of the base pointer. The length of a runtime array is
121 // the result of an OpArrayLength instruction acting on the pointer of
122 // the containing structure as noted above.
123 //
124 // - Access chain indices are always treated as signed, so:
125 // - Clamp the upper bound at the signed integer maximum.
126 // - Use SClamp for all clamping.
127 //
128 // - TODO(dneto): OpImageTexelPointer:
129 // - Clamp coordinate to the image size returned by OpImageQuerySize
130 // - If multi-sampled, clamp the sample index to the count returned by
131 // OpImageQuerySamples.
132 // - If not multi-sampled, set the sample index to 0.
133 //
134 // - Rely on the external validator to check that pointers are only
135 // used by the instructions as above.
136 //
137 // - Handles OpTypeRuntimeArray
138 // Track pointer back to original resource (pointer to struct), so we can
139 // query the runtime array size.
140 //
141
142 #include "graphics_robust_access_pass.h"
143
144 #include <algorithm>
145 #include <cstring>
146 #include <functional>
147 #include <initializer_list>
148 #include <limits>
149 #include <utility>
150
151 #include "constants.h"
152 #include "def_use_manager.h"
153 #include "function.h"
154 #include "ir_context.h"
155 #include "module.h"
156 #include "pass.h"
157 #include "source/diagnostic.h"
158 #include "source/util/make_unique.h"
159 #include "spirv-tools/libspirv.h"
160 #include "spirv/unified1/GLSL.std.450.h"
161 #include "spirv/unified1/spirv.h"
162 #include "type_manager.h"
163 #include "types.h"
164
165 namespace spvtools {
166 namespace opt {
167
168 using opt::Instruction;
169 using opt::Operand;
170 using spvtools::MakeUnique;
171
GraphicsRobustAccessPass()172 GraphicsRobustAccessPass::GraphicsRobustAccessPass() : module_status_() {}
173
Process()174 Pass::Status GraphicsRobustAccessPass::Process() {
175 module_status_ = PerModuleState();
176
177 ProcessCurrentModule();
178
179 auto result = module_status_.failed
180 ? Status::Failure
181 : (module_status_.modified ? Status::SuccessWithChange
182 : Status::SuccessWithoutChange);
183
184 return result;
185 }
186
Fail()187 spvtools::DiagnosticStream GraphicsRobustAccessPass::Fail() {
188 module_status_.failed = true;
189 // We don't really have a position, and we'll ignore the result.
190 return std::move(
191 spvtools::DiagnosticStream({}, consumer(), "", SPV_ERROR_INVALID_BINARY)
192 << name() << ": ");
193 }
194
IsCompatibleModule()195 spv_result_t GraphicsRobustAccessPass::IsCompatibleModule() {
196 auto* feature_mgr = context()->get_feature_mgr();
197 if (!feature_mgr->HasCapability(SpvCapabilityShader))
198 return Fail() << "Can only process Shader modules";
199 if (feature_mgr->HasCapability(SpvCapabilityVariablePointers))
200 return Fail() << "Can't process modules with VariablePointers capability";
201 if (feature_mgr->HasCapability(SpvCapabilityVariablePointersStorageBuffer))
202 return Fail() << "Can't process modules with VariablePointersStorageBuffer "
203 "capability";
204 if (feature_mgr->HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
205 // These have a RuntimeArray outside of Block-decorated struct. There
206 // is no way to compute the array length from within SPIR-V.
207 return Fail() << "Can't process modules with RuntimeDescriptorArrayEXT "
208 "capability";
209 }
210
211 {
212 auto* inst = context()->module()->GetMemoryModel();
213 const auto addressing_model = inst->GetSingleWordOperand(0);
214 if (addressing_model != SpvAddressingModelLogical)
215 return Fail() << "Addressing model must be Logical. Found "
216 << inst->PrettyPrint();
217 }
218 return SPV_SUCCESS;
219 }
220
ProcessCurrentModule()221 spv_result_t GraphicsRobustAccessPass::ProcessCurrentModule() {
222 auto err = IsCompatibleModule();
223 if (err != SPV_SUCCESS) return err;
224
225 ProcessFunction fn = [this](opt::Function* f) { return ProcessAFunction(f); };
226 module_status_.modified |= context()->ProcessReachableCallTree(fn);
227
228 // Need something here. It's the price we pay for easier failure paths.
229 return SPV_SUCCESS;
230 }
231
ProcessAFunction(opt::Function * function)232 bool GraphicsRobustAccessPass::ProcessAFunction(opt::Function* function) {
233 // Ensure that all pointers computed inside a function are within bounds.
234 // Find the access chains in this block before trying to modify them.
235 std::vector<Instruction*> access_chains;
236 std::vector<Instruction*> image_texel_pointers;
237 for (auto& block : *function) {
238 for (auto& inst : block) {
239 switch (inst.opcode()) {
240 case SpvOpAccessChain:
241 case SpvOpInBoundsAccessChain:
242 access_chains.push_back(&inst);
243 break;
244 case SpvOpImageTexelPointer:
245 image_texel_pointers.push_back(&inst);
246 break;
247 default:
248 break;
249 }
250 }
251 }
252 for (auto* inst : access_chains) {
253 ClampIndicesForAccessChain(inst);
254 if (module_status_.failed) return module_status_.modified;
255 }
256
257 for (auto* inst : image_texel_pointers) {
258 if (SPV_SUCCESS != ClampCoordinateForImageTexelPointer(inst)) break;
259 }
260 return module_status_.modified;
261 }
262
ClampIndicesForAccessChain(Instruction * access_chain)263 void GraphicsRobustAccessPass::ClampIndicesForAccessChain(
264 Instruction* access_chain) {
265 Instruction& inst = *access_chain;
266
267 auto* constant_mgr = context()->get_constant_mgr();
268 auto* def_use_mgr = context()->get_def_use_mgr();
269 auto* type_mgr = context()->get_type_mgr();
270 const bool have_int64_cap =
271 context()->get_feature_mgr()->HasCapability(SpvCapabilityInt64);
272
273 // Replaces one of the OpAccessChain index operands with a new value.
274 // Updates def-use analysis.
275 auto replace_index = [this, &inst, def_use_mgr](uint32_t operand_index,
276 Instruction* new_value) {
277 inst.SetOperand(operand_index, {new_value->result_id()});
278 def_use_mgr->AnalyzeInstUse(&inst);
279 module_status_.modified = true;
280 return SPV_SUCCESS;
281 };
282
283 // Replaces one of the OpAccesssChain index operands with a clamped value.
284 // Replace the operand at |operand_index| with the value computed from
285 // signed_clamp(%old_value, %min_value, %max_value). It also analyzes
286 // the new instruction and records that them module is modified.
287 // Assumes %min_value is signed-less-or-equal than %max_value. (All callees
288 // use 0 for %min_value).
289 auto clamp_index = [&inst, type_mgr, this, &replace_index](
290 uint32_t operand_index, Instruction* old_value,
291 Instruction* min_value, Instruction* max_value) {
292 auto* clamp_inst =
293 MakeSClampInst(*type_mgr, old_value, min_value, max_value, &inst);
294 return replace_index(operand_index, clamp_inst);
295 };
296
297 // Ensures the specified index of access chain |inst| has a value that is
298 // at most |count| - 1. If the index is already a constant value less than
299 // |count| then no change is made.
300 auto clamp_to_literal_count =
301 [&inst, this, &constant_mgr, &type_mgr, have_int64_cap, &replace_index,
302 &clamp_index](uint32_t operand_index, uint64_t count) -> spv_result_t {
303 Instruction* index_inst =
304 this->GetDef(inst.GetSingleWordOperand(operand_index));
305 const auto* index_type =
306 type_mgr->GetType(index_inst->type_id())->AsInteger();
307 assert(index_type);
308 const auto index_width = index_type->width();
309
310 if (count <= 1) {
311 // Replace the index with 0.
312 return replace_index(operand_index, GetValueForType(0, index_type));
313 }
314
315 uint64_t maxval = count - 1;
316
317 // Compute the bit width of a viable type to hold |maxval|.
318 // Look for a bit width, up to 64 bits wide, to fit maxval.
319 uint32_t maxval_width = index_width;
320 while ((maxval_width < 64) && (0 != (maxval >> maxval_width))) {
321 maxval_width *= 2;
322 }
323 // Determine the type for |maxval|.
324 uint32_t next_id = context()->module()->IdBound();
325 analysis::Integer signed_type_for_query(maxval_width, true);
326 auto* maxval_type =
327 type_mgr->GetRegisteredType(&signed_type_for_query)->AsInteger();
328 if (next_id != context()->module()->IdBound()) {
329 module_status_.modified = true;
330 }
331 // Access chain indices are treated as signed, so limit the maximum value
332 // of the index so it will always be positive for a signed clamp operation.
333 maxval = std::min(maxval, ((uint64_t(1) << (maxval_width - 1)) - 1));
334
335 if (index_width > 64) {
336 return this->Fail() << "Can't handle indices wider than 64 bits, found "
337 "constant index with "
338 << index_width << " bits as index number "
339 << operand_index << " of access chain "
340 << inst.PrettyPrint();
341 }
342
343 // Split into two cases: the current index is a constant, or not.
344
345 // If the index is a constant then |index_constant| will not be a null
346 // pointer. (If index is an |OpConstantNull| then it |index_constant| will
347 // not be a null pointer.) Since access chain indices must be scalar
348 // integers, this can't be a spec constant.
349 if (auto* index_constant = constant_mgr->GetConstantFromInst(index_inst)) {
350 auto* int_index_constant = index_constant->AsIntConstant();
351 int64_t value = 0;
352 // OpAccessChain indices are treated as signed. So get the signed
353 // constant value here.
354 if (index_width <= 32) {
355 value = int64_t(int_index_constant->GetS32BitValue());
356 } else if (index_width <= 64) {
357 value = int_index_constant->GetS64BitValue();
358 }
359 if (value < 0) {
360 return replace_index(operand_index, GetValueForType(0, index_type));
361 } else if (uint64_t(value) <= maxval) {
362 // Nothing to do.
363 return SPV_SUCCESS;
364 } else {
365 // Replace with maxval.
366 assert(count > 0); // Already took care of this case above.
367 return replace_index(operand_index,
368 GetValueForType(maxval, maxval_type));
369 }
370 } else {
371 // Generate a clamp instruction.
372 assert(maxval >= 1);
373 assert(index_width <= 64); // Otherwise, already returned above.
374 if (index_width >= 64 && !have_int64_cap) {
375 // An inconsistent module.
376 return Fail() << "Access chain index is wider than 64 bits, but Int64 "
377 "is not declared: "
378 << index_inst->PrettyPrint();
379 }
380 // Widen the index value if necessary
381 if (maxval_width > index_width) {
382 // Find the wider type. We only need this case if a constant array
383 // bound is too big.
384
385 // From how we calculated maxval_width, widening won't require adding
386 // the Int64 capability.
387 assert(have_int64_cap || maxval_width <= 32);
388 if (!have_int64_cap && maxval_width >= 64) {
389 // Be defensive, but this shouldn't happen.
390 return this->Fail()
391 << "Clamping index would require adding Int64 capability. "
392 << "Can't clamp 32-bit index " << operand_index
393 << " of access chain " << inst.PrettyPrint();
394 }
395 index_inst = WidenInteger(index_type->IsSigned(), maxval_width,
396 index_inst, &inst);
397 }
398
399 // Finally, clamp the index.
400 return clamp_index(operand_index, index_inst,
401 GetValueForType(0, maxval_type),
402 GetValueForType(maxval, maxval_type));
403 }
404 return SPV_SUCCESS;
405 };
406
407 // Ensures the specified index of access chain |inst| has a value that is at
408 // most the value of |count_inst| minus 1, where |count_inst| is treated as an
409 // unsigned integer. This can log a failure.
410 auto clamp_to_count = [&inst, this, &constant_mgr, &clamp_to_literal_count,
411 &clamp_index,
412 &type_mgr](uint32_t operand_index,
413 Instruction* count_inst) -> spv_result_t {
414 Instruction* index_inst =
415 this->GetDef(inst.GetSingleWordOperand(operand_index));
416 const auto* index_type =
417 type_mgr->GetType(index_inst->type_id())->AsInteger();
418 const auto* count_type =
419 type_mgr->GetType(count_inst->type_id())->AsInteger();
420 assert(index_type);
421 if (const auto* count_constant =
422 constant_mgr->GetConstantFromInst(count_inst)) {
423 uint64_t value = 0;
424 const auto width = count_constant->type()->AsInteger()->width();
425 if (width <= 32) {
426 value = count_constant->AsIntConstant()->GetU32BitValue();
427 } else if (width <= 64) {
428 value = count_constant->AsIntConstant()->GetU64BitValue();
429 } else {
430 return this->Fail() << "Can't handle indices wider than 64 bits, found "
431 "constant index with "
432 << index_type->width() << "bits";
433 }
434 return clamp_to_literal_count(operand_index, value);
435 } else {
436 // Widen them to the same width.
437 const auto index_width = index_type->width();
438 const auto count_width = count_type->width();
439 const auto target_width = std::max(index_width, count_width);
440 // UConvert requires the result type to have 0 signedness. So enforce
441 // that here.
442 auto* wider_type = index_width < count_width ? count_type : index_type;
443 if (index_type->width() < target_width) {
444 // Access chain indices are treated as signed integers.
445 index_inst = WidenInteger(true, target_width, index_inst, &inst);
446 } else if (count_type->width() < target_width) {
447 // Assume type sizes are treated as unsigned.
448 count_inst = WidenInteger(false, target_width, count_inst, &inst);
449 }
450 // Compute count - 1.
451 // It doesn't matter if 1 is signed or unsigned.
452 auto* one = GetValueForType(1, wider_type);
453 auto* count_minus_1 = InsertInst(
454 &inst, SpvOpISub, type_mgr->GetId(wider_type), TakeNextId(),
455 {{SPV_OPERAND_TYPE_ID, {count_inst->result_id()}},
456 {SPV_OPERAND_TYPE_ID, {one->result_id()}}});
457 auto* zero = GetValueForType(0, wider_type);
458 // Make sure we clamp to an upper bound that is at most the signed max
459 // for the target type.
460 const uint64_t max_signed_value =
461 ((uint64_t(1) << (target_width - 1)) - 1);
462 // Use unsigned-min to ensure that the result is always non-negative.
463 // That ensures we satisfy the invariant for SClamp, where the "min"
464 // argument we give it (zero), is no larger than the third argument.
465 auto* upper_bound =
466 MakeUMinInst(*type_mgr, count_minus_1,
467 GetValueForType(max_signed_value, wider_type), &inst);
468 // Now clamp the index to this upper bound.
469 return clamp_index(operand_index, index_inst, zero, upper_bound);
470 }
471 return SPV_SUCCESS;
472 };
473
474 const Instruction* base_inst = GetDef(inst.GetSingleWordInOperand(0));
475 const Instruction* base_type = GetDef(base_inst->type_id());
476 Instruction* pointee_type = GetDef(base_type->GetSingleWordInOperand(1));
477
478 // Walk the indices from earliest to latest, replacing indices with a
479 // clamped value, and updating the pointee_type. The order matters for
480 // the case when we have to compute the length of a runtime array. In
481 // that the algorithm relies on the fact that that the earlier indices
482 // have already been clamped.
483 const uint32_t num_operands = inst.NumOperands();
484 for (uint32_t idx = 3; !module_status_.failed && idx < num_operands; ++idx) {
485 const uint32_t index_id = inst.GetSingleWordOperand(idx);
486 Instruction* index_inst = GetDef(index_id);
487
488 switch (pointee_type->opcode()) {
489 case SpvOpTypeMatrix: // Use column count
490 case SpvOpTypeVector: // Use component count
491 {
492 const uint32_t count = pointee_type->GetSingleWordOperand(2);
493 clamp_to_literal_count(idx, count);
494 pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
495 } break;
496
497 case SpvOpTypeArray: {
498 // The array length can be a spec constant, so go through the general
499 // case.
500 Instruction* array_len = GetDef(pointee_type->GetSingleWordOperand(2));
501 clamp_to_count(idx, array_len);
502 pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
503 } break;
504
505 case SpvOpTypeStruct: {
506 // SPIR-V requires the index to be an OpConstant.
507 // We need to know the index literal value so we can compute the next
508 // pointee type.
509 if (index_inst->opcode() != SpvOpConstant ||
510 !constant_mgr->GetConstantFromInst(index_inst)
511 ->type()
512 ->AsInteger()) {
513 Fail() << "Member index into struct is not a constant integer: "
514 << index_inst->PrettyPrint(
515 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
516 << "\nin access chain: "
517 << inst.PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
518 return;
519 }
520 const auto num_members = pointee_type->NumInOperands();
521 const auto* index_constant =
522 constant_mgr->GetConstantFromInst(index_inst);
523 // Get the sign-extended value, since access index is always treated as
524 // signed.
525 const auto index_value = index_constant->GetSignExtendedValue();
526 if (index_value < 0 || index_value >= num_members) {
527 Fail() << "Member index " << index_value
528 << " is out of bounds for struct type: "
529 << pointee_type->PrettyPrint(
530 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
531 << "\nin access chain: "
532 << inst.PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
533 return;
534 }
535 pointee_type = GetDef(pointee_type->GetSingleWordInOperand(
536 static_cast<uint32_t>(index_value)));
537 // No need to clamp this index. We just checked that it's valid.
538 } break;
539
540 case SpvOpTypeRuntimeArray: {
541 auto* array_len = MakeRuntimeArrayLengthInst(&inst, idx);
542 if (!array_len) { // We've already signaled an error.
543 return;
544 }
545 clamp_to_count(idx, array_len);
546 if (module_status_.failed) return;
547 pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
548 } break;
549
550 default:
551 Fail() << " Unhandled pointee type for access chain "
552 << pointee_type->PrettyPrint(
553 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
554 }
555 }
556 }
557
GetGlslInsts()558 uint32_t GraphicsRobustAccessPass::GetGlslInsts() {
559 if (module_status_.glsl_insts_id == 0) {
560 // This string serves double-duty as raw data for a string and for a vector
561 // of 32-bit words
562 const char glsl[] = "GLSL.std.450";
563 // Use an existing import if we can.
564 for (auto& inst : context()->module()->ext_inst_imports()) {
565 if (inst.GetInOperand(0).AsString() == glsl) {
566 module_status_.glsl_insts_id = inst.result_id();
567 }
568 }
569 if (module_status_.glsl_insts_id == 0) {
570 // Make a new import instruction.
571 module_status_.glsl_insts_id = TakeNextId();
572 std::vector<uint32_t> words = spvtools::utils::MakeVector(glsl);
573 auto import_inst = MakeUnique<Instruction>(
574 context(), SpvOpExtInstImport, 0, module_status_.glsl_insts_id,
575 std::initializer_list<Operand>{
576 Operand{SPV_OPERAND_TYPE_LITERAL_STRING, std::move(words)}});
577 Instruction* inst = import_inst.get();
578 context()->module()->AddExtInstImport(std::move(import_inst));
579 module_status_.modified = true;
580 context()->AnalyzeDefUse(inst);
581 // Reanalyze the feature list, since we added an extended instruction
582 // set improt.
583 context()->get_feature_mgr()->Analyze(context()->module());
584 }
585 }
586 return module_status_.glsl_insts_id;
587 }
588
GetValueForType(uint64_t value,const analysis::Integer * type)589 opt::Instruction* opt::GraphicsRobustAccessPass::GetValueForType(
590 uint64_t value, const analysis::Integer* type) {
591 auto* mgr = context()->get_constant_mgr();
592 assert(type->width() <= 64);
593 std::vector<uint32_t> words;
594 words.push_back(uint32_t(value));
595 if (type->width() > 32) {
596 words.push_back(uint32_t(value >> 32u));
597 }
598 const auto* constant = mgr->GetConstant(type, words);
599 return mgr->GetDefiningInstruction(
600 constant, context()->get_type_mgr()->GetTypeInstruction(type));
601 }
602
WidenInteger(bool sign_extend,uint32_t bit_width,Instruction * value,Instruction * before_inst)603 opt::Instruction* opt::GraphicsRobustAccessPass::WidenInteger(
604 bool sign_extend, uint32_t bit_width, Instruction* value,
605 Instruction* before_inst) {
606 analysis::Integer unsigned_type_for_query(bit_width, false);
607 auto* type_mgr = context()->get_type_mgr();
608 auto* unsigned_type = type_mgr->GetRegisteredType(&unsigned_type_for_query);
609 auto type_id = context()->get_type_mgr()->GetId(unsigned_type);
610 auto conversion_id = TakeNextId();
611 auto* conversion = InsertInst(
612 before_inst, (sign_extend ? SpvOpSConvert : SpvOpUConvert), type_id,
613 conversion_id, {{SPV_OPERAND_TYPE_ID, {value->result_id()}}});
614 return conversion;
615 }
616
MakeUMinInst(const analysis::TypeManager & tm,Instruction * x,Instruction * y,Instruction * where)617 Instruction* GraphicsRobustAccessPass::MakeUMinInst(
618 const analysis::TypeManager& tm, Instruction* x, Instruction* y,
619 Instruction* where) {
620 // Get IDs of instructions we'll be referencing. Evaluate them before calling
621 // the function so we force a deterministic ordering in case both of them need
622 // to take a new ID.
623 const uint32_t glsl_insts_id = GetGlslInsts();
624 uint32_t smin_id = TakeNextId();
625 const auto xwidth = tm.GetType(x->type_id())->AsInteger()->width();
626 const auto ywidth = tm.GetType(y->type_id())->AsInteger()->width();
627 assert(xwidth == ywidth);
628 (void)xwidth;
629 (void)ywidth;
630 auto* smin_inst = InsertInst(
631 where, SpvOpExtInst, x->type_id(), smin_id,
632 {
633 {SPV_OPERAND_TYPE_ID, {glsl_insts_id}},
634 {SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, {GLSLstd450UMin}},
635 {SPV_OPERAND_TYPE_ID, {x->result_id()}},
636 {SPV_OPERAND_TYPE_ID, {y->result_id()}},
637 });
638 return smin_inst;
639 }
640
MakeSClampInst(const analysis::TypeManager & tm,Instruction * x,Instruction * min,Instruction * max,Instruction * where)641 Instruction* GraphicsRobustAccessPass::MakeSClampInst(
642 const analysis::TypeManager& tm, Instruction* x, Instruction* min,
643 Instruction* max, Instruction* where) {
644 // Get IDs of instructions we'll be referencing. Evaluate them before calling
645 // the function so we force a deterministic ordering in case both of them need
646 // to take a new ID.
647 const uint32_t glsl_insts_id = GetGlslInsts();
648 uint32_t clamp_id = TakeNextId();
649 const auto xwidth = tm.GetType(x->type_id())->AsInteger()->width();
650 const auto minwidth = tm.GetType(min->type_id())->AsInteger()->width();
651 const auto maxwidth = tm.GetType(max->type_id())->AsInteger()->width();
652 assert(xwidth == minwidth);
653 assert(xwidth == maxwidth);
654 (void)xwidth;
655 (void)minwidth;
656 (void)maxwidth;
657 auto* clamp_inst = InsertInst(
658 where, SpvOpExtInst, x->type_id(), clamp_id,
659 {
660 {SPV_OPERAND_TYPE_ID, {glsl_insts_id}},
661 {SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, {GLSLstd450SClamp}},
662 {SPV_OPERAND_TYPE_ID, {x->result_id()}},
663 {SPV_OPERAND_TYPE_ID, {min->result_id()}},
664 {SPV_OPERAND_TYPE_ID, {max->result_id()}},
665 });
666 return clamp_inst;
667 }
668
MakeRuntimeArrayLengthInst(Instruction * access_chain,uint32_t operand_index)669 Instruction* GraphicsRobustAccessPass::MakeRuntimeArrayLengthInst(
670 Instruction* access_chain, uint32_t operand_index) {
671 // The Index parameter to the access chain at |operand_index| is indexing
672 // *into* the runtime-array. To get the number of elements in the runtime
673 // array we need a pointer to the Block-decorated struct that contains the
674 // runtime array. So conceptually we have to go 2 steps backward in the
675 // access chain. The two steps backward might forces us to traverse backward
676 // across multiple dominating instructions.
677 auto* type_mgr = context()->get_type_mgr();
678
679 // How many access chain indices do we have to unwind to find the pointer
680 // to the struct containing the runtime array?
681 uint32_t steps_remaining = 2;
682 // Find or create an instruction computing the pointer to the structure
683 // containing the runtime array.
684 // Walk backward through pointer address calculations until we either get
685 // to exactly the right base pointer, or to an access chain instruction
686 // that we can replicate but truncate to compute the address of the right
687 // struct.
688 Instruction* current_access_chain = access_chain;
689 Instruction* pointer_to_containing_struct = nullptr;
690 while (steps_remaining > 0) {
691 switch (current_access_chain->opcode()) {
692 case SpvOpCopyObject:
693 // Whoops. Walk right through this one.
694 current_access_chain =
695 GetDef(current_access_chain->GetSingleWordInOperand(0));
696 break;
697 case SpvOpAccessChain:
698 case SpvOpInBoundsAccessChain: {
699 const int first_index_operand = 3;
700 // How many indices in this access chain contribute to getting us
701 // to an element in the runtime array?
702 const auto num_contributing_indices =
703 current_access_chain == access_chain
704 ? operand_index - (first_index_operand - 1)
705 : current_access_chain->NumInOperands() - 1 /* skip the base */;
706 Instruction* base =
707 GetDef(current_access_chain->GetSingleWordInOperand(0));
708 if (num_contributing_indices == steps_remaining) {
709 // The base pointer points to the structure.
710 pointer_to_containing_struct = base;
711 steps_remaining = 0;
712 break;
713 } else if (num_contributing_indices < steps_remaining) {
714 // Peel off the index and keep going backward.
715 steps_remaining -= num_contributing_indices;
716 current_access_chain = base;
717 } else {
718 // This access chain has more indices than needed. Generate a new
719 // access chain instruction, but truncating the list of indices.
720 const int base_operand = 2;
721 // We'll use the base pointer and the indices up to but not including
722 // the one indexing into the runtime array.
723 Instruction::OperandList ops;
724 // Use the base pointer
725 ops.push_back(current_access_chain->GetOperand(base_operand));
726 const uint32_t num_indices_to_keep =
727 num_contributing_indices - steps_remaining - 1;
728 for (uint32_t i = 0; i <= num_indices_to_keep; i++) {
729 ops.push_back(
730 current_access_chain->GetOperand(first_index_operand + i));
731 }
732 // Compute the type of the result of the new access chain. Start at
733 // the base and walk the indices in a forward direction.
734 auto* constant_mgr = context()->get_constant_mgr();
735 std::vector<uint32_t> indices_for_type;
736 for (uint32_t i = 0; i < ops.size() - 1; i++) {
737 uint32_t index_for_type_calculation = 0;
738 Instruction* index =
739 GetDef(current_access_chain->GetSingleWordOperand(
740 first_index_operand + i));
741 if (auto* index_constant =
742 constant_mgr->GetConstantFromInst(index)) {
743 // We only need 32 bits. For the type calculation, it's sufficient
744 // to take the zero-extended value. It only matters for the struct
745 // case, and struct member indices are unsigned.
746 index_for_type_calculation =
747 uint32_t(index_constant->GetZeroExtendedValue());
748 } else {
749 // Indexing into a variably-sized thing like an array. Use 0.
750 index_for_type_calculation = 0;
751 }
752 indices_for_type.push_back(index_for_type_calculation);
753 }
754 auto* base_ptr_type = type_mgr->GetType(base->type_id())->AsPointer();
755 auto* base_pointee_type = base_ptr_type->pointee_type();
756 auto* new_access_chain_result_pointee_type =
757 type_mgr->GetMemberType(base_pointee_type, indices_for_type);
758 const uint32_t new_access_chain_type_id = type_mgr->FindPointerToType(
759 type_mgr->GetId(new_access_chain_result_pointee_type),
760 base_ptr_type->storage_class());
761
762 // Create the instruction and insert it.
763 const auto new_access_chain_id = TakeNextId();
764 auto* new_access_chain =
765 InsertInst(current_access_chain, current_access_chain->opcode(),
766 new_access_chain_type_id, new_access_chain_id, ops);
767 pointer_to_containing_struct = new_access_chain;
768 steps_remaining = 0;
769 break;
770 }
771 } break;
772 default:
773 Fail() << "Unhandled access chain in logical addressing mode passes "
774 "through "
775 << current_access_chain->PrettyPrint(
776 SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET |
777 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
778 return nullptr;
779 }
780 }
781 assert(pointer_to_containing_struct);
782 auto* pointee_type =
783 type_mgr->GetType(pointer_to_containing_struct->type_id())
784 ->AsPointer()
785 ->pointee_type();
786
787 auto* struct_type = pointee_type->AsStruct();
788 const uint32_t member_index_of_runtime_array =
789 uint32_t(struct_type->element_types().size() - 1);
790 // Create the length-of-array instruction before the original access chain,
791 // but after the generation of the pointer to the struct.
792 const auto array_len_id = TakeNextId();
793 analysis::Integer uint_type_for_query(32, false);
794 auto* uint_type = type_mgr->GetRegisteredType(&uint_type_for_query);
795 auto* array_len = InsertInst(
796 access_chain, SpvOpArrayLength, type_mgr->GetId(uint_type), array_len_id,
797 {{SPV_OPERAND_TYPE_ID, {pointer_to_containing_struct->result_id()}},
798 {SPV_OPERAND_TYPE_LITERAL_INTEGER, {member_index_of_runtime_array}}});
799 return array_len;
800 }
801
ClampCoordinateForImageTexelPointer(opt::Instruction * image_texel_pointer)802 spv_result_t GraphicsRobustAccessPass::ClampCoordinateForImageTexelPointer(
803 opt::Instruction* image_texel_pointer) {
804 // TODO(dneto): Write tests for this code.
805 // TODO(dneto): Use signed-clamp
806 (void)(image_texel_pointer);
807 return SPV_SUCCESS;
808
809 // Do not compile this code until it is ready to be used.
810 #if 0
811 // Example:
812 // %texel_ptr = OpImageTexelPointer %texel_ptr_type %image_ptr %coord
813 // %sample
814 //
815 // We want to clamp %coord components between vector-0 and the result
816 // of OpImageQuerySize acting on the underlying image. So insert:
817 // %image = OpLoad %image_type %image_ptr
818 // %query_size = OpImageQuerySize %query_size_type %image
819 //
820 // For a multi-sampled image, %sample is the sample index, and we need
821 // to clamp it between zero and the number of samples in the image.
822 // %sample_count = OpImageQuerySamples %uint %image
823 // %max_sample_index = OpISub %uint %sample_count %uint_1
824 // For non-multi-sampled images, the sample index must be constant zero.
825
826 auto* def_use_mgr = context()->get_def_use_mgr();
827 auto* type_mgr = context()->get_type_mgr();
828 auto* constant_mgr = context()->get_constant_mgr();
829
830 auto* image_ptr = GetDef(image_texel_pointer->GetSingleWordInOperand(0));
831 auto* image_ptr_type = GetDef(image_ptr->type_id());
832 auto image_type_id = image_ptr_type->GetSingleWordInOperand(1);
833 auto* image_type = GetDef(image_type_id);
834 auto* coord = GetDef(image_texel_pointer->GetSingleWordInOperand(1));
835 auto* samples = GetDef(image_texel_pointer->GetSingleWordInOperand(2));
836
837 // We will modify the module, at least by adding image query instructions.
838 module_status_.modified = true;
839
840 // Declare the ImageQuery capability if the module doesn't already have it.
841 auto* feature_mgr = context()->get_feature_mgr();
842 if (!feature_mgr->HasCapability(SpvCapabilityImageQuery)) {
843 auto cap = MakeUnique<Instruction>(
844 context(), SpvOpCapability, 0, 0,
845 std::initializer_list<Operand>{
846 {SPV_OPERAND_TYPE_CAPABILITY, {SpvCapabilityImageQuery}}});
847 def_use_mgr->AnalyzeInstDefUse(cap.get());
848 context()->AddCapability(std::move(cap));
849 feature_mgr->Analyze(context()->module());
850 }
851
852 // OpImageTexelPointer is used to translate a coordinate and sample index
853 // into an address for use with an atomic operation. That is, it may only
854 // used with what Vulkan calls a "storage image"
855 // (OpTypeImage parameter Sampled=2).
856 // Note: A storage image never has a level-of-detail associated with it.
857
858 // Constraints on the sample id:
859 // - Only 2D images can be multi-sampled: OpTypeImage parameter MS=1
860 // only if Dim=2D.
861 // - Non-multi-sampled images (OpTypeImage parameter MS=0) must use
862 // sample ID to a constant 0.
863
864 // The coordinate is treated as unsigned, and should be clamped against the
865 // image "size", returned by OpImageQuerySize. (Note: OpImageQuerySizeLod
866 // is only usable with a sampled image, i.e. its image type has Sampled=1).
867
868 // Determine the result type for the OpImageQuerySize.
869 // For non-arrayed images:
870 // non-Cube:
871 // - Always the same as the coordinate type
872 // Cube:
873 // - Use all but the last component of the coordinate (which is the face
874 // index from 0 to 5).
875 // For arrayed images (in Vulkan the Dim is 1D, 2D, or Cube):
876 // non-Cube:
877 // - A vector with the components in the coordinate, and one more for
878 // the layer index.
879 // Cube:
880 // - The same as the coordinate type: 3-element integer vector.
881 // - The third component from the size query is the layer count.
882 // - The third component in the texel pointer calculation is
883 // 6 * layer + face, where 0 <= face < 6.
884 // Cube: Use all but the last component of the coordinate (which is the face
885 // index from 0 to 5).
886 const auto dim = SpvDim(image_type->GetSingleWordInOperand(1));
887 const bool arrayed = image_type->GetSingleWordInOperand(3) == 1;
888 const bool multisampled = image_type->GetSingleWordInOperand(4) != 0;
889 const auto query_num_components = [dim, arrayed, this]() -> int {
890 const int arrayness_bonus = arrayed ? 1 : 0;
891 int num_coords = 0;
892 switch (dim) {
893 case SpvDimBuffer:
894 case SpvDim1D:
895 num_coords = 1;
896 break;
897 case SpvDimCube:
898 // For cube, we need bounds for x, y, but not face.
899 case SpvDimRect:
900 case SpvDim2D:
901 num_coords = 2;
902 break;
903 case SpvDim3D:
904 num_coords = 3;
905 break;
906 case SpvDimSubpassData:
907 case SpvDimMax:
908 return Fail() << "Invalid image dimension for OpImageTexelPointer: "
909 << int(dim);
910 break;
911 }
912 return num_coords + arrayness_bonus;
913 }();
914 const auto* coord_component_type = [type_mgr, coord]() {
915 const analysis::Type* coord_type = type_mgr->GetType(coord->type_id());
916 if (auto* vector_type = coord_type->AsVector()) {
917 return vector_type->element_type()->AsInteger();
918 }
919 return coord_type->AsInteger();
920 }();
921 // For now, only handle 32-bit case for coordinates.
922 if (!coord_component_type) {
923 return Fail() << " Coordinates for OpImageTexelPointer are not integral: "
924 << image_texel_pointer->PrettyPrint(
925 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
926 }
927 if (coord_component_type->width() != 32) {
928 return Fail() << " Expected OpImageTexelPointer coordinate components to "
929 "be 32-bits wide. They are "
930 << coord_component_type->width() << " bits. "
931 << image_texel_pointer->PrettyPrint(
932 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
933 }
934 const auto* query_size_type =
935 [type_mgr, coord_component_type,
936 query_num_components]() -> const analysis::Type* {
937 if (query_num_components == 1) return coord_component_type;
938 analysis::Vector proposed(coord_component_type, query_num_components);
939 return type_mgr->GetRegisteredType(&proposed);
940 }();
941
942 const uint32_t image_id = TakeNextId();
943 auto* image =
944 InsertInst(image_texel_pointer, SpvOpLoad, image_type_id, image_id,
945 {{SPV_OPERAND_TYPE_ID, {image_ptr->result_id()}}});
946
947 const uint32_t query_size_id = TakeNextId();
948 auto* query_size =
949 InsertInst(image_texel_pointer, SpvOpImageQuerySize,
950 type_mgr->GetTypeInstruction(query_size_type), query_size_id,
951 {{SPV_OPERAND_TYPE_ID, {image->result_id()}}});
952
953 auto* component_1 = constant_mgr->GetConstant(coord_component_type, {1});
954 const uint32_t component_1_id =
955 constant_mgr->GetDefiningInstruction(component_1)->result_id();
956 auto* component_0 = constant_mgr->GetConstant(coord_component_type, {0});
957 const uint32_t component_0_id =
958 constant_mgr->GetDefiningInstruction(component_0)->result_id();
959
960 // If the image is a cube array, then the last component of the queried
961 // size is the layer count. In the query, we have to accommodate folding
962 // in the face index ranging from 0 through 5. The inclusive upper bound
963 // on the third coordinate therefore is multiplied by 6.
964 auto* query_size_including_faces = query_size;
965 if (arrayed && (dim == SpvDimCube)) {
966 // Multiply the last coordinate by 6.
967 auto* component_6 = constant_mgr->GetConstant(coord_component_type, {6});
968 const uint32_t component_6_id =
969 constant_mgr->GetDefiningInstruction(component_6)->result_id();
970 assert(query_num_components == 3);
971 auto* multiplicand = constant_mgr->GetConstant(
972 query_size_type, {component_1_id, component_1_id, component_6_id});
973 auto* multiplicand_inst =
974 constant_mgr->GetDefiningInstruction(multiplicand);
975 const auto query_size_including_faces_id = TakeNextId();
976 query_size_including_faces = InsertInst(
977 image_texel_pointer, SpvOpIMul,
978 type_mgr->GetTypeInstruction(query_size_type),
979 query_size_including_faces_id,
980 {{SPV_OPERAND_TYPE_ID, {query_size_including_faces->result_id()}},
981 {SPV_OPERAND_TYPE_ID, {multiplicand_inst->result_id()}}});
982 }
983
984 // Make a coordinate-type with all 1 components.
985 auto* coordinate_1 =
986 query_num_components == 1
987 ? component_1
988 : constant_mgr->GetConstant(
989 query_size_type,
990 std::vector<uint32_t>(query_num_components, component_1_id));
991 // Make a coordinate-type with all 1 components.
992 auto* coordinate_0 =
993 query_num_components == 0
994 ? component_0
995 : constant_mgr->GetConstant(
996 query_size_type,
997 std::vector<uint32_t>(query_num_components, component_0_id));
998
999 const uint32_t query_max_including_faces_id = TakeNextId();
1000 auto* query_max_including_faces = InsertInst(
1001 image_texel_pointer, SpvOpISub,
1002 type_mgr->GetTypeInstruction(query_size_type),
1003 query_max_including_faces_id,
1004 {{SPV_OPERAND_TYPE_ID, {query_size_including_faces->result_id()}},
1005 {SPV_OPERAND_TYPE_ID,
1006 {constant_mgr->GetDefiningInstruction(coordinate_1)->result_id()}}});
1007
1008 // Clamp the coordinate
1009 auto* clamp_coord = MakeSClampInst(
1010 *type_mgr, coord, constant_mgr->GetDefiningInstruction(coordinate_0),
1011 query_max_including_faces, image_texel_pointer);
1012 image_texel_pointer->SetInOperand(1, {clamp_coord->result_id()});
1013
1014 // Clamp the sample index
1015 if (multisampled) {
1016 // Get the sample count via OpImageQuerySamples
1017 const auto query_samples_id = TakeNextId();
1018 auto* query_samples = InsertInst(
1019 image_texel_pointer, SpvOpImageQuerySamples,
1020 constant_mgr->GetDefiningInstruction(component_0)->type_id(),
1021 query_samples_id, {{SPV_OPERAND_TYPE_ID, {image->result_id()}}});
1022
1023 const auto max_samples_id = TakeNextId();
1024 auto* max_samples = InsertInst(image_texel_pointer, SpvOpImageQuerySamples,
1025 query_samples->type_id(), max_samples_id,
1026 {{SPV_OPERAND_TYPE_ID, {query_samples_id}},
1027 {SPV_OPERAND_TYPE_ID, {component_1_id}}});
1028
1029 auto* clamp_samples = MakeSClampInst(
1030 *type_mgr, samples, constant_mgr->GetDefiningInstruction(coordinate_0),
1031 max_samples, image_texel_pointer);
1032 image_texel_pointer->SetInOperand(2, {clamp_samples->result_id()});
1033
1034 } else {
1035 // Just replace it with 0. Don't even check what was there before.
1036 image_texel_pointer->SetInOperand(2, {component_0_id});
1037 }
1038
1039 def_use_mgr->AnalyzeInstUse(image_texel_pointer);
1040
1041 return SPV_SUCCESS;
1042 #endif
1043 }
1044
InsertInst(opt::Instruction * where_inst,SpvOp opcode,uint32_t type_id,uint32_t result_id,const Instruction::OperandList & operands)1045 opt::Instruction* GraphicsRobustAccessPass::InsertInst(
1046 opt::Instruction* where_inst, SpvOp opcode, uint32_t type_id,
1047 uint32_t result_id, const Instruction::OperandList& operands) {
1048 module_status_.modified = true;
1049 auto* result = where_inst->InsertBefore(
1050 MakeUnique<Instruction>(context(), opcode, type_id, result_id, operands));
1051 context()->get_def_use_mgr()->AnalyzeInstDefUse(result);
1052 auto* basic_block = context()->get_instr_block(where_inst);
1053 context()->set_instr_block(result, basic_block);
1054 return result;
1055 }
1056
1057 } // namespace opt
1058 } // namespace spvtools
1059