reducer.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 <cassert>
  15. #include <sstream>
  16. #include "source/reduce/merge_blocks_reduction_opportunity_finder.h"
  17. #include "source/reduce/operand_to_const_reduction_opportunity_finder.h"
  18. #include "source/reduce/operand_to_dominating_id_reduction_opportunity_finder.h"
  19. #include "source/reduce/operand_to_undef_reduction_opportunity_finder.h"
  20. #include "source/reduce/remove_function_reduction_opportunity_finder.h"
  21. #include "source/reduce/remove_opname_instruction_reduction_opportunity_finder.h"
  22. #include "source/reduce/remove_unreferenced_instruction_reduction_opportunity_finder.h"
  23. #include "source/reduce/structured_loop_to_selection_reduction_opportunity_finder.h"
  24. #include "source/spirv_reducer_options.h"
  25. #include "reducer.h"
  26. namespace spvtools {
  27. namespace reduce {
  28. struct Reducer::Impl {
  29. explicit Impl(spv_target_env env) : target_env(env) {}
  30. bool ReachedStepLimit(uint32_t current_step,
  31. spv_const_reducer_options options);
  32. const spv_target_env target_env; // Target environment.
  33. MessageConsumer consumer; // Message consumer.
  34. InterestingnessFunction interestingness_function;
  35. std::vector<std::unique_ptr<ReductionPass>> passes;
  36. };
  37. Reducer::Reducer(spv_target_env env) : impl_(MakeUnique<Impl>(env)) {}
  38. Reducer::~Reducer() = default;
  39. void Reducer::SetMessageConsumer(MessageConsumer c) {
  40. for (auto& pass : impl_->passes) {
  41. pass->SetMessageConsumer(c);
  42. }
  43. impl_->consumer = std::move(c);
  44. }
  45. void Reducer::SetInterestingnessFunction(
  46. Reducer::InterestingnessFunction interestingness_function) {
  47. impl_->interestingness_function = std::move(interestingness_function);
  48. }
  49. Reducer::ReductionResultStatus Reducer::Run(
  50. std::vector<uint32_t>&& binary_in, std::vector<uint32_t>* binary_out,
  51. spv_const_reducer_options options,
  52. spv_validator_options validator_options) const {
  53. std::vector<uint32_t> current_binary(std::move(binary_in));
  54. spvtools::SpirvTools tools(impl_->target_env);
  55. assert(tools.IsValid() && "Failed to create SPIRV-Tools interface");
  56. // Keeps track of how many reduction attempts have been tried. Reduction
  57. // bails out if this reaches a given limit.
  58. uint32_t reductions_applied = 0;
  59. // Initial state should be valid.
  60. if (!tools.Validate(&current_binary[0], current_binary.size(),
  61. validator_options)) {
  62. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  63. "Initial binary is invalid; stopping.");
  64. return Reducer::ReductionResultStatus::kInitialStateInvalid;
  65. }
  66. // Initial state should be interesting.
  67. if (!impl_->interestingness_function(current_binary, reductions_applied)) {
  68. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  69. "Initial state was not interesting; stopping.");
  70. return Reducer::ReductionResultStatus::kInitialStateNotInteresting;
  71. }
  72. // Determines whether, on completing one round of reduction passes, it is
  73. // worthwhile trying a further round.
  74. bool another_round_worthwhile = true;
  75. // Apply round after round of reduction passes until we hit the reduction
  76. // step limit, or deem that another round is not going to be worthwhile.
  77. while (!impl_->ReachedStepLimit(reductions_applied, options) &&
  78. another_round_worthwhile) {
  79. // At the start of a round of reduction passes, assume another round will
  80. // not be worthwhile unless we find evidence to the contrary.
  81. another_round_worthwhile = false;
  82. // Iterate through the available passes
  83. for (auto& pass : impl_->passes) {
  84. // If this pass hasn't reached its minimum granularity then it's
  85. // worth eventually doing another round of reductions, in order to
  86. // try this pass at a finer granularity.
  87. another_round_worthwhile |= !pass->ReachedMinimumGranularity();
  88. // Keep applying this pass at its current granularity until it stops
  89. // working or we hit the reduction step limit.
  90. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  91. ("Trying pass " + pass->GetName() + ".").c_str());
  92. do {
  93. auto maybe_result = pass->TryApplyReduction(current_binary);
  94. if (maybe_result.empty()) {
  95. // For this round, the pass has no more opportunities (chunks) to
  96. // apply, so move on to the next pass.
  97. impl_->consumer(
  98. SPV_MSG_INFO, nullptr, {},
  99. ("Pass " + pass->GetName() + " did not make a reduction step.")
  100. .c_str());
  101. break;
  102. }
  103. bool interesting = false;
  104. std::stringstream stringstream;
  105. reductions_applied++;
  106. stringstream << "Pass " << pass->GetName() << " made reduction step "
  107. << reductions_applied << ".";
  108. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  109. (stringstream.str().c_str()));
  110. if (!tools.Validate(&maybe_result[0], maybe_result.size(),
  111. validator_options)) {
  112. // The reduction step went wrong and an invalid binary was produced.
  113. // By design, this shouldn't happen; this is a safeguard to stop an
  114. // invalid binary from being regarded as interesting.
  115. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  116. "Reduction step produced an invalid binary.");
  117. if (options->fail_on_validation_error) {
  118. return Reducer::ReductionResultStatus::kStateInvalid;
  119. }
  120. } else if (impl_->interestingness_function(maybe_result,
  121. reductions_applied)) {
  122. // Success! The binary produced by this reduction step is
  123. // interesting, so make it the binary of interest henceforth, and
  124. // note that it's worth doing another round of reduction passes.
  125. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  126. "Reduction step succeeded.");
  127. current_binary = std::move(maybe_result);
  128. interesting = true;
  129. another_round_worthwhile = true;
  130. }
  131. // We must call this before the next call to TryApplyReduction.
  132. pass->NotifyInteresting(interesting);
  133. // Bail out if the reduction step limit has been reached.
  134. } while (!impl_->ReachedStepLimit(reductions_applied, options));
  135. }
  136. }
  137. *binary_out = std::move(current_binary);
  138. // Report whether reduction completed, or bailed out early due to reaching
  139. // the step limit.
  140. if (impl_->ReachedStepLimit(reductions_applied, options)) {
  141. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  142. "Reached reduction step limit; stopping.");
  143. return Reducer::ReductionResultStatus::kReachedStepLimit;
  144. }
  145. impl_->consumer(SPV_MSG_INFO, nullptr, {}, "No more to reduce; stopping.");
  146. return Reducer::ReductionResultStatus::kComplete;
  147. }
  148. void Reducer::AddDefaultReductionPasses() {
  149. AddReductionPass(spvtools::MakeUnique<
  150. RemoveOpNameInstructionReductionOpportunityFinder>());
  151. AddReductionPass(
  152. spvtools::MakeUnique<OperandToUndefReductionOpportunityFinder>());
  153. AddReductionPass(
  154. spvtools::MakeUnique<OperandToConstReductionOpportunityFinder>());
  155. AddReductionPass(
  156. spvtools::MakeUnique<OperandToDominatingIdReductionOpportunityFinder>());
  157. AddReductionPass(spvtools::MakeUnique<
  158. RemoveUnreferencedInstructionReductionOpportunityFinder>());
  159. AddReductionPass(spvtools::MakeUnique<
  160. StructuredLoopToSelectionReductionOpportunityFinder>());
  161. AddReductionPass(
  162. spvtools::MakeUnique<MergeBlocksReductionOpportunityFinder>());
  163. AddReductionPass(
  164. spvtools::MakeUnique<RemoveFunctionReductionOpportunityFinder>());
  165. }
  166. void Reducer::AddReductionPass(
  167. std::unique_ptr<ReductionOpportunityFinder>&& finder) {
  168. impl_->passes.push_back(spvtools::MakeUnique<ReductionPass>(
  169. impl_->target_env, std::move(finder)));
  170. }
  171. bool Reducer::Impl::ReachedStepLimit(uint32_t current_step,
  172. spv_const_reducer_options options) {
  173. return current_step >= options->step_limit;
  174. }
  175. } // namespace reduce
  176. } // namespace spvtools