file_context.cpp 18 KB

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