handle_aggregates.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 "llvm/ADT/STLExtras.h"
  5. #include "llvm/ADT/StringRef.h"
  6. #include "llvm/ADT/Twine.h"
  7. #include "llvm/IR/Constants.h"
  8. #include "llvm/IR/Value.h"
  9. #include "toolchain/lower/function_context.h"
  10. #include "toolchain/sem_ir/expr_info.h"
  11. #include "toolchain/sem_ir/file.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Lower {
  15. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  16. SemIR::ClassDecl /*inst*/) -> void {
  17. // No action to perform.
  18. }
  19. // Extracts an element of an aggregate, such as a struct, tuple, or class, by
  20. // index. Depending on the expression category and value representation of the
  21. // aggregate input, this will either produce a value or a reference.
  22. static auto GetAggregateElement(FunctionContext& context,
  23. SemIR::InstId aggr_inst_id,
  24. SemIR::ElementIndex idx,
  25. SemIR::TypeId result_type_id, llvm::Twine name)
  26. -> llvm::Value* {
  27. auto aggr_inst = context.sem_ir().insts().Get(aggr_inst_id);
  28. auto* aggr_value = context.GetValue(aggr_inst_id);
  29. switch (SemIR::GetExprCategory(context.sem_ir(), aggr_inst_id)) {
  30. case SemIR::ExprCategory::Error:
  31. case SemIR::ExprCategory::NotExpr:
  32. case SemIR::ExprCategory::Initializing:
  33. case SemIR::ExprCategory::Mixed:
  34. CARBON_FATAL("Unexpected expression category for aggregate access");
  35. case SemIR::ExprCategory::Value: {
  36. auto value_rep =
  37. SemIR::ValueRepr::ForType(context.sem_ir(), aggr_inst.type_id());
  38. CARBON_CHECK(value_rep.aggregate_kind != SemIR::ValueRepr::NotAggregate,
  39. "aggregate type should have aggregate value representation");
  40. switch (value_rep.kind) {
  41. case SemIR::ValueRepr::Unknown:
  42. CARBON_FATAL("Lowering access to incomplete aggregate type");
  43. case SemIR::ValueRepr::None:
  44. return aggr_value;
  45. case SemIR::ValueRepr::Copy:
  46. // We are holding the values of the aggregate directly, elementwise.
  47. return context.builder().CreateExtractValue(aggr_value, idx.index,
  48. name);
  49. case SemIR::ValueRepr::Pointer: {
  50. // The value representation is a pointer to an aggregate that we want
  51. // to index into.
  52. auto pointee_type_id =
  53. context.sem_ir().GetPointeeType(value_rep.type_id);
  54. auto* value_type = context.GetType(pointee_type_id);
  55. auto* elem_ptr = context.builder().CreateStructGEP(
  56. value_type, aggr_value, idx.index, name);
  57. if (!value_rep.elements_are_values()) {
  58. // `elem_ptr` points to an object representation, which is our
  59. // result.
  60. return elem_ptr;
  61. }
  62. // `elem_ptr` points to a value representation. Load it.
  63. auto result_value_type_id =
  64. SemIR::ValueRepr::ForType(context.sem_ir(), result_type_id)
  65. .type_id;
  66. return context.builder().CreateLoad(
  67. context.GetType(result_value_type_id), elem_ptr, name + ".load");
  68. }
  69. case SemIR::ValueRepr::Custom:
  70. CARBON_FATAL(
  71. "Aggregate should never have custom value representation");
  72. }
  73. }
  74. case SemIR::ExprCategory::DurableRef:
  75. case SemIR::ExprCategory::EphemeralRef: {
  76. // Just locate the aggregate element.
  77. auto* aggr_type = context.GetType(aggr_inst.type_id());
  78. return context.builder().CreateStructGEP(aggr_type, aggr_value, idx.index,
  79. name);
  80. }
  81. }
  82. }
  83. static auto GetStructFieldName(FunctionContext& context,
  84. SemIR::TypeId struct_type_id,
  85. SemIR::ElementIndex index) -> llvm::StringRef {
  86. auto struct_type =
  87. context.sem_ir().types().GetAs<SemIR::StructType>(struct_type_id);
  88. auto fields =
  89. context.sem_ir().struct_type_fields().Get(struct_type.fields_id);
  90. return context.sem_ir().names().GetIRBaseName(fields[index.index].name_id);
  91. }
  92. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  93. SemIR::ClassElementAccess inst) -> void {
  94. // Find the class that we're performing access into.
  95. auto class_type_id = context.sem_ir().insts().Get(inst.base_id).type_id();
  96. SemIR::TypeId object_repr_id =
  97. context.sem_ir().types().GetObjectRepr(class_type_id);
  98. // Translate the class field access into a struct access on the object
  99. // representation.
  100. context.SetLocal(
  101. inst_id, GetAggregateElement(
  102. context, inst.base_id, inst.index, inst.type_id,
  103. GetStructFieldName(context, object_repr_id, inst.index)));
  104. }
  105. static auto EmitAggregateInitializer(FunctionContext& context,
  106. SemIR::TypeId type_id,
  107. SemIR::InstBlockId refs_id,
  108. llvm::Twine name) -> llvm::Value* {
  109. auto* llvm_type = context.GetType(type_id);
  110. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  111. switch (SemIR::InitRepr::ForType(context.sem_ir(), type_id).kind) {
  112. case SemIR::InitRepr::None: {
  113. // TODO: Add a helper to poison a value slot.
  114. return llvm::PoisonValue::get(llvm_type);
  115. }
  116. case SemIR::InitRepr::InPlace: {
  117. // Finish initialization of constant fields. We will have skipped this
  118. // when emitting the initializers because they have constant values.
  119. //
  120. // TODO: This emits the initializers for constant fields after all
  121. // initialization of non-constant fields. This may be observable in some
  122. // ways such as under a debugger in a debug build. It would be preferable
  123. // to initialize the constant portions of the aggregate first, but this
  124. // will likely need a change to the SemIR representation.
  125. //
  126. // TODO: If most of the bytes of the result have known constant values,
  127. // it'd be nice to emit a memcpy from a constant followed by the
  128. // non-constant initialization.
  129. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  130. if (context.sem_ir().constant_values().Get(ref_id).is_constant()) {
  131. auto dest_id =
  132. SemIR::FindReturnSlotArgForInitializer(context.sem_ir(), ref_id);
  133. auto src_id = ref_id;
  134. auto storage_type_id =
  135. context.sem_ir().insts().Get(dest_id).type_id();
  136. context.FinishInit(storage_type_id, dest_id, src_id);
  137. }
  138. }
  139. // TODO: Add a helper to poison a value slot.
  140. return llvm::PoisonValue::get(llvm_type);
  141. }
  142. case SemIR::InitRepr::ByCopy: {
  143. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  144. CARBON_CHECK(
  145. refs.size() == 1,
  146. "Unexpected size for aggregate with by-copy value representation");
  147. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  148. // need this `insert_value` wrapping.
  149. return context.builder().CreateInsertValue(
  150. llvm::PoisonValue::get(llvm_type), context.GetValue(refs[0]), {0},
  151. name);
  152. }
  153. case SemIR::InitRepr::Incomplete:
  154. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  155. context.sem_ir().types().GetAsInst(type_id));
  156. }
  157. }
  158. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  159. SemIR::ClassInit inst) -> void {
  160. context.SetLocal(
  161. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  162. "class.init"));
  163. }
  164. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  165. SemIR::StructAccess inst) -> void {
  166. auto struct_type_id = context.sem_ir().insts().Get(inst.struct_id).type_id();
  167. context.SetLocal(
  168. inst_id, GetAggregateElement(
  169. context, inst.struct_id, inst.index, inst.type_id,
  170. GetStructFieldName(context, struct_type_id, inst.index)));
  171. }
  172. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  173. SemIR::StructLiteral /*inst*/) -> void {
  174. // A StructLiteral should always be converted to a StructInit or StructValue
  175. // if its value is needed.
  176. }
  177. // Emits the value representation for a struct or tuple whose elements are the
  178. // contents of `refs_id`.
  179. static auto EmitAggregateValueRepr(FunctionContext& context,
  180. SemIR::TypeId type_id,
  181. SemIR::InstBlockId refs_id) -> llvm::Value* {
  182. auto value_rep = SemIR::ValueRepr::ForType(context.sem_ir(), type_id);
  183. switch (value_rep.kind) {
  184. case SemIR::ValueRepr::Unknown:
  185. CARBON_FATAL("Incomplete aggregate type in lowering");
  186. case SemIR::ValueRepr::None:
  187. // TODO: Add a helper to get a "no value representation" value.
  188. return llvm::PoisonValue::get(context.GetType(value_rep.type_id));
  189. case SemIR::ValueRepr::Copy: {
  190. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  191. CARBON_CHECK(
  192. refs.size() == 1,
  193. "Unexpected size for aggregate with by-copy value representation");
  194. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  195. // need this `insert_value` wrapping.
  196. return context.builder().CreateInsertValue(
  197. llvm::PoisonValue::get(context.GetType(value_rep.type_id)),
  198. context.GetValue(refs[0]), {0});
  199. }
  200. case SemIR::ValueRepr::Pointer: {
  201. auto pointee_type_id = context.sem_ir().GetPointeeType(value_rep.type_id);
  202. auto* llvm_value_rep_type = context.GetType(pointee_type_id);
  203. // Write the value representation to a local alloca so we can produce a
  204. // pointer to it as the value representation of the struct or tuple.
  205. auto* alloca = context.builder().CreateAlloca(llvm_value_rep_type);
  206. for (auto [i, ref] :
  207. llvm::enumerate(context.sem_ir().inst_blocks().Get(refs_id))) {
  208. context.builder().CreateStore(
  209. context.GetValue(ref),
  210. context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i));
  211. }
  212. return alloca;
  213. }
  214. case SemIR::ValueRepr::Custom:
  215. CARBON_FATAL("Aggregate should never have custom value representation");
  216. }
  217. }
  218. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  219. SemIR::StructInit inst) -> void {
  220. context.SetLocal(
  221. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  222. "struct.init"));
  223. }
  224. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  225. SemIR::StructValue inst) -> void {
  226. if (auto fn_type = context.sem_ir().types().TryGetAs<SemIR::FunctionType>(
  227. inst.type_id)) {
  228. context.SetLocal(inst_id, context.GetFunction(fn_type->function_id));
  229. return;
  230. }
  231. context.SetLocal(
  232. inst_id, EmitAggregateValueRepr(context, inst.type_id, inst.elements_id));
  233. }
  234. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  235. SemIR::TupleAccess inst) -> void {
  236. context.SetLocal(inst_id,
  237. GetAggregateElement(context, inst.tuple_id, inst.index,
  238. inst.type_id, "tuple.elem"));
  239. }
  240. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  241. SemIR::TupleLiteral /*inst*/) -> void {
  242. // A TupleLiteral should always be converted to a TupleInit or TupleValue if
  243. // its value is needed.
  244. }
  245. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  246. SemIR::TupleInit inst) -> void {
  247. context.SetLocal(
  248. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  249. "tuple.init"));
  250. }
  251. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  252. SemIR::TupleValue inst) -> void {
  253. context.SetLocal(
  254. inst_id, EmitAggregateValueRepr(context, inst.type_id, inst.elements_id));
  255. }
  256. } // namespace Carbon::Lower