handle_aggregates.cpp 14 KB

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