function_context.cpp 8.6 KB

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