inst_fingerprinter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 <array>
  6. #include <utility>
  7. #include <variant>
  8. #include "common/concepts.h"
  9. #include "common/ostream.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StableHashing.h"
  13. #include "toolchain/base/fixed_size_value_store.h"
  14. #include "toolchain/base/kind_switch.h"
  15. #include "toolchain/base/value_ids.h"
  16. #include "toolchain/sem_ir/cpp_overload_set.h"
  17. #include "toolchain/sem_ir/entity_with_params_base.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::SemIR {
  21. namespace {
  22. struct Worklist {
  23. using FingerprintStore =
  24. FixedSizeValueStore<InstId, uint64_t, Tag<CheckIRId>>;
  25. using FilesFingerprintStores =
  26. FixedSizeValueStore<CheckIRId, FingerprintStore>;
  27. // The file containing the instruction we're currently processing.
  28. const File* sem_ir = nullptr;
  29. // The instructions we need to compute fingerprints for.
  30. llvm::SmallVector<std::pair<
  31. const File*, std::variant<InstId, InstBlockId, ImplId, CppOverloadSetId>>>
  32. todo;
  33. // The contents of the current instruction as accumulated so far. This is used
  34. // to build a Merkle tree containing a fingerprint for the current
  35. // instruction.
  36. llvm::SmallVector<llvm::stable_hash> contents = {};
  37. // Known cached instruction fingerprints. Each item in `todo` will be added to
  38. // the cache if not already present.
  39. FilesFingerprintStores* fingerprints;
  40. // Finish fingerprinting and compute the fingerprint.
  41. auto Finish() -> uint64_t { return llvm::stable_hash_combine(contents); }
  42. // Gets the known fingerprint from the cache, or returns 0.
  43. auto GetFingerprint(const File* file, InstId inst_id) -> uint64_t {
  44. auto& store = fingerprints->Get(file->check_ir_id());
  45. if (store.size() == 0) {
  46. return 0;
  47. }
  48. // These InstIds are constant values, so not in the ValueStore. We use a
  49. // constant (negative) fingerprint for them.
  50. if (inst_id == InstId::InitTombstone ||
  51. inst_id == InstId::ImplWitnessTablePlaceholder) {
  52. return inst_id.index;
  53. }
  54. return store.Get(inst_id);
  55. }
  56. // Sets the fingerprint for an instruction in the cache. Since 0 is used to
  57. // indicate empty, we map 0 to another fixed value.
  58. auto SetFingerprint(const File* file, InstId inst_id, uint64_t fingerprint) {
  59. auto& store = fingerprints->Get(file->check_ir_id());
  60. if (store.size() == 0) {
  61. store = FingerprintStore::MakeWithExplicitSize(
  62. file->insts().size(), file->insts().GetIdTag(), 0);
  63. }
  64. store.Set(inst_id, fingerprint ? fingerprint : 1);
  65. }
  66. // Add an invalid marker to the contents. This is used when the entity
  67. // contains a `None` ID. This uses an arbitrary fixed value that is assumed
  68. // to be unlikely to collide with a valid value.
  69. auto AddInvalid() -> void { contents.push_back(-1); }
  70. // Add a string to the contents.
  71. auto AddString(llvm::StringRef string) -> void {
  72. contents.push_back(llvm::stable_hash_name(string));
  73. }
  74. // Each of the following `Add` functions adds a typed argument to the contents
  75. // of the current instruction. If we don't yet have a fingerprint for the
  76. // argument, it instead adds that argument to the worklist instead.
  77. auto Add(InstKind kind) -> void {
  78. // TODO: Precompute or cache the hash of instruction IR names, or pick a
  79. // scheme that doesn't change when IR names change.
  80. AddString(kind.ir_name());
  81. }
  82. auto Add(IdentifierId ident_id) -> void {
  83. AddString(sem_ir->identifiers().Get(ident_id));
  84. }
  85. auto Add(StringLiteralValueId lit_id) -> void {
  86. AddString(sem_ir->string_literal_values().Get(lit_id));
  87. }
  88. auto Add(NameId name_id) -> void {
  89. AddString(sem_ir->names().GetIRBaseName(name_id));
  90. }
  91. auto Add(EntityNameId entity_name_id) -> void {
  92. if (!entity_name_id.has_value()) {
  93. AddInvalid();
  94. return;
  95. }
  96. const auto& entity_name = sem_ir->entity_names().Get(entity_name_id);
  97. if (entity_name.bind_index().has_value()) {
  98. Add(entity_name.bind_index());
  99. // Don't include the name. While it is part of the canonical identity of a
  100. // compile-time binding, renaming it (and its uses) is a compatible change
  101. // that we would like to not affect the fingerprint.
  102. //
  103. // Also don't include the `is_template` flag. Changing that flag should
  104. // also be a compatible change from the perspective of users of a generic.
  105. } else {
  106. Add(entity_name.name_id);
  107. }
  108. Add(entity_name.parent_scope_id);
  109. }
  110. auto AddInFile(const File* file, InstId inner_id) -> void {
  111. if (!inner_id.has_value()) {
  112. AddInvalid();
  113. return;
  114. }
  115. if (auto fingerprint = GetFingerprint(file, inner_id)) {
  116. contents.push_back(fingerprint);
  117. return;
  118. }
  119. todo.push_back({file, inner_id});
  120. }
  121. auto Add(InstId inner_id) -> void { AddInFile(sem_ir, inner_id); }
  122. auto Add(ConstantId constant_id) -> void {
  123. if (!constant_id.has_value()) {
  124. AddInvalid();
  125. return;
  126. }
  127. Add(sem_ir->constant_values().GetInstId(constant_id));
  128. }
  129. auto Add(TypeId type_id) -> void {
  130. if (!type_id.has_value()) {
  131. AddInvalid();
  132. return;
  133. }
  134. Add(sem_ir->types().GetTypeInstId(type_id));
  135. }
  136. template <typename T>
  137. auto AddBlock(llvm::ArrayRef<T> block) -> void {
  138. contents.push_back(block.size());
  139. for (auto inner_id : block) {
  140. Add(inner_id);
  141. }
  142. }
  143. auto Add(InstBlockId inst_block_id) -> void {
  144. if (!inst_block_id.has_value()) {
  145. AddInvalid();
  146. return;
  147. }
  148. AddBlock(sem_ir->inst_blocks().Get(inst_block_id));
  149. }
  150. auto Add(StructTypeField field) -> void {
  151. Add(field.name_id);
  152. Add(field.type_inst_id);
  153. }
  154. auto Add(StructTypeFieldsId struct_type_fields_id) -> void {
  155. if (!struct_type_fields_id.has_value()) {
  156. AddInvalid();
  157. return;
  158. }
  159. AddBlock(sem_ir->struct_type_fields().Get(struct_type_fields_id));
  160. }
  161. auto Add(CustomLayoutId custom_layout_id) -> void {
  162. if (!custom_layout_id.has_value()) {
  163. AddInvalid();
  164. return;
  165. }
  166. auto block = sem_ir->custom_layouts().Get(custom_layout_id);
  167. contents.push_back(block.size());
  168. for (auto size : block) {
  169. contents.push_back(size.bits());
  170. }
  171. }
  172. auto Add(NameScopeId name_scope_id) -> void {
  173. if (!name_scope_id.has_value()) {
  174. AddInvalid();
  175. return;
  176. }
  177. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  178. Add(scope.name_id());
  179. // For non-package scopes, add the parent scope.
  180. if (!scope.is_imported_package() && scope.parent_scope_id().has_value()) {
  181. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  182. }
  183. }
  184. template <typename EntityT = EntityWithParamsBase>
  185. auto AddEntity(const std::type_identity_t<EntityT>& entity) -> void {
  186. Add(entity.name_id);
  187. if (entity.parent_scope_id.has_value()) {
  188. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  189. }
  190. }
  191. auto Add(FunctionId function_id) -> void {
  192. AddEntity(sem_ir->functions().Get(function_id));
  193. }
  194. auto Add(CppOverloadSetId cpp_overload_set_id) -> void {
  195. const CppOverloadSet& cpp_overload_set =
  196. sem_ir->cpp_overload_sets().Get(cpp_overload_set_id);
  197. Add(cpp_overload_set.name_id);
  198. if (cpp_overload_set.parent_scope_id.has_value()) {
  199. Add(sem_ir->name_scopes()
  200. .Get(cpp_overload_set.parent_scope_id)
  201. .inst_id());
  202. }
  203. }
  204. auto Add(ClangDeclId /*decl_id*/) -> void {
  205. // TODO: For `CppTemplateNameType` we don't need to fingerprint the
  206. // `decl_id`, because fingerprinting the `NameId` is sufficient to identify
  207. // the template, but this won't necessarily be true for other
  208. // `ClangDeclId`s.
  209. // See also: https://github.com/carbon-language/carbon-lang/issues/6728
  210. }
  211. auto Add(ClassId class_id) -> void {
  212. AddEntity(sem_ir->classes().Get(class_id));
  213. }
  214. auto Add(VtableId vtable_id) -> void {
  215. const auto& vtable = sem_ir->vtables().Get(vtable_id);
  216. if (vtable.class_id.has_value()) {
  217. Add(vtable.class_id);
  218. }
  219. Add(vtable.virtual_functions_id);
  220. }
  221. auto Add(InterfaceId interface_id) -> void {
  222. AddEntity(sem_ir->interfaces().Get(interface_id));
  223. }
  224. auto Add(NamedConstraintId named_constraint_id) -> void {
  225. AddEntity(sem_ir->named_constraints().Get(named_constraint_id));
  226. }
  227. auto Add(RequireImplsId require_id) -> void {
  228. CARBON_CHECK(require_id.has_value());
  229. const auto& require = sem_ir->require_impls().Get(require_id);
  230. Add(sem_ir->constant_values().Get(require.self_id));
  231. Add(sem_ir->constant_values().Get(require.facet_type_inst_id));
  232. contents.push_back(require.extend_self);
  233. Add(require.parent_scope_id);
  234. }
  235. auto Add(AssociatedConstantId assoc_const_id) -> void {
  236. AddEntity<AssociatedConstant>(
  237. sem_ir->associated_constants().Get(assoc_const_id));
  238. }
  239. auto Add(ImplId impl_id) -> void {
  240. if (!impl_id.has_value()) {
  241. AddInvalid();
  242. return;
  243. }
  244. const auto& impl = sem_ir->impls().Get(impl_id);
  245. Add(sem_ir->constant_values().Get(impl.self_id));
  246. Add(sem_ir->constant_values().Get(impl.constraint_id));
  247. Add(impl.parent_scope_id);
  248. }
  249. auto Add(DeclInstBlockId /*block_id*/) -> void {
  250. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  251. // decl block don't change the identity of the declaration.
  252. }
  253. auto Add(LabelId /*block_id*/) -> void {
  254. CARBON_FATAL("Should never fingerprint a label");
  255. }
  256. auto Add(FacetTypeId facet_type_id) -> void {
  257. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  258. auto add_constraints = [&](auto constraints) {
  259. contents.push_back(constraints.size());
  260. for (auto [first, second] : constraints) {
  261. Add(first);
  262. Add(second);
  263. }
  264. };
  265. add_constraints(facet_type.extend_constraints);
  266. add_constraints(facet_type.self_impls_constraints);
  267. add_constraints(facet_type.rewrite_constraints);
  268. contents.push_back(facet_type.other_requirements);
  269. }
  270. auto Add(GenericId generic_id) -> void {
  271. if (!generic_id.has_value()) {
  272. AddInvalid();
  273. return;
  274. }
  275. Add(sem_ir->generics().Get(generic_id).decl_id);
  276. }
  277. auto Add(SpecificId specific_id) -> void {
  278. if (!specific_id.has_value()) {
  279. AddInvalid();
  280. return;
  281. }
  282. const auto& specific = sem_ir->specifics().Get(specific_id);
  283. Add(specific.generic_id);
  284. Add(specific.args_id);
  285. }
  286. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  287. if (!specific_interface_id.has_value()) {
  288. AddInvalid();
  289. return;
  290. }
  291. const auto& interface =
  292. sem_ir->specific_interfaces().Get(specific_interface_id);
  293. Add(interface.interface_id);
  294. Add(interface.specific_id);
  295. }
  296. auto Add(const llvm::APInt& value) -> void {
  297. contents.push_back(value.getBitWidth());
  298. contents.append(value.getRawData(),
  299. value.getRawData() + value.getNumWords());
  300. }
  301. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  302. auto Add(FloatId float_id) -> void {
  303. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  304. }
  305. auto Add(RealId real_id) -> void {
  306. const auto& real = sem_ir->reals().Get(real_id);
  307. Add(real.mantissa);
  308. Add(real.exponent);
  309. contents.push_back(real.is_decimal);
  310. }
  311. auto Add(PackageNameId package_id) -> void {
  312. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  313. AddString(sem_ir->identifiers().Get(ident_id));
  314. } else {
  315. // TODO: May collide with a user package of the same name. Consider using
  316. // a different value.
  317. AddString(package_id.AsSpecialName());
  318. }
  319. }
  320. auto Add(LibraryNameId lib_name_id) -> void {
  321. if (lib_name_id == LibraryNameId::Default) {
  322. AddString("");
  323. } else if (lib_name_id == LibraryNameId::Error) {
  324. AddString("<error>");
  325. } else if (lib_name_id.has_value()) {
  326. Add(lib_name_id.AsStringLiteralValueId());
  327. } else {
  328. AddInvalid();
  329. }
  330. }
  331. auto Add(ImportIRId ir_id) -> void {
  332. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  333. Add(ir->package_id());
  334. Add(ir->library_id());
  335. }
  336. auto Add(ImportIRInstId ir_inst_id) -> void {
  337. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  338. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  339. ir_inst.inst_id());
  340. }
  341. template <typename T>
  342. requires(SameAsOneOf<T, BoolValue, CharId, CompileTimeBindIndex,
  343. ElementIndex, FloatKind, IntKind, CallParamIndex>)
  344. auto Add(T arg) -> void {
  345. // Index-like ID: just include the value directly.
  346. contents.push_back(arg.index);
  347. }
  348. template <typename T>
  349. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId>)
  350. auto Add(T /*arg*/) -> void {
  351. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  352. }
  353. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  354. // Returns the arg handler for an `IdKind`.
  355. template <typename... Types>
  356. static auto GetAddFn(TypeEnum<Types...> id_kind) -> AddFnT* {
  357. static constexpr std::array<AddFnT*, IdKind::NumValues> Table = {
  358. [](Worklist& worklist, int32_t arg) {
  359. worklist.Add(Inst::FromRaw<Types>(arg));
  360. }...,
  361. // Invalid and None handling (ordering-sensitive).
  362. [](auto...) { CARBON_FATAL("Unexpected invalid IdKind"); },
  363. [](auto...) {},
  364. };
  365. return Table[id_kind.ToIndex()];
  366. }
  367. // Add an instruction argument to the contents of the current instruction.
  368. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  369. GetAddFn(arg.kind())(*this, arg.value());
  370. }
  371. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  372. // re-lookup, returns the fingerprint of the first instruction on the todo
  373. // list, and requires the todo list to be non-empty.
  374. auto Run() -> uint64_t {
  375. CARBON_CHECK(!todo.empty());
  376. while (true) {
  377. const size_t init_size = todo.size();
  378. auto [next_sem_ir, next] = todo.back();
  379. sem_ir = next_sem_ir;
  380. contents.clear();
  381. if (!std::holds_alternative<InstId>(next)) {
  382. // Add the contents of the `next` instruction so they all contribute to
  383. // the `contents`.
  384. CARBON_KIND_SWITCH(next) {
  385. case CARBON_KIND(InstId _):
  386. CARBON_FATAL("InstId is checked for above.");
  387. case CARBON_KIND(ImplId impl_id):
  388. Add(impl_id);
  389. break;
  390. case CARBON_KIND(InstBlockId inst_block_id):
  391. Add(inst_block_id);
  392. break;
  393. case CARBON_KIND(CppOverloadSetId overload_set_id):
  394. Add(overload_set_id);
  395. break;
  396. }
  397. // If we didn't add any more work, then we have a fingerprint for the
  398. // `next` instruction, otherwise we wait until that work is completed.
  399. // If the `next` is the last thing in `todo`, we return the fingerprint.
  400. // Otherwise we would just discard it because we don't currently cache
  401. // the fingerprint for things other than `InstId`, but we really only
  402. // expect other `next` types to be at the bottom of the `todo` stack
  403. // since they are not added to `todo` during Run().
  404. if (todo.size() == init_size) {
  405. auto fingerprint = Finish();
  406. todo.pop_back();
  407. CARBON_CHECK(todo.empty(),
  408. "A non-InstId was inserted into `todo` during Run()");
  409. return fingerprint;
  410. }
  411. // Move on to processing the instructions added above; we will come
  412. // back to this branch once they are done.
  413. continue;
  414. }
  415. auto next_inst_id = std::get<InstId>(next);
  416. // If we already have a fingerprint for this instruction, we have nothing
  417. // to do. Just pop it from `todo`.
  418. if (auto fingerprint = GetFingerprint(next_sem_ir, next_inst_id)) {
  419. todo.pop_back();
  420. if (todo.empty()) {
  421. return fingerprint;
  422. }
  423. continue;
  424. }
  425. // Keep this instruction in `todo` for now. If we add more work, we'll
  426. // finish that work and process this instruction again, and if not, we'll
  427. // pop the instruction at the end of the loop.
  428. auto inst = next_sem_ir->insts().Get(next_inst_id);
  429. // Add the instruction's fields to the contents.
  430. Add(inst.kind());
  431. // Don't include the type if it's `type` or `<error>`, because those types
  432. // are self-referential.
  433. if (inst.type_id() != TypeType::TypeId &&
  434. inst.type_id() != ErrorInst::TypeId) {
  435. Add(inst.type_id());
  436. }
  437. AddWithKind(inst.arg0_and_kind());
  438. AddWithKind(inst.arg1_and_kind());
  439. // If we didn't add any work, we have a fingerprint for this instruction;
  440. // pop it from the todo list. Otherwise, we leave it on the todo list so
  441. // we can compute its fingerprint once we've finished the work we added.
  442. if (todo.size() == init_size) {
  443. uint64_t fingerprint = Finish();
  444. SetFingerprint(next_sem_ir, next_inst_id, fingerprint);
  445. todo.pop_back();
  446. if (todo.empty()) {
  447. return fingerprint;
  448. }
  449. }
  450. }
  451. }
  452. };
  453. } // namespace
  454. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  455. -> uint64_t {
  456. Worklist worklist = {.todo = {{file, inst_id}},
  457. .fingerprints = &fingerprints_};
  458. return worklist.Run();
  459. }
  460. auto InstFingerprinter::GetOrCompute(const File* file,
  461. InstBlockId inst_block_id) -> uint64_t {
  462. Worklist worklist = {.todo = {{file, inst_block_id}},
  463. .fingerprints = &fingerprints_};
  464. return worklist.Run();
  465. }
  466. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  467. -> uint64_t {
  468. Worklist worklist = {.todo = {{file, impl_id}},
  469. .fingerprints = &fingerprints_};
  470. return worklist.Run();
  471. }
  472. auto InstFingerprinter::GetOrCompute(const File* file,
  473. CppOverloadSetId overload_set_id)
  474. -> uint64_t {
  475. Worklist worklist = {.todo = {{file, overload_set_id}},
  476. .fingerprints = &fingerprints_};
  477. return worklist.Run();
  478. }
  479. } // namespace Carbon::SemIR