lowering_context.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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/lowering/lowering_context.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/Sequence.h"
  8. #include "toolchain/lowering/lowering_function_context.h"
  9. #include "toolchain/semantics/semantics_ir.h"
  10. #include "toolchain/semantics/semantics_node.h"
  11. #include "toolchain/semantics/semantics_node_kind.h"
  12. namespace Carbon {
  13. LoweringContext::LoweringContext(llvm::LLVMContext& llvm_context,
  14. llvm::StringRef module_name,
  15. const SemIR::File& semantics_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. semantics_ir_(&semantics_ir),
  20. vlog_stream_(vlog_stream) {
  21. CARBON_CHECK(!semantics_ir.has_errors())
  22. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  23. }
  24. // TODO: Move this to lower_to_llvm.cpp.
  25. auto LoweringContext::Run() -> std::unique_ptr<llvm::Module> {
  26. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  27. // Lower types.
  28. auto types = semantics_ir_->types();
  29. types_.resize_for_overwrite(types.size());
  30. for (auto [i, type] : llvm::enumerate(types)) {
  31. types_[i] = BuildType(type);
  32. }
  33. // Lower function declarations.
  34. functions_.resize_for_overwrite(semantics_ir_->functions_size());
  35. for (auto i : llvm::seq(semantics_ir_->functions_size())) {
  36. functions_[i] = BuildFunctionDeclaration(SemIR::FunctionId(i));
  37. }
  38. // TODO: Lower global variable declarations.
  39. // Lower function definitions.
  40. for (auto i : llvm::seq(semantics_ir_->functions_size())) {
  41. BuildFunctionDefinition(SemIR::FunctionId(i));
  42. }
  43. // TODO: Lower global variable initializers.
  44. return std::move(llvm_module_);
  45. }
  46. auto LoweringContext::BuildFunctionDeclaration(SemIR::FunctionId function_id)
  47. -> llvm::Function* {
  48. auto function = semantics_ir().GetFunction(function_id);
  49. // TODO: Lower type information for the arguments prior to building args.
  50. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  51. llvm::SmallVector<llvm::Type*> args;
  52. args.resize_for_overwrite(param_refs.size());
  53. for (auto [i, param_ref] : llvm::enumerate(param_refs)) {
  54. args[i] = GetType(semantics_ir().GetNode(param_ref).type_id());
  55. }
  56. // If return type is not valid, the function does not have a return type.
  57. // Hence, set return type to void.
  58. llvm::Type* return_type = function.return_type_id.is_valid()
  59. ? GetType(function.return_type_id)
  60. : llvm::Type::getVoidTy(llvm_context());
  61. llvm::FunctionType* function_type =
  62. llvm::FunctionType::get(return_type, args, /*isVarArg=*/false);
  63. auto* llvm_function = llvm::Function::Create(
  64. function_type, llvm::Function::ExternalLinkage,
  65. semantics_ir().GetString(function.name_id), llvm_module());
  66. // Set parameter names.
  67. for (auto [i, param_ref] : llvm::enumerate(param_refs)) {
  68. auto name_id = semantics_ir().GetNode(param_ref).GetAsParameter();
  69. llvm_function->getArg(i)->setName(semantics_ir().GetString(name_id));
  70. }
  71. return llvm_function;
  72. }
  73. auto LoweringContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  74. -> void {
  75. auto function = semantics_ir().GetFunction(function_id);
  76. const auto& body_block_ids = function.body_block_ids;
  77. if (body_block_ids.empty()) {
  78. // Function is probably defined in another file; not an error.
  79. return;
  80. }
  81. llvm::Function* llvm_function = GetFunction(function_id);
  82. LoweringFunctionContext function_lowering(*this, llvm_function);
  83. // Add parameters to locals.
  84. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  85. for (auto [i, param_ref] : llvm::enumerate(param_refs)) {
  86. function_lowering.SetLocal(param_ref, llvm_function->getArg(i));
  87. }
  88. // Lower all blocks.
  89. // TODO: Determine the set of reachable blocks, and only lower those ones.
  90. for (auto block_id : body_block_ids) {
  91. CARBON_VLOG() << "Lowering " << block_id << "\n";
  92. auto* llvm_block = function_lowering.GetBlock(block_id);
  93. // Keep the LLVM blocks in lexical order.
  94. llvm_block->moveBefore(llvm_function->end());
  95. function_lowering.builder().SetInsertPoint(llvm_block);
  96. for (const auto& node_id : semantics_ir().GetNodeBlock(block_id)) {
  97. auto node = semantics_ir().GetNode(node_id);
  98. CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n";
  99. switch (node.kind()) {
  100. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  101. case SemIR::NodeKind::Name: \
  102. LoweringHandle##Name(function_lowering, node_id, node); \
  103. break;
  104. #include "toolchain/semantics/semantics_node_kind.def"
  105. }
  106. }
  107. }
  108. }
  109. auto LoweringContext::BuildType(SemIR::NodeId node_id) -> llvm::Type* {
  110. switch (node_id.index) {
  111. case SemIR::BuiltinKind::FloatingPointType.AsInt():
  112. // TODO: Handle different sizes.
  113. return llvm::Type::getDoubleTy(*llvm_context_);
  114. case SemIR::BuiltinKind::IntegerType.AsInt():
  115. // TODO: Handle different sizes.
  116. return llvm::Type::getInt32Ty(*llvm_context_);
  117. case SemIR::BuiltinKind::BoolType.AsInt():
  118. // TODO: We may want to have different representations for `bool` storage
  119. // (`i8`) versus for `bool` values (`i1`).
  120. return llvm::Type::getInt1Ty(*llvm_context_);
  121. }
  122. auto node = semantics_ir_->GetNode(node_id);
  123. switch (node.kind()) {
  124. case SemIR::NodeKind::ArrayType: {
  125. auto [bound_node_id, type_id] = node.GetAsArrayType();
  126. return llvm::ArrayType::get(
  127. GetType(type_id), semantics_ir_->GetArrayBoundValue(bound_node_id));
  128. }
  129. case SemIR::NodeKind::ConstType:
  130. return GetType(node.GetAsConstType());
  131. case SemIR::NodeKind::PointerType:
  132. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  133. case SemIR::NodeKind::StructType: {
  134. auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType());
  135. llvm::SmallVector<llvm::Type*> subtypes;
  136. subtypes.reserve(refs.size());
  137. for (auto ref_id : refs) {
  138. auto [field_name_id, field_type_id] =
  139. semantics_ir_->GetNode(ref_id).GetAsStructTypeField();
  140. // TODO: Handle recursive types. The restriction for builtins prevents
  141. // recursion while still letting them cache.
  142. CARBON_CHECK(field_type_id.index < SemIR::BuiltinKind::ValidCount)
  143. << field_type_id;
  144. subtypes.push_back(GetType(field_type_id));
  145. }
  146. return llvm::StructType::get(*llvm_context_, subtypes);
  147. }
  148. case SemIR::NodeKind::TupleType: {
  149. // TODO: Investigate special-casing handling of empty tuples so that they
  150. // can be collectively replaced with LLVM's void, particularly around
  151. // function returns. LLVM doesn't allow declaring variables with a void
  152. // type, so that may require significant special casing.
  153. auto refs = semantics_ir_->GetTypeBlock(node.GetAsTupleType());
  154. llvm::SmallVector<llvm::Type*> subtypes;
  155. subtypes.reserve(refs.size());
  156. for (auto ref_id : refs) {
  157. subtypes.push_back(GetType(ref_id));
  158. }
  159. return llvm::StructType::get(*llvm_context_, subtypes);
  160. }
  161. default: {
  162. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  163. }
  164. }
  165. }
  166. } // namespace Carbon