lowering_context.cpp 6.9 KB

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