aggregate.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/aggregate.h"
  5. #include "llvm/ADT/STLExtras.h"
  6. #include "toolchain/sem_ir/expr_info.h"
  7. #include "toolchain/sem_ir/inst.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::Lower {
  10. static auto GetPointeeType(FunctionContext::TypeInFile type)
  11. -> FunctionContext::TypeInFile {
  12. return {.file = type.file,
  13. .type_id = type.file->GetPointeeType(type.type_id)};
  14. }
  15. // Given an index within a SemIR aggregate type, returns the corresponding index
  16. // of the element within the LLVM type suitable for use with the getelementptr
  17. // instruction.
  18. static auto GetElementIndex(FunctionContext::TypeInFile type,
  19. SemIR::ElementIndex idx) -> unsigned int {
  20. auto type_inst = type.file->types().GetAsInst(type.type_id);
  21. if (auto custom_layout_type = type_inst.TryAs<SemIR::CustomLayoutType>()) {
  22. // For custom layout types, we form an array of i8 as the LLVM type, so the
  23. // offset in the type is the getelementptr index.
  24. // TODO: This offset might not fit into an `unsigned int`.
  25. return type.file->custom_layouts().Get(
  26. custom_layout_type
  27. ->layout_id)[SemIR::CustomLayoutId::FirstFieldIndex + idx.index];
  28. }
  29. // For now, struct and tuple types map directly into LLVM struct types with
  30. // identical field numbering.
  31. CARBON_CHECK((type_inst.IsOneOf<SemIR::StructType, SemIR::TupleType>()),
  32. "Indexing unexpected aggregate type {0}", type_inst);
  33. return idx.index;
  34. }
  35. // Extracts an element of an aggregate, such as a struct, tuple, or class, by
  36. // index. Depending on the expression category and value representation of the
  37. // aggregate input, this will either produce a value or a reference.
  38. auto GetAggregateElement(FunctionContext& context, SemIR::InstId aggr_inst_id,
  39. SemIR::ElementIndex idx, SemIR::InstId result_inst_id,
  40. llvm::Twine name) -> llvm::Value* {
  41. auto* aggr_value = context.GetValue(aggr_inst_id);
  42. switch (SemIR::GetExprCategory(context.sem_ir(), aggr_inst_id)) {
  43. case SemIR::ExprCategory::RefTagged:
  44. case SemIR::ExprCategory::Error:
  45. case SemIR::ExprCategory::NotExpr:
  46. case SemIR::ExprCategory::Pattern:
  47. case SemIR::ExprCategory::ReprInitializing:
  48. case SemIR::ExprCategory::InPlaceInitializing:
  49. case SemIR::ExprCategory::Mixed:
  50. case SemIR::ExprCategory::Dependent:
  51. CARBON_FATAL(
  52. "Unexpected expression category for aggregate access into {0}",
  53. context.sem_ir().insts().Get(aggr_inst_id));
  54. case SemIR::ExprCategory::Value: {
  55. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  56. auto value_repr = context.GetValueRepr(aggr_type);
  57. CARBON_CHECK(
  58. value_repr.repr.aggregate_kind != SemIR::ValueRepr::NotAggregate,
  59. "aggregate type should have aggregate value representation");
  60. switch (value_repr.repr.kind) {
  61. case SemIR::ValueRepr::Unknown:
  62. CARBON_FATAL("Lowering access to incomplete aggregate type");
  63. case SemIR::ValueRepr::Dependent:
  64. CARBON_FATAL("Lowering access to dependent aggregate type");
  65. case SemIR::ValueRepr::None:
  66. return aggr_value;
  67. case SemIR::ValueRepr::Copy:
  68. // We are holding the values of the aggregate directly, elementwise.
  69. return context.builder().CreateExtractValue(
  70. aggr_value, GetElementIndex(value_repr.type(), idx), name);
  71. case SemIR::ValueRepr::Pointer: {
  72. // The value representation is a pointer to an aggregate that we want
  73. // to index into.
  74. auto value_rep_type = GetPointeeType(value_repr.type());
  75. auto* value_type = context.GetType(value_rep_type);
  76. auto* elem_ptr = context.builder().CreateStructGEP(
  77. value_type, aggr_value, GetElementIndex(value_rep_type, idx),
  78. name);
  79. if (!value_repr.repr.elements_are_values()) {
  80. // `elem_ptr` points to an object representation, which is our
  81. // result.
  82. return elem_ptr;
  83. }
  84. // `elem_ptr` points to a value representation. Load it.
  85. auto result_type = context.GetTypeIdOfInst(result_inst_id);
  86. auto result_value_type = context.GetValueRepr(result_type).type();
  87. return context.LoadObject(result_value_type, elem_ptr,
  88. name + ".load");
  89. }
  90. case SemIR::ValueRepr::Custom:
  91. CARBON_FATAL(
  92. "Aggregate should never have custom value representation");
  93. }
  94. }
  95. case SemIR::ExprCategory::DurableRef:
  96. case SemIR::ExprCategory::EphemeralRef: {
  97. // Just locate the aggregate element.
  98. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  99. auto object_repr = FunctionContext::TypeInFile{
  100. .file = aggr_type.file,
  101. .type_id = aggr_type.file->types().GetObjectRepr(aggr_type.type_id)};
  102. return context.builder().CreateStructGEP(
  103. context.GetType(object_repr), aggr_value,
  104. GetElementIndex(object_repr, idx), name);
  105. }
  106. }
  107. }
  108. auto EmitAggregateValueRepr(FunctionContext& context,
  109. SemIR::InstId value_inst_id,
  110. SemIR::InstBlockId refs_id) -> llvm::Value* {
  111. auto type = context.GetTypeIdOfInst(value_inst_id);
  112. auto value_repr = context.GetValueRepr(type);
  113. auto value_type = value_repr.type();
  114. switch (value_repr.repr.kind) {
  115. case SemIR::ValueRepr::Unknown:
  116. CARBON_FATAL("Lowering value of incomplete aggregate type");
  117. case SemIR::ValueRepr::Dependent:
  118. CARBON_FATAL("Lowering value of dependent aggregate type");
  119. case SemIR::ValueRepr::None:
  120. // TODO: Add a helper to get a "no value representation" value.
  121. return llvm::PoisonValue::get(context.GetType(value_type));
  122. case SemIR::ValueRepr::Copy: {
  123. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  124. CARBON_CHECK(
  125. refs.size() == 1,
  126. "Unexpected size for aggregate with by-copy value representation");
  127. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  128. // need this `insert_value` wrapping.
  129. return context.builder().CreateInsertValue(
  130. llvm::PoisonValue::get(context.GetType(value_type)),
  131. context.GetValue(refs[0]), {0});
  132. }
  133. case SemIR::ValueRepr::Pointer: {
  134. auto* llvm_value_rep_type = context.GetType(GetPointeeType(value_type));
  135. // Write the value representation to a local alloca so we can produce a
  136. // pointer to it as the value representation of the struct or tuple.
  137. auto* alloca = context.builder().CreateAlloca(llvm_value_rep_type);
  138. for (auto [i, ref_id] :
  139. llvm::enumerate(context.sem_ir().inst_blocks().Get(refs_id))) {
  140. context.StoreObject(
  141. context.GetValueRepr(context.GetTypeIdOfInst(ref_id)).type(),
  142. context.GetValue(ref_id),
  143. context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i));
  144. }
  145. return alloca;
  146. }
  147. case SemIR::ValueRepr::Custom:
  148. CARBON_FATAL("Aggregate should never have custom value representation");
  149. }
  150. }
  151. auto EmitAggregateInitializer(FunctionContext& context,
  152. SemIR::InstId init_inst_id,
  153. SemIR::InstBlockId refs_id, llvm::Twine name)
  154. -> llvm::Value* {
  155. auto type = context.GetTypeIdOfInst(init_inst_id);
  156. auto* llvm_type = context.GetType(type);
  157. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  158. switch (context.GetInitRepr(type).kind) {
  159. case SemIR::InitRepr::None: {
  160. // TODO: Add a helper to poison a value slot.
  161. return llvm::PoisonValue::get(llvm_type);
  162. }
  163. case SemIR::InitRepr::InPlace: {
  164. // Finish initialization of constant fields. We will have skipped this
  165. // when emitting the initializers because they have constant values.
  166. //
  167. // TODO: This emits the initializers for constant fields after all
  168. // initialization of non-constant fields. This may be observable in some
  169. // ways such as under a debugger in a debug build. It would be preferable
  170. // to initialize the constant portions of the aggregate first, but this
  171. // will likely need a change to the SemIR representation.
  172. //
  173. // TODO: If most of the bytes of the result have known constant values,
  174. // it'd be nice to emit a memcpy from a constant followed by the
  175. // non-constant initialization.
  176. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  177. if (context.sem_ir().constant_values().Get(ref_id).is_constant()) {
  178. auto dest_id =
  179. SemIR::FindStorageArgForInitializer(context.sem_ir(), ref_id);
  180. auto src_id = ref_id;
  181. auto storage_type = context.GetTypeIdOfInst(dest_id);
  182. context.InitializeStorage(storage_type, dest_id, src_id);
  183. }
  184. }
  185. // TODO: Add a helper to poison a value slot.
  186. return llvm::PoisonValue::get(llvm_type);
  187. }
  188. case SemIR::InitRepr::ByCopy: {
  189. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  190. CARBON_CHECK(
  191. refs.size() == 1,
  192. "Unexpected size for aggregate with by-copy value representation");
  193. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  194. // need this `insert_value` wrapping.
  195. return context.builder().CreateInsertValue(
  196. llvm::PoisonValue::get(llvm_type), context.GetValue(refs[0]), {0},
  197. name);
  198. }
  199. case SemIR::InitRepr::Abstract:
  200. CARBON_FATAL("Lowering aggregate initialization of abstract type {0}",
  201. type.file->types().GetAsInst(type.type_id));
  202. case SemIR::InitRepr::Incomplete:
  203. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  204. type.file->types().GetAsInst(type.type_id));
  205. case SemIR::InitRepr::Dependent:
  206. CARBON_FATAL("Lowering aggregate initialization of dependent type {0}",
  207. type.file->types().GetAsInst(type.type_id));
  208. }
  209. }
  210. } // namespace Carbon::Lower