decompose_initialized_variables_pass.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include "source/opt/decompose_initialized_variables_pass.h"
  15. #include "source/opt/ir_context.h"
  16. namespace spvtools {
  17. namespace opt {
  18. using inst_iterator = InstructionList::iterator;
  19. namespace {
  20. bool HasInitializer(Instruction* inst) {
  21. if (inst->opcode() != SpvOpVariable) return false;
  22. if (inst->NumOperands() < 4) return false;
  23. return true;
  24. }
  25. } // namespace
  26. Pass::Status DecomposeInitializedVariablesPass::Process() {
  27. auto* module = context()->module();
  28. bool changed = false;
  29. // TODO(zoddicus): Handle 'Output' variables
  30. // TODO(zoddicus): Handle 'Private' variables
  31. // Handle 'Function' variables
  32. for (auto func = module->begin(); func != module->end(); ++func) {
  33. auto block = func->entry().get();
  34. std::vector<Instruction*> new_stores;
  35. auto last_var = block->begin();
  36. for (auto iter = block->begin();
  37. iter != block->end() && iter->opcode() == SpvOpVariable; ++iter) {
  38. last_var = iter;
  39. Instruction* inst = &(*iter);
  40. if (!HasInitializer(inst)) continue;
  41. changed = true;
  42. auto var_id = inst->result_id();
  43. auto val_id = inst->GetOperand(3).words[0];
  44. Instruction* store_inst = new Instruction(
  45. context(), SpvOpStore, 0, 0,
  46. {{SPV_OPERAND_TYPE_ID, {var_id}}, {SPV_OPERAND_TYPE_ID, {val_id}}});
  47. new_stores.push_back(store_inst);
  48. iter->RemoveOperand(3);
  49. get_def_use_mgr()->UpdateDefUse(&*iter);
  50. }
  51. for (auto store = new_stores.begin(); store != new_stores.end(); ++store) {
  52. context()->AnalyzeDefUse(*store);
  53. context()->set_instr_block(*store, block);
  54. (*store)->InsertAfter(&*last_var);
  55. last_var = *store;
  56. }
  57. }
  58. return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  59. }
  60. } // namespace opt
  61. } // namespace spvtools