handle.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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/lower/function_context.h"
  7. #include "toolchain/sem_ir/node_kind.h"
  8. namespace Carbon::Lower {
  9. auto HandleCrossReference(FunctionContext& /*context*/,
  10. SemIR::NodeId /*node_id*/, SemIR::CrossReference node)
  11. -> void {
  12. CARBON_FATAL() << "TODO: Add support: " << node;
  13. }
  14. auto HandleAddressOf(FunctionContext& context, SemIR::NodeId node_id,
  15. SemIR::AddressOf node) -> void {
  16. context.SetLocal(node_id, context.GetLocal(node.lvalue_id));
  17. }
  18. auto HandleArrayIndex(FunctionContext& context, SemIR::NodeId node_id,
  19. SemIR::ArrayIndex node) -> void {
  20. auto* array_value = context.GetLocal(node.array_id);
  21. auto* llvm_type =
  22. context.GetType(context.semantics_ir().GetNode(node.array_id).type_id());
  23. llvm::Value* indexes[2] = {
  24. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  25. context.GetLocal(node.index_id)};
  26. context.SetLocal(node_id,
  27. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  28. indexes, "array.index"));
  29. }
  30. auto HandleArrayInit(FunctionContext& context, SemIR::NodeId node_id,
  31. SemIR::ArrayInit node) -> void {
  32. // The result of initialization is the return slot of the initializer.
  33. context.SetLocal(
  34. node_id, context.GetLocal(context.semantics_ir()
  35. .GetNodeBlock(node.inits_and_return_slot_id)
  36. .back()));
  37. }
  38. auto HandleAssign(FunctionContext& context, SemIR::NodeId /*node_id*/,
  39. SemIR::Assign node) -> void {
  40. auto storage_type_id = context.semantics_ir().GetNode(node.lhs_id).type_id();
  41. context.FinishInitialization(storage_type_id, node.lhs_id, node.rhs_id);
  42. }
  43. auto HandleBinaryOperatorAdd(FunctionContext& /*context*/,
  44. SemIR::NodeId /*node_id*/,
  45. SemIR::BinaryOperatorAdd node) -> void {
  46. CARBON_FATAL() << "TODO: Add support: " << node;
  47. }
  48. auto HandleBindName(FunctionContext& context, SemIR::NodeId node_id,
  49. SemIR::BindName node) -> void {
  50. context.SetLocal(node_id, context.GetLocal(node.value_id));
  51. }
  52. auto HandleBlockArg(FunctionContext& context, SemIR::NodeId node_id,
  53. SemIR::BlockArg node) -> void {
  54. context.SetLocal(node_id, context.GetBlockArg(node.block_id, node.type_id));
  55. }
  56. auto HandleBoolLiteral(FunctionContext& context, SemIR::NodeId node_id,
  57. SemIR::BoolLiteral node) -> void {
  58. llvm::Value* v =
  59. llvm::ConstantInt::get(context.builder().getInt1Ty(), node.value.index);
  60. context.SetLocal(node_id, v);
  61. }
  62. auto HandleBranch(FunctionContext& context, SemIR::NodeId /*node_id*/,
  63. SemIR::Branch node) -> void {
  64. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  65. // TODO: Don't do this if it would remove a loop preheader block.
  66. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  67. if (block->empty() && context.TryToReuseBlock(node.target_id, block)) {
  68. // Reuse this block as the branch target.
  69. } else {
  70. context.builder().CreateBr(context.GetBlock(node.target_id));
  71. }
  72. context.builder().ClearInsertionPoint();
  73. }
  74. auto HandleBranchIf(FunctionContext& context, SemIR::NodeId /*node_id*/,
  75. SemIR::BranchIf node) -> void {
  76. llvm::Value* cond = context.GetLocal(node.cond_id);
  77. llvm::BasicBlock* then_block = context.GetBlock(node.target_id);
  78. llvm::BasicBlock* else_block = context.CreateSyntheticBlock();
  79. context.builder().CreateCondBr(cond, then_block, else_block);
  80. context.builder().SetInsertPoint(else_block);
  81. }
  82. auto HandleBranchWithArg(FunctionContext& context, SemIR::NodeId /*node_id*/,
  83. SemIR::BranchWithArg node) -> void {
  84. llvm::Value* arg = context.GetLocal(node.arg_id);
  85. SemIR::TypeId arg_type_id =
  86. context.semantics_ir().GetNode(node.arg_id).type_id();
  87. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  88. // We only do this for a block that we know will only have a single
  89. // predecessor, so that we can correctly populate the predecessors of the
  90. // PHINode.
  91. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  92. llvm::BasicBlock* phi_predecessor = block;
  93. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  94. context.TryToReuseBlock(node.target_id, block)) {
  95. // Reuse this block as the branch target.
  96. phi_predecessor = block->getSinglePredecessor();
  97. CARBON_CHECK(phi_predecessor)
  98. << "Synthetic block did not have a single predecessor";
  99. } else {
  100. context.builder().CreateBr(context.GetBlock(node.target_id));
  101. }
  102. context.GetBlockArg(node.target_id, arg_type_id)
  103. ->addIncoming(arg, phi_predecessor);
  104. context.builder().ClearInsertionPoint();
  105. }
  106. auto HandleBuiltin(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  107. SemIR::Builtin node) -> void {
  108. CARBON_FATAL() << "TODO: Add support: " << node;
  109. }
  110. auto HandleCall(FunctionContext& context, SemIR::NodeId node_id,
  111. SemIR::Call node) -> void {
  112. auto* llvm_function = context.GetFunction(node.function_id);
  113. const auto& function = context.semantics_ir().GetFunction(node.function_id);
  114. std::vector<llvm::Value*> args;
  115. llvm::ArrayRef<SemIR::NodeId> arg_ids =
  116. context.semantics_ir().GetNodeBlock(node.args_id);
  117. if (function.return_slot_id.is_valid()) {
  118. args.push_back(context.GetLocal(arg_ids.back()));
  119. arg_ids = arg_ids.drop_back();
  120. }
  121. for (auto arg_id : arg_ids) {
  122. auto arg_type_id = context.semantics_ir().GetNode(arg_id).type_id();
  123. if (SemIR::GetValueRepresentation(context.semantics_ir(), arg_type_id)
  124. .kind != SemIR::ValueRepresentation::None) {
  125. args.push_back(context.GetLocal(arg_id));
  126. }
  127. }
  128. if (llvm_function->getReturnType()->isVoidTy()) {
  129. context.builder().CreateCall(llvm_function, args);
  130. // The value of a function call with a void return type shouldn't used, but
  131. // StubReference needs a value to propagate.
  132. // TODO: Remove this now the StubReferences are gone.
  133. context.SetLocal(node_id,
  134. llvm::PoisonValue::get(context.GetType(node.type_id)));
  135. } else {
  136. context.SetLocal(node_id,
  137. context.builder().CreateCall(llvm_function, args,
  138. llvm_function->getName()));
  139. }
  140. }
  141. auto HandleDereference(FunctionContext& context, SemIR::NodeId node_id,
  142. SemIR::Dereference node) -> void {
  143. context.SetLocal(node_id, context.GetLocal(node.pointer_id));
  144. }
  145. auto HandleFunctionDeclaration(FunctionContext& /*context*/,
  146. SemIR::NodeId /*node_id*/,
  147. SemIR::FunctionDeclaration node) -> void {
  148. CARBON_FATAL()
  149. << "Should not be encountered. If that changes, we may want to change "
  150. "higher-level logic to skip them rather than calling this. "
  151. << node;
  152. }
  153. auto HandleInitializeFrom(FunctionContext& context, SemIR::NodeId /*node_id*/,
  154. SemIR::InitializeFrom node) -> void {
  155. auto storage_type_id = context.semantics_ir().GetNode(node.dest_id).type_id();
  156. context.FinishInitialization(storage_type_id, node.dest_id, node.src_id);
  157. }
  158. auto HandleIntegerLiteral(FunctionContext& context, SemIR::NodeId node_id,
  159. SemIR::IntegerLiteral node) -> void {
  160. const llvm::APInt& i = context.semantics_ir().GetInteger(node.integer_id);
  161. // TODO: This won't offer correct semantics, but seems close enough for now.
  162. llvm::Value* v =
  163. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue());
  164. context.SetLocal(node_id, v);
  165. }
  166. auto HandleNameReference(FunctionContext& context, SemIR::NodeId node_id,
  167. SemIR::NameReference node) -> void {
  168. context.SetLocal(node_id, context.GetLocal(node.value_id));
  169. }
  170. auto HandleNameReferenceUntyped(FunctionContext& /*context*/,
  171. SemIR::NodeId /*node_id*/,
  172. SemIR::NameReferenceUntyped /*node*/) -> void {
  173. // No action to take: untyped name references don't hold a value.
  174. }
  175. auto HandleNamespace(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  176. SemIR::Namespace /*node*/) -> void {
  177. // No action to take.
  178. }
  179. auto HandleNoOp(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  180. SemIR::NoOp /*node*/) -> void {
  181. // No action to take.
  182. }
  183. auto HandleParameter(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  184. SemIR::Parameter /*node*/) -> void {
  185. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  186. }
  187. auto HandleRealLiteral(FunctionContext& context, SemIR::NodeId node_id,
  188. SemIR::RealLiteral node) -> void {
  189. const SemIR::Real& real = context.semantics_ir().GetReal(node.real_id);
  190. // TODO: This will probably have overflow issues, and should be fixed.
  191. double val =
  192. real.mantissa.getZExtValue() *
  193. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  194. llvm::APFloat llvm_val(val);
  195. context.SetLocal(node_id, llvm::ConstantFP::get(
  196. context.builder().getDoubleTy(), llvm_val));
  197. }
  198. auto HandleReturn(FunctionContext& context, SemIR::NodeId /*node_id*/,
  199. SemIR::Return /*node*/) -> void {
  200. context.builder().CreateRetVoid();
  201. }
  202. auto HandleReturnExpression(FunctionContext& context, SemIR::NodeId /*node_id*/,
  203. SemIR::ReturnExpression node) -> void {
  204. switch (SemIR::GetInitializingRepresentation(
  205. context.semantics_ir(),
  206. context.semantics_ir().GetNode(node.expr_id).type_id())
  207. .kind) {
  208. case SemIR::InitializingRepresentation::None:
  209. case SemIR::InitializingRepresentation::InPlace:
  210. // Nothing to return.
  211. context.builder().CreateRetVoid();
  212. return;
  213. case SemIR::InitializingRepresentation::ByCopy:
  214. // The expression produces the value representation for the type.
  215. context.builder().CreateRet(context.GetLocal(node.expr_id));
  216. return;
  217. }
  218. }
  219. auto HandleSpliceBlock(FunctionContext& context, SemIR::NodeId node_id,
  220. SemIR::SpliceBlock node) -> void {
  221. context.LowerBlock(node.block_id);
  222. context.SetLocal(node_id, context.GetLocal(node.result_id));
  223. }
  224. auto HandleStringLiteral(FunctionContext& /*context*/,
  225. SemIR::NodeId /*node_id*/, SemIR::StringLiteral node)
  226. -> void {
  227. CARBON_FATAL() << "TODO: Add support: " << node;
  228. }
  229. // Extracts an element of either a struct or a tuple by index. Depending on the
  230. // expression category of the aggregate input, this will either produce a value
  231. // or a reference.
  232. static auto GetStructOrTupleElement(FunctionContext& context,
  233. SemIR::NodeId aggr_node_id, unsigned idx,
  234. SemIR::TypeId result_type_id,
  235. llvm::Twine name) -> llvm::Value* {
  236. auto aggr_node = context.semantics_ir().GetNode(aggr_node_id);
  237. auto* aggr_value = context.GetLocal(aggr_node_id);
  238. auto aggr_cat =
  239. SemIR::GetExpressionCategory(context.semantics_ir(), aggr_node_id);
  240. if (aggr_cat == SemIR::ExpressionCategory::Value &&
  241. SemIR::GetValueRepresentation(context.semantics_ir(), aggr_node.type_id())
  242. .kind == SemIR::ValueRepresentation::Copy) {
  243. // We are holding the values of the aggregate directly, elementwise.
  244. return context.builder().CreateExtractValue(aggr_value, idx, name);
  245. }
  246. // Either we're accessing an element of a reference and producing a reference,
  247. // or we're accessing an element of a value that is held by pointer and we're
  248. // producing a value.
  249. auto* aggr_type = context.GetType(aggr_node.type_id());
  250. auto* elem_ptr =
  251. context.builder().CreateStructGEP(aggr_type, aggr_value, idx, name);
  252. // If this is a value access, load the element if necessary.
  253. if (aggr_cat == SemIR::ExpressionCategory::Value) {
  254. switch (
  255. SemIR::GetValueRepresentation(context.semantics_ir(), result_type_id)
  256. .kind) {
  257. case SemIR::ValueRepresentation::None:
  258. return llvm::PoisonValue::get(context.GetType(result_type_id));
  259. case SemIR::ValueRepresentation::Copy:
  260. return context.builder().CreateLoad(context.GetType(result_type_id),
  261. elem_ptr, name + ".load");
  262. case SemIR::ValueRepresentation::Pointer:
  263. return elem_ptr;
  264. case SemIR::ValueRepresentation::Custom:
  265. CARBON_FATAL() << "TODO: Add support for custom value representation";
  266. }
  267. }
  268. return elem_ptr;
  269. }
  270. auto HandleStructAccess(FunctionContext& context, SemIR::NodeId node_id,
  271. SemIR::StructAccess node) -> void {
  272. auto struct_type_id =
  273. context.semantics_ir().GetNode(node.struct_id).type_id();
  274. // Get type information for member names.
  275. auto fields = context.semantics_ir().GetNodeBlock(
  276. context.semantics_ir()
  277. .GetNodeAs<SemIR::StructType>(
  278. context.semantics_ir().GetType(struct_type_id))
  279. .fields_id);
  280. auto field = context.semantics_ir().GetNodeAs<SemIR::StructTypeField>(
  281. fields[node.index.index]);
  282. auto member_name = context.semantics_ir().GetString(field.name_id);
  283. context.SetLocal(node_id, GetStructOrTupleElement(context, node.struct_id,
  284. node.index.index,
  285. node.type_id, member_name));
  286. }
  287. auto HandleStructLiteral(FunctionContext& context, SemIR::NodeId node_id,
  288. SemIR::StructLiteral node) -> void {
  289. // A StructLiteral should always be converted to a StructInit or StructValue
  290. // if its value is needed.
  291. context.SetLocal(node_id,
  292. llvm::PoisonValue::get(context.GetType(node.type_id)));
  293. }
  294. // Emits the value representation for a struct or tuple whose elements are the
  295. // contents of `refs_id`.
  296. auto EmitStructOrTupleValueRepresentation(FunctionContext& context,
  297. SemIR::TypeId type_id,
  298. SemIR::NodeBlockId refs_id,
  299. llvm::Twine name) -> llvm::Value* {
  300. auto* llvm_type = context.GetType(type_id);
  301. switch (SemIR::GetValueRepresentation(context.semantics_ir(), type_id).kind) {
  302. case SemIR::ValueRepresentation::None:
  303. // TODO: Add a helper to get a "no value representation" value.
  304. return llvm::PoisonValue::get(llvm_type);
  305. case SemIR::ValueRepresentation::Copy: {
  306. auto refs = context.semantics_ir().GetNodeBlock(refs_id);
  307. CARBON_CHECK(refs.size() == 1)
  308. << "Unexpected size for aggregate with by-copy value representation";
  309. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  310. // need this `insert_value` wrapping.
  311. return context.builder().CreateInsertValue(
  312. llvm::PoisonValue::get(llvm_type), context.GetLocal(refs[0]), {0});
  313. }
  314. case SemIR::ValueRepresentation::Pointer: {
  315. // Write the object representation to a local alloca so we can produce a
  316. // pointer to it as the value representation.
  317. auto* alloca = context.builder().CreateAlloca(
  318. llvm_type, /*ArraySize=*/nullptr, name);
  319. for (auto [i, ref] :
  320. llvm::enumerate(context.semantics_ir().GetNodeBlock(refs_id))) {
  321. auto* gep = context.builder().CreateStructGEP(llvm_type, alloca, i);
  322. // TODO: We are loading a value representation here and storing an
  323. // object representation!
  324. context.builder().CreateStore(context.GetLocal(ref), gep);
  325. }
  326. return alloca;
  327. }
  328. case SemIR::ValueRepresentation::Custom:
  329. CARBON_FATAL()
  330. << "Aggregate should never have custom value representation";
  331. }
  332. }
  333. auto HandleStructInit(FunctionContext& context, SemIR::NodeId node_id,
  334. SemIR::StructInit node) -> void {
  335. auto* llvm_type = context.GetType(node.type_id);
  336. switch (
  337. SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id)
  338. .kind) {
  339. case SemIR::InitializingRepresentation::None:
  340. case SemIR::InitializingRepresentation::InPlace:
  341. // TODO: Add a helper to poison a value slot.
  342. context.SetLocal(node_id, llvm::PoisonValue::get(llvm_type));
  343. break;
  344. case SemIR::InitializingRepresentation::ByCopy: {
  345. context.SetLocal(
  346. node_id, EmitStructOrTupleValueRepresentation(
  347. context, node.type_id, node.elements_id, "struct.init"));
  348. break;
  349. }
  350. }
  351. }
  352. auto HandleStructValue(FunctionContext& context, SemIR::NodeId node_id,
  353. SemIR::StructValue node) -> void {
  354. context.SetLocal(node_id,
  355. EmitStructOrTupleValueRepresentation(
  356. context, node.type_id, node.elements_id, "struct"));
  357. }
  358. auto HandleStructTypeField(FunctionContext& /*context*/,
  359. SemIR::NodeId /*node_id*/,
  360. SemIR::StructTypeField /*node*/) -> void {
  361. // No action to take.
  362. }
  363. auto HandleTupleAccess(FunctionContext& context, SemIR::NodeId node_id,
  364. SemIR::TupleAccess node) -> void {
  365. context.SetLocal(
  366. node_id, GetStructOrTupleElement(context, node.tuple_id, node.index.index,
  367. node.type_id, "tuple.elem"));
  368. }
  369. auto HandleTupleIndex(FunctionContext& context, SemIR::NodeId node_id,
  370. SemIR::TupleIndex node) -> void {
  371. auto index_node =
  372. context.semantics_ir().GetNodeAs<SemIR::IntegerLiteral>(node.index_id);
  373. auto index =
  374. context.semantics_ir().GetInteger(index_node.integer_id).getZExtValue();
  375. context.SetLocal(node_id,
  376. GetStructOrTupleElement(context, node.tuple_id, index,
  377. node.type_id, "tuple.index"));
  378. }
  379. auto HandleTupleLiteral(FunctionContext& context, SemIR::NodeId node_id,
  380. SemIR::TupleLiteral node) -> void {
  381. // A TupleLiteral should always be converted to a TupleInit or TupleValue if
  382. // its value is needed.
  383. context.SetLocal(node_id,
  384. llvm::PoisonValue::get(context.GetType(node.type_id)));
  385. }
  386. auto HandleTupleInit(FunctionContext& context, SemIR::NodeId node_id,
  387. SemIR::TupleInit node) -> void {
  388. auto* llvm_type = context.GetType(node.type_id);
  389. switch (
  390. SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id)
  391. .kind) {
  392. case SemIR::InitializingRepresentation::None:
  393. case SemIR::InitializingRepresentation::InPlace:
  394. // TODO: Add a helper to poison a value slot.
  395. context.SetLocal(node_id, llvm::PoisonValue::get(llvm_type));
  396. break;
  397. case SemIR::InitializingRepresentation::ByCopy: {
  398. context.SetLocal(
  399. node_id, EmitStructOrTupleValueRepresentation(
  400. context, node.type_id, node.elements_id, "tuple.init"));
  401. break;
  402. }
  403. }
  404. }
  405. auto HandleTupleValue(FunctionContext& context, SemIR::NodeId node_id,
  406. SemIR::TupleValue node) -> void {
  407. context.SetLocal(
  408. node_id, EmitStructOrTupleValueRepresentation(context, node.type_id,
  409. node.elements_id, "tuple"));
  410. }
  411. auto HandleUnaryOperatorNot(FunctionContext& context, SemIR::NodeId node_id,
  412. SemIR::UnaryOperatorNot node) -> void {
  413. context.SetLocal(
  414. node_id, context.builder().CreateNot(context.GetLocal(node.operand_id)));
  415. }
  416. auto HandleVarStorage(FunctionContext& context, SemIR::NodeId node_id,
  417. SemIR::VarStorage node) -> void {
  418. // TODO: Eventually this name will be optional, and we'll want to provide
  419. // something like `var` as a default. However, that's not possible right now
  420. // so cannot be tested.
  421. auto name = context.semantics_ir().GetString(node.name_id);
  422. auto* alloca = context.builder().CreateAlloca(context.GetType(node.type_id),
  423. /*ArraySize=*/nullptr, name);
  424. context.SetLocal(node_id, alloca);
  425. }
  426. } // namespace Carbon::Lower