file_context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. // Information about how a given function declaration is lowered.
  16. struct FunctionInfo {
  17. // The type of the lowered function.
  18. llvm::FunctionType* type;
  19. // The debug info type of the lowered function.
  20. llvm::DISubroutineType* di_type;
  21. // The indices of the `Call` parameter patterns that correspond to parameters
  22. // of the LLVM IR function, in the order of the LLVM IR parameter list. Some
  23. // `Call` parameters may be omitted (e.g. if they are stateless), and the
  24. // order may differ from the SemIR `Call` parameter list (e.g. the return
  25. // parameter, if any, always goes first).
  26. llvm::SmallVector<SemIR::CallParamIndex> lowered_param_indices;
  27. // The indices of any `Call` param patterns that aren't present in
  28. // lowered_param_pattern_ids.
  29. llvm::SmallVector<SemIR::CallParamIndex> unused_param_indices;
  30. // The lowered function declaration.
  31. llvm::Function* llvm_function;
  32. // Whether the function type information is inexact, because some component
  33. // type was incomplete. If this is set, the function should not be used to
  34. // emit a definition or a call.
  35. bool inexact;
  36. };
  37. // Context and shared functionality for lowering within a SemIR file.
  38. class FileContext {
  39. public:
  40. using LoweredConstantStore =
  41. FixedSizeValueStore<SemIR::InstId, llvm::Constant*,
  42. Tag<SemIR::CheckIRId>>;
  43. explicit FileContext(Context& context, const SemIR::File& sem_ir,
  44. const SemIR::InstNamer* inst_namer,
  45. llvm::raw_ostream* vlog_stream);
  46. // Prepares to lower code in this IR, by precomputing needed LLVM types,
  47. // constants, declarations, etc. Should only be called once, before we lower
  48. // anything in this file.
  49. auto PrepareToLower() -> void;
  50. // Lowers all the definitions provided by the SemIR::File to LLVM IR.
  51. auto LowerDefinitions() -> void;
  52. // Perform final cleanup tasks once all lowering has been completed.
  53. auto Finalize() -> void;
  54. // Gets a callable's function. Returns nullptr for a builtin or a function we
  55. // have not lowered.
  56. auto GetFunction(SemIR::FunctionId function_id,
  57. SemIR::SpecificId specific_id = SemIR::SpecificId::None)
  58. -> llvm::Function* {
  59. const auto& function_info = GetFunctionInfo(function_id, specific_id);
  60. return function_info ? function_info->llvm_function : nullptr;
  61. }
  62. // Returns the FunctionInfo for the given function in the given specific, if
  63. // it has already been computed.
  64. auto GetFunctionInfo(SemIR::FunctionId function_id,
  65. SemIR::SpecificId specific_id)
  66. -> std::optional<FunctionInfo>& {
  67. return specific_id.has_value() ? specific_functions_.Get(specific_id)
  68. : functions_.Get(function_id);
  69. }
  70. // Returns the FunctionInfo for the given function in the given specific. If
  71. // it's not already available, this function will compute it, including
  72. // creating the `llvm::Function` for it. Returns nullopt for a builtin.
  73. //
  74. // The fallback information is used if the specific function has incomplete
  75. // types.
  76. auto GetOrCreateFunctionInfo(
  77. SemIR::FunctionId function_id, SemIR::SpecificId specific_id,
  78. FileContext* fallback_file = nullptr,
  79. SemIR::FunctionId fallback_function_id = SemIR::FunctionId::None,
  80. SemIR::SpecificId fallback_specific_id = SemIR::SpecificId::None)
  81. -> std::optional<FunctionInfo>&;
  82. // Returns a lowered type for the given type_id.
  83. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  84. return GetTypeAndDIType(type_id).llvm_ir_type;
  85. }
  86. struct LoweredTypes {
  87. llvm::Type* llvm_ir_type;
  88. llvm::DIType* llvm_di_type;
  89. };
  90. // Returns both the lowered llvm IR type and the lowered llvm IR debug info
  91. // type for the given type_id.
  92. auto GetTypeAndDIType(SemIR::TypeId type_id) const -> LoweredTypes {
  93. CARBON_CHECK(type_id.has_value(), "Should not be called with `None`");
  94. CARBON_CHECK(type_id.is_concrete(), "Lowering symbolic type {0}: {1}",
  95. type_id, sem_ir().types().GetAsInst(type_id));
  96. auto result = types_.Get(type_id);
  97. if (!result.llvm_ir_type) {
  98. result.llvm_ir_type = context_->GetOpaqueType();
  99. }
  100. return result;
  101. }
  102. // Returns location information for use with DebugInfo.
  103. auto GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI;
  104. // Returns a lowered value to use for a value of type `type`.
  105. auto GetTypeAsValue() -> llvm::Constant* {
  106. return context().GetTypeAsValue();
  107. }
  108. // Returns a lowered value to use for a value of literal type.
  109. auto GetLiteralAsValue() -> llvm::Constant* {
  110. return context().GetLiteralAsValue();
  111. }
  112. // Returns a value for the given constant. If specified, `use_inst_id` is the
  113. // instruction that is using this constant.
  114. auto GetConstant(SemIR::ConstantId const_id, SemIR::InstId use_inst_id)
  115. -> llvm::Value*;
  116. auto GetVtable(SemIR::VtableId vtable_id, SemIR::SpecificId specific_id)
  117. -> llvm::GlobalVariable* {
  118. if (!specific_id.has_value()) {
  119. return vtables_.Get(vtable_id);
  120. }
  121. auto*& specific_vtable = specific_vtables_.Get(specific_id);
  122. if (!specific_vtable) {
  123. specific_vtable =
  124. BuildVtable(sem_ir().vtables().Get(vtable_id), specific_id);
  125. }
  126. return specific_vtable;
  127. }
  128. // Returns the empty LLVM struct type used to represent the type `type`.
  129. auto GetTypeType() -> llvm::StructType* { return context().GetTypeType(); }
  130. auto GetFormType() -> llvm::StructType* { return context().GetFormType(); }
  131. auto context() -> Context& { return *context_; }
  132. auto llvm_context() -> llvm::LLVMContext& { return context().llvm_context(); }
  133. auto llvm_module() -> llvm::Module& { return context().llvm_module(); }
  134. auto cpp_code_generator() -> clang::CodeGenerator& {
  135. CARBON_CHECK(cpp_code_generator_);
  136. return *cpp_code_generator_;
  137. }
  138. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  139. auto cpp_file() -> const SemIR::CppFile* { return sem_ir().cpp_file(); }
  140. auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }
  141. auto global_variables() -> const Map<SemIR::InstId, llvm::GlobalVariable*>& {
  142. return global_variables_;
  143. }
  144. auto printf_int_format_string() -> llvm::Value* {
  145. return context().printf_int_format_string();
  146. }
  147. auto SetPrintfIntFormatString(llvm::Value* printf_int_format_string) {
  148. context().SetPrintfIntFormatString(printf_int_format_string);
  149. }
  150. // Builds the global for the given instruction, which should then be cached by
  151. // the caller.
  152. auto BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  153. -> llvm::Constant*;
  154. // Builds the global for the given instruction which is known to not be
  155. // imported from C++.
  156. auto BuildNonCppGlobalVariableDecl(SemIR::VarStorage var_storage)
  157. -> llvm::GlobalVariable*;
  158. // Builds the definition for the given function. If the function is only a
  159. // declaration with no definition, does nothing. If this is a generic it'll
  160. // only be lowered if the specific_id is specified. During this lowering of
  161. // a generic, more generic functions may be added for lowering.
  162. auto BuildFunctionDefinition(
  163. SemIR::FunctionId function_id,
  164. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  165. private:
  166. // Notes that a C++ function has been referenced for the first time, so we
  167. // should ask Clang to generate a definition for it if possible.
  168. auto HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl)
  169. -> llvm::Function*;
  170. // Notes that a specific function has been referenced for the first time.
  171. // Updates the fingerprint to include the function's type, and adds the
  172. // function to the list of specific functions whose definitions should be
  173. // lowered.
  174. auto HandleReferencedSpecificFunction(SemIR::FunctionId function_id,
  175. SemIR::SpecificId specific_id,
  176. llvm::Type* llvm_type) -> void;
  177. // Information used to build a `FunctionInfo`.
  178. // TODO: Rename this, since it's not limited to type information, and/or
  179. // restructure the code so it's not needed.
  180. struct FunctionTypeInfo {
  181. // See documentation for the corresponding members of FunctionInfo.
  182. llvm::FunctionType* type;
  183. llvm::DISubroutineType* di_type;
  184. llvm::SmallVector<SemIR::CallParamIndex> lowered_param_indices;
  185. llvm::SmallVector<SemIR::CallParamIndex> unused_param_indices;
  186. // The names of the lowered `Call` parameters, in the same order as
  187. // `lowered_param_indices`.
  188. llvm::SmallVector<SemIR::NameId> param_name_ids;
  189. // When `return_param_id` is not `None`, the corresponding lowered parameter
  190. // should be given an `sret` attribute with this type.
  191. llvm::Type* sret_type = nullptr;
  192. // Whether the function type information is inexact, because some component
  193. // type was incomplete.
  194. bool inexact;
  195. };
  196. class FunctionTypeInfoBuilder;
  197. // Builds an LLVM function declaration for the given function, or returns an
  198. // existing one if we've already lowered another declaration of the same
  199. // function.
  200. auto GetOrCreateLLVMFunction(const FunctionTypeInfo& function_type_info,
  201. SemIR::FunctionId function_id,
  202. SemIR::SpecificId specific_id)
  203. -> llvm::Function*;
  204. // Builds the declaration for the given function, which should then be cached
  205. // by the caller.
  206. auto BuildFunctionDecl(
  207. SemIR::FunctionId function_id,
  208. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  209. FileContext* fallback_file = nullptr,
  210. SemIR::FunctionId fallback_function_id = SemIR::FunctionId::None,
  211. SemIR::SpecificId fallback_specific_id = SemIR::SpecificId::None)
  212. -> std::optional<FunctionInfo>;
  213. // Builds a function's body. Common functionality for all functions.
  214. //
  215. // The `function_id` and `specific_id` identify the function within this
  216. // context's file. If the function was defined in a different file,
  217. // `definition_context` is a `FileContext` for that other file.
  218. // `definition_function` is the `Function` object within the file that owns
  219. // the definition.
  220. auto BuildFunctionBody(SemIR::FunctionId function_id,
  221. SemIR::SpecificId specific_id,
  222. const SemIR::Function& declaration_function,
  223. FileContext& definition_context,
  224. const SemIR::Function& definition_function) -> void;
  225. // Build the DISubprogram metadata for the given function.
  226. auto BuildDISubprogram(const SemIR::Function& function,
  227. const FunctionInfo& function_info)
  228. -> llvm::DISubprogram*;
  229. // Builds the `llvm::Type` and `llvm::DIType` for the given instruction, which
  230. // should then be cached by the caller.
  231. auto BuildType(SemIR::InstId inst_id) -> LoweredTypes;
  232. auto BuildVtable(const SemIR::Vtable& vtable, SemIR::SpecificId specific_id)
  233. -> llvm::GlobalVariable*;
  234. // Records a specific that was lowered for a generic. These are added one
  235. // by one while lowering their definitions.
  236. auto AddLoweredSpecificForGeneric(SemIR::GenericId generic_id,
  237. SemIR::SpecificId specific_id) {
  238. lowered_specifics_.Get(generic_id).push_back(specific_id);
  239. }
  240. // The overall lowering context.
  241. Context* context_;
  242. // The input SemIR.
  243. const SemIR::File* const sem_ir_;
  244. // The Clang `CodeGenerator` to generate LLVM module from imported C++
  245. // code. Can be null if no C++ code is imported.
  246. clang::CodeGenerator* cpp_code_generator_;
  247. // The instruction namer, if given.
  248. const SemIR::InstNamer* const inst_namer_;
  249. // The optional vlog stream.
  250. llvm::raw_ostream* vlog_stream_;
  251. // Maps callables to lowered functions. SemIR treats callables as the
  252. // canonical form of a function, so lowering needs to do the same.
  253. using LoweredFunctionStore =
  254. FixedSizeValueStore<SemIR::FunctionId, std::optional<FunctionInfo>,
  255. Tag<SemIR::CheckIRId>>;
  256. LoweredFunctionStore functions_;
  257. // Maps specific callables to lowered functions.
  258. FixedSizeValueStore<SemIR::SpecificId, std::optional<FunctionInfo>,
  259. Tag<SemIR::CheckIRId>>
  260. specific_functions_;
  261. // Provides lowered versions of types. Entries are non-symbolic types.
  262. //
  263. // TypeIds internally are concrete ConstantIds.
  264. using LoweredTypeStore =
  265. FixedSizeValueStore<SemIR::TypeId, LoweredTypes, Tag<SemIR::CheckIRId>>;
  266. LoweredTypeStore types_;
  267. // Maps constants to their lowered values. Indexes are the `InstId` for
  268. // constant instructions.
  269. LoweredConstantStore constants_;
  270. // Maps global variables to their lowered variant.
  271. Map<SemIR::InstId, llvm::GlobalVariable*> global_variables_;
  272. // For a generic function, keep track of the specifics for which LLVM
  273. // function declarations were created. Those can be retrieved then from
  274. // `specific_functions_`.
  275. FixedSizeValueStore<SemIR::GenericId, llvm::SmallVector<SemIR::SpecificId>,
  276. Tag<SemIR::CheckIRId>>
  277. lowered_specifics_;
  278. SpecificCoalescer coalescer_;
  279. FixedSizeValueStore<SemIR::VtableId, llvm::GlobalVariable*,
  280. Tag<SemIR::CheckIRId>>
  281. vtables_;
  282. FixedSizeValueStore<SemIR::SpecificId, llvm::GlobalVariable*,
  283. Tag<SemIR::CheckIRId>>
  284. specific_vtables_;
  285. };
  286. } // namespace Carbon::Lower
  287. #endif // CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_