file_context.h 11 KB

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