set_spec_constant_default_value_pass.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Copyright (c) 2016 Google Inc.
  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/set_spec_constant_default_value_pass.h"
  15. #include <algorithm>
  16. #include <cctype>
  17. #include <cstring>
  18. #include <tuple>
  19. #include <vector>
  20. #include "source/opt/def_use_manager.h"
  21. #include "source/opt/ir_context.h"
  22. #include "source/opt/type_manager.h"
  23. #include "source/opt/types.h"
  24. #include "source/util/make_unique.h"
  25. #include "source/util/parse_number.h"
  26. #include "spirv-tools/libspirv.h"
  27. namespace spvtools {
  28. namespace opt {
  29. namespace {
  30. using utils::EncodeNumberStatus;
  31. using utils::NumberType;
  32. using utils::ParseAndEncodeNumber;
  33. using utils::ParseNumber;
  34. // Given a numeric value in a null-terminated c string and the expected type of
  35. // the value, parses the string and encodes it in a vector of words. If the
  36. // value is a scalar integer or floating point value, encodes the value in
  37. // SPIR-V encoding format. If the value is 'false' or 'true', returns a vector
  38. // with single word with value 0 or 1 respectively. Returns the vector
  39. // containing the encoded value on success. Otherwise returns an empty vector.
  40. std::vector<uint32_t> ParseDefaultValueStr(const char* text,
  41. const analysis::Type* type) {
  42. std::vector<uint32_t> result;
  43. if (!strcmp(text, "true") && type->AsBool()) {
  44. result.push_back(1u);
  45. } else if (!strcmp(text, "false") && type->AsBool()) {
  46. result.push_back(0u);
  47. } else {
  48. NumberType number_type = {32, SPV_NUMBER_UNSIGNED_INT};
  49. if (const auto* IT = type->AsInteger()) {
  50. number_type.bitwidth = IT->width();
  51. number_type.kind =
  52. IT->IsSigned() ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
  53. } else if (const auto* FT = type->AsFloat()) {
  54. number_type.bitwidth = FT->width();
  55. number_type.kind = SPV_NUMBER_FLOATING;
  56. } else {
  57. // Does not handle types other then boolean, integer or float. Returns
  58. // empty vector.
  59. result.clear();
  60. return result;
  61. }
  62. EncodeNumberStatus rc = ParseAndEncodeNumber(
  63. text, number_type, [&result](uint32_t word) { result.push_back(word); },
  64. nullptr);
  65. // Clear the result vector on failure.
  66. if (rc != EncodeNumberStatus::kSuccess) {
  67. result.clear();
  68. }
  69. }
  70. return result;
  71. }
  72. // Given a bit pattern and a type, checks if the bit pattern is compatible
  73. // with the type. If so, returns the bit pattern, otherwise returns an empty
  74. // bit pattern. If the given bit pattern is empty, returns an empty bit
  75. // pattern. If the given type represents a SPIR-V Boolean type, the bit pattern
  76. // to be returned is determined with the following standard:
  77. // If any words in the input bit pattern are non zero, returns a bit pattern
  78. // with 0x1, which represents a 'true'.
  79. // If all words in the bit pattern are zero, returns a bit pattern with 0x0,
  80. // which represents a 'false'.
  81. std::vector<uint32_t> ParseDefaultValueBitPattern(
  82. const std::vector<uint32_t>& input_bit_pattern,
  83. const analysis::Type* type) {
  84. std::vector<uint32_t> result;
  85. if (type->AsBool()) {
  86. if (std::any_of(input_bit_pattern.begin(), input_bit_pattern.end(),
  87. [](uint32_t i) { return i != 0; })) {
  88. result.push_back(1u);
  89. } else {
  90. result.push_back(0u);
  91. }
  92. return result;
  93. } else if (const auto* IT = type->AsInteger()) {
  94. if (IT->width() == input_bit_pattern.size() * sizeof(uint32_t) * 8) {
  95. return std::vector<uint32_t>(input_bit_pattern);
  96. }
  97. } else if (const auto* FT = type->AsFloat()) {
  98. if (FT->width() == input_bit_pattern.size() * sizeof(uint32_t) * 8) {
  99. return std::vector<uint32_t>(input_bit_pattern);
  100. }
  101. }
  102. result.clear();
  103. return result;
  104. }
  105. // Returns true if the given instruction's result id could have a SpecId
  106. // decoration.
  107. bool CanHaveSpecIdDecoration(const Instruction& inst) {
  108. switch (inst.opcode()) {
  109. case SpvOp::SpvOpSpecConstant:
  110. case SpvOp::SpvOpSpecConstantFalse:
  111. case SpvOp::SpvOpSpecConstantTrue:
  112. return true;
  113. default:
  114. return false;
  115. }
  116. }
  117. // Given a decoration group defining instruction that is decorated with SpecId
  118. // decoration, finds the spec constant defining instruction which is the real
  119. // target of the SpecId decoration. Returns the spec constant defining
  120. // instruction if such an instruction is found, otherwise returns a nullptr.
  121. Instruction* GetSpecIdTargetFromDecorationGroup(
  122. const Instruction& decoration_group_defining_inst,
  123. analysis::DefUseManager* def_use_mgr) {
  124. // Find the OpGroupDecorate instruction which consumes the given decoration
  125. // group. Note that the given decoration group has SpecId decoration, which
  126. // is unique for different spec constants. So the decoration group cannot be
  127. // consumed by different OpGroupDecorate instructions. Therefore we only need
  128. // the first OpGroupDecoration instruction that uses the given decoration
  129. // group.
  130. Instruction* group_decorate_inst = nullptr;
  131. if (def_use_mgr->WhileEachUser(&decoration_group_defining_inst,
  132. [&group_decorate_inst](Instruction* user) {
  133. if (user->opcode() ==
  134. SpvOp::SpvOpGroupDecorate) {
  135. group_decorate_inst = user;
  136. return false;
  137. }
  138. return true;
  139. }))
  140. return nullptr;
  141. // Scan through the target ids of the OpGroupDecorate instruction. There
  142. // should be only one spec constant target consumes the SpecId decoration.
  143. // If multiple target ids are presented in the OpGroupDecorate instruction,
  144. // they must be the same one that defined by an eligible spec constant
  145. // instruction. If the OpGroupDecorate instruction has different target ids
  146. // or a target id is not defined by an eligible spec cosntant instruction,
  147. // returns a nullptr.
  148. Instruction* target_inst = nullptr;
  149. for (uint32_t i = 1; i < group_decorate_inst->NumInOperands(); i++) {
  150. // All the operands of a OpGroupDecorate instruction should be of type
  151. // SPV_OPERAND_TYPE_ID.
  152. uint32_t candidate_id = group_decorate_inst->GetSingleWordInOperand(i);
  153. Instruction* candidate_inst = def_use_mgr->GetDef(candidate_id);
  154. if (!candidate_inst) {
  155. continue;
  156. }
  157. if (!target_inst) {
  158. // If the spec constant target has not been found yet, check if the
  159. // candidate instruction is the target.
  160. if (CanHaveSpecIdDecoration(*candidate_inst)) {
  161. target_inst = candidate_inst;
  162. } else {
  163. // Spec id decoration should not be applied on other instructions.
  164. // TODO(qining): Emit an error message in the invalid case once the
  165. // error handling is done.
  166. return nullptr;
  167. }
  168. } else {
  169. // If the spec constant target has been found, check if the candidate
  170. // instruction is the same one as the target. The module is invalid if
  171. // the candidate instruction is different with the found target.
  172. // TODO(qining): Emit an error messaage in the invalid case once the
  173. // error handling is done.
  174. if (candidate_inst != target_inst) return nullptr;
  175. }
  176. }
  177. return target_inst;
  178. }
  179. } // namespace
  180. Pass::Status SetSpecConstantDefaultValuePass::Process() {
  181. // The operand index of decoration target in an OpDecorate instruction.
  182. const uint32_t kTargetIdOperandIndex = 0;
  183. // The operand index of the decoration literal in an OpDecorate instruction.
  184. const uint32_t kDecorationOperandIndex = 1;
  185. // The operand index of Spec id literal value in an OpDecorate SpecId
  186. // instruction.
  187. const uint32_t kSpecIdLiteralOperandIndex = 2;
  188. // The number of operands in an OpDecorate SpecId instruction.
  189. const uint32_t kOpDecorateSpecIdNumOperands = 3;
  190. // The in-operand index of the default value in a OpSpecConstant instruction.
  191. const uint32_t kOpSpecConstantLiteralInOperandIndex = 0;
  192. bool modified = false;
  193. // Scan through all the annotation instructions to find 'OpDecorate SpecId'
  194. // instructions. Then extract the decoration target of those instructions.
  195. // The decoration targets should be spec constant defining instructions with
  196. // opcode: OpSpecConstant{|True|False}. The spec id of those spec constants
  197. // will be used to look up their new default values in the mapping from
  198. // spec id to new default value strings. Once a new default value string
  199. // is found for a spec id, the string will be parsed according to the target
  200. // spec constant type. The parsed value will be used to replace the original
  201. // default value of the target spec constant.
  202. for (Instruction& inst : context()->annotations()) {
  203. // Only process 'OpDecorate SpecId' instructions
  204. if (inst.opcode() != SpvOp::SpvOpDecorate) continue;
  205. if (inst.NumOperands() != kOpDecorateSpecIdNumOperands) continue;
  206. if (inst.GetSingleWordInOperand(kDecorationOperandIndex) !=
  207. uint32_t(SpvDecoration::SpvDecorationSpecId)) {
  208. continue;
  209. }
  210. // 'inst' is an OpDecorate SpecId instruction.
  211. uint32_t spec_id = inst.GetSingleWordOperand(kSpecIdLiteralOperandIndex);
  212. uint32_t target_id = inst.GetSingleWordOperand(kTargetIdOperandIndex);
  213. // Find the spec constant defining instruction. Note that the
  214. // target_id might be a decoration group id.
  215. Instruction* spec_inst = nullptr;
  216. if (Instruction* target_inst = get_def_use_mgr()->GetDef(target_id)) {
  217. if (target_inst->opcode() == SpvOp::SpvOpDecorationGroup) {
  218. spec_inst =
  219. GetSpecIdTargetFromDecorationGroup(*target_inst, get_def_use_mgr());
  220. } else {
  221. spec_inst = target_inst;
  222. }
  223. } else {
  224. continue;
  225. }
  226. if (!spec_inst) continue;
  227. // Get the default value bit pattern for this spec id.
  228. std::vector<uint32_t> bit_pattern;
  229. if (spec_id_to_value_str_.size() != 0) {
  230. // Search for the new string-form default value for this spec id.
  231. auto iter = spec_id_to_value_str_.find(spec_id);
  232. if (iter == spec_id_to_value_str_.end()) {
  233. continue;
  234. }
  235. // Gets the string of the default value and parses it to bit pattern
  236. // with the type of the spec constant.
  237. const std::string& default_value_str = iter->second;
  238. bit_pattern = ParseDefaultValueStr(
  239. default_value_str.c_str(),
  240. context()->get_type_mgr()->GetType(spec_inst->type_id()));
  241. } else {
  242. // Search for the new bit-pattern-form default value for this spec id.
  243. auto iter = spec_id_to_value_bit_pattern_.find(spec_id);
  244. if (iter == spec_id_to_value_bit_pattern_.end()) {
  245. continue;
  246. }
  247. // Gets the bit-pattern of the default value from the map directly.
  248. bit_pattern = ParseDefaultValueBitPattern(
  249. iter->second,
  250. context()->get_type_mgr()->GetType(spec_inst->type_id()));
  251. }
  252. if (bit_pattern.empty()) continue;
  253. // Update the operand bit patterns of the spec constant defining
  254. // instruction.
  255. switch (spec_inst->opcode()) {
  256. case SpvOp::SpvOpSpecConstant:
  257. // If the new value is the same with the original value, no
  258. // need to do anything. Otherwise update the operand words.
  259. if (spec_inst->GetInOperand(kOpSpecConstantLiteralInOperandIndex)
  260. .words != bit_pattern) {
  261. spec_inst->SetInOperand(kOpSpecConstantLiteralInOperandIndex,
  262. std::move(bit_pattern));
  263. modified = true;
  264. }
  265. break;
  266. case SpvOp::SpvOpSpecConstantTrue:
  267. // If the new value is also 'true', no need to change anything.
  268. // Otherwise, set the opcode to OpSpecConstantFalse;
  269. if (!static_cast<bool>(bit_pattern.front())) {
  270. spec_inst->SetOpcode(SpvOp::SpvOpSpecConstantFalse);
  271. modified = true;
  272. }
  273. break;
  274. case SpvOp::SpvOpSpecConstantFalse:
  275. // If the new value is also 'false', no need to change anything.
  276. // Otherwise, set the opcode to OpSpecConstantTrue;
  277. if (static_cast<bool>(bit_pattern.front())) {
  278. spec_inst->SetOpcode(SpvOp::SpvOpSpecConstantTrue);
  279. modified = true;
  280. }
  281. break;
  282. default:
  283. break;
  284. }
  285. // No need to update the DefUse manager, as this pass does not change any
  286. // ids.
  287. }
  288. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  289. }
  290. // Returns true if the given char is ':', '\0' or considered as blank space
  291. // (i.e.: '\n', '\r', '\v', '\t', '\f' and ' ').
  292. bool IsSeparator(char ch) {
  293. return std::strchr(":\0", ch) || std::isspace(ch) != 0;
  294. }
  295. std::unique_ptr<SetSpecConstantDefaultValuePass::SpecIdToValueStrMap>
  296. SetSpecConstantDefaultValuePass::ParseDefaultValuesString(const char* str) {
  297. if (!str) return nullptr;
  298. auto spec_id_to_value = MakeUnique<SpecIdToValueStrMap>();
  299. // The parsing loop, break when points to the end.
  300. while (*str) {
  301. // Find the spec id.
  302. while (std::isspace(*str)) str++; // skip leading spaces.
  303. const char* entry_begin = str;
  304. while (!IsSeparator(*str)) str++;
  305. const char* entry_end = str;
  306. std::string spec_id_str(entry_begin, entry_end - entry_begin);
  307. uint32_t spec_id = 0;
  308. if (!ParseNumber(spec_id_str.c_str(), &spec_id)) {
  309. // The spec id is not a valid uint32 number.
  310. return nullptr;
  311. }
  312. auto iter = spec_id_to_value->find(spec_id);
  313. if (iter != spec_id_to_value->end()) {
  314. // Same spec id has been defined before
  315. return nullptr;
  316. }
  317. // Find the ':', spaces between the spec id and the ':' are not allowed.
  318. if (*str++ != ':') {
  319. // ':' not found
  320. return nullptr;
  321. }
  322. // Find the value string
  323. const char* val_begin = str;
  324. while (!IsSeparator(*str)) str++;
  325. const char* val_end = str;
  326. if (val_end == val_begin) {
  327. // Value string is empty.
  328. return nullptr;
  329. }
  330. // Update the mapping with spec id and value string.
  331. (*spec_id_to_value)[spec_id] = std::string(val_begin, val_end - val_begin);
  332. // Skip trailing spaces.
  333. while (std::isspace(*str)) str++;
  334. }
  335. return spec_id_to_value;
  336. }
  337. } // namespace opt
  338. } // namespace spvtools