inst_fingerprinter.cpp 14 KB

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