inst_fingerprinter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/inst_fingerprinter.h"
  5. #include <variant>
  6. #include "common/ostream.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/StableHashing.h"
  10. #include "toolchain/base/value_ids.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::SemIR {
  14. namespace {
  15. struct Worklist {
  16. // The file containing the instruction we're currently processing.
  17. const File* sem_ir = nullptr;
  18. // The instructions we need to compute fingerprints for.
  19. llvm::SmallVector<std::pair<const File*, std::variant<InstId, InstBlockId>>>
  20. todo;
  21. // The contents of the current instruction as accumulated so far. This is used
  22. // to build a Merkle tree containing a fingerprint for the current
  23. // instruction.
  24. llvm::SmallVector<llvm::stable_hash> contents = {};
  25. // Known cached instruction fingerprints. Each item in `todo` will be added to
  26. // the cache if not already present.
  27. Map<std::pair<const File*, InstId>, uint64_t>* fingerprints;
  28. // Finish fingerprinting and compute the fingerprint.
  29. auto Finish() -> uint64_t { return llvm::stable_hash_combine(contents); }
  30. // Add an invalid marker to the contents. This is used when the entity
  31. // contains an invalid ID. This uses an arbitrary fixed value that is assumed
  32. // to be unlikely to collide with a valid value.
  33. auto AddInvalid() -> void { contents.push_back(-1); }
  34. // Add a string to the contents.
  35. auto AddString(llvm::StringRef string) {
  36. contents.push_back(llvm::stable_hash_name(string));
  37. }
  38. // Each of the following `Add` functions adds a typed argument to the contents
  39. // of the current instruction. If we don't yet have a fingerprint for the
  40. // argument, it instead adds that argument to the worklist instead.
  41. auto Add(InstKind kind) -> void {
  42. // TODO: Precompute or cache the hash of instruction IR names, or pick a
  43. // scheme that doesn't change when IR names change.
  44. AddString(kind.ir_name());
  45. }
  46. auto Add(IdentifierId ident_id) -> void {
  47. AddString(sem_ir->identifiers().Get(ident_id));
  48. }
  49. auto Add(StringLiteralValueId lit_id) -> void {
  50. AddString(sem_ir->string_literal_values().Get(lit_id));
  51. }
  52. auto Add(NameId name_id) -> void {
  53. AddString(sem_ir->names().GetIRBaseName(name_id));
  54. }
  55. auto Add(EntityNameId entity_name_id) -> void {
  56. if (!entity_name_id.is_valid()) {
  57. AddInvalid();
  58. return;
  59. }
  60. Add(sem_ir->entity_names().Get(entity_name_id).name_id);
  61. // TODO: Should we include the other parts of the entity name?
  62. }
  63. auto AddInFile(const File* file, InstId inner_id) -> void {
  64. if (!inner_id.is_valid()) {
  65. AddInvalid();
  66. return;
  67. }
  68. if (auto lookup = fingerprints->Lookup(std::pair(file, inner_id))) {
  69. contents.push_back(lookup.value());
  70. } else {
  71. todo.push_back({file, inner_id});
  72. }
  73. }
  74. auto Add(InstId inner_id) -> void { AddInFile(sem_ir, inner_id); }
  75. auto Add(ConstantId constant_id) -> void {
  76. if (!constant_id.is_valid()) {
  77. AddInvalid();
  78. return;
  79. }
  80. Add(sem_ir->constant_values().GetInstId(constant_id));
  81. }
  82. auto Add(TypeId type_id) -> void {
  83. if (!type_id.is_valid()) {
  84. AddInvalid();
  85. return;
  86. }
  87. Add(sem_ir->types().GetInstId(type_id));
  88. }
  89. template <typename T>
  90. auto AddBlock(llvm::ArrayRef<T> block) -> void {
  91. contents.push_back(block.size());
  92. for (auto inner_id : block) {
  93. Add(inner_id);
  94. }
  95. }
  96. auto Add(InstBlockId inst_block_id) -> void {
  97. if (!inst_block_id.is_valid()) {
  98. AddInvalid();
  99. return;
  100. }
  101. AddBlock(sem_ir->inst_blocks().Get(inst_block_id));
  102. }
  103. auto Add(TypeBlockId type_block_id) -> void {
  104. if (!type_block_id.is_valid()) {
  105. AddInvalid();
  106. return;
  107. }
  108. AddBlock(sem_ir->type_blocks().Get(type_block_id));
  109. }
  110. auto Add(StructTypeField field) -> void {
  111. Add(field.name_id);
  112. Add(field.type_id);
  113. }
  114. auto Add(StructTypeFieldsId struct_type_fields_id) -> void {
  115. if (!struct_type_fields_id.is_valid()) {
  116. AddInvalid();
  117. return;
  118. }
  119. AddBlock(sem_ir->struct_type_fields().Get(struct_type_fields_id));
  120. }
  121. auto Add(NameScopeId name_scope_id) -> void {
  122. if (!name_scope_id.is_valid()) {
  123. AddInvalid();
  124. return;
  125. }
  126. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  127. Add(scope.name_id());
  128. if (!sem_ir->name_scopes().IsPackage(name_scope_id) &&
  129. scope.parent_scope_id().is_valid()) {
  130. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  131. }
  132. }
  133. auto AddEntity(const EntityWithParamsBase& entity) -> void {
  134. Add(entity.name_id);
  135. if (entity.parent_scope_id.is_valid()) {
  136. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  137. }
  138. }
  139. auto Add(FunctionId function_id) -> void {
  140. AddEntity(sem_ir->functions().Get(function_id));
  141. }
  142. auto Add(ClassId class_id) -> void {
  143. AddEntity(sem_ir->classes().Get(class_id));
  144. }
  145. auto Add(InterfaceId interface_id) -> void {
  146. AddEntity(sem_ir->interfaces().Get(interface_id));
  147. }
  148. auto Add(ImplId impl_id) -> void {
  149. const auto& impl = sem_ir->impls().Get(impl_id);
  150. Add(impl.self_id);
  151. Add(impl.constraint_id);
  152. Add(impl.parent_scope_id);
  153. }
  154. auto Add(FacetTypeId facet_type_id) -> void {
  155. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  156. for (auto [interface_id, specific_id] : facet_type.impls_constraints) {
  157. Add(interface_id);
  158. Add(specific_id);
  159. }
  160. for (auto [lhs_id, rhs_id] : facet_type.rewrite_constraints) {
  161. Add(lhs_id);
  162. Add(rhs_id);
  163. }
  164. contents.push_back(facet_type.other_requirements);
  165. }
  166. auto Add(GenericId generic_id) -> void {
  167. if (!generic_id.is_valid()) {
  168. AddInvalid();
  169. return;
  170. }
  171. Add(sem_ir->generics().Get(generic_id).decl_id);
  172. }
  173. auto Add(SpecificId specific_id) -> void {
  174. if (!specific_id.is_valid()) {
  175. AddInvalid();
  176. return;
  177. }
  178. const auto& specific = sem_ir->specifics().Get(specific_id);
  179. Add(specific.generic_id);
  180. Add(specific.args_id);
  181. }
  182. auto Add(const llvm::APInt& value) -> void {
  183. contents.push_back(value.getBitWidth());
  184. for (auto word : llvm::seq((value.getBitWidth() + 63) / 64)) {
  185. // TODO: Is there a better way to copy the words from an APInt?
  186. contents.push_back(value.extractBitsAsZExtValue(64, 64 * word));
  187. }
  188. }
  189. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  190. auto Add(FloatId float_id) -> void {
  191. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  192. }
  193. auto Add(LibraryNameId lib_name_id) -> void {
  194. if (lib_name_id == LibraryNameId::Default) {
  195. AddString("");
  196. } else if (lib_name_id == LibraryNameId::Error) {
  197. AddString("<error>");
  198. } else if (lib_name_id.is_valid()) {
  199. Add(lib_name_id.AsStringLiteralValueId());
  200. } else {
  201. AddInvalid();
  202. }
  203. }
  204. auto Add(ImportIRId ir_id) -> void {
  205. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  206. Add(ir->package_id());
  207. Add(ir->library_id());
  208. }
  209. auto Add(ImportIRInstId ir_inst_id) -> void {
  210. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  211. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id).sem_ir, ir_inst.inst_id);
  212. }
  213. template <typename T>
  214. requires(std::same_as<T, BoolValue> ||
  215. std::same_as<T, CompileTimeBindIndex> ||
  216. std::same_as<T, ElementIndex> || std::same_as<T, FloatKind> ||
  217. std::same_as<T, IntKind> || std::same_as<T, RuntimeParamIndex>)
  218. auto Add(T arg) {
  219. // Index-like ID: just include the value directly.
  220. contents.push_back(arg.index);
  221. }
  222. template <typename T>
  223. requires(std::same_as<T, AnyRawId> || std::same_as<T, ExprRegionId> ||
  224. std::same_as<T, LocId> || std::same_as<T, RealId>)
  225. auto Add(T /*arg*/) {
  226. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  227. }
  228. // Add an instruction argument to the contents of the current instruction.
  229. template <typename... Types>
  230. auto AddWithKind(uint64_t arg, TypeEnum<Types...> kind) -> void {
  231. using AddFunction = void (*)(Worklist& worklist, uint64_t arg);
  232. using Kind = decltype(kind);
  233. // Build a lookup table to add an argument of the given kind.
  234. static constexpr std::array<AddFunction, Kind::NumTypes + 2> Table = [] {
  235. std::array<AddFunction, Kind::NumTypes + 2> table;
  236. table[Kind::None.ToIndex()] = [](Worklist& /*worklist*/,
  237. uint64_t /*arg*/) {};
  238. table[Kind::Invalid.ToIndex()] = [](Worklist& /*worklist*/,
  239. uint64_t /*arg*/) {
  240. CARBON_FATAL("Unexpected invalid argument kind");
  241. };
  242. ((table[Kind::template For<Types>.ToIndex()] =
  243. [](Worklist& worklist, uint64_t arg) {
  244. return worklist.Add(Inst::FromRaw<Types>(arg));
  245. }),
  246. ...);
  247. return table;
  248. }();
  249. Table[kind.ToIndex()](*this, arg);
  250. }
  251. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  252. // re-lookup, returns the fingerprint of the first instruction on the todo
  253. // list, and requires the todo list to be non-empty.
  254. auto Run() -> uint64_t {
  255. CARBON_CHECK(!todo.empty());
  256. while (true) {
  257. const size_t init_size = todo.size();
  258. auto [next_sem_ir, next_inst_id_or_block] = todo.back();
  259. sem_ir = next_sem_ir;
  260. contents.clear();
  261. if (auto* inst_block_id =
  262. std::get_if<InstBlockId>(&next_inst_id_or_block)) {
  263. // Add all the instructions in the block so they all contribute to the
  264. // `contents`.
  265. Add(*inst_block_id);
  266. // If we didn't add any more work, then we have a fingerprint for the
  267. // instruction block, otherwise we wait until that work is completed. If
  268. // the block is the last thing in `todo`, we return the fingerprint.
  269. // Otherwise we would just discard it because we don't currently cache
  270. // the fingerprint for blocks, but we really only expect `InstBlockId`
  271. // to be at the bottom of the `todo` stack since they are not added to
  272. // `todo` during Run().
  273. if (todo.size() == init_size) {
  274. auto fingerprint = Finish();
  275. todo.pop_back();
  276. CARBON_CHECK(todo.empty(),
  277. "An InstBlockId was inserted into `todo` during Run()");
  278. return fingerprint;
  279. }
  280. // Move on to processing the instructions in the block; we will come
  281. // back to this branch once they are done.
  282. continue;
  283. }
  284. auto next_inst_id = std::get<InstId>(next_inst_id_or_block);
  285. // If we already have a fingerprint for this instruction, we have nothing
  286. // to do. Just pop it from `todo`.
  287. if (auto lookup =
  288. fingerprints->Lookup(std::pair(next_sem_ir, next_inst_id))) {
  289. todo.pop_back();
  290. if (todo.empty()) {
  291. return lookup.value();
  292. }
  293. continue;
  294. }
  295. // Keep this instruction in `todo` for now. If we add more work, we'll
  296. // finish that work and process this instruction again, and if not, we'll
  297. // pop the instruction at the end of the loop.
  298. auto inst = next_sem_ir->insts().Get(next_inst_id);
  299. auto [arg0_kind, arg1_kind] = inst.ArgKinds();
  300. // Add the instruction's fields to the contents.
  301. Add(inst.kind());
  302. // Don't include the type if it's `type` or `<error>`, because those types
  303. // are self-referential.
  304. if (inst.type_id() != TypeType::SingletonTypeId &&
  305. inst.type_id() != ErrorInst::SingletonTypeId) {
  306. Add(inst.type_id());
  307. }
  308. AddWithKind(inst.arg0(), arg0_kind);
  309. AddWithKind(inst.arg1(), arg1_kind);
  310. // If we didn't add any work, we have a fingerprint for this instruction;
  311. // pop it from the todo list. Otherwise, we leave it on the todo list so
  312. // we can compute its fingerprint once we've finished the work we added.
  313. if (todo.size() == init_size) {
  314. uint64_t fingerprint = Finish();
  315. fingerprints->Insert(std::pair(next_sem_ir, next_inst_id), fingerprint);
  316. todo.pop_back();
  317. if (todo.empty()) {
  318. return fingerprint;
  319. }
  320. }
  321. }
  322. }
  323. };
  324. } // namespace
  325. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  326. -> uint64_t {
  327. Worklist worklist = {.todo = {{file, inst_id}},
  328. .fingerprints = &fingerprints_};
  329. return worklist.Run();
  330. }
  331. auto InstFingerprinter::GetOrCompute(const File* file,
  332. InstBlockId inst_block_id) -> uint64_t {
  333. Worklist worklist = {.todo = {{file, inst_block_id}},
  334. .fingerprints = &fingerprints_};
  335. return worklist.Run();
  336. }
  337. } // namespace Carbon::SemIR