function_context.cpp 8.9 KB

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