file_context.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. #include "toolchain/lower/file_context.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/Sequence.h"
  8. #include "toolchain/base/kind_switch.h"
  9. #include "toolchain/lower/constant.h"
  10. #include "toolchain/lower/function_context.h"
  11. #include "toolchain/sem_ir/entry_point.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/function.h"
  14. #include "toolchain/sem_ir/ids.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Lower {
  18. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  19. llvm::StringRef module_name, const SemIR::File& sem_ir,
  20. const SemIR::InstNamer* inst_namer,
  21. llvm::raw_ostream* vlog_stream)
  22. : llvm_context_(&llvm_context),
  23. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  24. sem_ir_(&sem_ir),
  25. inst_namer_(inst_namer),
  26. vlog_stream_(vlog_stream) {
  27. CARBON_CHECK(!sem_ir.has_errors())
  28. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  29. }
  30. // TODO: Move this to lower.cpp.
  31. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  32. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  33. // Lower all types that were required to be complete.
  34. types_.resize(sem_ir_->insts().size());
  35. for (auto type_id : sem_ir_->types().complete_types()) {
  36. if (type_id.index >= 0) {
  37. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  38. }
  39. }
  40. // Lower function declarations.
  41. functions_.resize_for_overwrite(sem_ir_->functions().size());
  42. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  43. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  44. }
  45. // TODO: Lower global variable declarations.
  46. // Lower constants.
  47. constants_.resize(sem_ir_->insts().size());
  48. LowerConstants(*this, constants_);
  49. // Lower function definitions.
  50. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  51. BuildFunctionDefinition(SemIR::FunctionId(i));
  52. }
  53. // TODO: Lower global variable initializers.
  54. return std::move(llvm_module_);
  55. }
  56. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  57. auto inst = sem_ir().insts().Get(inst_id);
  58. auto const_id = sem_ir().constant_values().Get(inst_id);
  59. if (const_id.is_template()) {
  60. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  61. // For value expressions and initializing expressions, the value produced by
  62. // a constant instruction is a value representation of the constant. For
  63. // initializing expressions, `FinishInit` will perform a copy if needed.
  64. // TODO: Handle reference expression constants.
  65. auto* const_value = constants_[const_inst_id.index];
  66. // If we want a pointer to the constant, materialize a global to hold it.
  67. // TODO: We could reuse the same global if the constant is used more than
  68. // once.
  69. auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), inst.type_id());
  70. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  71. // Include both the name of the constant, if any, and the point of use in
  72. // the name of the variable.
  73. llvm::StringRef const_name;
  74. llvm::StringRef use_name;
  75. if (inst_namer_) {
  76. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  77. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  78. }
  79. // We always need to give the global a name even if the instruction namer
  80. // doesn't have one to use.
  81. if (const_name.empty()) {
  82. const_name = "const";
  83. }
  84. if (use_name.empty()) {
  85. use_name = "anon";
  86. }
  87. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  88. return new llvm::GlobalVariable(
  89. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  90. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage,
  91. const_value, const_name + sep + use_name);
  92. }
  93. // Otherwise, we can use the constant value directly.
  94. return const_value;
  95. }
  96. // TODO: For generics, handle references to symbolic constants.
  97. CARBON_FATAL() << "Missing value: " << inst_id << " "
  98. << sem_ir().insts().Get(inst_id);
  99. }
  100. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  101. -> llvm::Function* {
  102. const auto& function = sem_ir().functions().Get(function_id);
  103. // Don't lower generic functions or associated functions.
  104. // TODO: Associated functions have `Self` in scope so should be treated as
  105. // generic functions.
  106. if (function.generic_id.is_valid() ||
  107. sem_ir().insts().Is<SemIR::InterfaceDecl>(
  108. sem_ir().name_scopes().Get(function.parent_scope_id).inst_id)) {
  109. return nullptr;
  110. }
  111. // Don't lower builtins.
  112. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  113. return nullptr;
  114. }
  115. // TODO: Consider tracking whether the function has been used, and only
  116. // lowering it if it's needed.
  117. // TODO: Pass in a specific ID for generic functions.
  118. const auto specific_id = SemIR::SpecificId::Invalid;
  119. const auto return_info =
  120. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  121. CARBON_CHECK(return_info.is_valid()) << "Should not lower invalid functions.";
  122. auto implicit_param_refs =
  123. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  124. // TODO: Include parameters corresponding to positional parameters.
  125. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  126. auto* return_type =
  127. return_info.type_id.is_valid() ? GetType(return_info.type_id) : nullptr;
  128. llvm::SmallVector<llvm::Type*> param_types;
  129. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  130. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  131. // out a mechanism to compute the mapping between parameters and arguments on
  132. // demand.
  133. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  134. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  135. implicit_param_refs.size() + param_refs.size();
  136. param_types.reserve(max_llvm_params);
  137. param_inst_ids.reserve(max_llvm_params);
  138. if (return_info.has_return_slot()) {
  139. param_types.push_back(return_type->getPointerTo());
  140. param_inst_ids.push_back(function.return_storage_id);
  141. }
  142. for (auto param_ref_id :
  143. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  144. auto param_type_id =
  145. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id)
  146. .second.type_id;
  147. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  148. value_rep.kind) {
  149. case SemIR::ValueRepr::Unknown:
  150. CARBON_FATAL()
  151. << "Incomplete parameter type lowering function declaration";
  152. case SemIR::ValueRepr::None:
  153. break;
  154. case SemIR::ValueRepr::Copy:
  155. case SemIR::ValueRepr::Custom:
  156. case SemIR::ValueRepr::Pointer:
  157. param_types.push_back(GetType(value_rep.type_id));
  158. param_inst_ids.push_back(param_ref_id);
  159. break;
  160. }
  161. }
  162. // Compute the return type to use for the LLVM function. If the initializing
  163. // representation doesn't produce a value, set the return type to void.
  164. llvm::Type* function_return_type =
  165. return_info.init_repr.kind == SemIR::InitRepr::ByCopy
  166. ? return_type
  167. : llvm::Type::getVoidTy(llvm_context());
  168. std::string mangled_name;
  169. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  170. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  171. mangled_name = "main";
  172. } else if (auto name =
  173. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  174. // TODO: Decide on a name mangling scheme.
  175. mangled_name = *name;
  176. } else {
  177. CARBON_FATAL() << "Unexpected special name for function: "
  178. << function.name_id;
  179. }
  180. llvm::FunctionType* function_type = llvm::FunctionType::get(
  181. function_return_type, param_types, /*isVarArg=*/false);
  182. auto* llvm_function =
  183. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  184. mangled_name, llvm_module());
  185. // Set up parameters and the return slot.
  186. for (auto [inst_id, arg] :
  187. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  188. auto name_id = SemIR::NameId::Invalid;
  189. if (inst_id == function.return_storage_id) {
  190. name_id = SemIR::NameId::ReturnSlot;
  191. arg.addAttr(
  192. llvm::Attribute::getWithStructRetType(llvm_context(), return_type));
  193. } else {
  194. name_id = SemIR::Function::GetParamFromParamRefId(sem_ir(), inst_id)
  195. .second.name_id;
  196. }
  197. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  198. }
  199. return llvm_function;
  200. }
  201. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  202. -> void {
  203. const auto& function = sem_ir().functions().Get(function_id);
  204. const auto& body_block_ids = function.body_block_ids;
  205. if (body_block_ids.empty()) {
  206. // Function is probably defined in another file; not an error.
  207. return;
  208. }
  209. llvm::Function* llvm_function = GetFunction(function_id);
  210. if (!llvm_function) {
  211. // We chose not to lower this function at all, for example because it's a
  212. // generic function.
  213. return;
  214. }
  215. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  216. // TODO: Pass in a specific ID for generic functions.
  217. const auto specific_id = SemIR::SpecificId::Invalid;
  218. // Add parameters to locals.
  219. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  220. // function parameters that was already computed in BuildFunctionDecl.
  221. // We should only do that once.
  222. auto implicit_param_refs =
  223. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  224. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  225. int param_index = 0;
  226. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id)
  227. .has_return_slot()) {
  228. function_lowering.SetLocal(function.return_storage_id,
  229. llvm_function->getArg(param_index));
  230. ++param_index;
  231. }
  232. for (auto param_ref_id :
  233. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  234. auto [param_id, param] =
  235. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id);
  236. // Get the value of the parameter from the function argument.
  237. auto param_type_id = param.type_id;
  238. llvm::Value* param_value = llvm::PoisonValue::get(GetType(param_type_id));
  239. if (SemIR::ValueRepr::ForType(sem_ir(), param_type_id).kind !=
  240. SemIR::ValueRepr::None) {
  241. param_value = llvm_function->getArg(param_index);
  242. ++param_index;
  243. }
  244. // The value of the parameter is the value of the argument.
  245. function_lowering.SetLocal(param_id, param_value);
  246. // Match the portion of the pattern corresponding to the parameter against
  247. // the parameter value. For now this is always a single name binding,
  248. // possibly wrapped in `addr`.
  249. //
  250. // TODO: Support general patterns here.
  251. auto bind_name_id = param_ref_id;
  252. if (auto addr =
  253. sem_ir().insts().TryGetAs<SemIR::AddrPattern>(param_ref_id)) {
  254. bind_name_id = addr->inner_id;
  255. }
  256. auto bind_name = sem_ir().insts().Get(bind_name_id);
  257. // TODO: Should we stop passing compile-time bindings at runtime?
  258. CARBON_CHECK(bind_name.Is<SemIR::AnyBindName>());
  259. function_lowering.SetLocal(bind_name_id, param_value);
  260. }
  261. // Lower all blocks.
  262. for (auto block_id : body_block_ids) {
  263. CARBON_VLOG() << "Lowering " << block_id << "\n";
  264. auto* llvm_block = function_lowering.GetBlock(block_id);
  265. // Keep the LLVM blocks in lexical order.
  266. llvm_block->moveBefore(llvm_function->end());
  267. function_lowering.builder().SetInsertPoint(llvm_block);
  268. function_lowering.LowerBlock(block_id);
  269. }
  270. // LLVM requires that the entry block has no predecessors.
  271. auto* entry_block = &llvm_function->getEntryBlock();
  272. if (entry_block->hasNPredecessorsOrMore(1)) {
  273. auto* new_entry_block = llvm::BasicBlock::Create(
  274. llvm_context(), "entry", llvm_function, entry_block);
  275. llvm::BranchInst::Create(entry_block, new_entry_block);
  276. }
  277. }
  278. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  279. -> llvm::Type* {
  280. return llvm::ArrayType::get(
  281. context.GetType(inst.element_type_id),
  282. context.sem_ir().GetArrayBoundValue(inst.bound_id));
  283. }
  284. static auto BuildTypeForInst(FileContext& context, SemIR::BuiltinInst inst)
  285. -> llvm::Type* {
  286. switch (inst.builtin_inst_kind) {
  287. case SemIR::BuiltinInstKind::Invalid:
  288. CARBON_FATAL() << "Unexpected builtin type in lowering.";
  289. case SemIR::BuiltinInstKind::Error:
  290. // This is a complete type but uses of it should never be lowered.
  291. return nullptr;
  292. case SemIR::BuiltinInstKind::TypeType:
  293. return context.GetTypeType();
  294. case SemIR::BuiltinInstKind::FloatType:
  295. return llvm::Type::getDoubleTy(context.llvm_context());
  296. case SemIR::BuiltinInstKind::IntType:
  297. return llvm::Type::getInt32Ty(context.llvm_context());
  298. case SemIR::BuiltinInstKind::BoolType:
  299. // TODO: We may want to have different representations for `bool`
  300. // storage
  301. // (`i8`) versus for `bool` values (`i1`).
  302. return llvm::Type::getInt1Ty(context.llvm_context());
  303. case SemIR::BuiltinInstKind::StringType:
  304. // TODO: Decide how we want to represent `StringType`.
  305. return llvm::PointerType::get(context.llvm_context(), 0);
  306. case SemIR::BuiltinInstKind::BoundMethodType:
  307. case SemIR::BuiltinInstKind::NamespaceType:
  308. case SemIR::BuiltinInstKind::WitnessType:
  309. // Return an empty struct as a placeholder.
  310. return llvm::StructType::get(context.llvm_context());
  311. }
  312. }
  313. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  314. // Implementations return the LLVM type for the instruction. This first overload
  315. // is the fallback handler for non-type instructions.
  316. template <typename InstT>
  317. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  318. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  319. -> llvm::Type* {
  320. CARBON_FATAL() << "Cannot use inst as type: " << inst;
  321. }
  322. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  323. -> llvm::Type* {
  324. auto object_repr_id =
  325. context.sem_ir().classes().Get(inst.class_id).object_repr_id;
  326. return context.GetType(object_repr_id);
  327. }
  328. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  329. -> llvm::Type* {
  330. return context.GetType(inst.inner_id);
  331. }
  332. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  333. -> llvm::Type* {
  334. // TODO: Handle different sizes.
  335. return llvm::Type::getDoubleTy(context.llvm_context());
  336. }
  337. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  338. -> llvm::Type* {
  339. auto width =
  340. context.sem_ir().insts().TryGetAs<SemIR::IntLiteral>(inst.bit_width_id);
  341. CARBON_CHECK(width) << "Can't lower int type with symbolic width";
  342. return llvm::IntegerType::get(
  343. context.llvm_context(),
  344. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  345. }
  346. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  347. -> llvm::Type* {
  348. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  349. }
  350. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  351. -> llvm::Type* {
  352. auto fields = context.sem_ir().inst_blocks().Get(inst.fields_id);
  353. llvm::SmallVector<llvm::Type*> subtypes;
  354. subtypes.reserve(fields.size());
  355. for (auto field_id : fields) {
  356. auto field =
  357. context.sem_ir().insts().GetAs<SemIR::StructTypeField>(field_id);
  358. subtypes.push_back(context.GetType(field.field_type_id));
  359. }
  360. return llvm::StructType::get(context.llvm_context(), subtypes);
  361. }
  362. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  363. -> llvm::Type* {
  364. // TODO: Investigate special-casing handling of empty tuples so that they
  365. // can be collectively replaced with LLVM's void, particularly around
  366. // function returns. LLVM doesn't allow declaring variables with a void
  367. // type, so that may require significant special casing.
  368. auto elements = context.sem_ir().type_blocks().Get(inst.elements_id);
  369. llvm::SmallVector<llvm::Type*> subtypes;
  370. subtypes.reserve(elements.size());
  371. for (auto element_id : elements) {
  372. subtypes.push_back(context.GetType(element_id));
  373. }
  374. return llvm::StructType::get(context.llvm_context(), subtypes);
  375. }
  376. template <typename InstT>
  377. requires(InstT::Kind.template IsAnyOf<
  378. SemIR::AssociatedEntityType, SemIR::FunctionType,
  379. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  380. SemIR::InterfaceType, SemIR::UnboundElementType>())
  381. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  382. -> llvm::Type* {
  383. // Return an empty struct as a placeholder.
  384. // TODO: Should we model an interface as a witness table, or an associated
  385. // entity as an index?
  386. return llvm::StructType::get(context.llvm_context());
  387. }
  388. // Treat non-monomorphized symbolic types as opaque.
  389. template <typename InstT>
  390. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  391. SemIR::InterfaceWitnessAccess>())
  392. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  393. -> llvm::Type* {
  394. return llvm::StructType::get(context.llvm_context());
  395. }
  396. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  397. // Use overload resolution to select the implementation, producing compile
  398. // errors when BuildTypeForInst isn't defined for a given instruction.
  399. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  400. #define CARBON_SEM_IR_INST_KIND(Name) \
  401. case CARBON_KIND(SemIR::Name inst): { \
  402. return BuildTypeForInst(*this, inst); \
  403. }
  404. #include "toolchain/sem_ir/inst_kind.def"
  405. }
  406. }
  407. } // namespace Carbon::Lower