lowering_handle.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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/Sequence.h"
  6. #include "toolchain/lowering/lowering_function_context.h"
  7. #include "toolchain/semantics/semantics_node_kind.h"
  8. namespace Carbon {
  9. auto LoweringHandleInvalid(LoweringFunctionContext& /*context*/,
  10. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  11. -> void {
  12. llvm_unreachable("never in actual IR");
  13. }
  14. auto LoweringHandleCrossReference(LoweringFunctionContext& /*context*/,
  15. SemIR::NodeId /*node_id*/, SemIR::Node node)
  16. -> void {
  17. CARBON_FATAL() << "TODO: Add support: " << node;
  18. }
  19. auto LoweringHandleAddressOf(LoweringFunctionContext& context,
  20. SemIR::NodeId node_id, SemIR::Node node) -> void {
  21. context.SetLocal(node_id, context.GetLocal(node.GetAsAddressOf()));
  22. }
  23. auto LoweringHandleArrayIndex(LoweringFunctionContext& context,
  24. SemIR::NodeId node_id, SemIR::Node node) -> void {
  25. auto [array_node_id, index_node_id] = node.GetAsArrayIndex();
  26. auto* array_value = context.GetLocal(array_node_id);
  27. auto* llvm_type =
  28. context.GetType(context.semantics_ir().GetNode(array_node_id).type_id());
  29. auto index_node = context.semantics_ir().GetNode(index_node_id);
  30. llvm::Value* array_element_value;
  31. if (index_node.kind() == SemIR::NodeKind::IntegerLiteral) {
  32. const auto index = context.semantics_ir()
  33. .GetIntegerLiteral(index_node.GetAsIntegerLiteral())
  34. .getZExtValue();
  35. array_element_value = context.GetIndexFromStructOrArray(
  36. llvm_type, array_value, index, "array.index");
  37. } else {
  38. auto* index = context.builder().CreateLoad(llvm_type->getArrayElementType(),
  39. context.GetLocal(index_node_id));
  40. // TODO: Handle return value or call such as `F()[a]`.
  41. array_element_value = context.builder().CreateInBoundsGEP(
  42. llvm_type, array_value, index, "array.index");
  43. }
  44. context.SetLocal(node_id, array_element_value);
  45. }
  46. auto LoweringHandleArrayValue(LoweringFunctionContext& context,
  47. SemIR::NodeId node_id, SemIR::Node node) -> void {
  48. auto* llvm_type = context.GetType(node.type_id());
  49. auto* alloca =
  50. context.builder().CreateAlloca(llvm_type, /*ArraySize=*/nullptr, "array");
  51. context.SetLocal(node_id, alloca);
  52. auto tuple_node_id = node.GetAsArrayValue();
  53. auto* tuple_value = context.GetLocal(tuple_node_id);
  54. auto* tuple_type =
  55. context.GetType(context.semantics_ir().GetNode(tuple_node_id).type_id());
  56. for (auto i : llvm::seq(llvm_type->getArrayNumElements())) {
  57. llvm::Value* array_element_value = context.GetIndexFromStructOrArray(
  58. tuple_type, tuple_value, i, "array.element");
  59. if (tuple_value->getType()->isPointerTy()) {
  60. array_element_value = context.builder().CreateLoad(
  61. llvm_type->getArrayElementType(), array_element_value);
  62. }
  63. // Initializing the array with values.
  64. context.builder().CreateStore(
  65. array_element_value,
  66. context.builder().CreateStructGEP(llvm_type, alloca, i));
  67. }
  68. }
  69. auto LoweringHandleAssign(LoweringFunctionContext& context,
  70. SemIR::NodeId /*node_id*/, SemIR::Node node) -> void {
  71. auto [storage_id, value_id] = node.GetAsAssign();
  72. auto storage_type_id = context.semantics_ir().GetNode(storage_id).type_id();
  73. // We can assign from either a value expression or a by-copy initializing
  74. // expression. In either case, the value of the source is the value
  75. // representation of the target.
  76. // TODO: Should we use different semantic nodes for those operations?
  77. switch (auto rep = SemIR::GetValueRepresentation(context.semantics_ir(),
  78. storage_type_id);
  79. rep.kind) {
  80. case SemIR::ValueRepresentation::None:
  81. break;
  82. case SemIR::ValueRepresentation::Copy:
  83. context.builder().CreateStore(context.GetLocalLoaded(value_id),
  84. context.GetLocal(storage_id));
  85. break;
  86. case SemIR::ValueRepresentation::Pointer: {
  87. const auto& layout = context.llvm_module().getDataLayout();
  88. auto* type = context.GetType(storage_type_id);
  89. // TODO: Compute known alignment of the source and destination, which may
  90. // be greater than the alignment computed by LLVM.
  91. auto align = layout.getABITypeAlign(type);
  92. // TODO: Attach !tbaa.struct metadata indicating which portions of the
  93. // type we actually need to copy and which are padding.
  94. context.builder().CreateMemCpy(context.GetLocal(storage_id), align,
  95. context.GetLocal(value_id), align,
  96. layout.getTypeAllocSize(type));
  97. break;
  98. }
  99. case SemIR::ValueRepresentation::Custom:
  100. CARBON_FATAL() << "TODO: Add support for Assign with custom value rep";
  101. }
  102. }
  103. auto LoweringHandleBinaryOperatorAdd(LoweringFunctionContext& /*context*/,
  104. SemIR::NodeId /*node_id*/,
  105. SemIR::Node node) -> void {
  106. CARBON_FATAL() << "TODO: Add support: " << node;
  107. }
  108. auto LoweringHandleBindName(LoweringFunctionContext& /*context*/,
  109. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  110. -> void {
  111. // Probably need to do something here, but not necessary for now.
  112. }
  113. auto LoweringHandleBlockArg(LoweringFunctionContext& context,
  114. SemIR::NodeId node_id, SemIR::Node node) -> void {
  115. SemIR::NodeBlockId block_id = node.GetAsBlockArg();
  116. context.SetLocal(node_id, context.GetBlockArg(block_id, node.type_id()));
  117. }
  118. auto LoweringHandleBoolLiteral(LoweringFunctionContext& context,
  119. SemIR::NodeId node_id, SemIR::Node node)
  120. -> void {
  121. llvm::Value* v = llvm::ConstantInt::get(context.builder().getInt1Ty(),
  122. node.GetAsBoolLiteral().index);
  123. context.SetLocal(node_id, v);
  124. }
  125. auto LoweringHandleBranch(LoweringFunctionContext& context,
  126. SemIR::NodeId /*node_id*/, SemIR::Node node) -> void {
  127. SemIR::NodeBlockId target_block_id = node.GetAsBranch();
  128. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  129. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  130. if (block->empty() && context.TryToReuseBlock(target_block_id, block)) {
  131. // Reuse this block as the branch target.
  132. } else {
  133. context.builder().CreateBr(context.GetBlock(target_block_id));
  134. }
  135. context.builder().ClearInsertionPoint();
  136. }
  137. auto LoweringHandleBranchIf(LoweringFunctionContext& context,
  138. SemIR::NodeId /*node_id*/, SemIR::Node node)
  139. -> void {
  140. auto [target_block_id, cond_id] = node.GetAsBranchIf();
  141. llvm::Value* cond = context.GetLocalLoaded(cond_id);
  142. llvm::BasicBlock* then_block = context.GetBlock(target_block_id);
  143. llvm::BasicBlock* else_block = context.CreateSyntheticBlock();
  144. context.builder().CreateCondBr(cond, then_block, else_block);
  145. context.builder().SetInsertPoint(else_block);
  146. }
  147. auto LoweringHandleBranchWithArg(LoweringFunctionContext& context,
  148. SemIR::NodeId /*node_id*/, SemIR::Node node)
  149. -> void {
  150. auto [target_block_id, arg_id] = node.GetAsBranchWithArg();
  151. llvm::Value* arg = context.GetLocalLoaded(arg_id);
  152. SemIR::TypeId arg_type_id = context.semantics_ir().GetNode(arg_id).type_id();
  153. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  154. // We only do this for a block that we know will only have a single
  155. // predecessor, so that we can correctly populate the predecessors of the
  156. // PHINode.
  157. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  158. llvm::BasicBlock* phi_predecessor = block;
  159. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  160. context.TryToReuseBlock(target_block_id, block)) {
  161. // Reuse this block as the branch target.
  162. phi_predecessor = block->getSinglePredecessor();
  163. CARBON_CHECK(phi_predecessor)
  164. << "Synthetic block did not have a single predecessor";
  165. } else {
  166. context.builder().CreateBr(context.GetBlock(target_block_id));
  167. }
  168. context.GetBlockArg(target_block_id, arg_type_id)
  169. ->addIncoming(arg, phi_predecessor);
  170. context.builder().ClearInsertionPoint();
  171. }
  172. auto LoweringHandleBuiltin(LoweringFunctionContext& /*context*/,
  173. SemIR::NodeId /*node_id*/, SemIR::Node node)
  174. -> void {
  175. CARBON_FATAL() << "TODO: Add support: " << node;
  176. }
  177. auto LoweringHandleCall(LoweringFunctionContext& context, SemIR::NodeId node_id,
  178. SemIR::Node node) -> void {
  179. auto [refs_id, function_id] = node.GetAsCall();
  180. auto* llvm_function = context.GetFunction(function_id);
  181. const auto& function = context.semantics_ir().GetFunction(function_id);
  182. std::vector<llvm::Value*> args;
  183. llvm::ArrayRef<SemIR::NodeId> arg_ids =
  184. context.semantics_ir().GetNodeBlock(refs_id);
  185. if (function.return_slot_id.is_valid()) {
  186. args.push_back(context.GetLocal(arg_ids.back()));
  187. arg_ids = arg_ids.drop_back();
  188. }
  189. for (auto ref_id : arg_ids) {
  190. auto arg_type_id = context.semantics_ir().GetNode(ref_id).type_id();
  191. switch (SemIR::GetValueRepresentation(context.semantics_ir(), arg_type_id)
  192. .kind) {
  193. case SemIR::ValueRepresentation::None:
  194. break;
  195. case SemIR::ValueRepresentation::Copy:
  196. case SemIR::ValueRepresentation::Custom:
  197. args.push_back(context.GetLocalLoaded(ref_id));
  198. break;
  199. case SemIR::ValueRepresentation::Pointer:
  200. args.push_back(context.GetLocal(ref_id));
  201. break;
  202. }
  203. }
  204. if (llvm_function->getReturnType()->isVoidTy()) {
  205. context.builder().CreateCall(llvm_function, args);
  206. // The value of a function call with a void return type shouldn't used, but
  207. // StubReference needs a value to propagate.
  208. context.SetLocal(node_id,
  209. llvm::PoisonValue::get(context.GetType(node.type_id())));
  210. } else {
  211. context.SetLocal(node_id,
  212. context.builder().CreateCall(llvm_function, args,
  213. llvm_function->getName()));
  214. }
  215. }
  216. auto LoweringHandleDereference(LoweringFunctionContext& context,
  217. SemIR::NodeId node_id, SemIR::Node node)
  218. -> void {
  219. context.SetLocal(node_id, context.GetLocal(node.GetAsDereference()));
  220. }
  221. auto LoweringHandleFunctionDeclaration(LoweringFunctionContext& /*context*/,
  222. SemIR::NodeId /*node_id*/,
  223. SemIR::Node node) -> void {
  224. CARBON_FATAL()
  225. << "Should not be encountered. If that changes, we may want to change "
  226. "higher-level logic to skip them rather than calling this. "
  227. << node;
  228. }
  229. auto LoweringHandleIntegerLiteral(LoweringFunctionContext& context,
  230. SemIR::NodeId node_id, SemIR::Node node)
  231. -> void {
  232. llvm::APInt i =
  233. context.semantics_ir().GetIntegerLiteral(node.GetAsIntegerLiteral());
  234. // TODO: This won't offer correct semantics, but seems close enough for now.
  235. llvm::Value* v =
  236. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getSExtValue());
  237. context.SetLocal(node_id, v);
  238. }
  239. auto LoweringHandleNamespace(LoweringFunctionContext& /*context*/,
  240. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  241. -> void {
  242. // No action to take.
  243. }
  244. auto LoweringHandleNoOp(LoweringFunctionContext& /*context*/,
  245. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  246. -> void {
  247. // No action to take.
  248. }
  249. auto LoweringHandleParameter(LoweringFunctionContext& /*context*/,
  250. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  251. -> void {
  252. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  253. }
  254. auto LoweringHandleRealLiteral(LoweringFunctionContext& context,
  255. SemIR::NodeId node_id, SemIR::Node node)
  256. -> void {
  257. SemIR::RealLiteral real =
  258. context.semantics_ir().GetRealLiteral(node.GetAsRealLiteral());
  259. // TODO: This will probably have overflow issues, and should be fixed.
  260. double val =
  261. real.mantissa.getSExtValue() *
  262. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  263. llvm::APFloat llvm_val(val);
  264. context.SetLocal(node_id, llvm::ConstantFP::get(
  265. context.builder().getDoubleTy(), llvm_val));
  266. }
  267. auto LoweringHandleReturn(LoweringFunctionContext& context,
  268. SemIR::NodeId /*node_id*/, SemIR::Node /*node*/)
  269. -> void {
  270. context.builder().CreateRetVoid();
  271. }
  272. auto LoweringHandleReturnExpression(LoweringFunctionContext& context,
  273. SemIR::NodeId /*node_id*/, SemIR::Node node)
  274. -> void {
  275. SemIR::NodeId expr_id = node.GetAsReturnExpression();
  276. context.builder().CreateRet(context.GetLocalLoaded(expr_id));
  277. }
  278. auto LoweringHandleStringLiteral(LoweringFunctionContext& /*context*/,
  279. SemIR::NodeId /*node_id*/, SemIR::Node node)
  280. -> void {
  281. CARBON_FATAL() << "TODO: Add support: " << node;
  282. }
  283. auto LoweringHandleStructAccess(LoweringFunctionContext& context,
  284. SemIR::NodeId node_id, SemIR::Node node)
  285. -> void {
  286. auto [struct_id, member_index] = node.GetAsStructAccess();
  287. auto struct_type_id = context.semantics_ir().GetNode(struct_id).type_id();
  288. auto* llvm_type = context.GetType(struct_type_id);
  289. // Get type information for member names.
  290. auto type_refs = context.semantics_ir().GetNodeBlock(
  291. context.semantics_ir()
  292. .GetNode(context.semantics_ir().GetType(struct_type_id))
  293. .GetAsStructType());
  294. auto [field_name_id, field_type_id] =
  295. context.semantics_ir()
  296. .GetNode(type_refs[member_index.index])
  297. .GetAsStructTypeField();
  298. auto member_name = context.semantics_ir().GetString(field_name_id);
  299. auto* gep = context.builder().CreateStructGEP(
  300. llvm_type, context.GetLocal(struct_id), member_index.index, member_name);
  301. context.SetLocal(node_id, gep);
  302. }
  303. auto LoweringHandleTupleIndex(LoweringFunctionContext& context,
  304. SemIR::NodeId node_id, SemIR::Node node) -> void {
  305. auto [tuple_node_id, index_node_id] = node.GetAsTupleIndex();
  306. auto* tuple_value = context.GetLocal(tuple_node_id);
  307. auto index_node = context.semantics_ir().GetNode(index_node_id);
  308. const auto index = context.semantics_ir()
  309. .GetIntegerLiteral(index_node.GetAsIntegerLiteral())
  310. .getZExtValue();
  311. auto* llvm_type =
  312. context.GetType(context.semantics_ir().GetNode(tuple_node_id).type_id());
  313. context.SetLocal(node_id, context.GetIndexFromStructOrArray(
  314. llvm_type, tuple_value, index, "tuple.index"));
  315. }
  316. auto LoweringHandleTupleValue(LoweringFunctionContext& context,
  317. SemIR::NodeId node_id, SemIR::Node node) -> void {
  318. auto* llvm_type = context.GetType(node.type_id());
  319. auto* alloca =
  320. context.builder().CreateAlloca(llvm_type, /*ArraySize=*/nullptr, "tuple");
  321. context.SetLocal(node_id, alloca);
  322. auto refs = context.semantics_ir().GetNodeBlock(node.GetAsTupleValue());
  323. for (auto [i, ref] : llvm::enumerate(refs)) {
  324. auto* gep = context.builder().CreateStructGEP(llvm_type, alloca, i);
  325. context.builder().CreateStore(context.GetLocal(ref), gep);
  326. }
  327. }
  328. auto LoweringHandleStructTypeField(LoweringFunctionContext& /*context*/,
  329. SemIR::NodeId /*node_id*/,
  330. SemIR::Node /*node*/) -> void {
  331. // No action to take.
  332. }
  333. auto LoweringHandleStructValue(LoweringFunctionContext& context,
  334. SemIR::NodeId node_id, SemIR::Node node)
  335. -> void {
  336. auto* llvm_type = context.GetType(node.type_id());
  337. auto* alloca = context.builder().CreateAlloca(
  338. llvm_type, /*ArraySize=*/nullptr, "struct");
  339. context.SetLocal(node_id, alloca);
  340. auto refs = context.semantics_ir().GetNodeBlock(node.GetAsStructValue());
  341. // Get type information for member names.
  342. auto type_refs = context.semantics_ir().GetNodeBlock(
  343. context.semantics_ir()
  344. .GetNode(context.semantics_ir().GetType(node.type_id()))
  345. .GetAsStructType());
  346. for (auto [i, ref, type_ref] : llvm::enumerate(refs, type_refs)) {
  347. auto [field_name_id, field_type_id] =
  348. context.semantics_ir().GetNode(type_ref).GetAsStructTypeField();
  349. auto member_name = context.semantics_ir().GetString(field_name_id);
  350. auto* gep =
  351. context.builder().CreateStructGEP(llvm_type, alloca, i, member_name);
  352. context.builder().CreateStore(context.GetLocal(ref), gep);
  353. }
  354. }
  355. auto LoweringHandleStubReference(LoweringFunctionContext& context,
  356. SemIR::NodeId node_id, SemIR::Node node)
  357. -> void {
  358. context.SetLocal(node_id, context.GetLocal(node.GetAsStubReference()));
  359. }
  360. auto LoweringHandleUnaryOperatorNot(LoweringFunctionContext& context,
  361. SemIR::NodeId node_id, SemIR::Node node)
  362. -> void {
  363. context.SetLocal(node_id, context.builder().CreateNot(context.GetLocal(
  364. node.GetAsUnaryOperatorNot())));
  365. }
  366. auto LoweringHandleVarStorage(LoweringFunctionContext& context,
  367. SemIR::NodeId node_id, SemIR::Node node) -> void {
  368. // TODO: Eventually this name will be optional, and we'll want to provide
  369. // something like `var` as a default. However, that's not possible right now
  370. // so cannot be tested.
  371. auto name = context.semantics_ir().GetString(node.GetAsVarStorage());
  372. auto* alloca = context.builder().CreateAlloca(context.GetType(node.type_id()),
  373. /*ArraySize=*/nullptr, name);
  374. context.SetLocal(node_id, alloca);
  375. }
  376. } // namespace Carbon