file_context.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/lower/function_context.h"
  9. #include "toolchain/sem_ir/entry_point.h"
  10. #include "toolchain/sem_ir/file.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Lower {
  14. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  15. llvm::StringRef module_name, const SemIR::File& sem_ir,
  16. llvm::raw_ostream* vlog_stream)
  17. : llvm_context_(&llvm_context),
  18. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  19. sem_ir_(&sem_ir),
  20. vlog_stream_(vlog_stream) {
  21. CARBON_CHECK(!sem_ir.has_errors())
  22. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  23. }
  24. // TODO: Move this to lower.cpp.
  25. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  26. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  27. // Lower all types that were required to be complete. Note that this may
  28. // leave some entries in `types_` null, if those types were mentioned but not
  29. // used.
  30. types_.resize(sem_ir_->types().size());
  31. for (auto type_id : sem_ir_->complete_types()) {
  32. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  33. }
  34. // Lower function declarations.
  35. functions_.resize_for_overwrite(sem_ir_->functions().size());
  36. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  37. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  38. }
  39. // TODO: Lower global variable declarations.
  40. // Lower function definitions.
  41. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  42. BuildFunctionDefinition(SemIR::FunctionId(i));
  43. }
  44. // TODO: Lower global variable initializers.
  45. return std::move(llvm_module_);
  46. }
  47. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  48. // All builtins are types, with the same empty lowered value.
  49. if (inst_id.is_builtin()) {
  50. return GetTypeAsValue();
  51. }
  52. auto target = sem_ir().insts().Get(inst_id);
  53. if (auto function_decl = target.TryAs<SemIR::FunctionDecl>()) {
  54. return GetFunction(function_decl->function_id);
  55. }
  56. if (target.Is<SemIR::AssociatedEntity>()) {
  57. return llvm::ConstantStruct::getAnon(llvm_context(), {});
  58. }
  59. if (target.type_id() == SemIR::TypeId::TypeType) {
  60. return GetTypeAsValue();
  61. }
  62. CARBON_FATAL() << "Missing value: " << inst_id << " " << target;
  63. }
  64. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  65. -> llvm::Function* {
  66. const auto& function = sem_ir().functions().Get(function_id);
  67. const bool has_return_slot = function.return_slot_id.is_valid();
  68. auto implicit_param_refs =
  69. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  70. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  71. SemIR::InitRepr return_rep =
  72. function.return_type_id.is_valid()
  73. ? SemIR::GetInitRepr(sem_ir(), function.return_type_id)
  74. : SemIR::InitRepr{.kind = SemIR::InitRepr::None};
  75. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  76. llvm::SmallVector<llvm::Type*> param_types;
  77. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  78. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  79. // out a mechanism to compute the mapping between parameters and arguments on
  80. // demand.
  81. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  82. auto max_llvm_params =
  83. has_return_slot + implicit_param_refs.size() + param_refs.size();
  84. param_types.reserve(max_llvm_params);
  85. param_inst_ids.reserve(max_llvm_params);
  86. if (has_return_slot) {
  87. param_types.push_back(GetType(function.return_type_id)->getPointerTo());
  88. param_inst_ids.push_back(function.return_slot_id);
  89. }
  90. for (auto param_ref_id :
  91. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  92. auto param_type_id =
  93. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id)
  94. .second.type_id;
  95. switch (auto value_rep = SemIR::GetValueRepr(sem_ir(), param_type_id);
  96. value_rep.kind) {
  97. case SemIR::ValueRepr::Unknown:
  98. CARBON_FATAL()
  99. << "Incomplete parameter type lowering function declaration";
  100. case SemIR::ValueRepr::None:
  101. break;
  102. case SemIR::ValueRepr::Copy:
  103. case SemIR::ValueRepr::Custom:
  104. case SemIR::ValueRepr::Pointer:
  105. param_types.push_back(GetType(value_rep.type_id));
  106. param_inst_ids.push_back(param_ref_id);
  107. break;
  108. }
  109. }
  110. // If the initializing representation doesn't produce a value, set the return
  111. // type to void.
  112. llvm::Type* return_type = return_rep.kind == SemIR::InitRepr::ByCopy
  113. ? GetType(function.return_type_id)
  114. : llvm::Type::getVoidTy(llvm_context());
  115. std::string mangled_name;
  116. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  117. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  118. mangled_name = "main";
  119. } else if (auto name =
  120. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  121. // TODO: Decide on a name mangling scheme.
  122. mangled_name = *name;
  123. } else {
  124. CARBON_FATAL() << "Unexpected special name for function: "
  125. << function.name_id;
  126. }
  127. llvm::FunctionType* function_type =
  128. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  129. auto* llvm_function =
  130. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  131. mangled_name, llvm_module());
  132. // Set up parameters and the return slot.
  133. for (auto [inst_id, arg] :
  134. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  135. auto name_id = SemIR::NameId::Invalid;
  136. if (inst_id == function.return_slot_id) {
  137. name_id = SemIR::NameId::ReturnSlot;
  138. arg.addAttr(llvm::Attribute::getWithStructRetType(
  139. llvm_context(), GetType(function.return_type_id)));
  140. } else {
  141. name_id = SemIR::Function::GetParamFromParamRefId(sem_ir(), inst_id)
  142. .second.name_id;
  143. }
  144. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  145. }
  146. return llvm_function;
  147. }
  148. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  149. -> void {
  150. const auto& function = sem_ir().functions().Get(function_id);
  151. const auto& body_block_ids = function.body_block_ids;
  152. if (body_block_ids.empty()) {
  153. // Function is probably defined in another file; not an error.
  154. return;
  155. }
  156. llvm::Function* llvm_function = GetFunction(function_id);
  157. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  158. const bool has_return_slot = function.return_slot_id.is_valid();
  159. // Add parameters to locals.
  160. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  161. // function parameters that was already computed in BuildFunctionDecl.
  162. // We should only do that once.
  163. auto implicit_param_refs =
  164. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  165. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  166. int param_index = 0;
  167. if (has_return_slot) {
  168. function_lowering.SetLocal(function.return_slot_id,
  169. llvm_function->getArg(param_index));
  170. ++param_index;
  171. }
  172. for (auto param_ref_id :
  173. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  174. auto [param_id, param] =
  175. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id);
  176. // Get the value of the parameter from the function argument.
  177. auto param_type_id = param.type_id;
  178. llvm::Value* param_value = llvm::PoisonValue::get(GetType(param_type_id));
  179. if (SemIR::GetValueRepr(sem_ir(), param_type_id).kind !=
  180. SemIR::ValueRepr::None) {
  181. param_value = llvm_function->getArg(param_index);
  182. ++param_index;
  183. }
  184. // The value of the parameter is the value of the argument.
  185. function_lowering.SetLocal(param_id, param_value);
  186. // Match the portion of the pattern corresponding to the parameter against
  187. // the parameter value. For now this is always a single name binding,
  188. // possibly wrapped in `addr`.
  189. //
  190. // TODO: Support general patterns here.
  191. auto bind_name_id = param_ref_id;
  192. if (auto addr =
  193. sem_ir().insts().TryGetAs<SemIR::AddrPattern>(param_ref_id)) {
  194. bind_name_id = addr->inner_id;
  195. }
  196. auto bind_name = sem_ir().insts().Get(bind_name_id);
  197. // TODO: Should we stop passing compile-time bindings at runtime?
  198. CARBON_CHECK(bind_name.Is<SemIR::AnyBindName>());
  199. function_lowering.SetLocal(bind_name_id, param_value);
  200. }
  201. // Lower all blocks.
  202. for (auto block_id : body_block_ids) {
  203. CARBON_VLOG() << "Lowering " << block_id << "\n";
  204. auto* llvm_block = function_lowering.GetBlock(block_id);
  205. // Keep the LLVM blocks in lexical order.
  206. llvm_block->moveBefore(llvm_function->end());
  207. function_lowering.builder().SetInsertPoint(llvm_block);
  208. function_lowering.LowerBlock(block_id);
  209. }
  210. // LLVM requires that the entry block has no predecessors.
  211. auto* entry_block = &llvm_function->getEntryBlock();
  212. if (entry_block->hasNPredecessorsOrMore(1)) {
  213. auto* new_entry_block = llvm::BasicBlock::Create(
  214. llvm_context(), "entry", llvm_function, entry_block);
  215. llvm::BranchInst::Create(entry_block, new_entry_block);
  216. }
  217. }
  218. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  219. switch (inst_id.index) {
  220. case SemIR::BuiltinKind::FloatType.AsInt():
  221. // TODO: Handle different sizes.
  222. return llvm::Type::getDoubleTy(*llvm_context_);
  223. case SemIR::BuiltinKind::IntType.AsInt():
  224. // TODO: Handle different sizes.
  225. return llvm::Type::getInt32Ty(*llvm_context_);
  226. case SemIR::BuiltinKind::BoolType.AsInt():
  227. // TODO: We may want to have different representations for `bool` storage
  228. // (`i8`) versus for `bool` values (`i1`).
  229. return llvm::Type::getInt1Ty(*llvm_context_);
  230. case SemIR::BuiltinKind::FunctionType.AsInt():
  231. case SemIR::BuiltinKind::BoundMethodType.AsInt():
  232. case SemIR::BuiltinKind::NamespaceType.AsInt():
  233. // Return an empty struct as a placeholder.
  234. return llvm::StructType::get(*llvm_context_);
  235. default:
  236. // Handled below.
  237. break;
  238. }
  239. auto inst = sem_ir_->insts().Get(inst_id);
  240. switch (inst.kind()) {
  241. case SemIR::ArrayType::Kind: {
  242. auto array_type = inst.As<SemIR::ArrayType>();
  243. return llvm::ArrayType::get(
  244. GetType(array_type.element_type_id),
  245. sem_ir_->GetArrayBoundValue(array_type.bound_id));
  246. }
  247. case SemIR::AssociatedEntityType::Kind:
  248. // No runtime operations are provided on an associated entity name, so use
  249. // an empty representation.
  250. return llvm::StructType::get(*llvm_context_);
  251. case SemIR::BindSymbolicName::Kind:
  252. // Treat non-monomorphized type bindings as opaque.
  253. return llvm::StructType::get(*llvm_context_);
  254. case SemIR::ClassType::Kind: {
  255. auto object_repr_id = sem_ir_->classes()
  256. .Get(inst.As<SemIR::ClassType>().class_id)
  257. .object_repr_id;
  258. return GetType(object_repr_id);
  259. }
  260. case SemIR::ConstType::Kind:
  261. return GetType(inst.As<SemIR::ConstType>().inner_id);
  262. case SemIR::InterfaceType::Kind:
  263. // Return an empty struct as a placeholder.
  264. // TODO: Should we model an interface as a witness table?
  265. return llvm::StructType::get(*llvm_context_);
  266. case SemIR::PointerType::Kind:
  267. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  268. case SemIR::StructType::Kind: {
  269. auto fields =
  270. sem_ir_->inst_blocks().Get(inst.As<SemIR::StructType>().fields_id);
  271. llvm::SmallVector<llvm::Type*> subtypes;
  272. subtypes.reserve(fields.size());
  273. for (auto field_id : fields) {
  274. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  275. subtypes.push_back(GetType(field.field_type_id));
  276. }
  277. return llvm::StructType::get(*llvm_context_, subtypes);
  278. }
  279. case SemIR::TupleType::Kind: {
  280. // TODO: Investigate special-casing handling of empty tuples so that they
  281. // can be collectively replaced with LLVM's void, particularly around
  282. // function returns. LLVM doesn't allow declaring variables with a void
  283. // type, so that may require significant special casing.
  284. auto elements =
  285. sem_ir_->type_blocks().Get(inst.As<SemIR::TupleType>().elements_id);
  286. llvm::SmallVector<llvm::Type*> subtypes;
  287. subtypes.reserve(elements.size());
  288. for (auto element_id : elements) {
  289. subtypes.push_back(GetType(element_id));
  290. }
  291. return llvm::StructType::get(*llvm_context_, subtypes);
  292. }
  293. case SemIR::UnboundElementType::Kind: {
  294. // Return an empty struct as a placeholder.
  295. return llvm::StructType::get(*llvm_context_);
  296. }
  297. default: {
  298. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " " << inst;
  299. }
  300. }
  301. }
  302. } // namespace Carbon::Lower