loop_fusion_pass.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include "source/opt/loop_fusion_pass.h"
  15. #include "source/opt/loop_descriptor.h"
  16. #include "source/opt/loop_fusion.h"
  17. #include "source/opt/register_pressure.h"
  18. namespace spvtools {
  19. namespace opt {
  20. Pass::Status LoopFusionPass::Process() {
  21. Status status = Status::SuccessWithoutChange;
  22. Module* module = context()->module();
  23. // Process each function in the module
  24. for (Function& f : *module) {
  25. status = CombineStatus(status, ProcessFunction(&f));
  26. if (status == Status::Failure) return Status::Failure;
  27. }
  28. return status;
  29. }
  30. Pass::Status LoopFusionPass::ProcessFunction(Function* function) {
  31. LoopDescriptor& ld = *context()->GetLoopDescriptor(function);
  32. // If a loop doesn't have a preheader needs then it needs to be created. Make
  33. // sure to return Status::SuccessWithChange in that case.
  34. bool modified = false;
  35. auto status = ld.CreatePreHeaderBlocksIfMissing();
  36. if (status == LoopDescriptor::Status::Failure) return Status::Failure;
  37. modified = status == LoopDescriptor::Status::SuccessWithChange;
  38. // TODO(tremmelg): Could the only loop that |loop| could possibly be fused be
  39. // picked out so don't have to check every loop
  40. for (auto& loop_0 : ld) {
  41. for (auto& loop_1 : ld) {
  42. LoopFusion fusion(context(), &loop_0, &loop_1);
  43. if (fusion.AreCompatible() && fusion.IsLegal()) {
  44. RegisterLiveness liveness(context(), function);
  45. RegisterLiveness::RegionRegisterLiveness reg_pressure{};
  46. liveness.SimulateFusion(loop_0, loop_1, &reg_pressure);
  47. if (reg_pressure.used_registers_ <= max_registers_per_loop_) {
  48. fusion.Fuse();
  49. // Recurse, as the current iterators will have been invalidated.
  50. ProcessFunction(function);
  51. return Status::SuccessWithChange;
  52. }
  53. }
  54. }
  55. }
  56. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  57. }
  58. } // namespace opt
  59. } // namespace spvtools