markv_encoder.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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/comp/markv_encoder.h"
  15. #include "source/binary.h"
  16. #include "source/opcode.h"
  17. #include "spirv-tools/libspirv.hpp"
  18. namespace spvtools {
  19. namespace comp {
  20. namespace {
  21. const size_t kCommentNumWhitespaces = 2;
  22. } // namespace
  23. spv_result_t MarkvEncoder::EncodeNonIdWord(uint32_t word) {
  24. auto* codec = model_->GetNonIdWordHuffmanCodec(inst_.opcode, operand_index_);
  25. if (codec) {
  26. uint64_t bits = 0;
  27. size_t num_bits = 0;
  28. if (codec->Encode(word, &bits, &num_bits)) {
  29. // Encoding successful.
  30. writer_.WriteBits(bits, num_bits);
  31. return SPV_SUCCESS;
  32. } else {
  33. // Encoding failed, write kMarkvNoneOfTheAbove flag.
  34. if (!codec->Encode(MarkvModel::GetMarkvNoneOfTheAbove(), &bits,
  35. &num_bits))
  36. return Diag(SPV_ERROR_INTERNAL)
  37. << "Non-id word Huffman table for "
  38. << spvOpcodeString(SpvOp(inst_.opcode)) << " operand index "
  39. << operand_index_ << " is missing kMarkvNoneOfTheAbove";
  40. writer_.WriteBits(bits, num_bits);
  41. }
  42. }
  43. // Fallback encoding.
  44. const size_t chunk_length =
  45. model_->GetOperandVariableWidthChunkLength(operand_.type);
  46. if (chunk_length) {
  47. writer_.WriteVariableWidthU32(word, chunk_length);
  48. } else {
  49. writer_.WriteUnencoded(word);
  50. }
  51. return SPV_SUCCESS;
  52. }
  53. spv_result_t MarkvEncoder::EncodeOpcodeAndNumOperands(uint32_t opcode,
  54. uint32_t num_operands) {
  55. uint64_t bits = 0;
  56. size_t num_bits = 0;
  57. const uint32_t word = opcode | (num_operands << 16);
  58. // First try to use the Markov chain codec.
  59. auto* codec =
  60. model_->GetOpcodeAndNumOperandsMarkovHuffmanCodec(GetPrevOpcode());
  61. if (codec) {
  62. if (codec->Encode(word, &bits, &num_bits)) {
  63. // The word was successfully encoded into bits/num_bits.
  64. writer_.WriteBits(bits, num_bits);
  65. return SPV_SUCCESS;
  66. } else {
  67. // The word is not in the Huffman table. Write kMarkvNoneOfTheAbove
  68. // and use fallback encoding.
  69. if (!codec->Encode(MarkvModel::GetMarkvNoneOfTheAbove(), &bits,
  70. &num_bits))
  71. return Diag(SPV_ERROR_INTERNAL)
  72. << "opcode_and_num_operands Huffman table for "
  73. << spvOpcodeString(GetPrevOpcode())
  74. << "is missing kMarkvNoneOfTheAbove";
  75. writer_.WriteBits(bits, num_bits);
  76. }
  77. }
  78. // Fallback to base-rate codec.
  79. codec = model_->GetOpcodeAndNumOperandsMarkovHuffmanCodec(SpvOpNop);
  80. assert(codec);
  81. if (codec->Encode(word, &bits, &num_bits)) {
  82. // The word was successfully encoded into bits/num_bits.
  83. writer_.WriteBits(bits, num_bits);
  84. return SPV_SUCCESS;
  85. } else {
  86. // The word is not in the Huffman table. Write kMarkvNoneOfTheAbove
  87. // and return false.
  88. if (!codec->Encode(MarkvModel::GetMarkvNoneOfTheAbove(), &bits, &num_bits))
  89. return Diag(SPV_ERROR_INTERNAL)
  90. << "Global opcode_and_num_operands Huffman table is missing "
  91. << "kMarkvNoneOfTheAbove";
  92. writer_.WriteBits(bits, num_bits);
  93. return SPV_UNSUPPORTED;
  94. }
  95. }
  96. spv_result_t MarkvEncoder::EncodeMtfRankHuffman(uint32_t rank, uint64_t mtf,
  97. uint64_t fallback_method) {
  98. const auto* codec = GetMtfHuffmanCodec(mtf);
  99. if (!codec) {
  100. assert(fallback_method != kMtfNone);
  101. codec = GetMtfHuffmanCodec(fallback_method);
  102. }
  103. if (!codec) return Diag(SPV_ERROR_INTERNAL) << "No codec to encode MTF rank";
  104. uint64_t bits = 0;
  105. size_t num_bits = 0;
  106. if (rank < MarkvCodec::kMtfSmallestRankEncodedByValue) {
  107. // Encode using Huffman coding.
  108. if (!codec->Encode(rank, &bits, &num_bits))
  109. return Diag(SPV_ERROR_INTERNAL)
  110. << "Failed to encode MTF rank with Huffman";
  111. writer_.WriteBits(bits, num_bits);
  112. } else {
  113. // Encode by value.
  114. if (!codec->Encode(MarkvCodec::kMtfRankEncodedByValueSignal, &bits,
  115. &num_bits))
  116. return Diag(SPV_ERROR_INTERNAL)
  117. << "Failed to encode kMtfRankEncodedByValueSignal";
  118. writer_.WriteBits(bits, num_bits);
  119. writer_.WriteVariableWidthU32(
  120. rank - MarkvCodec::kMtfSmallestRankEncodedByValue,
  121. model_->mtf_rank_chunk_length());
  122. }
  123. return SPV_SUCCESS;
  124. }
  125. spv_result_t MarkvEncoder::EncodeIdWithDescriptor(uint32_t id) {
  126. // Get the descriptor for id.
  127. const uint32_t long_descriptor = long_id_descriptors_.GetDescriptor(id);
  128. auto* codec =
  129. model_->GetIdDescriptorHuffmanCodec(inst_.opcode, operand_index_);
  130. uint64_t bits = 0;
  131. size_t num_bits = 0;
  132. uint64_t mtf = kMtfNone;
  133. if (long_descriptor && codec &&
  134. codec->Encode(long_descriptor, &bits, &num_bits)) {
  135. // If the descriptor exists and is in the table, write the descriptor and
  136. // proceed to encoding the rank.
  137. writer_.WriteBits(bits, num_bits);
  138. mtf = GetMtfLongIdDescriptor(long_descriptor);
  139. } else {
  140. if (codec) {
  141. // The descriptor doesn't exist or we have no coding for it. Write
  142. // kMarkvNoneOfTheAbove and go to fallback method.
  143. if (!codec->Encode(MarkvModel::GetMarkvNoneOfTheAbove(), &bits,
  144. &num_bits))
  145. return Diag(SPV_ERROR_INTERNAL)
  146. << "Descriptor Huffman table for "
  147. << spvOpcodeString(SpvOp(inst_.opcode)) << " operand index "
  148. << operand_index_ << " is missing kMarkvNoneOfTheAbove";
  149. writer_.WriteBits(bits, num_bits);
  150. }
  151. if (model_->id_fallback_strategy() !=
  152. MarkvModel::IdFallbackStrategy::kShortDescriptor) {
  153. return SPV_UNSUPPORTED;
  154. }
  155. const uint32_t short_descriptor = short_id_descriptors_.GetDescriptor(id);
  156. writer_.WriteBits(short_descriptor, MarkvCodec::kShortDescriptorNumBits);
  157. if (short_descriptor == 0) {
  158. // Forward declared id.
  159. return SPV_UNSUPPORTED;
  160. }
  161. mtf = GetMtfShortIdDescriptor(short_descriptor);
  162. }
  163. // Descriptor has been encoded. Now encode the rank of the id in the
  164. // associated mtf sequence.
  165. return EncodeExistingId(mtf, id);
  166. }
  167. spv_result_t MarkvEncoder::EncodeExistingId(uint64_t mtf, uint32_t id) {
  168. assert(multi_mtf_.GetSize(mtf) > 0);
  169. if (multi_mtf_.GetSize(mtf) == 1) {
  170. // If the sequence has only one element no need to write rank, the decoder
  171. // would make the same decision.
  172. return SPV_SUCCESS;
  173. }
  174. uint32_t rank = 0;
  175. if (!multi_mtf_.RankFromValue(mtf, id, &rank))
  176. return Diag(SPV_ERROR_INTERNAL) << "Id is not in the MTF sequence";
  177. return EncodeMtfRankHuffman(rank, mtf, kMtfGenericNonZeroRank);
  178. }
  179. spv_result_t MarkvEncoder::EncodeRefId(uint32_t id) {
  180. {
  181. // Try to encode using id descriptor mtfs.
  182. const spv_result_t result = EncodeIdWithDescriptor(id);
  183. if (result != SPV_UNSUPPORTED) return result;
  184. // If can't be done continue with other methods.
  185. }
  186. const bool can_forward_declare = spvOperandCanBeForwardDeclaredFunction(
  187. SpvOp(inst_.opcode))(operand_index_);
  188. uint32_t rank = 0;
  189. if (model_->id_fallback_strategy() ==
  190. MarkvModel::IdFallbackStrategy::kRuleBased) {
  191. // Encode using rule-based mtf.
  192. uint64_t mtf = GetRuleBasedMtf();
  193. if (mtf != kMtfNone && !can_forward_declare) {
  194. assert(multi_mtf_.HasValue(kMtfAll, id));
  195. return EncodeExistingId(mtf, id);
  196. }
  197. if (mtf == kMtfNone) mtf = kMtfAll;
  198. if (!multi_mtf_.RankFromValue(mtf, id, &rank)) {
  199. // This is the first occurrence of a forward declared id.
  200. multi_mtf_.Insert(kMtfAll, id);
  201. multi_mtf_.Insert(kMtfForwardDeclared, id);
  202. if (mtf != kMtfAll) multi_mtf_.Insert(mtf, id);
  203. rank = 0;
  204. }
  205. return EncodeMtfRankHuffman(rank, mtf, kMtfAll);
  206. } else {
  207. assert(can_forward_declare);
  208. if (!multi_mtf_.RankFromValue(kMtfForwardDeclared, id, &rank)) {
  209. // This is the first occurrence of a forward declared id.
  210. multi_mtf_.Insert(kMtfForwardDeclared, id);
  211. rank = 0;
  212. }
  213. writer_.WriteVariableWidthU32(rank, model_->mtf_rank_chunk_length());
  214. return SPV_SUCCESS;
  215. }
  216. }
  217. spv_result_t MarkvEncoder::EncodeTypeId() {
  218. if (inst_.opcode == SpvOpFunctionParameter) {
  219. assert(!remaining_function_parameter_types_.empty());
  220. assert(inst_.type_id == remaining_function_parameter_types_.front());
  221. remaining_function_parameter_types_.pop_front();
  222. return SPV_SUCCESS;
  223. }
  224. {
  225. // Try to encode using id descriptor mtfs.
  226. const spv_result_t result = EncodeIdWithDescriptor(inst_.type_id);
  227. if (result != SPV_UNSUPPORTED) return result;
  228. // If can't be done continue with other methods.
  229. }
  230. assert(model_->id_fallback_strategy() ==
  231. MarkvModel::IdFallbackStrategy::kRuleBased);
  232. uint64_t mtf = GetRuleBasedMtf();
  233. assert(!spvOperandCanBeForwardDeclaredFunction(SpvOp(inst_.opcode))(
  234. operand_index_));
  235. if (mtf == kMtfNone) {
  236. mtf = kMtfTypeNonFunction;
  237. // Function types should have been handled by GetRuleBasedMtf.
  238. assert(inst_.opcode != SpvOpFunction);
  239. }
  240. return EncodeExistingId(mtf, inst_.type_id);
  241. }
  242. spv_result_t MarkvEncoder::EncodeResultId() {
  243. uint32_t rank = 0;
  244. const uint64_t num_still_forward_declared =
  245. multi_mtf_.GetSize(kMtfForwardDeclared);
  246. if (num_still_forward_declared) {
  247. // We write the rank only if kMtfForwardDeclared is not empty. If it is
  248. // empty the decoder knows that there are no forward declared ids to expect.
  249. if (multi_mtf_.RankFromValue(kMtfForwardDeclared, inst_.result_id, &rank)) {
  250. // This is a definition of a forward declared id. We can remove the id
  251. // from kMtfForwardDeclared.
  252. if (!multi_mtf_.Remove(kMtfForwardDeclared, inst_.result_id))
  253. return Diag(SPV_ERROR_INTERNAL)
  254. << "Failed to remove id from kMtfForwardDeclared";
  255. writer_.WriteBits(1, 1);
  256. writer_.WriteVariableWidthU32(rank, model_->mtf_rank_chunk_length());
  257. } else {
  258. rank = 0;
  259. writer_.WriteBits(0, 1);
  260. }
  261. }
  262. if (model_->id_fallback_strategy() ==
  263. MarkvModel::IdFallbackStrategy::kRuleBased) {
  264. if (!rank) {
  265. multi_mtf_.Insert(kMtfAll, inst_.result_id);
  266. }
  267. }
  268. return SPV_SUCCESS;
  269. }
  270. spv_result_t MarkvEncoder::EncodeLiteralNumber(
  271. const spv_parsed_operand_t& operand) {
  272. if (operand.number_bit_width <= 32) {
  273. const uint32_t word = inst_.words[operand.offset];
  274. return EncodeNonIdWord(word);
  275. } else {
  276. assert(operand.number_bit_width <= 64);
  277. const uint64_t word = uint64_t(inst_.words[operand.offset]) |
  278. (uint64_t(inst_.words[operand.offset + 1]) << 32);
  279. if (operand.number_kind == SPV_NUMBER_UNSIGNED_INT) {
  280. writer_.WriteVariableWidthU64(word, model_->u64_chunk_length());
  281. } else if (operand.number_kind == SPV_NUMBER_SIGNED_INT) {
  282. int64_t val = 0;
  283. std::memcpy(&val, &word, 8);
  284. writer_.WriteVariableWidthS64(val, model_->s64_chunk_length(),
  285. model_->s64_block_exponent());
  286. } else if (operand.number_kind == SPV_NUMBER_FLOATING) {
  287. writer_.WriteUnencoded(word);
  288. } else {
  289. return Diag(SPV_ERROR_INTERNAL) << "Unsupported bit length";
  290. }
  291. }
  292. return SPV_SUCCESS;
  293. }
  294. void MarkvEncoder::AddByteBreak(size_t byte_break_if_less_than) {
  295. const size_t num_bits_to_next_byte =
  296. GetNumBitsToNextByte(writer_.GetNumBits());
  297. if (num_bits_to_next_byte == 0 ||
  298. num_bits_to_next_byte > byte_break_if_less_than)
  299. return;
  300. if (logger_) {
  301. logger_->AppendWhitespaces(kCommentNumWhitespaces);
  302. logger_->AppendText("<byte break>");
  303. }
  304. writer_.WriteBits(0, num_bits_to_next_byte);
  305. }
  306. spv_result_t MarkvEncoder::EncodeInstruction(
  307. const spv_parsed_instruction_t& inst) {
  308. SpvOp opcode = SpvOp(inst.opcode);
  309. inst_ = inst;
  310. LogDisassemblyInstruction();
  311. const spv_result_t opcode_encodig_result =
  312. EncodeOpcodeAndNumOperands(opcode, inst.num_operands);
  313. if (opcode_encodig_result < 0) return opcode_encodig_result;
  314. if (opcode_encodig_result != SPV_SUCCESS) {
  315. // Fallback encoding for opcode and num_operands.
  316. writer_.WriteVariableWidthU32(opcode, model_->opcode_chunk_length());
  317. if (!OpcodeHasFixedNumberOfOperands(opcode)) {
  318. // If the opcode has a variable number of operands, encode the number of
  319. // operands with the instruction.
  320. if (logger_) logger_->AppendWhitespaces(kCommentNumWhitespaces);
  321. writer_.WriteVariableWidthU16(inst.num_operands,
  322. model_->num_operands_chunk_length());
  323. }
  324. }
  325. // Write operands.
  326. const uint32_t num_operands = inst_.num_operands;
  327. for (operand_index_ = 0; operand_index_ < num_operands; ++operand_index_) {
  328. operand_ = inst_.operands[operand_index_];
  329. if (logger_) {
  330. logger_->AppendWhitespaces(kCommentNumWhitespaces);
  331. logger_->AppendText("<");
  332. logger_->AppendText(spvOperandTypeStr(operand_.type));
  333. logger_->AppendText(">");
  334. }
  335. switch (operand_.type) {
  336. case SPV_OPERAND_TYPE_RESULT_ID:
  337. case SPV_OPERAND_TYPE_TYPE_ID:
  338. case SPV_OPERAND_TYPE_ID:
  339. case SPV_OPERAND_TYPE_OPTIONAL_ID:
  340. case SPV_OPERAND_TYPE_SCOPE_ID:
  341. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID: {
  342. const uint32_t id = inst_.words[operand_.offset];
  343. if (operand_.type == SPV_OPERAND_TYPE_TYPE_ID) {
  344. const spv_result_t result = EncodeTypeId();
  345. if (result != SPV_SUCCESS) return result;
  346. } else if (operand_.type == SPV_OPERAND_TYPE_RESULT_ID) {
  347. const spv_result_t result = EncodeResultId();
  348. if (result != SPV_SUCCESS) return result;
  349. } else {
  350. const spv_result_t result = EncodeRefId(id);
  351. if (result != SPV_SUCCESS) return result;
  352. }
  353. PromoteIfNeeded(id);
  354. break;
  355. }
  356. case SPV_OPERAND_TYPE_LITERAL_INTEGER: {
  357. const spv_result_t result =
  358. EncodeNonIdWord(inst_.words[operand_.offset]);
  359. if (result != SPV_SUCCESS) return result;
  360. break;
  361. }
  362. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
  363. const spv_result_t result = EncodeLiteralNumber(operand_);
  364. if (result != SPV_SUCCESS) return result;
  365. break;
  366. }
  367. case SPV_OPERAND_TYPE_LITERAL_STRING: {
  368. const char* src =
  369. reinterpret_cast<const char*>(&inst_.words[operand_.offset]);
  370. auto* codec = model_->GetLiteralStringHuffmanCodec(opcode);
  371. if (codec) {
  372. uint64_t bits = 0;
  373. size_t num_bits = 0;
  374. const std::string str = src;
  375. if (codec->Encode(str, &bits, &num_bits)) {
  376. writer_.WriteBits(bits, num_bits);
  377. break;
  378. } else {
  379. bool result =
  380. codec->Encode("kMarkvNoneOfTheAbove", &bits, &num_bits);
  381. (void)result;
  382. assert(result);
  383. writer_.WriteBits(bits, num_bits);
  384. }
  385. }
  386. const size_t length = spv_strnlen_s(src, operand_.num_words * 4);
  387. if (length == operand_.num_words * 4)
  388. return Diag(SPV_ERROR_INVALID_BINARY)
  389. << "Failed to find terminal character of literal string";
  390. for (size_t i = 0; i < length + 1; ++i) writer_.WriteUnencoded(src[i]);
  391. break;
  392. }
  393. default: {
  394. for (int i = 0; i < operand_.num_words; ++i) {
  395. const uint32_t word = inst_.words[operand_.offset + i];
  396. const spv_result_t result = EncodeNonIdWord(word);
  397. if (result != SPV_SUCCESS) return result;
  398. }
  399. break;
  400. }
  401. }
  402. }
  403. AddByteBreak(MarkvCodec::kByteBreakAfterInstIfLessThanUntilNextByte);
  404. if (logger_) {
  405. logger_->NewLine();
  406. logger_->NewLine();
  407. if (!logger_->DebugInstruction(inst_)) return SPV_REQUESTED_TERMINATION;
  408. }
  409. ProcessCurInstruction();
  410. return SPV_SUCCESS;
  411. }
  412. } // namespace comp
  413. } // namespace spvtools