function_context.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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/function_context.h"
  5. #include "common/vlog.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/sem_ir/file.h"
  8. namespace Carbon::Lower {
  9. FunctionContext::FunctionContext(FileContext& file_context,
  10. llvm::Function* function,
  11. llvm::raw_ostream* vlog_stream)
  12. : file_context_(&file_context),
  13. function_(function),
  14. builder_(file_context.llvm_context(), llvm::ConstantFolder(),
  15. Inserter(file_context.inst_namer())),
  16. vlog_stream_(vlog_stream) {}
  17. auto FunctionContext::GetBlock(SemIR::InstBlockId block_id)
  18. -> llvm::BasicBlock* {
  19. auto result = blocks_.Insert(block_id, [&] {
  20. llvm::StringRef label_name;
  21. if (const auto* inst_namer = file_context_->inst_namer()) {
  22. label_name = inst_namer->GetUnscopedLabelFor(block_id);
  23. }
  24. return llvm::BasicBlock::Create(llvm_context(), label_name, function_);
  25. });
  26. return result.value();
  27. }
  28. auto FunctionContext::TryToReuseBlock(SemIR::InstBlockId block_id,
  29. llvm::BasicBlock* block) -> bool {
  30. if (!blocks_.Insert(block_id, block).is_inserted()) {
  31. return false;
  32. }
  33. if (block == synthetic_block_) {
  34. synthetic_block_ = nullptr;
  35. }
  36. if (const auto* inst_namer = file_context_->inst_namer()) {
  37. block->setName(inst_namer->GetUnscopedLabelFor(block_id));
  38. }
  39. return true;
  40. }
  41. auto FunctionContext::LowerBlock(SemIR::InstBlockId block_id) -> void {
  42. for (auto inst_id : sem_ir().inst_blocks().Get(block_id)) {
  43. LowerInst(inst_id);
  44. }
  45. }
  46. // Handles typed instructions for LowerInst. Many instructions lower using
  47. // HandleInst, but others are unsupported or have trivial lowering.
  48. //
  49. // This only calls HandleInst for versions that should have implementations. A
  50. // different approach would be to have the logic below implemented as HandleInst
  51. // overloads. However, forward declarations of HandleInst exist for all `InstT`
  52. // types, which would make getting the right overload resolution complex.
  53. template <typename InstT>
  54. static auto LowerInstHelper(FunctionContext& context, SemIR::InstId inst_id,
  55. InstT inst) {
  56. if constexpr (!InstT::Kind.is_lowered()) {
  57. CARBON_FATAL()
  58. << "Encountered an instruction that isn't expected to lower. It's "
  59. "possible that logic needs to be changed in order to stop "
  60. "showing this instruction in lowered contexts. Instruction: "
  61. << inst;
  62. } else if constexpr (InstT::Kind.constant_kind() ==
  63. SemIR::InstConstantKind::Always) {
  64. CARBON_FATAL() << "Missing constant value for constant instruction "
  65. << inst;
  66. } else if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Always) {
  67. // For instructions that are always of type `type`, produce the trivial
  68. // runtime representation of type `type`.
  69. context.SetLocal(inst_id, context.GetTypeAsValue());
  70. } else {
  71. HandleInst(context, inst_id, inst);
  72. }
  73. }
  74. // TODO: Consider renaming Handle##Name, instead relying on typed_inst overload
  75. // resolution. That would allow putting the nonexistent handler implementations
  76. // in `requires`-style overloads.
  77. // NOLINTNEXTLINE(readability-function-size): The define confuses lint.
  78. auto FunctionContext::LowerInst(SemIR::InstId inst_id) -> void {
  79. // Skip over constants. `FileContext::GetGlobal` lowers them as needed.
  80. if (sem_ir().constant_values().Get(inst_id).is_constant()) {
  81. return;
  82. }
  83. auto inst = sem_ir().insts().Get(inst_id);
  84. CARBON_VLOG() << "Lowering " << inst_id << ": " << inst << "\n";
  85. builder_.getInserter().SetCurrentInstId(inst_id);
  86. CARBON_KIND_SWITCH(inst) {
  87. #define CARBON_SEM_IR_INST_KIND(Name) \
  88. case CARBON_KIND(SemIR::Name typed_inst): { \
  89. LowerInstHelper(*this, inst_id, typed_inst); \
  90. break; \
  91. }
  92. #include "toolchain/sem_ir/inst_kind.def"
  93. }
  94. builder_.getInserter().SetCurrentInstId(SemIR::InstId::Invalid);
  95. }
  96. auto FunctionContext::GetBlockArg(SemIR::InstBlockId block_id,
  97. SemIR::TypeId type_id) -> llvm::PHINode* {
  98. llvm::BasicBlock* block = GetBlock(block_id);
  99. // Find the existing phi, if any.
  100. auto phis = block->phis();
  101. if (!phis.empty()) {
  102. CARBON_CHECK(std::next(phis.begin()) == phis.end())
  103. << "Expected at most one phi, found "
  104. << std::distance(phis.begin(), phis.end());
  105. return &*phis.begin();
  106. }
  107. // The number of predecessor slots to reserve.
  108. static constexpr unsigned NumReservedPredecessors = 2;
  109. auto* phi = llvm::PHINode::Create(GetType(type_id), NumReservedPredecessors);
  110. phi->insertInto(block, block->begin());
  111. return phi;
  112. }
  113. auto FunctionContext::MakeSyntheticBlock() -> llvm::BasicBlock* {
  114. synthetic_block_ = llvm::BasicBlock::Create(llvm_context(), "", function_);
  115. return synthetic_block_;
  116. }
  117. auto FunctionContext::FinishInit(SemIR::TypeId type_id, SemIR::InstId dest_id,
  118. SemIR::InstId source_id) -> void {
  119. switch (SemIR::InitRepr::ForType(sem_ir(), type_id).kind) {
  120. case SemIR::InitRepr::None:
  121. break;
  122. case SemIR::InitRepr::InPlace:
  123. if (sem_ir().constant_values().Get(source_id).is_constant()) {
  124. // When initializing from a constant, emission of the source doesn't
  125. // initialize the destination. Copy the constant value instead.
  126. CopyValue(type_id, source_id, dest_id);
  127. }
  128. break;
  129. case SemIR::InitRepr::ByCopy:
  130. CopyValue(type_id, source_id, dest_id);
  131. break;
  132. case SemIR::InitRepr::Incomplete:
  133. CARBON_FATAL() << "Lowering aggregate initialization of incomplete type "
  134. << sem_ir().types().GetAsInst(type_id);
  135. }
  136. }
  137. auto FunctionContext::CopyValue(SemIR::TypeId type_id, SemIR::InstId source_id,
  138. SemIR::InstId dest_id) -> void {
  139. switch (auto rep = SemIR::ValueRepr::ForType(sem_ir(), type_id); rep.kind) {
  140. case SemIR::ValueRepr::Unknown:
  141. CARBON_FATAL() << "Attempt to copy incomplete type";
  142. case SemIR::ValueRepr::None:
  143. break;
  144. case SemIR::ValueRepr::Copy:
  145. builder().CreateStore(GetValue(source_id), GetValue(dest_id));
  146. break;
  147. case SemIR::ValueRepr::Pointer:
  148. CopyObject(type_id, source_id, dest_id);
  149. break;
  150. case SemIR::ValueRepr::Custom:
  151. CARBON_FATAL() << "TODO: Add support for CopyValue with custom value rep";
  152. }
  153. }
  154. auto FunctionContext::CopyObject(SemIR::TypeId type_id, SemIR::InstId source_id,
  155. SemIR::InstId dest_id) -> void {
  156. const auto& layout = llvm_module().getDataLayout();
  157. auto* type = GetType(type_id);
  158. // TODO: Compute known alignment of the source and destination, which may
  159. // be greater than the alignment computed by LLVM.
  160. auto align = layout.getABITypeAlign(type);
  161. // TODO: Attach !tbaa.struct metadata indicating which portions of the
  162. // type we actually need to copy and which are padding.
  163. builder().CreateMemCpy(GetValue(dest_id), align, GetValue(source_id), align,
  164. layout.getTypeAllocSize(type));
  165. }
  166. auto FunctionContext::Inserter::InsertHelper(
  167. llvm::Instruction* inst, const llvm::Twine& name,
  168. llvm::BasicBlock::iterator insert_pt) const -> void {
  169. llvm::StringRef base_name;
  170. llvm::StringRef separator;
  171. if (inst_namer_ && !inst->getType()->isVoidTy()) {
  172. base_name = inst_namer_->GetUnscopedNameFor(inst_id_);
  173. }
  174. if (!base_name.empty() && !name.isTriviallyEmpty()) {
  175. separator = ".";
  176. }
  177. IRBuilderDefaultInserter::InsertHelper(inst, base_name + separator + name,
  178. insert_pt);
  179. }
  180. } // namespace Carbon::Lower