inst_namer.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 "llvm/Support/raw_ostream.h"
  7. #include "toolchain/lex/tokenized_buffer.h"
  8. #include "toolchain/parse/tree.h"
  9. #include "toolchain/sem_ir/file.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/inst_fingerprinter.h"
  12. namespace Carbon::SemIR {
  13. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  14. class InstNamer {
  15. public:
  16. // int32_t matches the input value size.
  17. enum class ScopeId : int32_t {
  18. None = -1,
  19. File = 0,
  20. ImportRefs = 1,
  21. Constants = 2,
  22. FirstFunction = 3,
  23. };
  24. static_assert(sizeof(ScopeId) == sizeof(FunctionId));
  25. struct NumberOfScopesTag {};
  26. // Construct the instruction namer, and assign names to all instructions in
  27. // the provided file.
  28. explicit InstNamer(const File* sem_ir);
  29. // Returns the scope ID corresponding to an ID of a function, class, or
  30. // interface.
  31. template <typename IdT>
  32. auto GetScopeFor(IdT id) const -> ScopeId {
  33. auto index = static_cast<int32_t>(ScopeId::FirstFunction);
  34. if constexpr (!std::same_as<FunctionId, IdT>) {
  35. index += sem_ir_->functions().size();
  36. if constexpr (!std::same_as<ClassId, IdT>) {
  37. index += sem_ir_->classes().size();
  38. if constexpr (!std::same_as<InterfaceId, IdT>) {
  39. index += sem_ir_->interfaces().size();
  40. if constexpr (!std::same_as<AssociatedConstantId, IdT>) {
  41. index += sem_ir_->associated_constants().size();
  42. if constexpr (!std::same_as<ImplId, IdT>) {
  43. index += sem_ir_->impls().size();
  44. if constexpr (!std::same_as<SpecificInterfaceId, IdT>) {
  45. index += sem_ir_->specific_interfaces().size();
  46. static_assert(std::same_as<NumberOfScopesTag, IdT>,
  47. "Unknown ID kind for scope");
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. if constexpr (!std::same_as<NumberOfScopesTag, IdT>) {
  55. index += id.index;
  56. }
  57. return static_cast<ScopeId>(index);
  58. }
  59. // Returns the scope ID corresponding to a generic. A generic object shares
  60. // its scope with its generic entity.
  61. auto GetScopeFor(GenericId id) const -> ScopeId {
  62. return generic_scopes_[id.index];
  63. }
  64. // Returns the IR name for the specified scope.
  65. auto GetScopeName(ScopeId scope) const -> std::string;
  66. // Returns the IR name to use for a function, class, or interface.
  67. template <typename IdT>
  68. auto GetNameFor(IdT id) const -> std::string {
  69. if (!id.has_value()) {
  70. return "invalid";
  71. }
  72. return GetScopeName(GetScopeFor(id));
  73. }
  74. // Returns the IR name to use for an instruction within its own scope, without
  75. // any prefix. Returns an empty string if there isn't a good name.
  76. auto GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef;
  77. // Returns the IR name to use for an instruction, when referenced from a given
  78. // scope.
  79. auto GetNameFor(ScopeId scope_id, InstId inst_id) const -> std::string;
  80. // Returns the IR name to use for a label within its own scope, without any
  81. // prefix. Returns an empty string if there isn't a good name.
  82. auto GetUnscopedLabelFor(InstBlockId block_id) const -> llvm::StringRef;
  83. // Returns the IR name to use for a label, when referenced from a given scope.
  84. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) const -> std::string;
  85. private:
  86. // A space in which unique names can be allocated.
  87. struct Namespace {
  88. // A result of a name lookup.
  89. struct NameResult;
  90. // A name in a namespace, which might be redirected to refer to another name
  91. // for disambiguation purposes.
  92. class Name {
  93. public:
  94. Name() : value_(nullptr) {}
  95. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  96. explicit operator bool() const { return value_; }
  97. auto str() const -> llvm::StringRef;
  98. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  99. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  100. private:
  101. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  102. };
  103. struct NameResult {
  104. bool ambiguous = false;
  105. Name fallback = Name();
  106. };
  107. llvm::StringMap<NameResult> allocated = {};
  108. int unnamed_count = 0;
  109. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  110. return Name(allocated.insert({name, NameResult()}).first);
  111. }
  112. auto AllocateName(const InstNamer& inst_namer,
  113. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  114. std::string name) -> Name;
  115. };
  116. // A named scope that contains named entities.
  117. struct Scope {
  118. Namespace::Name name;
  119. Namespace insts;
  120. Namespace labels;
  121. };
  122. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  123. return scopes_[static_cast<int>(scope_id)];
  124. }
  125. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  126. return scopes_[static_cast<int>(scope_id)];
  127. }
  128. auto AddBlockLabel(
  129. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  130. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  131. -> void;
  132. // Finds and adds a suitable block label for the given SemIR instruction that
  133. // represents some kind of branch.
  134. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  135. auto CollectNamesInBlock(ScopeId scope_id, InstBlockId block_id) -> void;
  136. // Collects names from the provided block.
  137. //
  138. // This is essential for finding instructions that we need to name. If
  139. // `<unexpected>` occurs in output of valid SemIR, it often means the
  140. // instruction needs to be handled here. Note that `<unexpected>` can occur in
  141. // invalid SemIR just because we're unable to correctly walk the SemIR.
  142. auto CollectNamesInBlock(ScopeId scope_id, llvm::ArrayRef<InstId> block)
  143. -> void;
  144. auto CollectNamesInGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  145. const File* sem_ir_;
  146. InstFingerprinter fingerprinter_;
  147. // The namespace for entity names. Names within this namespace are prefixed
  148. // with `@` in formatted SemIR.
  149. Namespace globals_;
  150. // The enclosing scope and name for each instruction, indexed by the InstId's
  151. // index.
  152. std::vector<std::pair<ScopeId, Namespace::Name>> insts_;
  153. // The enclosing scope and name for each block that might be a branch target,
  154. // indexed by the InstBlockId's index.
  155. std::vector<std::pair<ScopeId, Namespace::Name>> labels_;
  156. // The scopes corresponding to ScopeId values.
  157. std::vector<Scope> scopes_;
  158. // The scope IDs corresponding to generics. The vector indexes are the
  159. // GenericId index.
  160. std::vector<ScopeId> generic_scopes_;
  161. };
  162. } // namespace Carbon::SemIR
  163. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_