aggregate.cpp 10 KB

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