inst_fingerprinter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. if (!sem_ir->name_scopes().IsPackage(name_scope_id) &&
  177. 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(ClassId class_id) -> void {
  202. AddEntity(sem_ir->classes().Get(class_id));
  203. }
  204. auto Add(VtableId vtable_id) -> void {
  205. const auto& vtable = sem_ir->vtables().Get(vtable_id);
  206. if (vtable.class_id.has_value()) {
  207. Add(vtable.class_id);
  208. }
  209. Add(vtable.virtual_functions_id);
  210. }
  211. auto Add(InterfaceId interface_id) -> void {
  212. AddEntity(sem_ir->interfaces().Get(interface_id));
  213. }
  214. auto Add(NamedConstraintId named_constraint_id) -> void {
  215. AddEntity(sem_ir->named_constraints().Get(named_constraint_id));
  216. }
  217. auto Add(RequireImplsId require_id) -> void {
  218. CARBON_CHECK(require_id.has_value());
  219. const auto& require = sem_ir->require_impls().Get(require_id);
  220. Add(sem_ir->constant_values().Get(require.self_id));
  221. Add(sem_ir->constant_values().Get(require.facet_type_inst_id));
  222. contents.push_back(require.extend_self);
  223. Add(require.parent_scope_id);
  224. }
  225. auto Add(AssociatedConstantId assoc_const_id) -> void {
  226. AddEntity<AssociatedConstant>(
  227. sem_ir->associated_constants().Get(assoc_const_id));
  228. }
  229. auto Add(ImplId impl_id) -> void {
  230. if (!impl_id.has_value()) {
  231. AddInvalid();
  232. return;
  233. }
  234. const auto& impl = sem_ir->impls().Get(impl_id);
  235. Add(sem_ir->constant_values().Get(impl.self_id));
  236. Add(sem_ir->constant_values().Get(impl.constraint_id));
  237. Add(impl.parent_scope_id);
  238. }
  239. auto Add(DeclInstBlockId /*block_id*/) -> void {
  240. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  241. // decl block don't change the identity of the declaration.
  242. }
  243. auto Add(LabelId /*block_id*/) -> void {
  244. CARBON_FATAL("Should never fingerprint a label");
  245. }
  246. auto Add(FacetTypeId facet_type_id) -> void {
  247. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  248. auto add_constraints = [&](auto constraints) {
  249. contents.push_back(constraints.size());
  250. for (auto [first, second] : constraints) {
  251. Add(first);
  252. Add(second);
  253. }
  254. };
  255. add_constraints(facet_type.extend_constraints);
  256. add_constraints(facet_type.self_impls_constraints);
  257. add_constraints(facet_type.rewrite_constraints);
  258. contents.push_back(facet_type.builtin_constraint_mask.AsInt());
  259. contents.push_back(facet_type.other_requirements);
  260. }
  261. auto Add(GenericId generic_id) -> void {
  262. if (!generic_id.has_value()) {
  263. AddInvalid();
  264. return;
  265. }
  266. Add(sem_ir->generics().Get(generic_id).decl_id);
  267. }
  268. auto Add(SpecificId specific_id) -> void {
  269. if (!specific_id.has_value()) {
  270. AddInvalid();
  271. return;
  272. }
  273. const auto& specific = sem_ir->specifics().Get(specific_id);
  274. Add(specific.generic_id);
  275. Add(specific.args_id);
  276. }
  277. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  278. if (!specific_interface_id.has_value()) {
  279. AddInvalid();
  280. return;
  281. }
  282. const auto& interface =
  283. sem_ir->specific_interfaces().Get(specific_interface_id);
  284. Add(interface.interface_id);
  285. Add(interface.specific_id);
  286. }
  287. auto Add(const llvm::APInt& value) -> void {
  288. unsigned width = value.getBitWidth();
  289. contents.push_back(width);
  290. for (auto word : llvm::seq((width + 63) / 64)) {
  291. // TODO: Is there a better way to copy the words from an APInt?
  292. unsigned start = 64 * word;
  293. contents.push_back(
  294. value.extractBitsAsZExtValue(std::min(64U, width - start), start));
  295. }
  296. }
  297. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  298. auto Add(FloatId float_id) -> void {
  299. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  300. }
  301. auto Add(RealId real_id) -> void {
  302. const auto& real = sem_ir->reals().Get(real_id);
  303. Add(real.mantissa);
  304. Add(real.exponent);
  305. contents.push_back(real.is_decimal);
  306. }
  307. auto Add(PackageNameId package_id) -> void {
  308. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  309. AddString(sem_ir->identifiers().Get(ident_id));
  310. } else {
  311. // TODO: May collide with a user package of the same name. Consider using
  312. // a different value.
  313. AddString(package_id.AsSpecialName());
  314. }
  315. }
  316. auto Add(LibraryNameId lib_name_id) -> void {
  317. if (lib_name_id == LibraryNameId::Default) {
  318. AddString("");
  319. } else if (lib_name_id == LibraryNameId::Error) {
  320. AddString("<error>");
  321. } else if (lib_name_id.has_value()) {
  322. Add(lib_name_id.AsStringLiteralValueId());
  323. } else {
  324. AddInvalid();
  325. }
  326. }
  327. auto Add(ImportIRId ir_id) -> void {
  328. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  329. Add(ir->package_id());
  330. Add(ir->library_id());
  331. }
  332. auto Add(ImportIRInstId ir_inst_id) -> void {
  333. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  334. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  335. ir_inst.inst_id());
  336. }
  337. template <typename T>
  338. requires(SameAsOneOf<T, BoolValue, CharId, CompileTimeBindIndex,
  339. ElementIndex, FloatKind, IntKind, CallParamIndex>)
  340. auto Add(T arg) -> void {
  341. // Index-like ID: just include the value directly.
  342. contents.push_back(arg.index);
  343. }
  344. template <typename T>
  345. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId>)
  346. auto Add(T /*arg*/) -> void {
  347. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  348. }
  349. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  350. // Returns the arg handler for an `IdKind`.
  351. template <typename... Types>
  352. static auto GetAddFn(TypeEnum<Types...> id_kind) -> AddFnT* {
  353. static constexpr std::array<AddFnT*, IdKind::NumValues> Table = {
  354. [](Worklist& worklist, int32_t arg) {
  355. worklist.Add(Inst::FromRaw<Types>(arg));
  356. }...,
  357. // Invalid and None handling (ordering-sensitive).
  358. [](auto...) { CARBON_FATAL("Unexpected invalid IdKind"); },
  359. [](auto...) {},
  360. };
  361. return Table[id_kind.ToIndex()];
  362. }
  363. // Add an instruction argument to the contents of the current instruction.
  364. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  365. GetAddFn(arg.kind())(*this, arg.value());
  366. }
  367. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  368. // re-lookup, returns the fingerprint of the first instruction on the todo
  369. // list, and requires the todo list to be non-empty.
  370. auto Run() -> uint64_t {
  371. CARBON_CHECK(!todo.empty());
  372. while (true) {
  373. const size_t init_size = todo.size();
  374. auto [next_sem_ir, next] = todo.back();
  375. sem_ir = next_sem_ir;
  376. contents.clear();
  377. if (!std::holds_alternative<InstId>(next)) {
  378. // Add the contents of the `next` instruction so they all contribute to
  379. // the `contents`.
  380. CARBON_KIND_SWITCH(next) {
  381. case CARBON_KIND(InstId _):
  382. CARBON_FATAL("InstId is checked for above.");
  383. case CARBON_KIND(ImplId impl_id):
  384. Add(impl_id);
  385. break;
  386. case CARBON_KIND(InstBlockId inst_block_id):
  387. Add(inst_block_id);
  388. break;
  389. case CARBON_KIND(CppOverloadSetId overload_set_id):
  390. Add(overload_set_id);
  391. break;
  392. }
  393. // If we didn't add any more work, then we have a fingerprint for the
  394. // `next` instruction, otherwise we wait until that work is completed.
  395. // If the `next` is the last thing in `todo`, we return the fingerprint.
  396. // Otherwise we would just discard it because we don't currently cache
  397. // the fingerprint for things other than `InstId`, but we really only
  398. // expect other `next` types to be at the bottom of the `todo` stack
  399. // since they are not added to `todo` during Run().
  400. if (todo.size() == init_size) {
  401. auto fingerprint = Finish();
  402. todo.pop_back();
  403. CARBON_CHECK(todo.empty(),
  404. "A non-InstId was inserted into `todo` during Run()");
  405. return fingerprint;
  406. }
  407. // Move on to processing the instructions added above; we will come
  408. // back to this branch once they are done.
  409. continue;
  410. }
  411. auto next_inst_id = std::get<InstId>(next);
  412. // If we already have a fingerprint for this instruction, we have nothing
  413. // to do. Just pop it from `todo`.
  414. if (auto fingerprint = GetFingerprint(next_sem_ir, next_inst_id)) {
  415. todo.pop_back();
  416. if (todo.empty()) {
  417. return fingerprint;
  418. }
  419. continue;
  420. }
  421. // Keep this instruction in `todo` for now. If we add more work, we'll
  422. // finish that work and process this instruction again, and if not, we'll
  423. // pop the instruction at the end of the loop.
  424. auto inst = next_sem_ir->insts().Get(next_inst_id);
  425. // Add the instruction's fields to the contents.
  426. Add(inst.kind());
  427. // Don't include the type if it's `type` or `<error>`, because those types
  428. // are self-referential.
  429. if (inst.type_id() != TypeType::TypeId &&
  430. inst.type_id() != ErrorInst::TypeId) {
  431. Add(inst.type_id());
  432. }
  433. AddWithKind(inst.arg0_and_kind());
  434. AddWithKind(inst.arg1_and_kind());
  435. // If we didn't add any work, we have a fingerprint for this instruction;
  436. // pop it from the todo list. Otherwise, we leave it on the todo list so
  437. // we can compute its fingerprint once we've finished the work we added.
  438. if (todo.size() == init_size) {
  439. uint64_t fingerprint = Finish();
  440. SetFingerprint(next_sem_ir, next_inst_id, fingerprint);
  441. todo.pop_back();
  442. if (todo.empty()) {
  443. return fingerprint;
  444. }
  445. }
  446. }
  447. }
  448. };
  449. } // namespace
  450. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  451. -> uint64_t {
  452. Worklist worklist = {.todo = {{file, inst_id}},
  453. .fingerprints = &fingerprints_};
  454. return worklist.Run();
  455. }
  456. auto InstFingerprinter::GetOrCompute(const File* file,
  457. InstBlockId inst_block_id) -> uint64_t {
  458. Worklist worklist = {.todo = {{file, inst_block_id}},
  459. .fingerprints = &fingerprints_};
  460. return worklist.Run();
  461. }
  462. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  463. -> uint64_t {
  464. Worklist worklist = {.todo = {{file, impl_id}},
  465. .fingerprints = &fingerprints_};
  466. return worklist.Run();
  467. }
  468. auto InstFingerprinter::GetOrCompute(const File* file,
  469. CppOverloadSetId overload_set_id)
  470. -> uint64_t {
  471. Worklist worklist = {.todo = {{file, overload_set_id}},
  472. .fingerprints = &fingerprints_};
  473. return worklist.Run();
  474. }
  475. } // namespace Carbon::SemIR