function_context.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. };
  59. // A value representation in a particular file. By convention, this represents
  60. // a value representation whose kind has been added to the fingerprint but
  61. // whose type has not.
  62. struct ValueReprInFile {
  63. const SemIR::File* file;
  64. SemIR::ValueRepr repr;
  65. auto type() -> TypeInFile {
  66. return {.file = file, .type_id = repr.type_id};
  67. }
  68. };
  69. // Information about a function's return type in a particular file. By
  70. // convention, this represents a value whose initializing representation has
  71. // been added to the fingerprint but whose type has not.
  72. struct ReturnTypeInfoInFile {
  73. const SemIR::File* file;
  74. SemIR::ReturnTypeInfo info;
  75. auto type() -> TypeInFile {
  76. return {.file = file, .type_id = info.type_id};
  77. }
  78. };
  79. // Returns a basic block corresponding to the start of the given semantics
  80. // block, and enqueues it for emission.
  81. auto GetBlock(SemIR::InstBlockId block_id) -> llvm::BasicBlock*;
  82. // If we have not yet allocated a `BasicBlock` for this `block_id`, set it to
  83. // `block`, and enqueue `block_id` for emission. Returns whether we set the
  84. // block.
  85. auto TryToReuseBlock(SemIR::InstBlockId block_id, llvm::BasicBlock* block)
  86. -> bool;
  87. // Builds LLVM IR for the sequence of instructions in `block_id`.
  88. auto LowerBlockContents(SemIR::InstBlockId block_id) -> void;
  89. // Builds LLVM IR for the specified instruction.
  90. auto LowerInst(SemIR::InstId inst_id) -> void;
  91. // Returns a phi node corresponding to the block argument of the given basic
  92. // block.
  93. auto GetBlockArg(SemIR::InstBlockId block_id, TypeInFile type)
  94. -> llvm::PHINode*;
  95. // Returns a value for the given instruction.
  96. auto GetValue(SemIR::InstId inst_id) -> llvm::Value*;
  97. // Sets the value for the given instruction.
  98. auto SetLocal(SemIR::InstId inst_id, llvm::Value* value) -> void {
  99. bool added = locals_.Insert(inst_id, value).is_inserted();
  100. CARBON_CHECK(added, "Duplicate local insert: {0} {1}", inst_id,
  101. sem_ir().insts().Get(inst_id));
  102. }
  103. // Gets a callable's function.
  104. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  105. return file_context_->GetFunction(function_id);
  106. }
  107. // Gets or creates a callable's function.
  108. auto GetOrCreateFunction(SemIR::FunctionId function_id,
  109. SemIR::SpecificId specific_id) -> llvm::Function* {
  110. return file_context_->GetOrCreateFunction(function_id, specific_id);
  111. }
  112. // Builds LLVM function type information for the specified function.
  113. auto BuildFunctionTypeInfo(const SemIR::Function& function,
  114. SemIR::SpecificId specific_id)
  115. -> FileContext::FunctionTypeInfo {
  116. return file_context_->BuildFunctionTypeInfo(function, specific_id);
  117. }
  118. // Returns a lowered type for the given type_id in the given file. This adds
  119. // the specified type to the fingerprint.
  120. auto GetType(TypeInFile type) -> llvm::Type* {
  121. auto* llvm_type = GetFileContext(type.file).GetType(type.type_id);
  122. AddTypeToCurrentFingerprint(llvm_type);
  123. return llvm_type;
  124. }
  125. // Returns the type of the given instruction in the current specific.
  126. auto GetTypeOfInst(SemIR::InstId inst_id) -> llvm::Type* {
  127. return GetType(GetTypeIdOfInst(inst_id));
  128. }
  129. // Returns the type of the given instruction in the current specific.
  130. auto GetTypeIdOfInst(SemIR::InstId inst_id) -> TypeInFile;
  131. // Returns the value representation of the given type. This adds the kind of
  132. // value representation, but not the underlying type, to the fingerprint.
  133. auto GetValueRepr(TypeInFile type) -> ValueReprInFile;
  134. // Returns the initializing representation of the given type. This adds the
  135. // kind of initializing representation to the fingerprint.
  136. auto GetInitRepr(TypeInFile type) -> SemIR::InitRepr;
  137. // Returns the return type information for the given type. This adds the
  138. // kind of initializing representation to the fingerprint.
  139. auto GetReturnTypeInfo(TypeInFile type) -> ReturnTypeInfoInFile;
  140. // Returns a lowered value to use for a value of type `type`.
  141. auto GetTypeAsValue() -> llvm::Value* {
  142. return file_context_->GetTypeAsValue();
  143. }
  144. // Returns a lowered value to use for a value of int literal type.
  145. auto GetIntLiteralAsValue() -> llvm::Constant* {
  146. return file_context_->GetIntLiteralAsValue();
  147. }
  148. // Returns the instruction immediately after all the existing static allocas.
  149. // This is the insert point for future static allocas.
  150. auto GetInstructionAfterAllocas() const -> llvm::Instruction* {
  151. return after_allocas_;
  152. }
  153. // Sets the instruction after static allocas. This should be called once,
  154. // after the first alloca is created.
  155. auto SetInstructionAfterAllocas(llvm::Instruction* after_allocas) -> void {
  156. CARBON_CHECK(!after_allocas_);
  157. after_allocas_ = after_allocas;
  158. }
  159. // Create a synthetic block that corresponds to no SemIR::InstBlockId. Such
  160. // a block should only ever have a single predecessor, and is used when we
  161. // need multiple `llvm::BasicBlock`s to model the linear control flow in a
  162. // single SemIR::File block.
  163. auto MakeSyntheticBlock() -> llvm::BasicBlock*;
  164. // Determine whether block is the most recently created synthetic block.
  165. auto IsCurrentSyntheticBlock(llvm::BasicBlock* block) -> bool {
  166. return synthetic_block_ == block;
  167. }
  168. // Returns the debug location to associate with the specified instruction.
  169. auto GetDebugLoc(SemIR::InstId inst_id) -> llvm::DebugLoc;
  170. // After emitting an initializer `init_id`, finishes performing the
  171. // initialization of `dest_id` from that initializer. This is a no-op if the
  172. // initialization was performed in-place, and otherwise performs a store or a
  173. // copy.
  174. auto FinishInit(TypeInFile type, SemIR::InstId dest_id,
  175. SemIR::InstId source_id) -> void;
  176. // When fingerprinting for a specific, adds the call, found in the function
  177. // body, to <function_id, specific_id>. `function_id` and `specific_id` are
  178. // IDs within the file identified by `function_file_id`.
  179. auto AddCallToCurrentFingerprint(SemIR::CheckIRId file_id,
  180. SemIR::FunctionId function_id,
  181. SemIR::SpecificId specific_id) -> void;
  182. // When fingerprinting for a specific, adds an integer.
  183. auto AddIntToCurrentFingerprint(uint64_t value) -> void;
  184. // When fingerprinting for a specific, adds an enumerator value.
  185. template <typename T>
  186. requires(std::is_enum_v<T>)
  187. auto AddEnumToCurrentFingerprint(T value) -> void {
  188. AddIntToCurrentFingerprint(static_cast<uint64_t>(value));
  189. }
  190. // When fingerprinting for a specific, adds the type.
  191. auto AddTypeToCurrentFingerprint(llvm::Type* type) -> void;
  192. // Emits the final function fingerprints. Only called when function lowering
  193. // is complete.
  194. auto EmitFinalFingerprint() -> void;
  195. // Returns the FileContext to use for lowering in the given file.
  196. auto GetFileContext(const SemIR::File* file) -> FileContext& {
  197. // Avoid hash table lookup for the expected files.
  198. if (file == &sem_ir()) {
  199. return *file_context_;
  200. }
  201. if (file == &specific_sem_ir()) {
  202. return *specific_file_context_;
  203. }
  204. return file_context_->context().GetFileContext(file);
  205. }
  206. auto llvm_context() -> llvm::LLVMContext& {
  207. return file_context_->llvm_context();
  208. }
  209. auto llvm_module() -> llvm::Module& { return file_context_->llvm_module(); }
  210. auto llvm_function() -> llvm::Function& { return *function_; }
  211. auto builder() -> llvm::IRBuilderBase& { return builder_; }
  212. auto sem_ir() -> const SemIR::File& { return file_context_->sem_ir(); }
  213. // The file context for the file that `specific_id()` is within.
  214. auto specific_file_context() -> FileContext& {
  215. return *specific_file_context_;
  216. }
  217. // The file that `specific_id()` is within.
  218. auto specific_sem_ir() -> const SemIR::File& {
  219. return specific_file_context_->sem_ir();
  220. }
  221. // The specific ID for the function that is being lowered. Note that this is
  222. // an ID from `specific_sem_ir()`, not from `sem_ir()`.
  223. auto specific_id() -> SemIR::SpecificId { return specific_id_; }
  224. // TODO: could template on BuiltinFunctionKind if more format
  225. // globals are eventually needed.
  226. auto printf_int_format_string() -> llvm::Value* {
  227. auto* format_string = file_context_->printf_int_format_string();
  228. if (!format_string) {
  229. format_string = builder().CreateGlobalString("%d\n", "printf.int.format");
  230. file_context_->SetPrintfIntFormatString(format_string);
  231. }
  232. return format_string;
  233. }
  234. private:
  235. // Custom instruction inserter for our IR builder. Automatically names
  236. // instructions.
  237. class Inserter : public llvm::IRBuilderDefaultInserter {
  238. public:
  239. explicit Inserter(const SemIR::InstNamer* inst_namer)
  240. : inst_namer_(inst_namer) {}
  241. // Sets the instruction we are currently emitting.
  242. auto SetCurrentInstId(SemIR::InstId inst_id) -> void { inst_id_ = inst_id; }
  243. private:
  244. auto InsertHelper(llvm::Instruction* inst, const llvm::Twine& name,
  245. llvm::BasicBlock::iterator insert_pt) const
  246. -> void override;
  247. // The instruction namer.
  248. const SemIR::InstNamer* inst_namer_;
  249. // The current instruction ID.
  250. SemIR::InstId inst_id_ = SemIR::InstId::None;
  251. };
  252. // Emits a value copy for type `type` from `source_id` to `dest_id`.
  253. // `source_id` must produce a value representation for `type`, and
  254. // `dest_id` must be a pointer to a `type` object.
  255. auto CopyValue(TypeInFile type, SemIR::InstId source_id,
  256. SemIR::InstId dest_id) -> void;
  257. // Emits an object representation copy for type `type` from `source_id` to
  258. // `dest_id`. `source_id` and `dest_id` must produce pointers to `type`
  259. // objects.
  260. auto CopyObject(TypeInFile type, SemIR::InstId source_id,
  261. SemIR::InstId dest_id) -> void;
  262. // When fingerprinting for a specific, adds the global.
  263. auto AddGlobalToCurrentFingerprint(llvm::Value* global) -> void;
  264. // Context for lowering in the file that contains this function's
  265. // instructions.
  266. FileContext* file_context_;
  267. // The IR function we're generating.
  268. llvm::Function* function_;
  269. // Context for lowering in the file that contains our `specific_id_`. Note
  270. // that this is a different file than the one referred to by `file_context_`
  271. // if we are lowering a specific that was generated for a generic function
  272. // defined in a different file.
  273. FileContext* specific_file_context_;
  274. // The specific id, if the function is a specific.
  275. SemIR::SpecificId specific_id_;
  276. // Builder for creating code in this function. The insertion point is held at
  277. // the location of the current SemIR instruction.
  278. llvm::IRBuilder<llvm::ConstantFolder, Inserter> builder_;
  279. // The instruction after all allocas. This is used as the insert point for new
  280. // allocas.
  281. llvm::Instruction* after_allocas_ = nullptr;
  282. llvm::DISubprogram* di_subprogram_;
  283. // The optional vlog stream.
  284. llvm::raw_ostream* vlog_stream_;
  285. // This is initialized and populated while lowering a specific function.
  286. // When complete, this is used to complete the function_fingerprint_.
  287. LoweringFunctionFingerprint current_fingerprint_;
  288. // The accumulated fingerprint is owned by the FileContext and passed into
  289. // the FunctionContext. The function fingerprint is currently only built for
  290. // specific functions, otherwise, this will be nullptr.
  291. SpecificCoalescer::SpecificFunctionFingerprint* function_fingerprint_;
  292. // Maps a function's SemIR::File blocks to lowered blocks.
  293. Map<SemIR::InstBlockId, llvm::BasicBlock*> blocks_;
  294. // The synthetic block we most recently created. May be null if there is no
  295. // such block.
  296. llvm::BasicBlock* synthetic_block_ = nullptr;
  297. // Maps a function's SemIR::File instructions to lowered values.
  298. Map<SemIR::InstId, llvm::Value*> locals_;
  299. };
  300. // Provides handlers for instructions that occur in a FunctionContext. Although
  301. // this is declared for all instructions, it should only be defined for
  302. // instructions which are non-constant and not always typed. See
  303. // `FunctionContext::LowerInst` for how this is used.
  304. #define CARBON_SEM_IR_INST_KIND(Name) \
  305. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id, \
  306. SemIR::Name inst) -> void;
  307. #include "toolchain/sem_ir/inst_kind.def"
  308. } // namespace Carbon::Lower
  309. #endif // CARBON_TOOLCHAIN_LOWER_FUNCTION_CONTEXT_H_