constants.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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/constants.h"
  15. #include <unordered_map>
  16. #include <vector>
  17. #include "source/opt/ir_context.h"
  18. namespace spvtools {
  19. namespace opt {
  20. namespace analysis {
  21. float Constant::GetFloat() const {
  22. assert(type()->AsFloat() != nullptr && type()->AsFloat()->width() == 32);
  23. if (const FloatConstant* fc = AsFloatConstant()) {
  24. return fc->GetFloatValue();
  25. } else {
  26. assert(AsNullConstant() && "Must be a floating point constant.");
  27. return 0.0f;
  28. }
  29. }
  30. double Constant::GetDouble() const {
  31. assert(type()->AsFloat() != nullptr && type()->AsFloat()->width() == 64);
  32. if (const FloatConstant* fc = AsFloatConstant()) {
  33. return fc->GetDoubleValue();
  34. } else {
  35. assert(AsNullConstant() && "Must be a floating point constant.");
  36. return 0.0;
  37. }
  38. }
  39. double Constant::GetValueAsDouble() const {
  40. assert(type()->AsFloat() != nullptr);
  41. if (type()->AsFloat()->width() == 32) {
  42. return GetFloat();
  43. } else {
  44. assert(type()->AsFloat()->width() == 64);
  45. return GetDouble();
  46. }
  47. }
  48. uint32_t Constant::GetU32() const {
  49. assert(type()->AsInteger() != nullptr);
  50. assert(type()->AsInteger()->width() == 32);
  51. if (const IntConstant* ic = AsIntConstant()) {
  52. return ic->GetU32BitValue();
  53. } else {
  54. assert(AsNullConstant() && "Must be an integer constant.");
  55. return 0u;
  56. }
  57. }
  58. uint64_t Constant::GetU64() const {
  59. assert(type()->AsInteger() != nullptr);
  60. assert(type()->AsInteger()->width() == 64);
  61. if (const IntConstant* ic = AsIntConstant()) {
  62. return ic->GetU64BitValue();
  63. } else {
  64. assert(AsNullConstant() && "Must be an integer constant.");
  65. return 0u;
  66. }
  67. }
  68. int32_t Constant::GetS32() const {
  69. assert(type()->AsInteger() != nullptr);
  70. assert(type()->AsInteger()->width() == 32);
  71. if (const IntConstant* ic = AsIntConstant()) {
  72. return ic->GetS32BitValue();
  73. } else {
  74. assert(AsNullConstant() && "Must be an integer constant.");
  75. return 0;
  76. }
  77. }
  78. int64_t Constant::GetS64() const {
  79. assert(type()->AsInteger() != nullptr);
  80. assert(type()->AsInteger()->width() == 64);
  81. if (const IntConstant* ic = AsIntConstant()) {
  82. return ic->GetS64BitValue();
  83. } else {
  84. assert(AsNullConstant() && "Must be an integer constant.");
  85. return 0;
  86. }
  87. }
  88. uint64_t Constant::GetZeroExtendedValue() const {
  89. const auto* int_type = type()->AsInteger();
  90. assert(int_type != nullptr);
  91. const auto width = int_type->width();
  92. assert(width <= 64);
  93. uint64_t value = 0;
  94. if (const IntConstant* ic = AsIntConstant()) {
  95. if (width <= 32) {
  96. value = ic->GetU32BitValue();
  97. } else {
  98. value = ic->GetU64BitValue();
  99. }
  100. } else {
  101. assert(AsNullConstant() && "Must be an integer constant.");
  102. }
  103. return value;
  104. }
  105. int64_t Constant::GetSignExtendedValue() const {
  106. const auto* int_type = type()->AsInteger();
  107. assert(int_type != nullptr);
  108. const auto width = int_type->width();
  109. assert(width <= 64);
  110. int64_t value = 0;
  111. if (const IntConstant* ic = AsIntConstant()) {
  112. if (width <= 32) {
  113. // Let the C++ compiler do the sign extension.
  114. value = int64_t(ic->GetS32BitValue());
  115. } else {
  116. value = ic->GetS64BitValue();
  117. }
  118. } else {
  119. assert(AsNullConstant() && "Must be an integer constant.");
  120. }
  121. return value;
  122. }
  123. ConstantManager::ConstantManager(IRContext* ctx) : ctx_(ctx) {
  124. // Populate the constant table with values from constant declarations in the
  125. // module. The values of each OpConstant declaration is the identity
  126. // assignment (i.e., each constant is its own value).
  127. for (const auto& inst : ctx_->module()->GetConstants()) {
  128. MapInst(inst);
  129. }
  130. }
  131. Type* ConstantManager::GetType(const Instruction* inst) const {
  132. return context()->get_type_mgr()->GetType(inst->type_id());
  133. }
  134. std::vector<const Constant*> ConstantManager::GetOperandConstants(
  135. Instruction* inst) const {
  136. std::vector<const Constant*> constants;
  137. for (uint32_t i = 0; i < inst->NumInOperands(); i++) {
  138. const Operand* operand = &inst->GetInOperand(i);
  139. if (operand->type != SPV_OPERAND_TYPE_ID) {
  140. constants.push_back(nullptr);
  141. } else {
  142. uint32_t id = operand->words[0];
  143. const analysis::Constant* constant = FindDeclaredConstant(id);
  144. constants.push_back(constant);
  145. }
  146. }
  147. return constants;
  148. }
  149. uint32_t ConstantManager::FindDeclaredConstant(const Constant* c,
  150. uint32_t type_id) const {
  151. c = FindConstant(c);
  152. if (c == nullptr) {
  153. return 0;
  154. }
  155. for (auto range = const_val_to_id_.equal_range(c);
  156. range.first != range.second; ++range.first) {
  157. Instruction* const_def =
  158. context()->get_def_use_mgr()->GetDef(range.first->second);
  159. if (type_id == 0 || const_def->type_id() == type_id) {
  160. return range.first->second;
  161. }
  162. }
  163. return 0;
  164. }
  165. std::vector<const Constant*> ConstantManager::GetConstantsFromIds(
  166. const std::vector<uint32_t>& ids) const {
  167. std::vector<const Constant*> constants;
  168. for (uint32_t id : ids) {
  169. if (const Constant* c = FindDeclaredConstant(id)) {
  170. constants.push_back(c);
  171. } else {
  172. return {};
  173. }
  174. }
  175. return constants;
  176. }
  177. Instruction* ConstantManager::BuildInstructionAndAddToModule(
  178. const Constant* new_const, Module::inst_iterator* pos, uint32_t type_id) {
  179. // TODO(1841): Handle id overflow.
  180. uint32_t new_id = context()->TakeNextId();
  181. if (new_id == 0) {
  182. return nullptr;
  183. }
  184. auto new_inst = CreateInstruction(new_id, new_const, type_id);
  185. if (!new_inst) {
  186. return nullptr;
  187. }
  188. auto* new_inst_ptr = new_inst.get();
  189. *pos = pos->InsertBefore(std::move(new_inst));
  190. ++(*pos);
  191. context()->get_def_use_mgr()->AnalyzeInstDefUse(new_inst_ptr);
  192. MapConstantToInst(new_const, new_inst_ptr);
  193. return new_inst_ptr;
  194. }
  195. Instruction* ConstantManager::GetDefiningInstruction(
  196. const Constant* c, uint32_t type_id, Module::inst_iterator* pos) {
  197. uint32_t decl_id = FindDeclaredConstant(c, type_id);
  198. if (decl_id == 0) {
  199. auto iter = context()->types_values_end();
  200. if (pos == nullptr) pos = &iter;
  201. return BuildInstructionAndAddToModule(c, pos, type_id);
  202. } else {
  203. auto def = context()->get_def_use_mgr()->GetDef(decl_id);
  204. assert(def != nullptr);
  205. assert((type_id == 0 || def->type_id() == type_id) &&
  206. "This constant already has an instruction with a different type.");
  207. return def;
  208. }
  209. }
  210. std::unique_ptr<Constant> ConstantManager::CreateConstant(
  211. const Type* type, const std::vector<uint32_t>& literal_words_or_ids) const {
  212. if (literal_words_or_ids.size() == 0) {
  213. // Constant declared with OpConstantNull
  214. return MakeUnique<NullConstant>(type);
  215. } else if (auto* bt = type->AsBool()) {
  216. assert(literal_words_or_ids.size() == 1 &&
  217. "Bool constant should be declared with one operand");
  218. return MakeUnique<BoolConstant>(bt, literal_words_or_ids.front());
  219. } else if (auto* it = type->AsInteger()) {
  220. return MakeUnique<IntConstant>(it, literal_words_or_ids);
  221. } else if (auto* ft = type->AsFloat()) {
  222. return MakeUnique<FloatConstant>(ft, literal_words_or_ids);
  223. } else if (auto* vt = type->AsVector()) {
  224. auto components = GetConstantsFromIds(literal_words_or_ids);
  225. if (components.empty()) return nullptr;
  226. // All components of VectorConstant must be of type Bool, Integer or Float.
  227. if (!std::all_of(components.begin(), components.end(),
  228. [](const Constant* c) {
  229. if (c->type()->AsBool() || c->type()->AsInteger() ||
  230. c->type()->AsFloat()) {
  231. return true;
  232. } else {
  233. return false;
  234. }
  235. }))
  236. return nullptr;
  237. // All components of VectorConstant must be in the same type.
  238. const auto* component_type = components.front()->type();
  239. if (!std::all_of(components.begin(), components.end(),
  240. [&component_type](const Constant* c) {
  241. if (c->type() == component_type) return true;
  242. return false;
  243. }))
  244. return nullptr;
  245. return MakeUnique<VectorConstant>(vt, components);
  246. } else if (auto* mt = type->AsMatrix()) {
  247. auto components = GetConstantsFromIds(literal_words_or_ids);
  248. if (components.empty()) return nullptr;
  249. return MakeUnique<MatrixConstant>(mt, components);
  250. } else if (auto* st = type->AsStruct()) {
  251. auto components = GetConstantsFromIds(literal_words_or_ids);
  252. if (components.empty()) return nullptr;
  253. return MakeUnique<StructConstant>(st, components);
  254. } else if (auto* at = type->AsArray()) {
  255. auto components = GetConstantsFromIds(literal_words_or_ids);
  256. if (components.empty()) return nullptr;
  257. return MakeUnique<ArrayConstant>(at, components);
  258. } else {
  259. return nullptr;
  260. }
  261. }
  262. const Constant* ConstantManager::GetConstantFromInst(const Instruction* inst) {
  263. std::vector<uint32_t> literal_words_or_ids;
  264. // Collect the constant defining literals or component ids.
  265. for (uint32_t i = 0; i < inst->NumInOperands(); i++) {
  266. literal_words_or_ids.insert(literal_words_or_ids.end(),
  267. inst->GetInOperand(i).words.begin(),
  268. inst->GetInOperand(i).words.end());
  269. }
  270. switch (inst->opcode()) {
  271. // OpConstant{True|False} have the value embedded in the opcode. So they
  272. // are not handled by the for-loop above. Here we add the value explicitly.
  273. case SpvOp::SpvOpConstantTrue:
  274. literal_words_or_ids.push_back(true);
  275. break;
  276. case SpvOp::SpvOpConstantFalse:
  277. literal_words_or_ids.push_back(false);
  278. break;
  279. case SpvOp::SpvOpConstantNull:
  280. case SpvOp::SpvOpConstant:
  281. case SpvOp::SpvOpConstantComposite:
  282. case SpvOp::SpvOpSpecConstantComposite:
  283. break;
  284. default:
  285. return nullptr;
  286. }
  287. return GetConstant(GetType(inst), literal_words_or_ids);
  288. }
  289. std::unique_ptr<Instruction> ConstantManager::CreateInstruction(
  290. uint32_t id, const Constant* c, uint32_t type_id) const {
  291. uint32_t type =
  292. (type_id == 0) ? context()->get_type_mgr()->GetId(c->type()) : type_id;
  293. if (c->AsNullConstant()) {
  294. return MakeUnique<Instruction>(context(), SpvOp::SpvOpConstantNull, type,
  295. id, std::initializer_list<Operand>{});
  296. } else if (const BoolConstant* bc = c->AsBoolConstant()) {
  297. return MakeUnique<Instruction>(
  298. context(),
  299. bc->value() ? SpvOp::SpvOpConstantTrue : SpvOp::SpvOpConstantFalse,
  300. type, id, std::initializer_list<Operand>{});
  301. } else if (const IntConstant* ic = c->AsIntConstant()) {
  302. return MakeUnique<Instruction>(
  303. context(), SpvOp::SpvOpConstant, type, id,
  304. std::initializer_list<Operand>{
  305. Operand(spv_operand_type_t::SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER,
  306. ic->words())});
  307. } else if (const FloatConstant* fc = c->AsFloatConstant()) {
  308. return MakeUnique<Instruction>(
  309. context(), SpvOp::SpvOpConstant, type, id,
  310. std::initializer_list<Operand>{
  311. Operand(spv_operand_type_t::SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER,
  312. fc->words())});
  313. } else if (const CompositeConstant* cc = c->AsCompositeConstant()) {
  314. return CreateCompositeInstruction(id, cc, type_id);
  315. } else {
  316. return nullptr;
  317. }
  318. }
  319. std::unique_ptr<Instruction> ConstantManager::CreateCompositeInstruction(
  320. uint32_t result_id, const CompositeConstant* cc, uint32_t type_id) const {
  321. std::vector<Operand> operands;
  322. Instruction* type_inst = context()->get_def_use_mgr()->GetDef(type_id);
  323. uint32_t component_index = 0;
  324. for (const Constant* component_const : cc->GetComponents()) {
  325. uint32_t component_type_id = 0;
  326. if (type_inst && type_inst->opcode() == SpvOpTypeStruct) {
  327. component_type_id = type_inst->GetSingleWordInOperand(component_index);
  328. } else if (type_inst && type_inst->opcode() == SpvOpTypeArray) {
  329. component_type_id = type_inst->GetSingleWordInOperand(0);
  330. }
  331. uint32_t id = FindDeclaredConstant(component_const, component_type_id);
  332. if (id == 0) {
  333. // Cannot get the id of the component constant, while all components
  334. // should have been added to the module prior to the composite constant.
  335. // Cannot create OpConstantComposite instruction in this case.
  336. return nullptr;
  337. }
  338. operands.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_ID,
  339. std::initializer_list<uint32_t>{id});
  340. component_index++;
  341. }
  342. uint32_t type =
  343. (type_id == 0) ? context()->get_type_mgr()->GetId(cc->type()) : type_id;
  344. return MakeUnique<Instruction>(context(), SpvOp::SpvOpConstantComposite, type,
  345. result_id, std::move(operands));
  346. }
  347. const Constant* ConstantManager::GetConstant(
  348. const Type* type, const std::vector<uint32_t>& literal_words_or_ids) {
  349. auto cst = CreateConstant(type, literal_words_or_ids);
  350. return cst ? RegisterConstant(std::move(cst)) : nullptr;
  351. }
  352. uint32_t ConstantManager::GetFloatConst(float val) {
  353. Type* float_type = context()->get_type_mgr()->GetFloatType();
  354. utils::FloatProxy<float> v(val);
  355. const Constant* c = GetConstant(float_type, v.GetWords());
  356. return GetDefiningInstruction(c)->result_id();
  357. }
  358. std::vector<const analysis::Constant*> Constant::GetVectorComponents(
  359. analysis::ConstantManager* const_mgr) const {
  360. std::vector<const analysis::Constant*> components;
  361. const analysis::VectorConstant* a = this->AsVectorConstant();
  362. const analysis::Vector* vector_type = this->type()->AsVector();
  363. assert(vector_type != nullptr);
  364. if (a != nullptr) {
  365. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  366. components.push_back(a->GetComponents()[i]);
  367. }
  368. } else {
  369. const analysis::Type* element_type = vector_type->element_type();
  370. const analysis::Constant* element_null_const =
  371. const_mgr->GetConstant(element_type, {});
  372. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  373. components.push_back(element_null_const);
  374. }
  375. }
  376. return components;
  377. }
  378. } // namespace analysis
  379. } // namespace opt
  380. } // namespace spvtools