handle.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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/APFloat.h"
  5. #include "llvm/ADT/APInt.h"
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "llvm/IR/BasicBlock.h"
  8. #include "llvm/IR/Constants.h"
  9. #include "llvm/IR/IRBuilder.h"
  10. #include "llvm/IR/Type.h"
  11. #include "llvm/IR/Value.h"
  12. #include "llvm/Support/Casting.h"
  13. #include "toolchain/lower/function_context.h"
  14. #include "toolchain/sem_ir/builtin_function_kind.h"
  15. #include "toolchain/sem_ir/expr_info.h"
  16. #include "toolchain/sem_ir/function.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Lower {
  20. // Returns whether this instruction names a namespace.
  21. static auto IsNamespace(FunctionContext& context, SemIR::InstId inst_id)
  22. -> bool {
  23. // Note, we don't use context.GetTypeOfInst here. An instruction can't change
  24. // from being a non-namespace in a generic to being a namespace in a specific,
  25. // because namespace names are not first-class.
  26. auto type_inst_id = context.sem_ir().types().GetTypeInstId(
  27. context.sem_ir().insts().Get(inst_id).type_id());
  28. return type_inst_id == SemIR::NamespaceType::TypeInstId;
  29. }
  30. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  31. SemIR::AddrOf inst) -> void {
  32. context.SetLocal(inst_id, context.GetValue(inst.lvalue_id));
  33. }
  34. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  35. SemIR::ArrayIndex inst) -> void {
  36. auto* array_value = context.GetValue(inst.array_id);
  37. auto* llvm_type = context.GetTypeOfInst(inst.array_id);
  38. // The index in an `ArrayIndex` can be of any integer type, including
  39. // IntLiteral. If it is an IntLiteral, its value representation is empty, so
  40. // create a ConstantInt from its SemIR value directly.
  41. llvm::Value* index;
  42. auto index_type = context.GetTypeIdOfInst(inst.index_id);
  43. if (index_type.file->types().GetTypeInstId(index_type.type_id) ==
  44. SemIR::IntLiteralType::TypeInstId) {
  45. auto value = context.sem_ir().insts().GetAs<SemIR::IntValue>(
  46. context.sem_ir().constant_values().GetConstantInstId(inst.index_id));
  47. const auto& apint_value = context.sem_ir().ints().Get(value.int_id);
  48. context.AddIntToCurrentFingerprint(apint_value.getSExtValue());
  49. index = llvm::ConstantInt::get(context.llvm_context(), apint_value);
  50. } else {
  51. context.AddIntToCurrentFingerprint(-1);
  52. index = context.GetValue(inst.index_id);
  53. }
  54. llvm::Value* indexes[2] = {
  55. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  56. index};
  57. context.SetLocal(inst_id,
  58. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  59. indexes, "array.index"));
  60. }
  61. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  62. SemIR::ArrayInit inst) -> void {
  63. // The result of initialization is the return slot of the initializer.
  64. context.SetLocal(inst_id, context.GetValue(inst.dest_id));
  65. }
  66. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  67. SemIR::AsCompatible inst) -> void {
  68. context.SetLocal(inst_id, context.GetValue(inst.source_id));
  69. }
  70. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  71. SemIR::Assign inst) -> void {
  72. if (SemIR::GetExprCategory(context.sem_ir(), inst.rhs_id) !=
  73. SemIR::ExprCategory::InPlaceInitializing) {
  74. context.InitializeStorage(context.GetTypeIdOfInst(inst.lhs_id), inst.lhs_id,
  75. inst.rhs_id);
  76. }
  77. }
  78. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  79. SemIR::AliasBinding inst) -> void {
  80. if (IsNamespace(context, inst_id)) {
  81. return;
  82. }
  83. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  84. }
  85. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  86. SemIR::ExportDecl inst) -> void {
  87. if (IsNamespace(context, inst_id)) {
  88. return;
  89. }
  90. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  91. }
  92. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  93. SemIR::RefBinding inst) -> void {
  94. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  95. }
  96. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  97. SemIR::ValueBinding inst) -> void {
  98. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  99. }
  100. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  101. SemIR::SymbolicBinding inst) -> void {
  102. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  103. }
  104. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  105. SemIR::BlockArg inst) -> void {
  106. context.SetLocal(
  107. inst_id,
  108. context.GetBlockArg(inst.block_id, context.GetTypeIdOfInst(inst_id)));
  109. }
  110. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  111. SemIR::BoundMethod inst) -> void {
  112. // Propagate just the function; the object is separately provided to the
  113. // enclosing call as an implicit argument.
  114. context.SetLocal(inst_id, context.GetValue(inst.function_decl_id));
  115. }
  116. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  117. SemIR::Branch inst) -> void {
  118. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  119. // TODO: Don't do this if it would remove a loop preheader block.
  120. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  121. if (block->empty() && context.TryToReuseBlock(inst.target_id, block)) {
  122. // Reuse this block as the branch target.
  123. } else {
  124. context.builder().CreateBr(context.GetBlock(inst.target_id));
  125. }
  126. context.builder().ClearInsertionPoint();
  127. }
  128. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  129. SemIR::BranchIf inst) -> void {
  130. llvm::Value* cond = context.GetValue(inst.cond_id);
  131. llvm::BasicBlock* then_block = context.GetBlock(inst.target_id);
  132. llvm::BasicBlock* else_block = context.MakeSyntheticBlock();
  133. context.builder().CreateCondBr(cond, then_block, else_block);
  134. context.builder().SetInsertPoint(else_block);
  135. }
  136. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  137. SemIR::BranchWithArg inst) -> void {
  138. llvm::Value* arg = context.GetValue(inst.arg_id);
  139. auto arg_type = context.GetTypeIdOfInst(inst.arg_id);
  140. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  141. // We only do this for a block that we know will only have a single
  142. // predecessor, so that we can correctly populate the predecessors of the
  143. // PHINode.
  144. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  145. llvm::BasicBlock* phi_predecessor = block;
  146. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  147. context.TryToReuseBlock(inst.target_id, block)) {
  148. // Reuse this block as the branch target.
  149. phi_predecessor = block->getSinglePredecessor();
  150. CARBON_CHECK(phi_predecessor,
  151. "Synthetic block did not have a single predecessor");
  152. } else {
  153. context.builder().CreateBr(context.GetBlock(inst.target_id));
  154. }
  155. context.GetBlockArg(inst.target_id, arg_type)
  156. ->addIncoming(arg, phi_predecessor);
  157. context.builder().ClearInsertionPoint();
  158. }
  159. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  160. SemIR::Converted inst) -> void {
  161. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  162. }
  163. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  164. SemIR::Deref inst) -> void {
  165. context.SetLocal(inst_id, context.GetValue(inst.pointer_id));
  166. }
  167. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  168. SemIR::FacetAccessType /*inst*/) -> void {
  169. context.SetLocal(inst_id, context.GetTypeAsValue());
  170. }
  171. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  172. SemIR::FacetValue /*inst*/) -> void {
  173. context.SetLocal(inst_id, context.GetTypeAsValue());
  174. }
  175. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  176. SemIR::InPlaceInit inst) -> void {
  177. context.InitializeStorage(context.GetTypeIdOfInst(inst.dest_id), inst.dest_id,
  178. inst.src_id);
  179. }
  180. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  181. SemIR::NameBindingDecl /*inst*/) -> void {
  182. // A NameBindingDecl is lowered by pattern matching.
  183. }
  184. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  185. SemIR::NameRef inst) -> void {
  186. if (IsNamespace(context, inst_id)) {
  187. return;
  188. }
  189. auto inner_inst_id = inst.value_id;
  190. // `GetValue` will fail on package-scope value bindings because they aren't
  191. // constants, and they aren't global variables, so as a workaround we
  192. // peek through bindings here to directly access the bound value.
  193. // TODO: Find a way of dealing with this that still works if the bound
  194. // value isn't a global variable or constant either.
  195. if (auto bind_name =
  196. context.sem_ir().insts().TryGetAs<SemIR::AnyBinding>(inner_inst_id)) {
  197. inner_inst_id = bind_name->value_id;
  198. }
  199. context.SetLocal(inst_id, context.GetValue(inner_inst_id));
  200. }
  201. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  202. SemIR::OutParam /*inst*/) -> void {
  203. // Parameters are lowered by `BuildFunctionDefinition`.
  204. }
  205. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  206. SemIR::RefParam /*inst*/) -> void {
  207. // Parameters are lowered by `BuildFunctionDefinition`.
  208. }
  209. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  210. SemIR::ValueParam /*inst*/) -> void {
  211. // Parameters are lowered by `BuildFunctionDefinition`.
  212. }
  213. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  214. SemIR::RefTagExpr inst) -> void {
  215. context.SetLocal(inst_id, context.GetValue(inst.expr_id));
  216. }
  217. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  218. SemIR::ReturnSlot inst) -> void {
  219. context.SetLocal(inst_id, context.GetValue(inst.storage_id));
  220. }
  221. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  222. SemIR::Return /*inst*/) -> void {
  223. context.builder().CreateRetVoid();
  224. }
  225. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  226. SemIR::ReturnExpr inst) -> void {
  227. auto result_type = context.GetTypeIdOfInst(inst.expr_id);
  228. switch (context.GetInitRepr(result_type).kind) {
  229. case SemIR::InitRepr::None:
  230. // Nothing to return.
  231. context.builder().CreateRetVoid();
  232. return;
  233. case SemIR::InitRepr::InPlace:
  234. CARBON_CHECK(context.GetValueRepr(result_type).repr.kind ==
  235. SemIR::ValueRepr::Pointer,
  236. "TODO: Add support for ReturnExpr with custom value repr");
  237. // TODO: find a way to avoid the redundant call to GetInitRepr inside
  238. // InitializeStorage.
  239. context.InitializeStorage(result_type, inst.dest_id, inst.expr_id);
  240. context.builder().CreateRetVoid();
  241. return;
  242. case SemIR::InitRepr::ByCopy: {
  243. auto* value = context.GetValue(inst.expr_id);
  244. switch (SemIR::GetExprCategory(context.sem_ir(), inst.expr_id)) {
  245. case SemIR::ExprCategory::Value:
  246. case SemIR::ExprCategory::ReprInitializing:
  247. case SemIR::ExprCategory::EphemeralRef:
  248. case SemIR::ExprCategory::DurableRef:
  249. break;
  250. case SemIR::ExprCategory::InPlaceInitializing:
  251. value =
  252. context.builder().CreateLoad(context.GetType(result_type), value);
  253. break;
  254. case SemIR::ExprCategory::Mixed:
  255. case SemIR::ExprCategory::RefTagged:
  256. case SemIR::ExprCategory::NotExpr:
  257. case SemIR::ExprCategory::Error:
  258. case SemIR::ExprCategory::Pattern:
  259. case SemIR::ExprCategory::Dependent:
  260. CARBON_FATAL("Unexpected category for `return` expression");
  261. }
  262. context.builder().CreateRet(value);
  263. return;
  264. }
  265. case SemIR::InitRepr::Abstract:
  266. CARBON_FATAL("Lowering return of abstract type {0}",
  267. result_type.file->types().GetAsInst(result_type.type_id));
  268. case SemIR::InitRepr::Incomplete:
  269. CARBON_FATAL("Lowering return of incomplete type {0}",
  270. result_type.file->types().GetAsInst(result_type.type_id));
  271. case SemIR::InitRepr::Dependent:
  272. CARBON_FATAL("Lowering return of dependent type {0}",
  273. result_type.file->types().GetAsInst(result_type.type_id));
  274. }
  275. }
  276. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  277. SemIR::RefReturn /*inst*/) -> void {
  278. // A `RefReturn` is a placeholder that represents the absence of a storage
  279. // location, so it should never actually be used, but in some cases it will
  280. // be propagated, so we poison it.
  281. context.SetLocal(inst_id,
  282. llvm::PoisonValue::get(context.GetTypeOfInst(inst_id)));
  283. }
  284. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  285. SemIR::SpecificFunction /*inst*/) -> void {
  286. // Nothing to do. This value should never be consumed.
  287. }
  288. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  289. SemIR::SpecificImplFunction /*inst*/) -> void {
  290. // Nothing to do. This value should never be consumed.
  291. }
  292. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  293. SemIR::SpliceBlock inst) -> void {
  294. context.LowerBlockContents(inst.block_id);
  295. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  296. }
  297. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  298. SemIR::SpliceInst /*inst*/) -> void {
  299. // TODO: Get the constant value of the spliced instruction from the current
  300. // specific, and lower the instruction in that constant value.
  301. CARBON_FATAL("Template lowering not implemented yet");
  302. }
  303. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  304. SemIR::TypeLiteral inst) -> void {
  305. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  306. }
  307. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  308. SemIR::UnaryOperatorNot inst) -> void {
  309. context.SetLocal(
  310. inst_id, context.builder().CreateNot(context.GetValue(inst.operand_id)));
  311. }
  312. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  313. SemIR::UpdateInit inst) -> void {
  314. // Ensure that our subordinate initializations have been performed. They may
  315. // have been skipped if they were constant.
  316. context.InitializeStorage(inst.base_init_id);
  317. context.InitializeStorage(inst.update_init_id);
  318. // TODO: Add a helper to poison a value slot.
  319. context.SetLocal(inst_id,
  320. llvm::PoisonValue::get(context.GetTypeOfInst(inst_id)));
  321. }
  322. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  323. SemIR::ValueReturn /*inst*/) -> void {
  324. // A `ValueReturn` is a placeholder that represents the absence of a storage
  325. // location, so it should never actually be used, but in some cases it will
  326. // be propagated, so we poison it.
  327. context.SetLocal(inst_id,
  328. llvm::PoisonValue::get(context.GetTypeOfInst(inst_id)));
  329. }
  330. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  331. SemIR::VarStorage /* inst */) -> void {
  332. context.SetLocal(inst_id,
  333. context.CreateAlloca(context.GetTypeOfInst(inst_id)));
  334. }
  335. } // namespace Carbon::Lower