file_context.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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_LOWER_FILE_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_
  6. #include "clang/CodeGen/ModuleBuilder.h"
  7. #include "clang/Lex/PreprocessorOptions.h"
  8. #include "toolchain/lower/context.h"
  9. #include "toolchain/lower/specific_coalescer.h"
  10. #include "toolchain/parse/tree_and_subtrees.h"
  11. #include "toolchain/sem_ir/file.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst_namer.h"
  14. namespace Carbon::Lower {
  15. // Context and shared functionality for lowering within a SemIR file.
  16. class FileContext {
  17. public:
  18. using LoweredConstantStore =
  19. FixedSizeValueStore<SemIR::InstId, llvm::Constant*,
  20. Tag<SemIR::CheckIRId>>;
  21. explicit FileContext(Context& context, const SemIR::File& sem_ir,
  22. const SemIR::InstNamer* inst_namer,
  23. llvm::raw_ostream* vlog_stream);
  24. // Prepares to lower code in this IR, by precomputing needed LLVM types,
  25. // constants, declarations, etc. Should only be called once, before we lower
  26. // anything in this file.
  27. auto PrepareToLower() -> void;
  28. // Lowers all the definitions provided by the SemIR::File to LLVM IR.
  29. auto LowerDefinitions() -> void;
  30. // Perform final cleanup tasks once all lowering has been completed.
  31. auto Finalize() -> void;
  32. // Gets a callable's function. Returns nullptr for a builtin or a function we
  33. // have not lowered.
  34. auto GetFunction(SemIR::FunctionId function_id,
  35. SemIR::SpecificId specific_id = SemIR::SpecificId::None)
  36. -> llvm::Function* {
  37. return *GetFunctionAddr(function_id, specific_id);
  38. }
  39. // Gets a or creates callable's function. Returns nullptr for a builtin.
  40. auto GetOrCreateFunction(SemIR::FunctionId function_id,
  41. SemIR::SpecificId specific_id) -> llvm::Function*;
  42. // Returns a lowered type for the given type_id.
  43. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  44. return GetTypeAndDIType(type_id).llvm_ir_type;
  45. }
  46. struct LoweredTypes {
  47. llvm::Type* llvm_ir_type;
  48. llvm::DIType* llvm_di_type;
  49. };
  50. // Returns both the lowered llvm IR type and the lowered llvm IR debug info
  51. // type for the given type_id.
  52. auto GetTypeAndDIType(SemIR::TypeId type_id) const -> LoweredTypes {
  53. CARBON_CHECK(type_id.has_value(), "Should not be called with `None`");
  54. CARBON_CHECK(type_id.is_concrete(), "Lowering symbolic type {0}: {1}",
  55. type_id, sem_ir().types().GetAsInst(type_id));
  56. auto result = types_.Get(type_id);
  57. if (!result.llvm_ir_type) {
  58. result.llvm_ir_type = context_->GetOpaqueType();
  59. }
  60. return result;
  61. }
  62. // Returns location information for use with DebugInfo.
  63. auto GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI;
  64. // Returns a lowered value to use for a value of type `type`.
  65. auto GetTypeAsValue() -> llvm::Constant* {
  66. return context().GetTypeAsValue();
  67. }
  68. // Returns a lowered value to use for a value of literal type.
  69. auto GetLiteralAsValue() -> llvm::Constant* {
  70. return context().GetLiteralAsValue();
  71. }
  72. // Returns a value for the given constant. If specified, `use_inst_id` is the
  73. // instruction that is using this constant.
  74. auto GetConstant(SemIR::ConstantId const_id, SemIR::InstId use_inst_id)
  75. -> llvm::Value*;
  76. auto GetVtable(SemIR::VtableId vtable_id, SemIR::SpecificId specific_id)
  77. -> llvm::GlobalVariable* {
  78. if (!specific_id.has_value()) {
  79. return vtables_.Get(vtable_id);
  80. }
  81. auto*& specific_vtable = specific_vtables_.Get(specific_id);
  82. if (!specific_vtable) {
  83. specific_vtable =
  84. BuildVtable(sem_ir().vtables().Get(vtable_id), specific_id);
  85. }
  86. return specific_vtable;
  87. }
  88. // Returns the empty LLVM struct type used to represent the type `type`.
  89. auto GetTypeType() -> llvm::StructType* { return context().GetTypeType(); }
  90. auto GetFormType() -> llvm::StructType* { return context().GetFormType(); }
  91. auto context() -> Context& { return *context_; }
  92. auto llvm_context() -> llvm::LLVMContext& { return context().llvm_context(); }
  93. auto llvm_module() -> llvm::Module& { return context().llvm_module(); }
  94. auto cpp_code_generator() -> clang::CodeGenerator& {
  95. CARBON_CHECK(cpp_code_generator_);
  96. return *cpp_code_generator_;
  97. }
  98. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  99. auto cpp_file() -> const SemIR::CppFile* { return sem_ir().cpp_file(); }
  100. auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }
  101. auto global_variables() -> const Map<SemIR::InstId, llvm::GlobalVariable*>& {
  102. return global_variables_;
  103. }
  104. auto printf_int_format_string() -> llvm::Value* {
  105. return context().printf_int_format_string();
  106. }
  107. auto SetPrintfIntFormatString(llvm::Value* printf_int_format_string) {
  108. context().SetPrintfIntFormatString(printf_int_format_string);
  109. }
  110. struct FunctionTypeInfo {
  111. llvm::FunctionType* type;
  112. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  113. llvm::Type* return_type = nullptr;
  114. SemIR::InstId return_param_id = SemIR::InstId::None;
  115. };
  116. // Retrieve various features of the function's type useful for constructing
  117. // the `llvm::Type` for the `llvm::Function`. If any part of the type can't be
  118. // manifest (eg: incomplete return or parameter types), then the result is as
  119. // if the type was `void()`.
  120. auto BuildFunctionTypeInfo(const SemIR::Function& function,
  121. SemIR::SpecificId specific_id) -> FunctionTypeInfo;
  122. // Builds the global for the given instruction, which should then be cached by
  123. // the caller.
  124. auto BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  125. -> llvm::GlobalVariable*;
  126. // Builds the definition for the given function. If the function is only a
  127. // declaration with no definition, does nothing. If this is a generic it'll
  128. // only be lowered if the specific_id is specified. During this lowering of
  129. // a generic, more generic functions may be added for lowering.
  130. auto BuildFunctionDefinition(
  131. SemIR::FunctionId function_id,
  132. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  133. private:
  134. // Gets the location in which a callable's function is stored.
  135. auto GetFunctionAddr(SemIR::FunctionId function_id,
  136. SemIR::SpecificId specific_id) -> llvm::Function** {
  137. return specific_id.has_value() ? &specific_functions_.Get(specific_id)
  138. : &functions_.Get(function_id);
  139. }
  140. // Notes that a C++ function has been referenced for the first time, so we
  141. // should ask Clang to generate a definition for it if possible.
  142. auto HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl) -> void;
  143. // Notes that a specific function has been referenced for the first time.
  144. // Updates the fingerprint to include the function's type, and adds the
  145. // function to the list of specific functions whose definitions should be
  146. // lowered.
  147. auto HandleReferencedSpecificFunction(SemIR::FunctionId function_id,
  148. SemIR::SpecificId specific_id,
  149. llvm::Type* llvm_type) -> void;
  150. // Builds the declaration for the given function, which should then be cached
  151. // by the caller.
  152. auto BuildFunctionDecl(SemIR::FunctionId function_id,
  153. SemIR::SpecificId specific_id =
  154. SemIR::SpecificId::None) -> llvm::Function*;
  155. // Builds a function's body. Common functionality for all functions.
  156. //
  157. // The `function_id` and `specific_id` identify the function within this
  158. // context's file. If the function was defined in a different file,
  159. // `definition_context` is a `FileContext` for that other file.
  160. // `definition_function` is the `Function` object within the file that owns
  161. // the definition.
  162. auto BuildFunctionBody(SemIR::FunctionId function_id,
  163. SemIR::SpecificId specific_id,
  164. const SemIR::Function& declaration_function,
  165. FileContext& definition_context,
  166. const SemIR::Function& definition_function) -> void;
  167. // Build the DISubprogram metadata for the given function.
  168. auto BuildDISubprogram(const SemIR::Function& function,
  169. SemIR::SpecificId specific_id,
  170. const llvm::Function* llvm_function)
  171. -> llvm::DISubprogram*;
  172. // Build a `DISubroutineType` for the given function, including the return and
  173. // parameter types.
  174. auto BuildDISubroutineType(const SemIR::Function&,
  175. SemIR::SpecificId specific_id)
  176. -> llvm::DISubroutineType*;
  177. // Builds the `llvm::Type` and `llvm::DIType` for the given instruction, which
  178. // should then be cached by the caller.
  179. auto BuildType(SemIR::InstId inst_id) -> LoweredTypes;
  180. auto BuildVtable(const SemIR::Vtable& vtable, SemIR::SpecificId specific_id)
  181. -> llvm::GlobalVariable*;
  182. // Records a specific that was lowered for a generic. These are added one
  183. // by one while lowering their definitions.
  184. auto AddLoweredSpecificForGeneric(SemIR::GenericId generic_id,
  185. SemIR::SpecificId specific_id) {
  186. lowered_specifics_.Get(generic_id).push_back(specific_id);
  187. }
  188. // The overall lowering context.
  189. Context* context_;
  190. // The input SemIR.
  191. const SemIR::File* const sem_ir_;
  192. // The Clang `CodeGenerator` to generate LLVM module from imported C++
  193. // code. Can be null if no C++ code is imported.
  194. clang::CodeGenerator* cpp_code_generator_;
  195. // The instruction namer, if given.
  196. const SemIR::InstNamer* const inst_namer_;
  197. // The optional vlog stream.
  198. llvm::raw_ostream* vlog_stream_;
  199. // Maps callables to lowered functions. SemIR treats callables as the
  200. // canonical form of a function, so lowering needs to do the same.
  201. using LoweredFunctionStore =
  202. FixedSizeValueStore<SemIR::FunctionId, llvm::Function*,
  203. Tag<SemIR::CheckIRId>>;
  204. LoweredFunctionStore functions_;
  205. // Maps specific callables to lowered functions.
  206. FixedSizeValueStore<SemIR::SpecificId, llvm::Function*, Tag<SemIR::CheckIRId>>
  207. specific_functions_;
  208. // Provides lowered versions of types. Entries are non-symbolic types.
  209. //
  210. // TypeIds internally are concrete ConstantIds.
  211. using LoweredTypeStore =
  212. FixedSizeValueStore<SemIR::TypeId, LoweredTypes, Tag<SemIR::CheckIRId>>;
  213. LoweredTypeStore types_;
  214. // Maps constants to their lowered values. Indexes are the `InstId` for
  215. // constant instructions.
  216. LoweredConstantStore constants_;
  217. // Maps global variables to their lowered variant.
  218. Map<SemIR::InstId, llvm::GlobalVariable*> global_variables_;
  219. // For a generic function, keep track of the specifics for which LLVM
  220. // function declarations were created. Those can be retrieved then from
  221. // `specific_functions_`.
  222. FixedSizeValueStore<SemIR::GenericId, llvm::SmallVector<SemIR::SpecificId>,
  223. Tag<SemIR::CheckIRId>>
  224. lowered_specifics_;
  225. SpecificCoalescer coalescer_;
  226. FixedSizeValueStore<SemIR::VtableId, llvm::GlobalVariable*,
  227. Tag<SemIR::CheckIRId>>
  228. vtables_;
  229. FixedSizeValueStore<SemIR::SpecificId, llvm::GlobalVariable*,
  230. Tag<SemIR::CheckIRId>>
  231. specific_vtables_;
  232. };
  233. } // namespace Carbon::Lower
  234. #endif // CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_