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 #include "eliminate_dead_functions_util.h"
16
17 namespace spvtools {
18 namespace opt {
19
20 namespace eliminatedeadfunctionsutil {
21
EliminateFunction(IRContext * context,Module::iterator * func_iter)22 Module::iterator EliminateFunction(IRContext* context,
23 Module::iterator* func_iter) {
24 bool first_func = *func_iter == context->module()->begin();
25 bool seen_func_end = false;
26 (*func_iter)
27 ->ForEachInst(
28 [context, first_func, func_iter, &seen_func_end](Instruction* inst) {
29 if (inst->opcode() == SpvOpFunctionEnd) {
30 seen_func_end = true;
31 }
32 // Move non-semantic instructions to the previous function or
33 // global values if this is the first function.
34 if (seen_func_end && inst->opcode() == SpvOpExtInst) {
35 assert(inst->IsNonSemanticInstruction());
36 std::unique_ptr<Instruction> clone(inst->Clone(context));
37 context->ForgetUses(inst);
38 context->AnalyzeDefUse(clone.get());
39 if (first_func) {
40 context->AddGlobalValue(std::move(clone));
41 } else {
42 auto prev_func_iter = *func_iter;
43 --prev_func_iter;
44 prev_func_iter->AddNonSemanticInstruction(std::move(clone));
45 }
46 inst->ToNop();
47 } else {
48 context->KillNonSemanticInfo(inst);
49 context->KillInst(inst);
50 }
51 },
52 true, true);
53 return func_iter->Erase();
54 }
55
56 } // namespace eliminatedeadfunctionsutil
57 } // namespace opt
58 } // namespace spvtools
59