inst_namer.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. #ifndef CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_
  6. #include "common/type_enum.h"
  7. #include "llvm/Support/raw_ostream.h"
  8. #include "toolchain/lex/tokenized_buffer.h"
  9. #include "toolchain/parse/tree.h"
  10. #include "toolchain/sem_ir/file.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/inst_categories.h"
  13. #include "toolchain/sem_ir/inst_fingerprinter.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::SemIR {
  16. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  17. //
  18. // If `<unexpected>` occurs in output of valid SemIR, it often means the
  19. // instruction needs to be handled by `NamingContext::NameInst` (see the cpp
  20. // file). Note that `<unexpected>` can occur in invalid SemIR just because we're
  21. // unable to correctly walk the SemIR.
  22. class InstNamer {
  23. public:
  24. // int32_t matches the input value size.
  25. enum class ScopeId : int32_t {
  26. None = -1,
  27. // The top-level scopes.
  28. File = 0,
  29. Generated = 1,
  30. Imports = 2,
  31. Constants = 3,
  32. // The first entity scope; see entities in `ScopeIdTypeEnum`.
  33. FirstEntityScope = 4,
  34. };
  35. static_assert(sizeof(ScopeId) == sizeof(AnyIdBase));
  36. // A wrapper around InterfaceId for dealing with the interface-with-self scope
  37. // nested within the interface entity's scope.
  38. struct InterfaceWithSelfId {
  39. static constexpr llvm::StringLiteral Label = "interface_with_self";
  40. InterfaceId id;
  41. };
  42. // A wrapper around NamedConstraintId for dealing with the
  43. // constraint-with-self scope nested within the constraint entity's scope.
  44. struct NamedConstraintWithSelfId {
  45. static constexpr llvm::StringLiteral Label = "constraint_with_self";
  46. NamedConstraintId id;
  47. };
  48. // Entities whose scopes get entries from `ScopeId`.
  49. using ScopeIdTypeEnum =
  50. TypeEnum<AssociatedConstantId, ClassId, CppOverloadSetId, FunctionId,
  51. ImplId, InterfaceId, InterfaceWithSelfId, NamedConstraintId,
  52. NamedConstraintWithSelfId, RequireImplsId, SpecificInterfaceId,
  53. VtableId>;
  54. // Construct the instruction namer, and assign names to all instructions in
  55. // the provided file.
  56. explicit InstNamer(const File* sem_ir, int total_ir_count);
  57. // Returns the scope ID corresponding to an ID of a function, class,
  58. // interface, or named constraint.
  59. template <typename IdT>
  60. requires ScopeIdTypeEnum::Contains<IdT>
  61. auto GetScopeFor(IdT id) const -> ScopeId {
  62. int32_t index;
  63. if constexpr (std::is_same_v<IdT, ClassId>) {
  64. index = sem_ir_->classes().GetRawIndex(id);
  65. } else if constexpr (std::is_same_v<IdT, CppOverloadSetId>) {
  66. index = sem_ir_->cpp_overload_sets().GetRawIndex(id);
  67. } else if constexpr (std::is_same_v<IdT, AssociatedConstantId>) {
  68. index = sem_ir_->associated_constants().GetRawIndex(id);
  69. } else if constexpr (std::is_same_v<IdT, FunctionId>) {
  70. index = sem_ir_->functions().GetRawIndex(id);
  71. } else if constexpr (std::is_same_v<IdT, ImplId>) {
  72. index = sem_ir_->impls().GetRawIndex(id);
  73. } else if constexpr (std::is_same_v<IdT, InterfaceId>) {
  74. index = sem_ir_->interfaces().GetRawIndex(id);
  75. } else if constexpr (std::is_same_v<IdT, InterfaceWithSelfId>) {
  76. index = sem_ir_->interfaces().GetRawIndex(id.id);
  77. } else if constexpr (std::is_same_v<IdT, NamedConstraintId>) {
  78. index = sem_ir_->named_constraints().GetRawIndex(id);
  79. } else if constexpr (std::is_same_v<IdT, NamedConstraintWithSelfId>) {
  80. index = sem_ir_->named_constraints().GetRawIndex(id.id);
  81. } else if constexpr (std::is_same_v<IdT, RequireImplsId>) {
  82. index = sem_ir_->require_impls().GetRawIndex(id);
  83. } else if constexpr (std::is_same_v<IdT, SpecificInterfaceId>) {
  84. index = sem_ir_->specific_interfaces().GetRawIndex(id);
  85. } else if constexpr (std::is_same_v<IdT, VtableId>) {
  86. index = sem_ir_->vtables().GetRawIndex(id);
  87. } else {
  88. index = id.index;
  89. }
  90. return static_cast<ScopeId>(GetScopeIdOffset(ScopeIdTypeEnum::For<IdT>) +
  91. index);
  92. }
  93. // Returns the scope ID corresponding to a generic. A generic object shares
  94. // its scope with its generic entity.
  95. auto GetScopeFor(GenericId id) const -> ScopeId {
  96. return generic_scopes_[sem_ir_->generics().GetRawIndex(id)];
  97. }
  98. // Returns the IR name for the specified scope.
  99. auto GetScopeName(ScopeId scope) const -> std::string;
  100. // Returns the name for a parent NameScope. Does not return a name for
  101. // namespaces. Used as part of naming functions with their containing scope.
  102. auto GetNameForParentNameScope(NameScopeId name_scope_id) -> llvm::StringRef;
  103. // Returns the IR name to use for a function, class, interface, etc.
  104. template <typename IdT>
  105. requires(ScopeIdTypeEnum::Contains<IdT> || std::same_as<IdT, GenericId>)
  106. auto GetNameFor(IdT id) const -> std::string {
  107. if (!id.has_value()) {
  108. return "invalid";
  109. }
  110. return GetScopeName(GetScopeFor(id));
  111. }
  112. // Returns the IR name to use for an instruction within its own scope, without
  113. // any prefix. Returns an empty string if there isn't a good name.
  114. auto GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef;
  115. // Returns the IR name to use for an instruction, when referenced from a given
  116. // scope.
  117. auto GetNameFor(ScopeId scope_id, InstId inst_id) const -> std::string;
  118. // Returns the IR name to use for a label within its own scope, without any
  119. // prefix. Returns an empty string if there isn't a good name.
  120. auto GetUnscopedLabelFor(InstBlockId block_id) const -> llvm::StringRef;
  121. // Returns the IR name to use for a label, when referenced from a given scope.
  122. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) const -> std::string;
  123. // Returns true if the instruction has a specific name assigned.
  124. auto has_name(InstId inst_id) const -> bool;
  125. private:
  126. // A space in which unique names can be allocated.
  127. class Namespace {
  128. private:
  129. // A result of a name lookup.
  130. struct NameResult;
  131. public:
  132. // A name in a namespace, which might be redirected to refer to another name
  133. // for disambiguation purposes.
  134. class Name {
  135. public:
  136. explicit Name() : value_(nullptr) {}
  137. explicit Name(llvm::StringMap<NameResult>::iterator it,
  138. size_t base_name_size)
  139. : value_(&*it), base_name_size_(base_name_size) {}
  140. explicit operator bool() const { return value_; }
  141. // Returns the disambiguated name.
  142. auto GetFullName() const -> llvm::StringRef;
  143. // Returns the base name, without any disambiguators.
  144. auto GetBaseName() const -> llvm::StringRef;
  145. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  146. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  147. private:
  148. llvm::StringMapEntry<NameResult>* value_;
  149. // The base name length within `value_->first()`.
  150. size_t base_name_size_;
  151. };
  152. // Allocates and returns a name, handling ambiguity.
  153. auto AllocateName(const InstNamer& inst_namer,
  154. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  155. std::string name) -> Name;
  156. private:
  157. struct NameResult {
  158. bool ambiguous = false;
  159. Name fallback = Name();
  160. };
  161. llvm::StringMap<NameResult> allocated_;
  162. };
  163. // A named scope that contains named entities.
  164. struct Scope {
  165. Namespace::Name name;
  166. Namespace insts;
  167. Namespace labels;
  168. };
  169. // Helper class for naming a single instruction.
  170. class NamingContext;
  171. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  172. return scopes_[static_cast<int>(scope_id)];
  173. }
  174. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  175. return scopes_[static_cast<int>(scope_id)];
  176. }
  177. // For the given `IdT`, returns its start offset in the `ScopeId` space. Each
  178. // of `ScopeIdTypeEnum` is stored sequentially. When called with
  179. // `ScopeIdTypeEnum::None`, returns the full count of scopes.
  180. auto GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int;
  181. auto AddBlockLabel(
  182. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  183. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  184. -> void;
  185. // Finds and adds a suitable block label for the given SemIR instruction that
  186. // represents some kind of branch.
  187. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  188. // Adds a scope and instructions to walk. Avoids recursion while allowing
  189. // the loop to below add more instructions during iteration. The new
  190. // instructions are pushed such that they will be the next to be walked.
  191. // Internally that means they are reversed and added to the end of the vector,
  192. // since we pop from the back of the vector.
  193. auto PushBlockInsts(ScopeId scope_id, llvm::ArrayRef<InstId> inst_ids)
  194. -> void;
  195. auto PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void;
  196. // Pushes generic information for an entity.
  197. auto PushGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  198. // Names an entity, and pushes processing of its blocks.
  199. auto PushEntity(AssociatedConstantId associated_constant_id, ScopeId scope_id,
  200. Scope& scope) -> void;
  201. auto PushEntity(ClassId class_id, ScopeId scope_id, Scope& scope) -> void;
  202. auto PushEntity(FunctionId function_id, ScopeId scope_id, Scope& scope)
  203. -> void;
  204. auto PushEntity(CppOverloadSetId cpp_overload_set_id, ScopeId scope_id,
  205. Scope& scope) -> void;
  206. auto PushEntity(ImplId impl_id, ScopeId scope_id, Scope& scope) -> void;
  207. auto PushEntity(InterfaceId interface_id, ScopeId scope_id, Scope& scope)
  208. -> void;
  209. auto PushEntity(InterfaceWithSelfId interface_id, ScopeId scope_id,
  210. Scope& scope) -> void;
  211. auto PushEntity(NamedConstraintId named_constraint_id, ScopeId scope_id,
  212. Scope& scope) -> void;
  213. auto PushEntity(NamedConstraintWithSelfId named_constraint_id,
  214. ScopeId scope_id, Scope& scope) -> void;
  215. auto PushEntity(RequireImplsId require_impls_id, ScopeId scope_id,
  216. Scope& scope) -> void;
  217. auto PushEntity(VtableId vtable_id, ScopeId scope_id, Scope& scope) -> void;
  218. // Always returns the name of the entity. May push it if it has not yet been
  219. // pushed.
  220. template <typename EntityIdT>
  221. auto MaybePushEntity(EntityIdT entity_id) -> llvm::StringRef {
  222. auto scope_id = GetScopeFor(entity_id);
  223. auto& scope = GetScopeInfo(scope_id);
  224. if (!scope.name) {
  225. PushEntity(entity_id, scope_id, scope);
  226. }
  227. return scope.name.GetBaseName();
  228. }
  229. const File* sem_ir_;
  230. InstFingerprinter fingerprinter_;
  231. // The namespace for entity names. Names within this namespace are prefixed
  232. // with `@` in formatted SemIR.
  233. Namespace globals_;
  234. // The enclosing scope and name for each instruction, indexed by the InstId's
  235. // index.
  236. std::vector<std::pair<ScopeId, Namespace::Name>> insts_;
  237. // The enclosing scope and name for each block that might be a branch target,
  238. // indexed by the InstBlockId's index.
  239. std::vector<std::pair<ScopeId, Namespace::Name>> labels_;
  240. // The scopes corresponding to ScopeId values.
  241. std::vector<Scope> scopes_;
  242. // The scope IDs corresponding to generics. The vector indexes are the
  243. // GenericId index.
  244. std::vector<ScopeId> generic_scopes_;
  245. // The stack of instructions to name.
  246. llvm::SmallVector<std::pair<ScopeId, InstId>> inst_stack_;
  247. // The stack of blocks to traverse.
  248. llvm::SmallVector<std::pair<ScopeId, InstBlockId>> inst_block_stack_;
  249. };
  250. } // namespace Carbon::SemIR
  251. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_