MCPcopy Create free account
hub / github.com/KhronosGroup/SPIRV-Tools / Process

Method Process

source/opt/dead_variable_elimination.cpp:27–81  ·  view source on GitHub ↗

This optimization removes global variables that are not needed because they are definitely not accessed.

Source from the content-addressed store, hash-verified

25// This optimization removes global variables that are not needed because they
26// are definitely not accessed.
27Pass::Status DeadVariableElimination::Process() {
28 // The algorithm will compute the reference count for every global variable.
29 // Anything with a reference count of 0 will then be deleted. For variables
30 // that might have references that are not explicit in this context, we use
31 // the value kMustKeep as the reference count.
32 std::vector<uint32_t> ids_to_remove;
33
34 // Get the reference count for all of the global OpVariable instructions.
35 for (auto& inst : context()->types_values()) {
36 if (inst.opcode() != spv::Op::OpVariable) {
37 continue;
38 }
39
40 size_t count = 0;
41 uint32_t result_id = inst.result_id();
42
43 // Check the linkage. If it is exported, it could be reference somewhere
44 // else, so we must keep the variable around.
45 get_decoration_mgr()->ForEachDecoration(
46 result_id, uint32_t(spv::Decoration::LinkageAttributes),
47 [&count](const Instruction& linkage_instruction) {
48 uint32_t last_operand = linkage_instruction.NumOperands() - 1;
49 if (spv::LinkageType(linkage_instruction.GetSingleWordOperand(
50 last_operand)) == spv::LinkageType::Export) {
51 count = kMustKeep;
52 }
53 });
54
55 if (count != kMustKeep) {
56 // If we don't have to keep the instruction for other reasons, then look
57 // at the uses and count the number of real references.
58 count = 0;
59 get_def_use_mgr()->ForEachUser(result_id, [&count](Instruction* user) {
60 if (!IsAnnotationInst(user->opcode()) &&
61 user->opcode() != spv::Op::OpName) {
62 ++count;
63 }
64 });
65 }
66 reference_count_[result_id] = count;
67 if (count == 0) {
68 ids_to_remove.push_back(result_id);
69 }
70 }
71
72 // Remove all of the variables that have a reference count of 0.
73 bool modified = false;
74 if (!ids_to_remove.empty()) {
75 modified = true;
76 for (auto result_id : ids_to_remove) {
77 DeleteVariable(result_id);
78 }
79 }
80 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
81}
82
83void DeadVariableElimination::DeleteVariable(uint32_t result_id) {
84 Instruction* inst = get_def_use_mgr()->GetDef(result_id);

Callers

nothing calls this directly

Calls 10

IsAnnotationInstFunction · 0.85
ForEachDecorationMethod · 0.80
NumOperandsMethod · 0.80
GetSingleWordOperandMethod · 0.80
ForEachUserMethod · 0.80
types_valuesMethod · 0.45
opcodeMethod · 0.45
result_idMethod · 0.45
push_backMethod · 0.45
emptyMethod · 0.45

Tested by

no test coverage detected