inst_namer.h 6.4 KB

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