blob: 2a3e7f06e9be95aa774630987c089f677c5efd15 [file] [log] [blame]
Chris Forbescc5697f2019-01-30 11:54:08 -08001// Copyright (c) 2018 The Khronos Group Inc.
2// Copyright (c) 2018 Valve Corporation
3// Copyright (c) 2018 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 "instrument_pass.h"
18
19#include "source/cfa.h"
Ben Claytonb73b7602019-07-29 13:56:13 +010020#include "source/spirv_constant.h"
Chris Forbescc5697f2019-01-30 11:54:08 -080021
22namespace {
23
24// Common Parameter Positions
25static const int kInstCommonParamInstIdx = 0;
26static const int kInstCommonParamCnt = 1;
27
28// Indices of operands in SPIR-V instructions
29static const int kEntryPointExecutionModelInIdx = 0;
30static const int kEntryPointFunctionIdInIdx = 1;
31
32} // anonymous namespace
33
34namespace spvtools {
35namespace opt {
36
37void InstrumentPass::MovePreludeCode(
38 BasicBlock::iterator ref_inst_itr,
39 UptrVectorIterator<BasicBlock> ref_block_itr,
40 std::unique_ptr<BasicBlock>* new_blk_ptr) {
41 same_block_pre_.clear();
42 same_block_post_.clear();
43 // Initialize new block. Reuse label from original block.
44 new_blk_ptr->reset(new BasicBlock(std::move(ref_block_itr->GetLabel())));
45 // Move contents of original ref block up to ref instruction.
46 for (auto cii = ref_block_itr->begin(); cii != ref_inst_itr;
47 cii = ref_block_itr->begin()) {
48 Instruction* inst = &*cii;
49 inst->RemoveFromList();
50 std::unique_ptr<Instruction> mv_ptr(inst);
51 // Remember same-block ops for possible regeneration.
52 if (IsSameBlockOp(&*mv_ptr)) {
53 auto* sb_inst_ptr = mv_ptr.get();
54 same_block_pre_[mv_ptr->result_id()] = sb_inst_ptr;
55 }
56 (*new_blk_ptr)->AddInstruction(std::move(mv_ptr));
57 }
58}
59
60void InstrumentPass::MovePostludeCode(
Ben Claytonb73b7602019-07-29 13:56:13 +010061 UptrVectorIterator<BasicBlock> ref_block_itr, BasicBlock* new_blk_ptr) {
Chris Forbescc5697f2019-01-30 11:54:08 -080062 // new_blk_ptr->reset(new BasicBlock(NewLabel(ref_block_itr->id())));
63 // Move contents of original ref block.
64 for (auto cii = ref_block_itr->begin(); cii != ref_block_itr->end();
65 cii = ref_block_itr->begin()) {
66 Instruction* inst = &*cii;
67 inst->RemoveFromList();
68 std::unique_ptr<Instruction> mv_inst(inst);
69 // Regenerate any same-block instruction that has not been seen in the
70 // current block.
71 if (same_block_pre_.size() > 0) {
72 CloneSameBlockOps(&mv_inst, &same_block_post_, &same_block_pre_,
73 new_blk_ptr);
74 // Remember same-block ops in this block.
75 if (IsSameBlockOp(&*mv_inst)) {
76 const uint32_t rid = mv_inst->result_id();
77 same_block_post_[rid] = rid;
78 }
79 }
Ben Claytonb73b7602019-07-29 13:56:13 +010080 new_blk_ptr->AddInstruction(std::move(mv_inst));
Chris Forbescc5697f2019-01-30 11:54:08 -080081 }
82}
83
84std::unique_ptr<Instruction> InstrumentPass::NewLabel(uint32_t label_id) {
85 std::unique_ptr<Instruction> newLabel(
86 new Instruction(context(), SpvOpLabel, 0, label_id, {}));
87 get_def_use_mgr()->AnalyzeInstDefUse(&*newLabel);
88 return newLabel;
89}
90
91uint32_t InstrumentPass::GenUintCastCode(uint32_t val_id,
92 InstructionBuilder* builder) {
93 // Cast value to 32-bit unsigned if necessary
94 if (get_def_use_mgr()->GetDef(val_id)->type_id() == GetUintId())
95 return val_id;
96 return builder->AddUnaryOp(GetUintId(), SpvOpBitcast, val_id)->result_id();
97}
98
99void InstrumentPass::GenDebugOutputFieldCode(uint32_t base_offset_id,
100 uint32_t field_offset,
101 uint32_t field_value_id,
102 InstructionBuilder* builder) {
103 // Cast value to 32-bit unsigned if necessary
104 uint32_t val_id = GenUintCastCode(field_value_id, builder);
105 // Store value
106 Instruction* data_idx_inst =
107 builder->AddBinaryOp(GetUintId(), SpvOpIAdd, base_offset_id,
108 builder->GetUintConstantId(field_offset));
109 uint32_t buf_id = GetOutputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100110 uint32_t buf_uint_ptr_id = GetOutputBufferPtrId();
Chris Forbescc5697f2019-01-30 11:54:08 -0800111 Instruction* achain_inst =
112 builder->AddTernaryOp(buf_uint_ptr_id, SpvOpAccessChain, buf_id,
113 builder->GetUintConstantId(kDebugOutputDataOffset),
114 data_idx_inst->result_id());
115 (void)builder->AddBinaryOp(0, SpvOpStore, achain_inst->result_id(), val_id);
116}
117
118void InstrumentPass::GenCommonStreamWriteCode(uint32_t record_sz,
119 uint32_t inst_id,
120 uint32_t stage_idx,
121 uint32_t base_offset_id,
122 InstructionBuilder* builder) {
123 // Store record size
124 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutSize,
125 builder->GetUintConstantId(record_sz), builder);
126 // Store Shader Id
127 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutShaderId,
128 builder->GetUintConstantId(shader_id_), builder);
129 // Store Instruction Idx
130 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutInstructionIdx, inst_id,
131 builder);
132 // Store Stage Idx
133 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutStageIdx,
134 builder->GetUintConstantId(stage_idx), builder);
135}
136
137void InstrumentPass::GenFragCoordEltDebugOutputCode(
138 uint32_t base_offset_id, uint32_t uint_frag_coord_id, uint32_t element,
139 InstructionBuilder* builder) {
140 Instruction* element_val_inst = builder->AddIdLiteralOp(
141 GetUintId(), SpvOpCompositeExtract, uint_frag_coord_id, element);
142 GenDebugOutputFieldCode(base_offset_id, kInstFragOutFragCoordX + element,
143 element_val_inst->result_id(), builder);
144}
145
Ben Claytonb73b7602019-07-29 13:56:13 +0100146uint32_t InstrumentPass::GenVarLoad(uint32_t var_id,
147 InstructionBuilder* builder) {
148 Instruction* var_inst = get_def_use_mgr()->GetDef(var_id);
149 uint32_t type_id = GetPointeeTypeId(var_inst);
150 Instruction* load_inst = builder->AddUnaryOp(type_id, SpvOpLoad, var_id);
151 return load_inst->result_id();
152}
153
Chris Forbescc5697f2019-01-30 11:54:08 -0800154void InstrumentPass::GenBuiltinOutputCode(uint32_t builtin_id,
155 uint32_t builtin_off,
156 uint32_t base_offset_id,
157 InstructionBuilder* builder) {
158 // Load and store builtin
Ben Claytonb73b7602019-07-29 13:56:13 +0100159 uint32_t load_id = GenVarLoad(builtin_id, builder);
160 GenDebugOutputFieldCode(base_offset_id, builtin_off, load_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800161}
162
163void InstrumentPass::GenStageStreamWriteCode(uint32_t stage_idx,
164 uint32_t base_offset_id,
165 InstructionBuilder* builder) {
166 // TODO(greg-lunarg): Add support for all stages
167 switch (stage_idx) {
168 case SpvExecutionModelVertex: {
169 // Load and store VertexId and InstanceId
Ben Claytonb73b7602019-07-29 13:56:13 +0100170 GenBuiltinOutputCode(
171 context()->GetBuiltinInputVarId(SpvBuiltInVertexIndex),
172 kInstVertOutVertexIndex, base_offset_id, builder);
173 GenBuiltinOutputCode(
174 context()->GetBuiltinInputVarId(SpvBuiltInInstanceIndex),
175 kInstVertOutInstanceIndex, base_offset_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800176 } break;
177 case SpvExecutionModelGLCompute: {
Ben Claytonb73b7602019-07-29 13:56:13 +0100178 // Load and store GlobalInvocationId.
179 uint32_t load_id = GenVarLoad(
180 context()->GetBuiltinInputVarId(SpvBuiltInGlobalInvocationId),
181 builder);
182 Instruction* x_inst = builder->AddIdLiteralOp(
183 GetUintId(), SpvOpCompositeExtract, load_id, 0);
184 Instruction* y_inst = builder->AddIdLiteralOp(
185 GetUintId(), SpvOpCompositeExtract, load_id, 1);
186 Instruction* z_inst = builder->AddIdLiteralOp(
187 GetUintId(), SpvOpCompositeExtract, load_id, 2);
188 if (version_ == 1) {
189 // For version 1 format, as a stopgap, pack uvec3 into first word:
190 // x << 21 | y << 10 | z. Second word is unused. (DEPRECATED)
191 Instruction* x_shft_inst = builder->AddBinaryOp(
192 GetUintId(), SpvOpShiftLeftLogical, x_inst->result_id(),
193 builder->GetUintConstantId(21));
194 Instruction* y_shft_inst = builder->AddBinaryOp(
195 GetUintId(), SpvOpShiftLeftLogical, y_inst->result_id(),
196 builder->GetUintConstantId(10));
197 Instruction* x_or_y_inst = builder->AddBinaryOp(
198 GetUintId(), SpvOpBitwiseOr, x_shft_inst->result_id(),
199 y_shft_inst->result_id());
200 Instruction* x_or_y_or_z_inst =
201 builder->AddBinaryOp(GetUintId(), SpvOpBitwiseOr,
202 x_or_y_inst->result_id(), z_inst->result_id());
203 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationId,
204 x_or_y_or_z_inst->result_id(), builder);
205 } else {
206 // For version 2 format, write all three words
207 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdX,
208 x_inst->result_id(), builder);
209 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdY,
210 y_inst->result_id(), builder);
211 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdZ,
212 z_inst->result_id(), builder);
213 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800214 } break;
215 case SpvExecutionModelGeometry: {
216 // Load and store PrimitiveId and InvocationId.
Ben Claytonb73b7602019-07-29 13:56:13 +0100217 GenBuiltinOutputCode(
218 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
219 kInstGeomOutPrimitiveId, base_offset_id, builder);
220 GenBuiltinOutputCode(
221 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
222 kInstGeomOutInvocationId, base_offset_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800223 } break;
Ben Claytonb73b7602019-07-29 13:56:13 +0100224 case SpvExecutionModelTessellationControl: {
225 // Load and store InvocationId and PrimitiveId
226 GenBuiltinOutputCode(
227 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
228 kInstTessCtlOutInvocationId, base_offset_id, builder);
229 GenBuiltinOutputCode(
230 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
231 kInstTessCtlOutPrimitiveId, base_offset_id, builder);
232 } break;
Chris Forbescc5697f2019-01-30 11:54:08 -0800233 case SpvExecutionModelTessellationEvaluation: {
Ben Claytonb73b7602019-07-29 13:56:13 +0100234 if (version_ == 1) {
235 // For format version 1, load and store InvocationId.
236 GenBuiltinOutputCode(
237 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
238 kInstTessOutInvocationId, base_offset_id, builder);
239 } else {
240 // For format version 2, load and store PrimitiveId and TessCoord.uv
241 GenBuiltinOutputCode(
242 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
243 kInstTessEvalOutPrimitiveId, base_offset_id, builder);
244 uint32_t load_id = GenVarLoad(
245 context()->GetBuiltinInputVarId(SpvBuiltInTessCoord), builder);
Ben Claytond0f684e2019-08-30 22:36:08 +0100246 Instruction* uvec3_cast_inst =
247 builder->AddUnaryOp(GetVec3UintId(), SpvOpBitcast, load_id);
248 uint32_t uvec3_cast_id = uvec3_cast_inst->result_id();
Ben Claytonb73b7602019-07-29 13:56:13 +0100249 Instruction* u_inst = builder->AddIdLiteralOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100250 GetUintId(), SpvOpCompositeExtract, uvec3_cast_id, 0);
Ben Claytonb73b7602019-07-29 13:56:13 +0100251 Instruction* v_inst = builder->AddIdLiteralOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100252 GetUintId(), SpvOpCompositeExtract, uvec3_cast_id, 1);
Ben Claytonb73b7602019-07-29 13:56:13 +0100253 GenDebugOutputFieldCode(base_offset_id, kInstTessEvalOutTessCoordU,
254 u_inst->result_id(), builder);
255 GenDebugOutputFieldCode(base_offset_id, kInstTessEvalOutTessCoordV,
256 v_inst->result_id(), builder);
257 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800258 } break;
259 case SpvExecutionModelFragment: {
260 // Load FragCoord and convert to Uint
Ben Claytonb73b7602019-07-29 13:56:13 +0100261 Instruction* frag_coord_inst = builder->AddUnaryOp(
262 GetVec4FloatId(), SpvOpLoad,
263 context()->GetBuiltinInputVarId(SpvBuiltInFragCoord));
Chris Forbescc5697f2019-01-30 11:54:08 -0800264 Instruction* uint_frag_coord_inst = builder->AddUnaryOp(
265 GetVec4UintId(), SpvOpBitcast, frag_coord_inst->result_id());
266 for (uint32_t u = 0; u < 2u; ++u)
267 GenFragCoordEltDebugOutputCode(
268 base_offset_id, uint_frag_coord_inst->result_id(), u, builder);
269 } break;
Ben Claytonb73b7602019-07-29 13:56:13 +0100270 case SpvExecutionModelRayGenerationNV:
271 case SpvExecutionModelIntersectionNV:
272 case SpvExecutionModelAnyHitNV:
273 case SpvExecutionModelClosestHitNV:
274 case SpvExecutionModelMissNV:
275 case SpvExecutionModelCallableNV: {
276 // Load and store LaunchIdNV.
277 uint32_t launch_id = GenVarLoad(
278 context()->GetBuiltinInputVarId(SpvBuiltInLaunchIdNV), builder);
279 Instruction* x_launch_inst = builder->AddIdLiteralOp(
280 GetUintId(), SpvOpCompositeExtract, launch_id, 0);
281 Instruction* y_launch_inst = builder->AddIdLiteralOp(
282 GetUintId(), SpvOpCompositeExtract, launch_id, 1);
283 Instruction* z_launch_inst = builder->AddIdLiteralOp(
284 GetUintId(), SpvOpCompositeExtract, launch_id, 2);
285 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdX,
286 x_launch_inst->result_id(), builder);
287 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdY,
288 y_launch_inst->result_id(), builder);
289 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdZ,
290 z_launch_inst->result_id(), builder);
291 } break;
Chris Forbescc5697f2019-01-30 11:54:08 -0800292 default: { assert(false && "unsupported stage"); } break;
293 }
294}
295
296void InstrumentPass::GenDebugStreamWrite(
297 uint32_t instruction_idx, uint32_t stage_idx,
298 const std::vector<uint32_t>& validation_ids, InstructionBuilder* builder) {
299 // Call debug output function. Pass func_idx, instruction_idx and
300 // validation ids as args.
301 uint32_t val_id_cnt = static_cast<uint32_t>(validation_ids.size());
302 uint32_t output_func_id = GetStreamWriteFunctionId(stage_idx, val_id_cnt);
303 std::vector<uint32_t> args = {output_func_id,
304 builder->GetUintConstantId(instruction_idx)};
305 (void)args.insert(args.end(), validation_ids.begin(), validation_ids.end());
306 (void)builder->AddNaryOp(GetVoidId(), SpvOpFunctionCall, args);
307}
308
Ben Claytonb73b7602019-07-29 13:56:13 +0100309uint32_t InstrumentPass::GenDebugDirectRead(
310 const std::vector<uint32_t>& offset_ids, InstructionBuilder* builder) {
311 // Call debug input function. Pass func_idx and offset ids as args.
312 uint32_t off_id_cnt = static_cast<uint32_t>(offset_ids.size());
313 uint32_t input_func_id = GetDirectReadFunctionId(off_id_cnt);
314 std::vector<uint32_t> args = {input_func_id};
315 (void)args.insert(args.end(), offset_ids.begin(), offset_ids.end());
316 return builder->AddNaryOp(GetUintId(), SpvOpFunctionCall, args)->result_id();
317}
318
Chris Forbescc5697f2019-01-30 11:54:08 -0800319bool InstrumentPass::IsSameBlockOp(const Instruction* inst) const {
320 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
321}
322
323void InstrumentPass::CloneSameBlockOps(
324 std::unique_ptr<Instruction>* inst,
325 std::unordered_map<uint32_t, uint32_t>* same_blk_post,
326 std::unordered_map<uint32_t, Instruction*>* same_blk_pre,
Ben Claytonb73b7602019-07-29 13:56:13 +0100327 BasicBlock* block_ptr) {
Ben Claytond552f632019-11-18 11:18:41 +0000328 bool changed = false;
329 (*inst)->ForEachInId([&same_blk_post, &same_blk_pre, &block_ptr, &changed,
330 this](uint32_t* iid) {
331 const auto map_itr = (*same_blk_post).find(*iid);
332 if (map_itr == (*same_blk_post).end()) {
333 const auto map_itr2 = (*same_blk_pre).find(*iid);
334 if (map_itr2 != (*same_blk_pre).end()) {
335 // Clone pre-call same-block ops, map result id.
336 const Instruction* in_inst = map_itr2->second;
337 std::unique_ptr<Instruction> sb_inst(in_inst->Clone(context()));
338 const uint32_t rid = sb_inst->result_id();
339 const uint32_t nid = this->TakeNextId();
340 get_decoration_mgr()->CloneDecorations(rid, nid);
341 sb_inst->SetResultId(nid);
342 get_def_use_mgr()->AnalyzeInstDefUse(&*sb_inst);
343 (*same_blk_post)[rid] = nid;
344 *iid = nid;
345 changed = true;
346 CloneSameBlockOps(&sb_inst, same_blk_post, same_blk_pre, block_ptr);
347 block_ptr->AddInstruction(std::move(sb_inst));
348 }
349 } else {
350 // Reset same-block op operand if necessary
351 if (*iid != map_itr->second) {
352 *iid = map_itr->second;
353 changed = true;
354 }
355 }
356 });
357 if (changed) get_def_use_mgr()->AnalyzeInstUse(&**inst);
Chris Forbescc5697f2019-01-30 11:54:08 -0800358}
359
360void InstrumentPass::UpdateSucceedingPhis(
361 std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
362 const auto first_blk = new_blocks.begin();
363 const auto last_blk = new_blocks.end() - 1;
364 const uint32_t first_id = (*first_blk)->id();
365 const uint32_t last_id = (*last_blk)->id();
366 const BasicBlock& const_last_block = *last_blk->get();
367 const_last_block.ForEachSuccessorLabel(
368 [&first_id, &last_id, this](const uint32_t succ) {
369 BasicBlock* sbp = this->id2block_[succ];
370 sbp->ForEachPhiInst([&first_id, &last_id, this](Instruction* phi) {
371 bool changed = false;
372 phi->ForEachInId([&first_id, &last_id, &changed](uint32_t* id) {
373 if (*id == first_id) {
374 *id = last_id;
375 changed = true;
376 }
377 });
378 if (changed) get_def_use_mgr()->AnalyzeInstUse(phi);
379 });
380 });
381}
382
Ben Claytond0f684e2019-08-30 22:36:08 +0100383uint32_t InstrumentPass::GetOutputBufferPtrId() {
384 if (output_buffer_ptr_id_ == 0) {
385 output_buffer_ptr_id_ = context()->get_type_mgr()->FindPointerToType(
Chris Forbescc5697f2019-01-30 11:54:08 -0800386 GetUintId(), SpvStorageClassStorageBuffer);
387 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100388 return output_buffer_ptr_id_;
389}
390
391uint32_t InstrumentPass::GetInputBufferTypeId() {
392 return (validation_id_ == kInstValidationIdBuffAddr) ? GetUint64Id()
393 : GetUintId();
394}
395
396uint32_t InstrumentPass::GetInputBufferPtrId() {
397 if (input_buffer_ptr_id_ == 0) {
398 input_buffer_ptr_id_ = context()->get_type_mgr()->FindPointerToType(
399 GetInputBufferTypeId(), SpvStorageClassStorageBuffer);
400 }
401 return input_buffer_ptr_id_;
Chris Forbescc5697f2019-01-30 11:54:08 -0800402}
403
404uint32_t InstrumentPass::GetOutputBufferBinding() {
405 switch (validation_id_) {
406 case kInstValidationIdBindless:
407 return kDebugOutputBindingStream;
Ben Claytond0f684e2019-08-30 22:36:08 +0100408 case kInstValidationIdBuffAddr:
409 return kDebugOutputBindingStream;
Chris Forbescc5697f2019-01-30 11:54:08 -0800410 default:
411 assert(false && "unexpected validation id");
412 }
413 return 0;
414}
415
Ben Claytonb73b7602019-07-29 13:56:13 +0100416uint32_t InstrumentPass::GetInputBufferBinding() {
417 switch (validation_id_) {
418 case kInstValidationIdBindless:
419 return kDebugInputBindingBindless;
Ben Claytond0f684e2019-08-30 22:36:08 +0100420 case kInstValidationIdBuffAddr:
421 return kDebugInputBindingBuffAddr;
Ben Claytonb73b7602019-07-29 13:56:13 +0100422 default:
423 assert(false && "unexpected validation id");
424 }
425 return 0;
426}
427
Ben Claytond0f684e2019-08-30 22:36:08 +0100428analysis::Type* InstrumentPass::GetUintXRuntimeArrayType(
429 uint32_t width, analysis::Type** rarr_ty) {
430 if (*rarr_ty == nullptr) {
431 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
432 analysis::TypeManager* type_mgr = context()->get_type_mgr();
433 analysis::Integer uint_ty(width, false);
Ben Claytonb73b7602019-07-29 13:56:13 +0100434 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
435 analysis::RuntimeArray uint_rarr_ty_tmp(reg_uint_ty);
Ben Claytond0f684e2019-08-30 22:36:08 +0100436 *rarr_ty = type_mgr->GetRegisteredType(&uint_rarr_ty_tmp);
437 uint32_t uint_arr_ty_id = type_mgr->GetTypeInstruction(*rarr_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100438 // By the Vulkan spec, a pre-existing RuntimeArray of uint must be part of
439 // a block, and will therefore be decorated with an ArrayStride. Therefore
440 // the undecorated type returned here will not be pre-existing and can
441 // safely be decorated. Since this type is now decorated, it is out of
442 // sync with the TypeManager and therefore the TypeManager must be
443 // invalidated after this pass.
444 assert(context()->get_def_use_mgr()->NumUses(uint_arr_ty_id) == 0 &&
445 "used RuntimeArray type returned");
Ben Claytond0f684e2019-08-30 22:36:08 +0100446 deco_mgr->AddDecorationVal(uint_arr_ty_id, SpvDecorationArrayStride,
447 width / 8u);
Ben Claytonb73b7602019-07-29 13:56:13 +0100448 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100449 return *rarr_ty;
450}
451
452analysis::Type* InstrumentPass::GetUintRuntimeArrayType(uint32_t width) {
453 analysis::Type** rarr_ty =
454 (width == 64) ? &uint64_rarr_ty_ : &uint32_rarr_ty_;
455 return GetUintXRuntimeArrayType(width, rarr_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100456}
457
458void InstrumentPass::AddStorageBufferExt() {
459 if (storage_buffer_ext_defined_) return;
460 if (!get_feature_mgr()->HasExtension(kSPV_KHR_storage_buffer_storage_class)) {
Ben Claytond0f684e2019-08-30 22:36:08 +0100461 context()->AddExtension("SPV_KHR_storage_buffer_storage_class");
Ben Claytonb73b7602019-07-29 13:56:13 +0100462 }
463 storage_buffer_ext_defined_ = true;
464}
465
Chris Forbescc5697f2019-01-30 11:54:08 -0800466// Return id for output buffer
467uint32_t InstrumentPass::GetOutputBufferId() {
468 if (output_buffer_id_ == 0) {
469 // If not created yet, create one
470 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
471 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100472 analysis::Type* reg_uint_rarr_ty = GetUintRuntimeArrayType(32);
Chris Forbescc5697f2019-01-30 11:54:08 -0800473 analysis::Integer uint_ty(32, false);
474 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100475 analysis::Struct buf_ty({reg_uint_ty, reg_uint_rarr_ty});
476 analysis::Type* reg_buf_ty = type_mgr->GetRegisteredType(&buf_ty);
477 uint32_t obufTyId = type_mgr->GetTypeInstruction(reg_buf_ty);
478 // By the Vulkan spec, a pre-existing struct containing a RuntimeArray
479 // must be a block, and will therefore be decorated with Block. Therefore
480 // the undecorated type returned here will not be pre-existing and can
481 // safely be decorated. Since this type is now decorated, it is out of
482 // sync with the TypeManager and therefore the TypeManager must be
483 // invalidated after this pass.
484 assert(context()->get_def_use_mgr()->NumUses(obufTyId) == 0 &&
485 "used struct type returned");
Chris Forbescc5697f2019-01-30 11:54:08 -0800486 deco_mgr->AddDecoration(obufTyId, SpvDecorationBlock);
487 deco_mgr->AddMemberDecoration(obufTyId, kDebugOutputSizeOffset,
488 SpvDecorationOffset, 0);
489 deco_mgr->AddMemberDecoration(obufTyId, kDebugOutputDataOffset,
490 SpvDecorationOffset, 4);
491 uint32_t obufTyPtrId_ =
492 type_mgr->FindPointerToType(obufTyId, SpvStorageClassStorageBuffer);
493 output_buffer_id_ = TakeNextId();
494 std::unique_ptr<Instruction> newVarOp(new Instruction(
495 context(), SpvOpVariable, obufTyPtrId_, output_buffer_id_,
496 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
497 {SpvStorageClassStorageBuffer}}}));
498 context()->AddGlobalValue(std::move(newVarOp));
499 deco_mgr->AddDecorationVal(output_buffer_id_, SpvDecorationDescriptorSet,
500 desc_set_);
501 deco_mgr->AddDecorationVal(output_buffer_id_, SpvDecorationBinding,
502 GetOutputBufferBinding());
Ben Claytonb73b7602019-07-29 13:56:13 +0100503 AddStorageBufferExt();
504 if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
505 // Add the new buffer to all entry points.
506 for (auto& entry : get_module()->entry_points()) {
507 entry.AddOperand({SPV_OPERAND_TYPE_ID, {output_buffer_id_}});
508 context()->AnalyzeUses(&entry);
509 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800510 }
511 }
512 return output_buffer_id_;
513}
514
Ben Claytonb73b7602019-07-29 13:56:13 +0100515uint32_t InstrumentPass::GetInputBufferId() {
516 if (input_buffer_id_ == 0) {
517 // If not created yet, create one
518 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
519 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100520 uint32_t width = (validation_id_ == kInstValidationIdBuffAddr) ? 64u : 32u;
521 analysis::Type* reg_uint_rarr_ty = GetUintRuntimeArrayType(width);
Ben Claytonb73b7602019-07-29 13:56:13 +0100522 analysis::Struct buf_ty({reg_uint_rarr_ty});
523 analysis::Type* reg_buf_ty = type_mgr->GetRegisteredType(&buf_ty);
524 uint32_t ibufTyId = type_mgr->GetTypeInstruction(reg_buf_ty);
525 // By the Vulkan spec, a pre-existing struct containing a RuntimeArray
526 // must be a block, and will therefore be decorated with Block. Therefore
527 // the undecorated type returned here will not be pre-existing and can
528 // safely be decorated. Since this type is now decorated, it is out of
529 // sync with the TypeManager and therefore the TypeManager must be
530 // invalidated after this pass.
531 assert(context()->get_def_use_mgr()->NumUses(ibufTyId) == 0 &&
532 "used struct type returned");
533 deco_mgr->AddDecoration(ibufTyId, SpvDecorationBlock);
534 deco_mgr->AddMemberDecoration(ibufTyId, 0, SpvDecorationOffset, 0);
535 uint32_t ibufTyPtrId_ =
536 type_mgr->FindPointerToType(ibufTyId, SpvStorageClassStorageBuffer);
537 input_buffer_id_ = TakeNextId();
538 std::unique_ptr<Instruction> newVarOp(new Instruction(
539 context(), SpvOpVariable, ibufTyPtrId_, input_buffer_id_,
540 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
541 {SpvStorageClassStorageBuffer}}}));
542 context()->AddGlobalValue(std::move(newVarOp));
543 deco_mgr->AddDecorationVal(input_buffer_id_, SpvDecorationDescriptorSet,
544 desc_set_);
545 deco_mgr->AddDecorationVal(input_buffer_id_, SpvDecorationBinding,
546 GetInputBufferBinding());
547 AddStorageBufferExt();
548 if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
549 // Add the new buffer to all entry points.
550 for (auto& entry : get_module()->entry_points()) {
551 entry.AddOperand({SPV_OPERAND_TYPE_ID, {input_buffer_id_}});
552 context()->AnalyzeUses(&entry);
553 }
554 }
555 }
556 return input_buffer_id_;
557}
558
Chris Forbescc5697f2019-01-30 11:54:08 -0800559uint32_t InstrumentPass::GetVec4FloatId() {
560 if (v4float_id_ == 0) {
561 analysis::TypeManager* type_mgr = context()->get_type_mgr();
562 analysis::Float float_ty(32);
563 analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
564 analysis::Vector v4float_ty(reg_float_ty, 4);
565 analysis::Type* reg_v4float_ty = type_mgr->GetRegisteredType(&v4float_ty);
566 v4float_id_ = type_mgr->GetTypeInstruction(reg_v4float_ty);
567 }
568 return v4float_id_;
569}
570
571uint32_t InstrumentPass::GetUintId() {
572 if (uint_id_ == 0) {
573 analysis::TypeManager* type_mgr = context()->get_type_mgr();
574 analysis::Integer uint_ty(32, false);
575 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
576 uint_id_ = type_mgr->GetTypeInstruction(reg_uint_ty);
577 }
578 return uint_id_;
579}
580
Ben Claytond0f684e2019-08-30 22:36:08 +0100581uint32_t InstrumentPass::GetUint64Id() {
582 if (uint64_id_ == 0) {
Chris Forbescc5697f2019-01-30 11:54:08 -0800583 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100584 analysis::Integer uint64_ty(64, false);
585 analysis::Type* reg_uint64_ty = type_mgr->GetRegisteredType(&uint64_ty);
586 uint64_id_ = type_mgr->GetTypeInstruction(reg_uint64_ty);
Chris Forbescc5697f2019-01-30 11:54:08 -0800587 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100588 return uint64_id_;
589}
590
591uint32_t InstrumentPass::GetVecUintId(uint32_t len) {
592 analysis::TypeManager* type_mgr = context()->get_type_mgr();
593 analysis::Integer uint_ty(32, false);
594 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
595 analysis::Vector v_uint_ty(reg_uint_ty, len);
596 analysis::Type* reg_v_uint_ty = type_mgr->GetRegisteredType(&v_uint_ty);
597 uint32_t v_uint_id = type_mgr->GetTypeInstruction(reg_v_uint_ty);
598 return v_uint_id;
599}
600
601uint32_t InstrumentPass::GetVec4UintId() {
602 if (v4uint_id_ == 0) v4uint_id_ = GetVecUintId(4u);
Chris Forbescc5697f2019-01-30 11:54:08 -0800603 return v4uint_id_;
604}
605
Ben Claytond0f684e2019-08-30 22:36:08 +0100606uint32_t InstrumentPass::GetVec3UintId() {
607 if (v3uint_id_ == 0) v3uint_id_ = GetVecUintId(3u);
608 return v3uint_id_;
609}
610
Chris Forbescc5697f2019-01-30 11:54:08 -0800611uint32_t InstrumentPass::GetBoolId() {
612 if (bool_id_ == 0) {
613 analysis::TypeManager* type_mgr = context()->get_type_mgr();
614 analysis::Bool bool_ty;
615 analysis::Type* reg_bool_ty = type_mgr->GetRegisteredType(&bool_ty);
616 bool_id_ = type_mgr->GetTypeInstruction(reg_bool_ty);
617 }
618 return bool_id_;
619}
620
621uint32_t InstrumentPass::GetVoidId() {
622 if (void_id_ == 0) {
623 analysis::TypeManager* type_mgr = context()->get_type_mgr();
624 analysis::Void void_ty;
625 analysis::Type* reg_void_ty = type_mgr->GetRegisteredType(&void_ty);
626 void_id_ = type_mgr->GetTypeInstruction(reg_void_ty);
627 }
628 return void_id_;
629}
630
631uint32_t InstrumentPass::GetStreamWriteFunctionId(uint32_t stage_idx,
632 uint32_t val_spec_param_cnt) {
633 // Total param count is common params plus validation-specific
634 // params
635 uint32_t param_cnt = kInstCommonParamCnt + val_spec_param_cnt;
636 if (output_func_id_ == 0) {
637 // Create function
638 output_func_id_ = TakeNextId();
639 analysis::TypeManager* type_mgr = context()->get_type_mgr();
640 std::vector<const analysis::Type*> param_types;
641 for (uint32_t c = 0; c < param_cnt; ++c)
642 param_types.push_back(type_mgr->GetType(GetUintId()));
643 analysis::Function func_ty(type_mgr->GetType(GetVoidId()), param_types);
644 analysis::Type* reg_func_ty = type_mgr->GetRegisteredType(&func_ty);
645 std::unique_ptr<Instruction> func_inst(new Instruction(
646 get_module()->context(), SpvOpFunction, GetVoidId(), output_func_id_,
647 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
648 {SpvFunctionControlMaskNone}},
649 {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
650 {type_mgr->GetTypeInstruction(reg_func_ty)}}}));
651 get_def_use_mgr()->AnalyzeInstDefUse(&*func_inst);
652 std::unique_ptr<Function> output_func =
653 MakeUnique<Function>(std::move(func_inst));
654 // Add parameters
655 std::vector<uint32_t> param_vec;
656 for (uint32_t c = 0; c < param_cnt; ++c) {
657 uint32_t pid = TakeNextId();
658 param_vec.push_back(pid);
659 std::unique_ptr<Instruction> param_inst(
660 new Instruction(get_module()->context(), SpvOpFunctionParameter,
661 GetUintId(), pid, {}));
662 get_def_use_mgr()->AnalyzeInstDefUse(&*param_inst);
663 output_func->AddParameter(std::move(param_inst));
664 }
665 // Create first block
666 uint32_t test_blk_id = TakeNextId();
667 std::unique_ptr<Instruction> test_label(NewLabel(test_blk_id));
668 std::unique_ptr<BasicBlock> new_blk_ptr =
669 MakeUnique<BasicBlock>(std::move(test_label));
670 InstructionBuilder builder(
671 context(), &*new_blk_ptr,
672 IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
673 // Gen test if debug output buffer size will not be exceeded.
Ben Claytonb73b7602019-07-29 13:56:13 +0100674 uint32_t val_spec_offset =
675 (version_ == 1) ? kInstStageOutCnt : kInst2StageOutCnt;
676 uint32_t obuf_record_sz = val_spec_offset + val_spec_param_cnt;
Chris Forbescc5697f2019-01-30 11:54:08 -0800677 uint32_t buf_id = GetOutputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100678 uint32_t buf_uint_ptr_id = GetOutputBufferPtrId();
Chris Forbescc5697f2019-01-30 11:54:08 -0800679 Instruction* obuf_curr_sz_ac_inst =
680 builder.AddBinaryOp(buf_uint_ptr_id, SpvOpAccessChain, buf_id,
681 builder.GetUintConstantId(kDebugOutputSizeOffset));
682 // Fetch the current debug buffer written size atomically, adding the
683 // size of the record to be written.
684 uint32_t obuf_record_sz_id = builder.GetUintConstantId(obuf_record_sz);
685 uint32_t mask_none_id = builder.GetUintConstantId(SpvMemoryAccessMaskNone);
686 uint32_t scope_invok_id = builder.GetUintConstantId(SpvScopeInvocation);
687 Instruction* obuf_curr_sz_inst = builder.AddQuadOp(
688 GetUintId(), SpvOpAtomicIAdd, obuf_curr_sz_ac_inst->result_id(),
689 scope_invok_id, mask_none_id, obuf_record_sz_id);
690 uint32_t obuf_curr_sz_id = obuf_curr_sz_inst->result_id();
691 // Compute new written size
692 Instruction* obuf_new_sz_inst =
693 builder.AddBinaryOp(GetUintId(), SpvOpIAdd, obuf_curr_sz_id,
694 builder.GetUintConstantId(obuf_record_sz));
695 // Fetch the data bound
696 Instruction* obuf_bnd_inst =
697 builder.AddIdLiteralOp(GetUintId(), SpvOpArrayLength,
698 GetOutputBufferId(), kDebugOutputDataOffset);
699 // Test that new written size is less than or equal to debug output
700 // data bound
701 Instruction* obuf_safe_inst = builder.AddBinaryOp(
702 GetBoolId(), SpvOpULessThanEqual, obuf_new_sz_inst->result_id(),
703 obuf_bnd_inst->result_id());
704 uint32_t merge_blk_id = TakeNextId();
705 uint32_t write_blk_id = TakeNextId();
706 std::unique_ptr<Instruction> merge_label(NewLabel(merge_blk_id));
707 std::unique_ptr<Instruction> write_label(NewLabel(write_blk_id));
708 (void)builder.AddConditionalBranch(obuf_safe_inst->result_id(),
709 write_blk_id, merge_blk_id, merge_blk_id,
710 SpvSelectionControlMaskNone);
711 // Close safety test block and gen write block
712 new_blk_ptr->SetParent(&*output_func);
713 output_func->AddBasicBlock(std::move(new_blk_ptr));
714 new_blk_ptr = MakeUnique<BasicBlock>(std::move(write_label));
715 builder.SetInsertPoint(&*new_blk_ptr);
716 // Generate common and stage-specific debug record members
717 GenCommonStreamWriteCode(obuf_record_sz, param_vec[kInstCommonParamInstIdx],
718 stage_idx, obuf_curr_sz_id, &builder);
719 GenStageStreamWriteCode(stage_idx, obuf_curr_sz_id, &builder);
720 // Gen writes of validation specific data
721 for (uint32_t i = 0; i < val_spec_param_cnt; ++i) {
Ben Claytonb73b7602019-07-29 13:56:13 +0100722 GenDebugOutputFieldCode(obuf_curr_sz_id, val_spec_offset + i,
Chris Forbescc5697f2019-01-30 11:54:08 -0800723 param_vec[kInstCommonParamCnt + i], &builder);
724 }
725 // Close write block and gen merge block
726 (void)builder.AddBranch(merge_blk_id);
727 new_blk_ptr->SetParent(&*output_func);
728 output_func->AddBasicBlock(std::move(new_blk_ptr));
729 new_blk_ptr = MakeUnique<BasicBlock>(std::move(merge_label));
730 builder.SetInsertPoint(&*new_blk_ptr);
731 // Close merge block and function and add function to module
732 (void)builder.AddNullaryOp(0, SpvOpReturn);
733 new_blk_ptr->SetParent(&*output_func);
734 output_func->AddBasicBlock(std::move(new_blk_ptr));
735 std::unique_ptr<Instruction> func_end_inst(
736 new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {}));
737 get_def_use_mgr()->AnalyzeInstDefUse(&*func_end_inst);
738 output_func->SetFunctionEnd(std::move(func_end_inst));
739 context()->AddFunction(std::move(output_func));
740 output_func_param_cnt_ = param_cnt;
741 }
742 assert(param_cnt == output_func_param_cnt_ && "bad arg count");
743 return output_func_id_;
744}
745
Ben Claytonb73b7602019-07-29 13:56:13 +0100746uint32_t InstrumentPass::GetDirectReadFunctionId(uint32_t param_cnt) {
747 uint32_t func_id = param2input_func_id_[param_cnt];
748 if (func_id != 0) return func_id;
Ben Claytond0f684e2019-08-30 22:36:08 +0100749 // Create input function for param_cnt.
Ben Claytonb73b7602019-07-29 13:56:13 +0100750 func_id = TakeNextId();
751 analysis::TypeManager* type_mgr = context()->get_type_mgr();
752 std::vector<const analysis::Type*> param_types;
753 for (uint32_t c = 0; c < param_cnt; ++c)
754 param_types.push_back(type_mgr->GetType(GetUintId()));
Ben Claytond0f684e2019-08-30 22:36:08 +0100755 uint32_t ibuf_type_id = GetInputBufferTypeId();
756 analysis::Function func_ty(type_mgr->GetType(ibuf_type_id), param_types);
Ben Claytonb73b7602019-07-29 13:56:13 +0100757 analysis::Type* reg_func_ty = type_mgr->GetRegisteredType(&func_ty);
758 std::unique_ptr<Instruction> func_inst(new Instruction(
Ben Claytond0f684e2019-08-30 22:36:08 +0100759 get_module()->context(), SpvOpFunction, ibuf_type_id, func_id,
Ben Claytonb73b7602019-07-29 13:56:13 +0100760 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
761 {SpvFunctionControlMaskNone}},
762 {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
763 {type_mgr->GetTypeInstruction(reg_func_ty)}}}));
764 get_def_use_mgr()->AnalyzeInstDefUse(&*func_inst);
765 std::unique_ptr<Function> input_func =
766 MakeUnique<Function>(std::move(func_inst));
767 // Add parameters
768 std::vector<uint32_t> param_vec;
769 for (uint32_t c = 0; c < param_cnt; ++c) {
770 uint32_t pid = TakeNextId();
771 param_vec.push_back(pid);
772 std::unique_ptr<Instruction> param_inst(new Instruction(
773 get_module()->context(), SpvOpFunctionParameter, GetUintId(), pid, {}));
774 get_def_use_mgr()->AnalyzeInstDefUse(&*param_inst);
775 input_func->AddParameter(std::move(param_inst));
776 }
777 // Create block
778 uint32_t blk_id = TakeNextId();
779 std::unique_ptr<Instruction> blk_label(NewLabel(blk_id));
780 std::unique_ptr<BasicBlock> new_blk_ptr =
781 MakeUnique<BasicBlock>(std::move(blk_label));
782 InstructionBuilder builder(
783 context(), &*new_blk_ptr,
784 IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
785 // For each offset parameter, generate new offset with parameter, adding last
786 // loaded value if it exists, and load value from input buffer at new offset.
787 // Return last loaded value.
788 uint32_t buf_id = GetInputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100789 uint32_t buf_ptr_id = GetInputBufferPtrId();
Ben Claytonb73b7602019-07-29 13:56:13 +0100790 uint32_t last_value_id = 0;
791 for (uint32_t p = 0; p < param_cnt; ++p) {
792 uint32_t offset_id;
793 if (p == 0) {
794 offset_id = param_vec[0];
795 } else {
Ben Claytond0f684e2019-08-30 22:36:08 +0100796 if (ibuf_type_id != GetUintId()) {
797 Instruction* ucvt_inst =
798 builder.AddUnaryOp(GetUintId(), SpvOpUConvert, last_value_id);
799 last_value_id = ucvt_inst->result_id();
800 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100801 Instruction* offset_inst = builder.AddBinaryOp(
802 GetUintId(), SpvOpIAdd, last_value_id, param_vec[p]);
803 offset_id = offset_inst->result_id();
804 }
805 Instruction* ac_inst = builder.AddTernaryOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100806 buf_ptr_id, SpvOpAccessChain, buf_id,
Ben Claytonb73b7602019-07-29 13:56:13 +0100807 builder.GetUintConstantId(kDebugInputDataOffset), offset_id);
808 Instruction* load_inst =
Ben Claytond0f684e2019-08-30 22:36:08 +0100809 builder.AddUnaryOp(ibuf_type_id, SpvOpLoad, ac_inst->result_id());
Ben Claytonb73b7602019-07-29 13:56:13 +0100810 last_value_id = load_inst->result_id();
811 }
812 (void)builder.AddInstruction(MakeUnique<Instruction>(
813 context(), SpvOpReturnValue, 0, 0,
814 std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {last_value_id}}}));
815 // Close block and function and add function to module
816 new_blk_ptr->SetParent(&*input_func);
817 input_func->AddBasicBlock(std::move(new_blk_ptr));
818 std::unique_ptr<Instruction> func_end_inst(
819 new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {}));
820 get_def_use_mgr()->AnalyzeInstDefUse(&*func_end_inst);
821 input_func->SetFunctionEnd(std::move(func_end_inst));
822 context()->AddFunction(std::move(input_func));
823 param2input_func_id_[param_cnt] = func_id;
824 return func_id;
825}
826
Chris Forbescc5697f2019-01-30 11:54:08 -0800827bool InstrumentPass::InstrumentFunction(Function* func, uint32_t stage_idx,
828 InstProcessFunction& pfn) {
829 bool modified = false;
830 // Compute function index
831 uint32_t function_idx = 0;
832 for (auto fii = get_module()->begin(); fii != get_module()->end(); ++fii) {
833 if (&*fii == func) break;
834 ++function_idx;
835 }
836 std::vector<std::unique_ptr<BasicBlock>> new_blks;
Chris Forbescc5697f2019-01-30 11:54:08 -0800837 // Using block iterators here because of block erasures and insertions.
838 for (auto bi = func->begin(); bi != func->end(); ++bi) {
Ben Claytonb73b7602019-07-29 13:56:13 +0100839 for (auto ii = bi->begin(); ii != bi->end();) {
Chris Forbescc5697f2019-01-30 11:54:08 -0800840 // Generate instrumentation if warranted
Ben Claytonb73b7602019-07-29 13:56:13 +0100841 pfn(ii, bi, stage_idx, &new_blks);
Chris Forbescc5697f2019-01-30 11:54:08 -0800842 if (new_blks.size() == 0) {
843 ++ii;
844 continue;
845 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100846 // Add new blocks to label id map
847 for (auto& blk : new_blks) id2block_[blk->id()] = &*blk;
Chris Forbescc5697f2019-01-30 11:54:08 -0800848 // If there are new blocks we know there will always be two or
849 // more, so update succeeding phis with label of new last block.
850 size_t newBlocksSize = new_blks.size();
851 assert(newBlocksSize > 1);
852 UpdateSucceedingPhis(new_blks);
853 // Replace original block with new block(s)
854 bi = bi.Erase();
855 for (auto& bb : new_blks) {
856 bb->SetParent(func);
857 }
858 bi = bi.InsertBefore(&new_blks);
859 // Reset block iterator to last new block
860 for (size_t i = 0; i < newBlocksSize - 1; i++) ++bi;
861 modified = true;
862 // Restart instrumenting at beginning of last new block,
863 // but skip over any new phi or copy instruction.
864 ii = bi->begin();
865 if (ii->opcode() == SpvOpPhi || ii->opcode() == SpvOpCopyObject) ++ii;
866 new_blks.clear();
867 }
868 }
869 return modified;
870}
871
872bool InstrumentPass::InstProcessCallTreeFromRoots(InstProcessFunction& pfn,
873 std::queue<uint32_t>* roots,
874 uint32_t stage_idx) {
875 bool modified = false;
876 std::unordered_set<uint32_t> done;
Ben Claytonb73b7602019-07-29 13:56:13 +0100877 // Don't process input and output functions
878 for (auto& ifn : param2input_func_id_) done.insert(ifn.second);
879 if (output_func_id_ != 0) done.insert(output_func_id_);
Chris Forbescc5697f2019-01-30 11:54:08 -0800880 // Process all functions from roots
881 while (!roots->empty()) {
882 const uint32_t fi = roots->front();
883 roots->pop();
884 if (done.insert(fi).second) {
885 Function* fn = id2function_.at(fi);
886 // Add calls first so we don't add new output function
887 context()->AddCalls(fn, roots);
888 modified = InstrumentFunction(fn, stage_idx, pfn) || modified;
889 }
890 }
891 return modified;
892}
893
894bool InstrumentPass::InstProcessEntryPointCallTree(InstProcessFunction& pfn) {
895 // Make sure all entry points have the same execution model. Do not
896 // instrument if they do not.
897 // TODO(greg-lunarg): Handle mixed stages. Technically, a shader module
898 // can contain entry points with different execution models, although
899 // such modules will likely be rare as GLSL and HLSL are geared toward
900 // one model per module. In such cases we will need
901 // to clone any functions which are in the call trees of entrypoints
902 // with differing execution models.
903 uint32_t ecnt = 0;
904 uint32_t stage = SpvExecutionModelMax;
905 for (auto& e : get_module()->entry_points()) {
906 if (ecnt == 0)
907 stage = e.GetSingleWordInOperand(kEntryPointExecutionModelInIdx);
908 else if (e.GetSingleWordInOperand(kEntryPointExecutionModelInIdx) != stage)
909 return false;
910 ++ecnt;
911 }
912 // Only supporting vertex, fragment and compute shaders at the moment.
913 // TODO(greg-lunarg): Handle all stages.
914 if (stage != SpvExecutionModelVertex && stage != SpvExecutionModelFragment &&
915 stage != SpvExecutionModelGeometry &&
916 stage != SpvExecutionModelGLCompute &&
917 stage != SpvExecutionModelTessellationControl &&
Ben Claytonb73b7602019-07-29 13:56:13 +0100918 stage != SpvExecutionModelTessellationEvaluation &&
919 stage != SpvExecutionModelRayGenerationNV &&
920 stage != SpvExecutionModelIntersectionNV &&
921 stage != SpvExecutionModelAnyHitNV &&
922 stage != SpvExecutionModelClosestHitNV &&
923 stage != SpvExecutionModelMissNV && stage != SpvExecutionModelCallableNV)
Chris Forbescc5697f2019-01-30 11:54:08 -0800924 return false;
925 // Add together the roots of all entry points
926 std::queue<uint32_t> roots;
927 for (auto& e : get_module()->entry_points()) {
928 roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
929 }
930 bool modified = InstProcessCallTreeFromRoots(pfn, &roots, stage);
931 return modified;
932}
933
934void InstrumentPass::InitializeInstrument() {
935 output_buffer_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100936 output_buffer_ptr_id_ = 0;
937 input_buffer_ptr_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800938 output_func_id_ = 0;
939 output_func_param_cnt_ = 0;
Ben Claytonb73b7602019-07-29 13:56:13 +0100940 input_buffer_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800941 v4float_id_ = 0;
942 uint_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100943 uint64_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800944 v4uint_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100945 v3uint_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800946 bool_id_ = 0;
947 void_id_ = 0;
Ben Claytonb73b7602019-07-29 13:56:13 +0100948 storage_buffer_ext_defined_ = false;
Ben Claytond0f684e2019-08-30 22:36:08 +0100949 uint32_rarr_ty_ = nullptr;
950 uint64_rarr_ty_ = nullptr;
Chris Forbescc5697f2019-01-30 11:54:08 -0800951
952 // clear collections
953 id2function_.clear();
954 id2block_.clear();
955
956 // Initialize function and block maps.
957 for (auto& fn : *get_module()) {
958 id2function_[fn.result_id()] = &fn;
959 for (auto& blk : fn) {
960 id2block_[blk.id()] = &blk;
961 }
962 }
963
Ben Claytonb73b7602019-07-29 13:56:13 +0100964 // Remember original instruction offsets
965 uint32_t module_offset = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800966 Module* module = get_module();
967 for (auto& i : context()->capabilities()) {
968 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100969 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800970 }
971 for (auto& i : module->extensions()) {
972 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100973 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800974 }
975 for (auto& i : module->ext_inst_imports()) {
976 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100977 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800978 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100979 ++module_offset; // memory_model
Chris Forbescc5697f2019-01-30 11:54:08 -0800980 for (auto& i : module->entry_points()) {
981 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100982 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800983 }
984 for (auto& i : module->execution_modes()) {
985 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100986 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800987 }
988 for (auto& i : module->debugs1()) {
989 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100990 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800991 }
992 for (auto& i : module->debugs2()) {
993 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100994 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800995 }
996 for (auto& i : module->debugs3()) {
997 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100998 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800999 }
1000 for (auto& i : module->annotations()) {
1001 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +01001002 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -08001003 }
1004 for (auto& i : module->types_values()) {
Ben Claytonb73b7602019-07-29 13:56:13 +01001005 module_offset += 1;
1006 module_offset += static_cast<uint32_t>(i.dbg_line_insts().size());
Chris Forbescc5697f2019-01-30 11:54:08 -08001007 }
Chris Forbescc5697f2019-01-30 11:54:08 -08001008
Ben Claytonb73b7602019-07-29 13:56:13 +01001009 auto curr_fn = get_module()->begin();
1010 for (; curr_fn != get_module()->end(); ++curr_fn) {
1011 // Count function instruction
1012 module_offset += 1;
1013 curr_fn->ForEachParam(
1014 [&module_offset](const Instruction*) { module_offset += 1; }, true);
1015 for (auto& blk : *curr_fn) {
Chris Forbescc5697f2019-01-30 11:54:08 -08001016 // Count label
Ben Claytonb73b7602019-07-29 13:56:13 +01001017 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001018 for (auto& inst : blk) {
Ben Claytonb73b7602019-07-29 13:56:13 +01001019 module_offset += static_cast<uint32_t>(inst.dbg_line_insts().size());
1020 uid2offset_[inst.unique_id()] = module_offset;
1021 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001022 }
1023 }
Ben Claytonb73b7602019-07-29 13:56:13 +01001024 // Count function end instruction
1025 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001026 }
1027}
1028
1029} // namespace opt
1030} // namespace spvtools