fold.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. // Copyright (c) 2017 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/fold.h"
  15. #include <cassert>
  16. #include <cstdint>
  17. #include <vector>
  18. #include "source/opt/const_folding_rules.h"
  19. #include "source/opt/def_use_manager.h"
  20. #include "source/opt/folding_rules.h"
  21. #include "source/opt/ir_builder.h"
  22. #include "source/opt/ir_context.h"
  23. namespace spvtools {
  24. namespace opt {
  25. namespace {
  26. #ifndef INT32_MIN
  27. #define INT32_MIN (-2147483648)
  28. #endif
  29. #ifndef INT32_MAX
  30. #define INT32_MAX 2147483647
  31. #endif
  32. #ifndef UINT32_MAX
  33. #define UINT32_MAX 0xffffffff /* 4294967295U */
  34. #endif
  35. } // namespace
  36. uint32_t InstructionFolder::UnaryOperate(SpvOp opcode, uint32_t operand) const {
  37. switch (opcode) {
  38. // Arthimetics
  39. case SpvOp::SpvOpSNegate:
  40. return -static_cast<int32_t>(operand);
  41. case SpvOp::SpvOpNot:
  42. return ~operand;
  43. case SpvOp::SpvOpLogicalNot:
  44. return !static_cast<bool>(operand);
  45. default:
  46. assert(false &&
  47. "Unsupported unary operation for OpSpecConstantOp instruction");
  48. return 0u;
  49. }
  50. }
  51. uint32_t InstructionFolder::BinaryOperate(SpvOp opcode, uint32_t a,
  52. uint32_t b) const {
  53. switch (opcode) {
  54. // Arthimetics
  55. case SpvOp::SpvOpIAdd:
  56. return a + b;
  57. case SpvOp::SpvOpISub:
  58. return a - b;
  59. case SpvOp::SpvOpIMul:
  60. return a * b;
  61. case SpvOp::SpvOpUDiv:
  62. if (b != 0) {
  63. return a / b;
  64. } else {
  65. // Dividing by 0 is undefined, so we will just pick 0.
  66. return 0;
  67. }
  68. case SpvOp::SpvOpSDiv:
  69. if (b != 0u) {
  70. return (static_cast<int32_t>(a)) / (static_cast<int32_t>(b));
  71. } else {
  72. // Dividing by 0 is undefined, so we will just pick 0.
  73. return 0;
  74. }
  75. case SpvOp::SpvOpSRem: {
  76. // The sign of non-zero result comes from the first operand: a. This is
  77. // guaranteed by C++11 rules for integer division operator. The division
  78. // result is rounded toward zero, so the result of '%' has the sign of
  79. // the first operand.
  80. if (b != 0u) {
  81. return static_cast<int32_t>(a) % static_cast<int32_t>(b);
  82. } else {
  83. // Remainder when dividing with 0 is undefined, so we will just pick 0.
  84. return 0;
  85. }
  86. }
  87. case SpvOp::SpvOpSMod: {
  88. // The sign of non-zero result comes from the second operand: b
  89. if (b != 0u) {
  90. int32_t rem = BinaryOperate(SpvOp::SpvOpSRem, a, b);
  91. int32_t b_prim = static_cast<int32_t>(b);
  92. return (rem + b_prim) % b_prim;
  93. } else {
  94. // Mod with 0 is undefined, so we will just pick 0.
  95. return 0;
  96. }
  97. }
  98. case SpvOp::SpvOpUMod:
  99. if (b != 0u) {
  100. return (a % b);
  101. } else {
  102. // Mod with 0 is undefined, so we will just pick 0.
  103. return 0;
  104. }
  105. // Shifting
  106. case SpvOp::SpvOpShiftRightLogical:
  107. if (b >= 32) {
  108. // This is undefined behaviour when |b| > 32. Choose 0 for consistency.
  109. // When |b| == 32, doing the shift in C++ in undefined, but the result
  110. // will be 0, so just return that value.
  111. return 0;
  112. }
  113. return a >> b;
  114. case SpvOp::SpvOpShiftRightArithmetic:
  115. if (b > 32) {
  116. // This is undefined behaviour. Choose 0 for consistency.
  117. return 0;
  118. }
  119. if (b == 32) {
  120. // Doing the shift in C++ is undefined, but the result is defined in the
  121. // spir-v spec. Find that value another way.
  122. if (static_cast<int32_t>(a) >= 0) {
  123. return 0;
  124. } else {
  125. return static_cast<uint32_t>(-1);
  126. }
  127. }
  128. return (static_cast<int32_t>(a)) >> b;
  129. case SpvOp::SpvOpShiftLeftLogical:
  130. if (b >= 32) {
  131. // This is undefined behaviour when |b| > 32. Choose 0 for consistency.
  132. // When |b| == 32, doing the shift in C++ in undefined, but the result
  133. // will be 0, so just return that value.
  134. return 0;
  135. }
  136. return a << b;
  137. // Bitwise operations
  138. case SpvOp::SpvOpBitwiseOr:
  139. return a | b;
  140. case SpvOp::SpvOpBitwiseAnd:
  141. return a & b;
  142. case SpvOp::SpvOpBitwiseXor:
  143. return a ^ b;
  144. // Logical
  145. case SpvOp::SpvOpLogicalEqual:
  146. return (static_cast<bool>(a)) == (static_cast<bool>(b));
  147. case SpvOp::SpvOpLogicalNotEqual:
  148. return (static_cast<bool>(a)) != (static_cast<bool>(b));
  149. case SpvOp::SpvOpLogicalOr:
  150. return (static_cast<bool>(a)) || (static_cast<bool>(b));
  151. case SpvOp::SpvOpLogicalAnd:
  152. return (static_cast<bool>(a)) && (static_cast<bool>(b));
  153. // Comparison
  154. case SpvOp::SpvOpIEqual:
  155. return a == b;
  156. case SpvOp::SpvOpINotEqual:
  157. return a != b;
  158. case SpvOp::SpvOpULessThan:
  159. return a < b;
  160. case SpvOp::SpvOpSLessThan:
  161. return (static_cast<int32_t>(a)) < (static_cast<int32_t>(b));
  162. case SpvOp::SpvOpUGreaterThan:
  163. return a > b;
  164. case SpvOp::SpvOpSGreaterThan:
  165. return (static_cast<int32_t>(a)) > (static_cast<int32_t>(b));
  166. case SpvOp::SpvOpULessThanEqual:
  167. return a <= b;
  168. case SpvOp::SpvOpSLessThanEqual:
  169. return (static_cast<int32_t>(a)) <= (static_cast<int32_t>(b));
  170. case SpvOp::SpvOpUGreaterThanEqual:
  171. return a >= b;
  172. case SpvOp::SpvOpSGreaterThanEqual:
  173. return (static_cast<int32_t>(a)) >= (static_cast<int32_t>(b));
  174. default:
  175. assert(false &&
  176. "Unsupported binary operation for OpSpecConstantOp instruction");
  177. return 0u;
  178. }
  179. }
  180. uint32_t InstructionFolder::TernaryOperate(SpvOp opcode, uint32_t a, uint32_t b,
  181. uint32_t c) const {
  182. switch (opcode) {
  183. case SpvOp::SpvOpSelect:
  184. return (static_cast<bool>(a)) ? b : c;
  185. default:
  186. assert(false &&
  187. "Unsupported ternary operation for OpSpecConstantOp instruction");
  188. return 0u;
  189. }
  190. }
  191. uint32_t InstructionFolder::OperateWords(
  192. SpvOp opcode, const std::vector<uint32_t>& operand_words) const {
  193. switch (operand_words.size()) {
  194. case 1:
  195. return UnaryOperate(opcode, operand_words.front());
  196. case 2:
  197. return BinaryOperate(opcode, operand_words.front(), operand_words.back());
  198. case 3:
  199. return TernaryOperate(opcode, operand_words[0], operand_words[1],
  200. operand_words[2]);
  201. default:
  202. assert(false && "Invalid number of operands");
  203. return 0;
  204. }
  205. }
  206. bool InstructionFolder::FoldInstructionInternal(Instruction* inst) const {
  207. auto identity_map = [](uint32_t id) { return id; };
  208. Instruction* folded_inst = FoldInstructionToConstant(inst, identity_map);
  209. if (folded_inst != nullptr) {
  210. inst->SetOpcode(SpvOpCopyObject);
  211. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {folded_inst->result_id()}}});
  212. return true;
  213. }
  214. SpvOp opcode = inst->opcode();
  215. analysis::ConstantManager* const_manager = context_->get_constant_mgr();
  216. std::vector<const analysis::Constant*> constants =
  217. const_manager->GetOperandConstants(inst);
  218. for (const FoldingRule& rule : GetFoldingRules().GetRulesForOpcode(opcode)) {
  219. if (rule(context_, inst, constants)) {
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. // Returns the result of performing an operation on scalar constant operands.
  226. // This function extracts the operand values as 32 bit words and returns the
  227. // result in 32 bit word. Scalar constants with longer than 32-bit width are
  228. // not accepted in this function.
  229. uint32_t InstructionFolder::FoldScalars(
  230. SpvOp opcode,
  231. const std::vector<const analysis::Constant*>& operands) const {
  232. assert(IsFoldableOpcode(opcode) &&
  233. "Unhandled instruction opcode in FoldScalars");
  234. std::vector<uint32_t> operand_values_in_raw_words;
  235. for (const auto& operand : operands) {
  236. if (const analysis::ScalarConstant* scalar = operand->AsScalarConstant()) {
  237. const auto& scalar_words = scalar->words();
  238. assert(scalar_words.size() == 1 &&
  239. "Scalar constants with longer than 32-bit width are not allowed "
  240. "in FoldScalars()");
  241. operand_values_in_raw_words.push_back(scalar_words.front());
  242. } else if (operand->AsNullConstant()) {
  243. operand_values_in_raw_words.push_back(0u);
  244. } else {
  245. assert(false &&
  246. "FoldScalars() only accepts ScalarConst or NullConst type of "
  247. "constant");
  248. }
  249. }
  250. return OperateWords(opcode, operand_values_in_raw_words);
  251. }
  252. bool InstructionFolder::FoldBinaryIntegerOpToConstant(
  253. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  254. uint32_t* result) const {
  255. SpvOp opcode = inst->opcode();
  256. analysis::ConstantManager* const_manger = context_->get_constant_mgr();
  257. uint32_t ids[2];
  258. const analysis::IntConstant* constants[2];
  259. for (uint32_t i = 0; i < 2; i++) {
  260. const Operand* operand = &inst->GetInOperand(i);
  261. if (operand->type != SPV_OPERAND_TYPE_ID) {
  262. return false;
  263. }
  264. ids[i] = id_map(operand->words[0]);
  265. const analysis::Constant* constant =
  266. const_manger->FindDeclaredConstant(ids[i]);
  267. constants[i] = (constant != nullptr ? constant->AsIntConstant() : nullptr);
  268. }
  269. switch (opcode) {
  270. // Arthimetics
  271. case SpvOp::SpvOpIMul:
  272. for (uint32_t i = 0; i < 2; i++) {
  273. if (constants[i] != nullptr && constants[i]->IsZero()) {
  274. *result = 0;
  275. return true;
  276. }
  277. }
  278. break;
  279. case SpvOp::SpvOpUDiv:
  280. case SpvOp::SpvOpSDiv:
  281. case SpvOp::SpvOpSRem:
  282. case SpvOp::SpvOpSMod:
  283. case SpvOp::SpvOpUMod:
  284. // This changes undefined behaviour (ie divide by 0) into a 0.
  285. for (uint32_t i = 0; i < 2; i++) {
  286. if (constants[i] != nullptr && constants[i]->IsZero()) {
  287. *result = 0;
  288. return true;
  289. }
  290. }
  291. break;
  292. // Shifting
  293. case SpvOp::SpvOpShiftRightLogical:
  294. case SpvOp::SpvOpShiftLeftLogical:
  295. if (constants[1] != nullptr) {
  296. // When shifting by a value larger than the size of the result, the
  297. // result is undefined. We are setting the undefined behaviour to a
  298. // result of 0. If the shift amount is the same as the size of the
  299. // result, then the result is defined, and it 0.
  300. uint32_t shift_amount = constants[1]->GetU32BitValue();
  301. if (shift_amount >= 32) {
  302. *result = 0;
  303. return true;
  304. }
  305. }
  306. break;
  307. // Bitwise operations
  308. case SpvOp::SpvOpBitwiseOr:
  309. for (uint32_t i = 0; i < 2; i++) {
  310. if (constants[i] != nullptr) {
  311. // TODO: Change the mask against a value based on the bit width of the
  312. // instruction result type. This way we can handle say 16-bit values
  313. // as well.
  314. uint32_t mask = constants[i]->GetU32BitValue();
  315. if (mask == 0xFFFFFFFF) {
  316. *result = 0xFFFFFFFF;
  317. return true;
  318. }
  319. }
  320. }
  321. break;
  322. case SpvOp::SpvOpBitwiseAnd:
  323. for (uint32_t i = 0; i < 2; i++) {
  324. if (constants[i] != nullptr) {
  325. if (constants[i]->IsZero()) {
  326. *result = 0;
  327. return true;
  328. }
  329. }
  330. }
  331. break;
  332. // Comparison
  333. case SpvOp::SpvOpULessThan:
  334. if (constants[0] != nullptr &&
  335. constants[0]->GetU32BitValue() == UINT32_MAX) {
  336. *result = false;
  337. return true;
  338. }
  339. if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
  340. *result = false;
  341. return true;
  342. }
  343. break;
  344. case SpvOp::SpvOpSLessThan:
  345. if (constants[0] != nullptr &&
  346. constants[0]->GetS32BitValue() == INT32_MAX) {
  347. *result = false;
  348. return true;
  349. }
  350. if (constants[1] != nullptr &&
  351. constants[1]->GetS32BitValue() == INT32_MIN) {
  352. *result = false;
  353. return true;
  354. }
  355. break;
  356. case SpvOp::SpvOpUGreaterThan:
  357. if (constants[0] != nullptr && constants[0]->IsZero()) {
  358. *result = false;
  359. return true;
  360. }
  361. if (constants[1] != nullptr &&
  362. constants[1]->GetU32BitValue() == UINT32_MAX) {
  363. *result = false;
  364. return true;
  365. }
  366. break;
  367. case SpvOp::SpvOpSGreaterThan:
  368. if (constants[0] != nullptr &&
  369. constants[0]->GetS32BitValue() == INT32_MIN) {
  370. *result = false;
  371. return true;
  372. }
  373. if (constants[1] != nullptr &&
  374. constants[1]->GetS32BitValue() == INT32_MAX) {
  375. *result = false;
  376. return true;
  377. }
  378. break;
  379. case SpvOp::SpvOpULessThanEqual:
  380. if (constants[0] != nullptr && constants[0]->IsZero()) {
  381. *result = true;
  382. return true;
  383. }
  384. if (constants[1] != nullptr &&
  385. constants[1]->GetU32BitValue() == UINT32_MAX) {
  386. *result = true;
  387. return true;
  388. }
  389. break;
  390. case SpvOp::SpvOpSLessThanEqual:
  391. if (constants[0] != nullptr &&
  392. constants[0]->GetS32BitValue() == INT32_MIN) {
  393. *result = true;
  394. return true;
  395. }
  396. if (constants[1] != nullptr &&
  397. constants[1]->GetS32BitValue() == INT32_MAX) {
  398. *result = true;
  399. return true;
  400. }
  401. break;
  402. case SpvOp::SpvOpUGreaterThanEqual:
  403. if (constants[0] != nullptr &&
  404. constants[0]->GetU32BitValue() == UINT32_MAX) {
  405. *result = true;
  406. return true;
  407. }
  408. if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
  409. *result = true;
  410. return true;
  411. }
  412. break;
  413. case SpvOp::SpvOpSGreaterThanEqual:
  414. if (constants[0] != nullptr &&
  415. constants[0]->GetS32BitValue() == INT32_MAX) {
  416. *result = true;
  417. return true;
  418. }
  419. if (constants[1] != nullptr &&
  420. constants[1]->GetS32BitValue() == INT32_MIN) {
  421. *result = true;
  422. return true;
  423. }
  424. break;
  425. default:
  426. break;
  427. }
  428. return false;
  429. }
  430. bool InstructionFolder::FoldBinaryBooleanOpToConstant(
  431. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  432. uint32_t* result) const {
  433. SpvOp opcode = inst->opcode();
  434. analysis::ConstantManager* const_manger = context_->get_constant_mgr();
  435. uint32_t ids[2];
  436. const analysis::BoolConstant* constants[2];
  437. for (uint32_t i = 0; i < 2; i++) {
  438. const Operand* operand = &inst->GetInOperand(i);
  439. if (operand->type != SPV_OPERAND_TYPE_ID) {
  440. return false;
  441. }
  442. ids[i] = id_map(operand->words[0]);
  443. const analysis::Constant* constant =
  444. const_manger->FindDeclaredConstant(ids[i]);
  445. constants[i] = (constant != nullptr ? constant->AsBoolConstant() : nullptr);
  446. }
  447. switch (opcode) {
  448. // Logical
  449. case SpvOp::SpvOpLogicalOr:
  450. for (uint32_t i = 0; i < 2; i++) {
  451. if (constants[i] != nullptr) {
  452. if (constants[i]->value()) {
  453. *result = true;
  454. return true;
  455. }
  456. }
  457. }
  458. break;
  459. case SpvOp::SpvOpLogicalAnd:
  460. for (uint32_t i = 0; i < 2; i++) {
  461. if (constants[i] != nullptr) {
  462. if (!constants[i]->value()) {
  463. *result = false;
  464. return true;
  465. }
  466. }
  467. }
  468. break;
  469. default:
  470. break;
  471. }
  472. return false;
  473. }
  474. bool InstructionFolder::FoldIntegerOpToConstant(
  475. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  476. uint32_t* result) const {
  477. assert(IsFoldableOpcode(inst->opcode()) &&
  478. "Unhandled instruction opcode in FoldScalars");
  479. switch (inst->NumInOperands()) {
  480. case 2:
  481. return FoldBinaryIntegerOpToConstant(inst, id_map, result) ||
  482. FoldBinaryBooleanOpToConstant(inst, id_map, result);
  483. default:
  484. return false;
  485. }
  486. }
  487. std::vector<uint32_t> InstructionFolder::FoldVectors(
  488. SpvOp opcode, uint32_t num_dims,
  489. const std::vector<const analysis::Constant*>& operands) const {
  490. assert(IsFoldableOpcode(opcode) &&
  491. "Unhandled instruction opcode in FoldVectors");
  492. std::vector<uint32_t> result;
  493. for (uint32_t d = 0; d < num_dims; d++) {
  494. std::vector<uint32_t> operand_values_for_one_dimension;
  495. for (const auto& operand : operands) {
  496. if (const analysis::VectorConstant* vector_operand =
  497. operand->AsVectorConstant()) {
  498. // Extract the raw value of the scalar component constants
  499. // in 32-bit words here. The reason of not using FoldScalars() here
  500. // is that we do not create temporary null constants as components
  501. // when the vector operand is a NullConstant because Constant creation
  502. // may need extra checks for the validity and that is not manageed in
  503. // here.
  504. if (const analysis::ScalarConstant* scalar_component =
  505. vector_operand->GetComponents().at(d)->AsScalarConstant()) {
  506. const auto& scalar_words = scalar_component->words();
  507. assert(
  508. scalar_words.size() == 1 &&
  509. "Vector components with longer than 32-bit width are not allowed "
  510. "in FoldVectors()");
  511. operand_values_for_one_dimension.push_back(scalar_words.front());
  512. } else if (operand->AsNullConstant()) {
  513. operand_values_for_one_dimension.push_back(0u);
  514. } else {
  515. assert(false &&
  516. "VectorConst should only has ScalarConst or NullConst as "
  517. "components");
  518. }
  519. } else if (operand->AsNullConstant()) {
  520. operand_values_for_one_dimension.push_back(0u);
  521. } else {
  522. assert(false &&
  523. "FoldVectors() only accepts VectorConst or NullConst type of "
  524. "constant");
  525. }
  526. }
  527. result.push_back(OperateWords(opcode, operand_values_for_one_dimension));
  528. }
  529. return result;
  530. }
  531. bool InstructionFolder::IsFoldableOpcode(SpvOp opcode) const {
  532. // NOTE: Extend to more opcodes as new cases are handled in the folder
  533. // functions.
  534. switch (opcode) {
  535. case SpvOp::SpvOpBitwiseAnd:
  536. case SpvOp::SpvOpBitwiseOr:
  537. case SpvOp::SpvOpBitwiseXor:
  538. case SpvOp::SpvOpIAdd:
  539. case SpvOp::SpvOpIEqual:
  540. case SpvOp::SpvOpIMul:
  541. case SpvOp::SpvOpINotEqual:
  542. case SpvOp::SpvOpISub:
  543. case SpvOp::SpvOpLogicalAnd:
  544. case SpvOp::SpvOpLogicalEqual:
  545. case SpvOp::SpvOpLogicalNot:
  546. case SpvOp::SpvOpLogicalNotEqual:
  547. case SpvOp::SpvOpLogicalOr:
  548. case SpvOp::SpvOpNot:
  549. case SpvOp::SpvOpSDiv:
  550. case SpvOp::SpvOpSelect:
  551. case SpvOp::SpvOpSGreaterThan:
  552. case SpvOp::SpvOpSGreaterThanEqual:
  553. case SpvOp::SpvOpShiftLeftLogical:
  554. case SpvOp::SpvOpShiftRightArithmetic:
  555. case SpvOp::SpvOpShiftRightLogical:
  556. case SpvOp::SpvOpSLessThan:
  557. case SpvOp::SpvOpSLessThanEqual:
  558. case SpvOp::SpvOpSMod:
  559. case SpvOp::SpvOpSNegate:
  560. case SpvOp::SpvOpSRem:
  561. case SpvOp::SpvOpUDiv:
  562. case SpvOp::SpvOpUGreaterThan:
  563. case SpvOp::SpvOpUGreaterThanEqual:
  564. case SpvOp::SpvOpULessThan:
  565. case SpvOp::SpvOpULessThanEqual:
  566. case SpvOp::SpvOpUMod:
  567. return true;
  568. default:
  569. return false;
  570. }
  571. }
  572. bool InstructionFolder::IsFoldableConstant(
  573. const analysis::Constant* cst) const {
  574. // Currently supported constants are 32-bit values or null constants.
  575. if (const analysis::ScalarConstant* scalar = cst->AsScalarConstant())
  576. return scalar->words().size() == 1;
  577. else
  578. return cst->AsNullConstant() != nullptr;
  579. }
  580. Instruction* InstructionFolder::FoldInstructionToConstant(
  581. Instruction* inst, std::function<uint32_t(uint32_t)> id_map) const {
  582. analysis::ConstantManager* const_mgr = context_->get_constant_mgr();
  583. if (!inst->IsFoldableByFoldScalar() &&
  584. !GetConstantFoldingRules().HasFoldingRule(inst->opcode())) {
  585. return nullptr;
  586. }
  587. // Collect the values of the constant parameters.
  588. std::vector<const analysis::Constant*> constants;
  589. bool missing_constants = false;
  590. inst->ForEachInId([&constants, &missing_constants, const_mgr,
  591. &id_map](uint32_t* op_id) {
  592. uint32_t id = id_map(*op_id);
  593. const analysis::Constant* const_op = const_mgr->FindDeclaredConstant(id);
  594. if (!const_op) {
  595. constants.push_back(nullptr);
  596. missing_constants = true;
  597. } else {
  598. constants.push_back(const_op);
  599. }
  600. });
  601. if (GetConstantFoldingRules().HasFoldingRule(inst->opcode())) {
  602. const analysis::Constant* folded_const = nullptr;
  603. for (auto rule :
  604. GetConstantFoldingRules().GetRulesForOpcode(inst->opcode())) {
  605. folded_const = rule(context_, inst, constants);
  606. if (folded_const != nullptr) {
  607. Instruction* const_inst =
  608. const_mgr->GetDefiningInstruction(folded_const, inst->type_id());
  609. assert(const_inst->type_id() == inst->type_id());
  610. // May be a new instruction that needs to be analysed.
  611. context_->UpdateDefUse(const_inst);
  612. return const_inst;
  613. }
  614. }
  615. }
  616. uint32_t result_val = 0;
  617. bool successful = false;
  618. // If all parameters are constant, fold the instruction to a constant.
  619. if (!missing_constants && inst->IsFoldableByFoldScalar()) {
  620. result_val = FoldScalars(inst->opcode(), constants);
  621. successful = true;
  622. }
  623. if (!successful && inst->IsFoldableByFoldScalar()) {
  624. successful = FoldIntegerOpToConstant(inst, id_map, &result_val);
  625. }
  626. if (successful) {
  627. const analysis::Constant* result_const =
  628. const_mgr->GetConstant(const_mgr->GetType(inst), {result_val});
  629. Instruction* folded_inst =
  630. const_mgr->GetDefiningInstruction(result_const, inst->type_id());
  631. return folded_inst;
  632. }
  633. return nullptr;
  634. }
  635. bool InstructionFolder::IsFoldableType(Instruction* type_inst) const {
  636. // Support 32-bit integers.
  637. if (type_inst->opcode() == SpvOpTypeInt) {
  638. return type_inst->GetSingleWordInOperand(0) == 32;
  639. }
  640. // Support booleans.
  641. if (type_inst->opcode() == SpvOpTypeBool) {
  642. return true;
  643. }
  644. // Nothing else yet.
  645. return false;
  646. }
  647. bool InstructionFolder::FoldInstruction(Instruction* inst) const {
  648. bool modified = false;
  649. Instruction* folded_inst(inst);
  650. while (folded_inst->opcode() != SpvOpCopyObject &&
  651. FoldInstructionInternal(&*folded_inst)) {
  652. modified = true;
  653. }
  654. return modified;
  655. }
  656. } // namespace opt
  657. } // namespace spvtools