inst_fingerprinter.cpp 17 KB

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