set_spec_constant_default_value_pass.cpp 15 KB

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