lowering_context.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 "toolchain/lowering/lowering_function_context.h"
  7. #include "toolchain/semantics/semantics_ir.h"
  8. #include "toolchain/semantics/semantics_node_kind.h"
  9. namespace Carbon {
  10. LoweringContext::LoweringContext(llvm::LLVMContext& llvm_context,
  11. llvm::StringRef module_name,
  12. const SemanticsIR& semantics_ir,
  13. llvm::raw_ostream* vlog_stream)
  14. : llvm_context_(&llvm_context),
  15. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  16. semantics_ir_(&semantics_ir),
  17. vlog_stream_(vlog_stream) {
  18. CARBON_CHECK(!semantics_ir.has_errors())
  19. << "Generating LLVM IR from invalid SemanticsIR is unsupported.";
  20. }
  21. // TODO: Move this to lower_to_llvm.cpp.
  22. auto LoweringContext::Run() -> std::unique_ptr<llvm::Module> {
  23. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  24. // Lower types.
  25. auto types = semantics_ir_->types();
  26. types_.resize_for_overwrite(types.size());
  27. for (int i = 0; i < static_cast<int>(types.size()); ++i) {
  28. types_[i] = BuildType(types[i]);
  29. }
  30. // Lower function declarations.
  31. functions_.resize_for_overwrite(semantics_ir_->functions_size());
  32. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  33. functions_[i] = BuildFunctionDeclaration(SemanticsFunctionId(i));
  34. }
  35. // TODO: Lower global variable declarations.
  36. // Lower function definitions.
  37. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  38. BuildFunctionDefinition(SemanticsFunctionId(i));
  39. }
  40. // TODO: Lower global variable initializers.
  41. return std::move(llvm_module_);
  42. }
  43. auto LoweringContext::BuildFunctionDeclaration(SemanticsFunctionId function_id)
  44. -> llvm::Function* {
  45. auto function = semantics_ir().GetFunction(function_id);
  46. // TODO: Lower type information for the arguments prior to building args.
  47. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  48. llvm::SmallVector<llvm::Type*> args;
  49. args.resize_for_overwrite(param_refs.size());
  50. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  51. args[i] = GetType(semantics_ir().GetNode(param_refs[i]).type_id());
  52. }
  53. llvm::Type* return_type = GetType(function.return_type_id.is_valid()
  54. ? function.return_type_id
  55. : semantics_ir().empty_tuple_type_id());
  56. llvm::FunctionType* function_type =
  57. llvm::FunctionType::get(return_type, args, /*isVarArg=*/false);
  58. auto* llvm_function = llvm::Function::Create(
  59. function_type, llvm::Function::ExternalLinkage,
  60. semantics_ir().GetString(function.name_id), llvm_module());
  61. // Set parameter names.
  62. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  63. auto [param_name_id, _] =
  64. semantics_ir().GetNode(param_refs[i]).GetAsBindName();
  65. llvm_function->getArg(i)->setName(semantics_ir().GetString(param_name_id));
  66. }
  67. return llvm_function;
  68. }
  69. auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id)
  70. -> void {
  71. auto function = semantics_ir().GetFunction(function_id);
  72. auto body_id = function.body_id;
  73. if (!body_id.is_valid()) {
  74. // Function is probably defined in another file; not an error.
  75. return;
  76. }
  77. llvm::Function* llvm_function = GetFunction(function_id);
  78. LoweringFunctionContext function_lowering(*this, llvm_function);
  79. // Add parameters to locals.
  80. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  81. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  82. auto param_storage =
  83. semantics_ir().GetNode(param_refs[i]).GetAsBindName().second;
  84. function_lowering.SetLocal(param_storage, llvm_function->getArg(i));
  85. }
  86. CARBON_VLOG() << "Lowering " << function.body_id << "\n";
  87. for (const auto& node_id : semantics_ir().GetNodeBlock(function.body_id)) {
  88. auto node = semantics_ir().GetNode(node_id);
  89. CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n";
  90. switch (node.kind()) {
  91. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  92. case SemanticsNodeKind::Name: \
  93. LoweringHandle##Name(function_lowering, node_id, node); \
  94. break;
  95. #include "toolchain/semantics/semantics_node_kind.def"
  96. }
  97. }
  98. }
  99. auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* {
  100. switch (node_id.index) {
  101. case SemanticsBuiltinKind::EmptyTupleType.AsInt():
  102. // Represent empty types as empty structs.
  103. // TODO: Investigate special-casing handling of these so that they can be
  104. // collectively replaced with LLVM's void, particularly around function
  105. // returns. LLVM doesn't allow declaring variables with a void type, so
  106. // that may require significant special casing.
  107. return llvm::StructType::create(
  108. *llvm_context_, llvm::ArrayRef<llvm::Type*>(),
  109. SemanticsBuiltinKind::FromInt(node_id.index).name());
  110. case SemanticsBuiltinKind::FloatingPointType.AsInt():
  111. // TODO: Handle different sizes.
  112. return llvm::Type::getDoubleTy(*llvm_context_);
  113. case SemanticsBuiltinKind::IntegerType.AsInt():
  114. // TODO: Handle different sizes.
  115. return llvm::Type::getInt32Ty(*llvm_context_);
  116. case SemanticsBuiltinKind::BoolType.AsInt():
  117. // TODO: We may want to have different representations for `bool` storage
  118. // (`i8`) versus for `bool` values (`i1`).
  119. return llvm::Type::getInt1Ty(*llvm_context_);
  120. }
  121. auto node = semantics_ir_->GetNode(node_id);
  122. switch (node.kind()) {
  123. case SemanticsNodeKind::StructType: {
  124. auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType());
  125. llvm::SmallVector<llvm::Type*> subtypes;
  126. subtypes.reserve(refs.size());
  127. for (auto ref_id : refs) {
  128. auto type_id = semantics_ir_->GetNode(ref_id).type_id();
  129. // TODO: Handle recursive types. The restriction for builtins prevents
  130. // recursion while still letting them cache.
  131. CARBON_CHECK(type_id.index < SemanticsBuiltinKind::ValidCount)
  132. << type_id;
  133. subtypes.push_back(GetType(type_id));
  134. }
  135. return llvm::StructType::create(*llvm_context_, subtypes,
  136. "StructLiteralType");
  137. }
  138. default: {
  139. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  140. }
  141. }
  142. }
  143. } // namespace Carbon