inst_fingerprinter.cpp 18 KB

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