1 // Copyright (c) 2018 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 #include "source/opt/replace_invalid_opc.h"
16
17 #include <bitset>
18 #include <vector>
19
20 namespace spvtools {
21 namespace opt {
22
Process()23 Pass::Status ReplaceInvalidOpcodePass::Process() {
24 bool modified = false;
25
26 if (context()->get_feature_mgr()->HasCapability(SpvCapabilityLinkage)) {
27 return Status::SuccessWithoutChange;
28 }
29
30 SpvExecutionModel execution_model = GetExecutionModel();
31 if (execution_model == SpvExecutionModelKernel) {
32 // We do not handle kernels.
33 return Status::SuccessWithoutChange;
34 }
35 if (execution_model == SpvExecutionModelMax) {
36 // Mixed execution models for the entry points. This case is not currently
37 // handled.
38 return Status::SuccessWithoutChange;
39 }
40
41 for (Function& func : *get_module()) {
42 modified |= RewriteFunction(&func, execution_model);
43 }
44 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
45 }
46
GetExecutionModel()47 SpvExecutionModel ReplaceInvalidOpcodePass::GetExecutionModel() {
48 SpvExecutionModel result = SpvExecutionModelMax;
49 bool first = true;
50 for (Instruction& entry_point : get_module()->entry_points()) {
51 if (first) {
52 result =
53 static_cast<SpvExecutionModel>(entry_point.GetSingleWordInOperand(0));
54 first = false;
55 } else {
56 SpvExecutionModel current_model =
57 static_cast<SpvExecutionModel>(entry_point.GetSingleWordInOperand(0));
58 if (current_model != result) {
59 result = SpvExecutionModelMax;
60 break;
61 }
62 }
63 }
64 return result;
65 }
66
RewriteFunction(Function * function,SpvExecutionModel model)67 bool ReplaceInvalidOpcodePass::RewriteFunction(Function* function,
68 SpvExecutionModel model) {
69 bool modified = false;
70 Instruction* last_line_dbg_inst = nullptr;
71 function->ForEachInst(
72 [model, &modified, &last_line_dbg_inst, this](Instruction* inst) {
73 // Track the debug information so we can have a meaningful message.
74 if (inst->opcode() == SpvOpLabel || inst->IsNoLine()) {
75 last_line_dbg_inst = nullptr;
76 return;
77 } else if (inst->IsLine()) {
78 last_line_dbg_inst = inst;
79 return;
80 }
81
82 bool replace = false;
83 if (model != SpvExecutionModelFragment &&
84 IsFragmentShaderOnlyInstruction(inst)) {
85 replace = true;
86 }
87
88 if (model != SpvExecutionModelTessellationControl &&
89 model != SpvExecutionModelGLCompute) {
90 if (inst->opcode() == SpvOpControlBarrier) {
91 assert(model != SpvExecutionModelKernel &&
92 "Expecting to be working on a shader module.");
93 replace = true;
94 }
95 }
96
97 if (replace) {
98 modified = true;
99 if (last_line_dbg_inst == nullptr) {
100 ReplaceInstruction(inst, nullptr, 0, 0);
101 } else {
102 // Get the name of the source file.
103 uint32_t file_name_id = 0;
104 if (last_line_dbg_inst->opcode() == SpvOpLine) {
105 file_name_id = last_line_dbg_inst->GetSingleWordInOperand(0);
106 } else { // Shader100::DebugLine
107 uint32_t debug_source_id =
108 last_line_dbg_inst->GetSingleWordInOperand(2);
109 Instruction* debug_source_inst =
110 context()->get_def_use_mgr()->GetDef(debug_source_id);
111 file_name_id = debug_source_inst->GetSingleWordInOperand(2);
112 }
113 Instruction* file_name =
114 context()->get_def_use_mgr()->GetDef(file_name_id);
115 const std::string source = file_name->GetInOperand(0).AsString();
116
117 // Get the line number and column number.
118 uint32_t line_number =
119 last_line_dbg_inst->GetSingleWordInOperand(1);
120 uint32_t col_number = last_line_dbg_inst->GetSingleWordInOperand(2);
121
122 // Replace the instruction.
123 ReplaceInstruction(inst, source.c_str(), line_number, col_number);
124 }
125 }
126 },
127 /* run_on_debug_line_insts = */ true);
128 return modified;
129 }
130
IsFragmentShaderOnlyInstruction(Instruction * inst)131 bool ReplaceInvalidOpcodePass::IsFragmentShaderOnlyInstruction(
132 Instruction* inst) {
133 switch (inst->opcode()) {
134 case SpvOpDPdx:
135 case SpvOpDPdy:
136 case SpvOpFwidth:
137 case SpvOpDPdxFine:
138 case SpvOpDPdyFine:
139 case SpvOpFwidthFine:
140 case SpvOpDPdxCoarse:
141 case SpvOpDPdyCoarse:
142 case SpvOpFwidthCoarse:
143 case SpvOpImageSampleImplicitLod:
144 case SpvOpImageSampleDrefImplicitLod:
145 case SpvOpImageSampleProjImplicitLod:
146 case SpvOpImageSampleProjDrefImplicitLod:
147 case SpvOpImageSparseSampleImplicitLod:
148 case SpvOpImageSparseSampleDrefImplicitLod:
149 case SpvOpImageQueryLod:
150 // TODO: Teach |ReplaceInstruction| to handle block terminators. Then
151 // uncomment the OpKill case.
152 // case SpvOpKill:
153 // case SpvOpTerminateInstruction:
154 return true;
155 default:
156 return false;
157 }
158 }
159
ReplaceInstruction(Instruction * inst,const char * source,uint32_t line_number,uint32_t column_number)160 void ReplaceInvalidOpcodePass::ReplaceInstruction(Instruction* inst,
161 const char* source,
162 uint32_t line_number,
163 uint32_t column_number) {
164 if (inst->result_id() != 0) {
165 uint32_t const_id = GetSpecialConstant(inst->type_id());
166 context()->KillNamesAndDecorates(inst);
167 context()->ReplaceAllUsesWith(inst->result_id(), const_id);
168 }
169 assert(!inst->IsBlockTerminator() &&
170 "We cannot simply delete a block terminator. It must be replaced "
171 "with something.");
172 if (consumer()) {
173 std::string message = BuildWarningMessage(inst->opcode());
174 consumer()(SPV_MSG_WARNING, source, {line_number, column_number, 0},
175 message.c_str());
176 }
177 context()->KillInst(inst);
178 }
179
GetSpecialConstant(uint32_t type_id)180 uint32_t ReplaceInvalidOpcodePass::GetSpecialConstant(uint32_t type_id) {
181 const analysis::Constant* special_const = nullptr;
182 analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
183 analysis::TypeManager* type_mgr = context()->get_type_mgr();
184
185 Instruction* type = context()->get_def_use_mgr()->GetDef(type_id);
186 if (type->opcode() == SpvOpTypeVector) {
187 uint32_t component_const =
188 GetSpecialConstant(type->GetSingleWordInOperand(0));
189 std::vector<uint32_t> ids;
190 for (uint32_t i = 0; i < type->GetSingleWordInOperand(1); ++i) {
191 ids.push_back(component_const);
192 }
193 special_const = const_mgr->GetConstant(type_mgr->GetType(type_id), ids);
194 } else {
195 assert(type->opcode() == SpvOpTypeInt || type->opcode() == SpvOpTypeFloat);
196 std::vector<uint32_t> literal_words;
197 for (uint32_t i = 0; i < type->GetSingleWordInOperand(0); i += 32) {
198 literal_words.push_back(0xDEADBEEF);
199 }
200 special_const =
201 const_mgr->GetConstant(type_mgr->GetType(type_id), literal_words);
202 }
203 assert(special_const != nullptr);
204 return const_mgr->GetDefiningInstruction(special_const)->result_id();
205 }
206
BuildWarningMessage(SpvOp opcode)207 std::string ReplaceInvalidOpcodePass::BuildWarningMessage(SpvOp opcode) {
208 spv_opcode_desc opcode_info;
209 context()->grammar().lookupOpcode(opcode, &opcode_info);
210 std::string message = "Removing ";
211 message += opcode_info->name;
212 message += " instruction because of incompatible execution model.";
213 return message;
214 }
215
216 } // namespace opt
217 } // namespace spvtools
218