function_context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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_FUNCTION_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_
  6. #include <type_traits>
  7. #include "common/map.h"
  8. #include "common/raw_string_ostream.h"
  9. #include "llvm/IR/IRBuilder.h"
  10. #include "llvm/IR/LLVMContext.h"
  11. #include "llvm/IR/Module.h"
  12. #include "toolchain/lower/file_context.h"
  13. #include "toolchain/lower/specific_coalescer.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. namespace Carbon::Lower {
  17. // Context and shared functionality for lowering handlers that produce an
  18. // `llvm::Function` definition.
  19. class FunctionContext {
  20. public:
  21. // `function` must not be null. `function_fingerprint` and `di_subprogram` may
  22. // be null (see members).
  23. explicit FunctionContext(
  24. FileContext& file_context, llvm::Function* function,
  25. FileContext& specific_file_context, SemIR::SpecificId specific_id,
  26. SpecificCoalescer::SpecificFunctionFingerprint* function_fingerprint,
  27. llvm::DISubprogram* di_subprogram, llvm::raw_ostream* vlog_stream);
  28. // Describes a function's body fingerprint while creating the function body.
  29. // The final fingerprint is stored in the `FileContext` as a
  30. // `SpecificFunctionFingerprint`.
  31. //
  32. // Create two function fingerprints, where both fingerprints include data
  33. // that's evaluated (and hence lowered) differently based on the
  34. // `SpecificId`. `common_fingerprint` includes global values, types
  35. // and `FunctionId` for functions called inside the function body.
  36. // `specific_fingerprint` includes `SpecificId`s for functions called.
  37. //
  38. // For two specifics of the same generic:
  39. // - If `common_fingerprint` is different, the specifics cannot be coalesced.
  40. // - If `common_fingerprint` and `specific_fingerprint` are the
  41. // same, the specifics can be coalesced without additional checks.
  42. // - If `common_fingerprint` is the same but `specific_fingerprint` is
  43. // different, additional checks are needed, i.e. inspecting the non-hashed
  44. // `SpecificId`s.
  45. //
  46. // TODO: Consider optimizations for repeated entries in both fingerprints.
  47. struct LoweringFunctionFingerprint {
  48. llvm::BLAKE3 common_fingerprint;
  49. llvm::BLAKE3 specific_fingerprint;
  50. };
  51. // A type in a particular file. This is used when lowering a specific and we
  52. // find a type that might be from the specific rather than the generic. By
  53. // convention, this represents a type that has not yet been added to the
  54. // specific fingerprint.
  55. struct TypeInFile {
  56. const SemIR::File* file;
  57. SemIR::TypeId type_id;
  58. auto GetPointeeType() -> TypeInFile {
  59. return {.file = file, .type_id = file->GetPointeeType(type_id)};
  60. }
  61. };
  62. // A value representation in a particular file. By convention, this represents
  63. // a value representation whose kind has been added to the fingerprint but
  64. // whose type has not.
  65. struct ValueReprInFile {
  66. const SemIR::File* file;
  67. SemIR::ValueRepr repr;
  68. auto type() -> TypeInFile {
  69. return {.file = file, .type_id = repr.type_id};
  70. }
  71. };
  72. // An inst in a particular file.
  73. struct InstInFile {
  74. const SemIR::File* file;
  75. SemIR::InstId inst_id;
  76. };
  77. // Returns a basic block corresponding to the start of the given semantics
  78. // block, and enqueues it for emission.
  79. auto GetBlock(SemIR::InstBlockId block_id) -> llvm::BasicBlock*;
  80. // If we have not yet allocated a `BasicBlock` for this `block_id`, set it to
  81. // `block`, and enqueue `block_id` for emission. Returns whether we set the
  82. // block.
  83. auto TryToReuseBlock(SemIR::InstBlockId block_id, llvm::BasicBlock* block)
  84. -> bool;
  85. // Builds LLVM IR for the sequence of instructions in `block_id`.
  86. auto LowerBlockContents(SemIR::InstBlockId block_id) -> void;
  87. // Builds LLVM IR for the specified instruction.
  88. auto LowerInst(SemIR::InstId inst_id) -> void;
  89. // Returns a phi node corresponding to the block argument of the given basic
  90. // block.
  91. auto GetBlockArg(SemIR::InstBlockId block_id, TypeInFile type)
  92. -> llvm::PHINode*;
  93. // Returns a value for the given instruction.
  94. auto GetValue(SemIR::InstId inst_id) -> llvm::Value*;
  95. // Sets the value for the given instruction.
  96. auto SetLocal(SemIR::InstId inst_id, llvm::Value* value) -> void {
  97. bool added = locals_.Insert(inst_id, value).is_inserted();
  98. CARBON_CHECK(added, "Duplicate local insert: {0} {1}", inst_id,
  99. sem_ir().insts().Get(inst_id));
  100. }
  101. // Returns a lowered type for the given type_id in the given file. This adds
  102. // the specified type to the fingerprint.
  103. auto GetType(TypeInFile type) -> llvm::Type* {
  104. auto* llvm_type = GetFileContext(type.file).GetType(type.type_id);
  105. AddTypeToCurrentFingerprint(llvm_type);
  106. return llvm_type;
  107. }
  108. // Returns the type of the given instruction in the current specific.
  109. auto GetTypeOfInst(SemIR::InstId inst_id) -> llvm::Type* {
  110. return GetType(GetTypeIdOfInst(inst_id));
  111. }
  112. // Returns the type of the given instruction in the current specific.
  113. auto GetTypeIdOfInst(SemIR::InstId inst_id) -> TypeInFile;
  114. // Returns the value representation of the given type. This adds the kind of
  115. // value representation, but not the underlying type, to the fingerprint.
  116. auto GetValueRepr(TypeInFile type) -> ValueReprInFile;
  117. // Returns the initializing representation of the given type. This adds the
  118. // kind of initializing representation to the fingerprint.
  119. auto GetInitRepr(TypeInFile type) -> SemIR::InitRepr;
  120. // Returns a lowered value to use for a value of type `type`.
  121. auto GetTypeAsValue() -> llvm::Value* {
  122. return file_context_->GetTypeAsValue();
  123. }
  124. // Returns a lowered value to use for a value of literal type.
  125. auto GetLiteralAsValue() -> llvm::Constant* {
  126. return file_context_->GetLiteralAsValue();
  127. }
  128. // Create a synthetic block that corresponds to no SemIR::InstBlockId. Such
  129. // a block should only ever have a single predecessor, and is used when we
  130. // need multiple `llvm::BasicBlock`s to model the linear control flow in a
  131. // single SemIR::File block.
  132. auto MakeSyntheticBlock() -> llvm::BasicBlock*;
  133. // Determine whether block is the most recently created synthetic block.
  134. auto IsCurrentSyntheticBlock(llvm::BasicBlock* block) -> bool {
  135. return synthetic_block_ == block;
  136. }
  137. // Creates an alloca instruction of the given type, adds it to the entry
  138. // block, and starts the lifetime of the corresponding storage.
  139. auto CreateAlloca(llvm::Type* type, const llvm::Twine& name = llvm::Twine())
  140. -> llvm::AllocaInst*;
  141. // Returns the debug location to associate with the specified instruction.
  142. auto GetDebugLoc(SemIR::InstId inst_id) -> llvm::DebugLoc;
  143. // Emits a load of an object representation of type `type`.
  144. auto LoadObject(TypeInFile type, llvm::Value* addr, llvm::Twine name = "")
  145. -> llvm::Value*;
  146. // Emits a store of an object representation of type `type`.
  147. auto StoreObject(TypeInFile type, llvm::Value* value, llvm::Value* addr)
  148. -> void;
  149. // Emits the instructions necessary to initialize the storage at `dest_id`
  150. // from the repr-initializing expression `source_id`. This assumes the
  151. // instructions for `source_id` have already been emitted, so it's a no-op if
  152. // the initialization was performed in-place, and otherwise performs a store
  153. // or a copy.
  154. auto InitializeStorage(TypeInFile type, SemIR::InstId dest_id,
  155. SemIR::InstId source_id) -> void;
  156. // Emits the instructions necessary to perform the initialization described by
  157. // `init_id` in-place in its storage.
  158. auto InitializeStorage(SemIR::InstId init_id) -> void;
  159. // When fingerprinting for a specific, adds the call, found in the function
  160. // body, to <function_id, specific_id>. `function_id` and `specific_id` are
  161. // IDs within the file identified by `function_file_id`.
  162. auto AddCallToCurrentFingerprint(SemIR::CheckIRId file_id,
  163. SemIR::FunctionId function_id,
  164. SemIR::SpecificId specific_id) -> void;
  165. // When fingerprinting for a specific, adds an integer.
  166. auto AddIntToCurrentFingerprint(uint64_t value) -> void;
  167. // When fingerprinting for a specific, adds an enumerator value.
  168. template <typename T>
  169. requires(std::is_enum_v<T>)
  170. auto AddEnumToCurrentFingerprint(T value) -> void {
  171. AddIntToCurrentFingerprint(static_cast<uint64_t>(value));
  172. }
  173. // When fingerprinting for a specific, adds the type.
  174. auto AddTypeToCurrentFingerprint(llvm::Type* type) -> void;
  175. // Emits the final function fingerprints. Only called when function lowering
  176. // is complete.
  177. auto EmitFinalFingerprint() -> void;
  178. // Returns the FileContext to use for lowering in the given file.
  179. auto GetFileContext(const SemIR::File* file) -> FileContext& {
  180. // Avoid hash table lookup for the expected files.
  181. if (file == &sem_ir()) {
  182. return *file_context_;
  183. }
  184. if (file == &specific_sem_ir()) {
  185. return *specific_file_context_;
  186. }
  187. return file_context_->context().GetFileContext(file);
  188. }
  189. auto llvm_context() -> llvm::LLVMContext& {
  190. return file_context_->llvm_context();
  191. }
  192. auto llvm_module() -> llvm::Module& { return file_context_->llvm_module(); }
  193. auto llvm_function() -> llvm::Function& { return *function_; }
  194. auto builder() -> llvm::IRBuilderBase& { return builder_; }
  195. auto sem_ir() -> const SemIR::File& { return file_context_->sem_ir(); }
  196. // The file context for the file that `specific_id()` is within.
  197. auto specific_file_context() -> FileContext& {
  198. return *specific_file_context_;
  199. }
  200. // The file that `specific_id()` is within.
  201. auto specific_sem_ir() -> const SemIR::File& {
  202. return specific_file_context_->sem_ir();
  203. }
  204. // The specific ID for the function that is being lowered. Note that this is
  205. // an ID from `specific_sem_ir()`, not from `sem_ir()`.
  206. auto specific_id() -> SemIR::SpecificId { return specific_id_; }
  207. // TODO: could template on BuiltinFunctionKind if more format
  208. // globals are eventually needed.
  209. auto printf_int_format_string() -> llvm::Value* {
  210. auto* format_string = file_context_->printf_int_format_string();
  211. if (!format_string) {
  212. format_string = builder().CreateGlobalString("%d\n", "printf.int.format");
  213. file_context_->SetPrintfIntFormatString(format_string);
  214. }
  215. return format_string;
  216. }
  217. auto GetVtable(SemIR::VtableId vtable_id, SemIR::SpecificId specific_id) const
  218. -> llvm::GlobalVariable* {
  219. return file_context_->GetVtable(vtable_id, specific_id);
  220. }
  221. private:
  222. // Custom instruction inserter for our IR builder. Automatically names
  223. // instructions.
  224. class Inserter : public llvm::IRBuilderDefaultInserter {
  225. public:
  226. explicit Inserter(const SemIR::InstNamer* inst_namer)
  227. : inst_namer_(inst_namer) {}
  228. // Sets the instruction we are currently emitting.
  229. auto SetCurrentInstId(SemIR::InstId inst_id) -> void { inst_id_ = inst_id; }
  230. private:
  231. auto InsertHelper(llvm::Instruction* inst, const llvm::Twine& name,
  232. llvm::BasicBlock::iterator insert_pt) const
  233. -> void override;
  234. // The instruction namer.
  235. const SemIR::InstNamer* inst_namer_;
  236. // The current instruction ID.
  237. SemIR::InstId inst_id_ = SemIR::InstId::None;
  238. };
  239. // Emits a value copy for type `type` from `source_id` to `dest_id`.
  240. // `source_id` must produce a value representation for `type`, and
  241. // `dest_id` must be a pointer to a `type` object.
  242. auto CopyValue(TypeInFile type, SemIR::InstId source_id,
  243. SemIR::InstId dest_id) -> void;
  244. // Emits an object representation copy for type `type` from `source_id` to
  245. // `dest_id`. `source_id` and `dest_id` must produce pointers to `type`
  246. // objects.
  247. auto CopyObject(TypeInFile type, SemIR::InstId source_id,
  248. SemIR::InstId dest_id) -> void;
  249. // When fingerprinting for a specific, adds the global.
  250. auto AddGlobalToCurrentFingerprint(llvm::Value* global) -> void;
  251. // Context for lowering in the file that contains this function's
  252. // instructions.
  253. FileContext* file_context_;
  254. // The IR function we're generating.
  255. llvm::Function* function_;
  256. // Context for lowering in the file that contains our `specific_id_`. Note
  257. // that this is a different file than the one referred to by `file_context_`
  258. // if we are lowering a specific that was generated for a generic function
  259. // defined in a different file.
  260. FileContext* specific_file_context_;
  261. // The specific id, if the function is a specific.
  262. SemIR::SpecificId specific_id_;
  263. // Builder for creating code in this function. The insertion point is held at
  264. // the location of the current SemIR instruction.
  265. llvm::IRBuilder<llvm::ConstantFolder, Inserter> builder_;
  266. // The instruction after all allocas. This is used as the insert point for new
  267. // allocas.
  268. llvm::Instruction* after_allocas_ = nullptr;
  269. llvm::DISubprogram* di_subprogram_;
  270. // The optional vlog stream.
  271. llvm::raw_ostream* vlog_stream_;
  272. // This is initialized and populated while lowering a specific function.
  273. // When complete, this is used to complete the function_fingerprint_.
  274. LoweringFunctionFingerprint current_fingerprint_;
  275. // The accumulated fingerprint is owned by the FileContext and passed into
  276. // the FunctionContext. The function fingerprint is currently only built for
  277. // specific functions, otherwise, this will be nullptr.
  278. SpecificCoalescer::SpecificFunctionFingerprint* function_fingerprint_;
  279. // Maps a function's SemIR::File blocks to lowered blocks.
  280. Map<SemIR::InstBlockId, llvm::BasicBlock*> blocks_;
  281. // The synthetic block we most recently created. May be null if there is no
  282. // such block.
  283. llvm::BasicBlock* synthetic_block_ = nullptr;
  284. // Maps a function's SemIR::File instructions to lowered values.
  285. Map<SemIR::InstId, llvm::Value*> locals_;
  286. };
  287. // Provides handlers for instructions that occur in a FunctionContext. Although
  288. // this is declared for all instructions, it should only be defined for
  289. // instructions which are non-constant and not always typed. See
  290. // `FunctionContext::LowerInst` for how this is used.
  291. #define CARBON_SEM_IR_INST_KIND(Name) \
  292. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id, \
  293. SemIR::Name inst) -> void;
  294. #include "toolchain/sem_ir/inst_kind.def"
  295. } // namespace Carbon::Lower
  296. #endif // CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_