handle.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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::FormBinding inst) -> void {
  106. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  107. }
  108. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  109. SemIR::BlockArg inst) -> void {
  110. context.SetLocal(
  111. inst_id,
  112. context.GetBlockArg(inst.block_id, context.GetTypeIdOfInst(inst_id)));
  113. }
  114. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  115. SemIR::BoundMethod inst) -> void {
  116. // Propagate just the function; the object is separately provided to the
  117. // enclosing call as an implicit argument.
  118. context.SetLocal(inst_id, context.GetValue(inst.function_decl_id));
  119. }
  120. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  121. SemIR::Branch inst) -> void {
  122. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  123. // TODO: Don't do this if it would remove a loop preheader block.
  124. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  125. if (block->empty() && context.TryToReuseBlock(inst.target_id, block)) {
  126. // Reuse this block as the branch target.
  127. } else {
  128. context.builder().CreateBr(context.GetBlock(inst.target_id));
  129. }
  130. context.builder().ClearInsertionPoint();
  131. }
  132. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  133. SemIR::BranchIf inst) -> void {
  134. llvm::Value* cond = context.GetValue(inst.cond_id);
  135. llvm::BasicBlock* then_block = context.GetBlock(inst.target_id);
  136. llvm::BasicBlock* else_block = context.MakeSyntheticBlock();
  137. context.builder().CreateCondBr(cond, then_block, else_block);
  138. context.builder().SetInsertPoint(else_block);
  139. }
  140. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  141. SemIR::BranchWithArg inst) -> void {
  142. llvm::Value* arg = context.GetValue(inst.arg_id);
  143. auto arg_type = context.GetTypeIdOfInst(inst.arg_id);
  144. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  145. // We only do this for a block that we know will only have a single
  146. // predecessor, so that we can correctly populate the predecessors of the
  147. // PHINode.
  148. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  149. llvm::BasicBlock* phi_predecessor = block;
  150. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  151. context.TryToReuseBlock(inst.target_id, block)) {
  152. // Reuse this block as the branch target.
  153. phi_predecessor = block->getSinglePredecessor();
  154. CARBON_CHECK(phi_predecessor,
  155. "Synthetic block did not have a single predecessor");
  156. } else {
  157. context.builder().CreateBr(context.GetBlock(inst.target_id));
  158. }
  159. context.GetBlockArg(inst.target_id, arg_type)
  160. ->addIncoming(arg, phi_predecessor);
  161. context.builder().ClearInsertionPoint();
  162. }
  163. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  164. SemIR::Converted inst) -> void {
  165. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  166. }
  167. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  168. SemIR::Deref inst) -> void {
  169. context.SetLocal(inst_id, context.GetValue(inst.pointer_id));
  170. }
  171. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  172. SemIR::FacetAccessType /*inst*/) -> void {
  173. context.SetLocal(inst_id, context.GetTypeAsValue());
  174. }
  175. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  176. SemIR::FacetValue /*inst*/) -> void {
  177. context.SetLocal(inst_id, context.GetTypeAsValue());
  178. }
  179. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  180. SemIR::InPlaceInit inst) -> void {
  181. context.InitializeStorage(context.GetTypeIdOfInst(inst.dest_id), inst.dest_id,
  182. inst.src_id);
  183. }
  184. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  185. SemIR::NameBindingDecl /*inst*/) -> void {
  186. // A NameBindingDecl is lowered by pattern matching.
  187. }
  188. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  189. SemIR::NameRef inst) -> void {
  190. if (IsNamespace(context, inst_id)) {
  191. return;
  192. }
  193. auto inner_inst_id = inst.value_id;
  194. // `GetValue` will fail on package-scope value bindings because they aren't
  195. // constants, and they aren't global variables, so as a workaround we
  196. // peek through bindings here to directly access the bound value.
  197. // TODO: Find a way of dealing with this that still works if the bound
  198. // value isn't a global variable or constant either.
  199. if (auto bind_name =
  200. context.sem_ir().insts().TryGetAs<SemIR::AnyBinding>(inner_inst_id)) {
  201. inner_inst_id = bind_name->value_id;
  202. }
  203. context.SetLocal(inst_id, context.GetValue(inner_inst_id));
  204. }
  205. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  206. SemIR::OutParam /*inst*/) -> void {
  207. // Parameters are lowered by `BuildFunctionDefinition`.
  208. }
  209. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  210. SemIR::RefParam /*inst*/) -> void {
  211. // Parameters are lowered by `BuildFunctionDefinition`.
  212. }
  213. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  214. SemIR::ValueParam /*inst*/) -> void {
  215. // Parameters are lowered by `BuildFunctionDefinition`.
  216. }
  217. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  218. SemIR::RefTagExpr inst) -> void {
  219. context.SetLocal(inst_id, context.GetValue(inst.expr_id));
  220. }
  221. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  222. SemIR::ReturnSlot inst) -> void {
  223. context.SetLocal(inst_id, context.GetValue(inst.storage_id));
  224. }
  225. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  226. SemIR::Return /*inst*/) -> void {
  227. context.builder().CreateRetVoid();
  228. }
  229. auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/,
  230. SemIR::ReturnExpr inst) -> void {
  231. auto result_type = context.GetTypeIdOfInst(inst.expr_id);
  232. switch (context.GetInitRepr(result_type).kind) {
  233. case SemIR::InitRepr::None:
  234. // Nothing to return.
  235. context.builder().CreateRetVoid();
  236. return;
  237. case SemIR::InitRepr::InPlace:
  238. CARBON_CHECK(context.GetValueRepr(result_type).repr.kind ==
  239. SemIR::ValueRepr::Pointer,
  240. "TODO: Add support for ReturnExpr with custom value repr");
  241. // TODO: find a way to avoid the redundant call to GetInitRepr inside
  242. // InitializeStorage.
  243. context.InitializeStorage(result_type, inst.dest_id, inst.expr_id);
  244. context.builder().CreateRetVoid();
  245. return;
  246. case SemIR::InitRepr::ByCopy: {
  247. auto* value = context.GetValue(inst.expr_id);
  248. switch (SemIR::GetExprCategory(context.sem_ir(), inst.expr_id)) {
  249. case SemIR::ExprCategory::Value:
  250. case SemIR::ExprCategory::ReprInitializing:
  251. case SemIR::ExprCategory::EphemeralRef:
  252. case SemIR::ExprCategory::DurableRef:
  253. break;
  254. case SemIR::ExprCategory::InPlaceInitializing:
  255. value =
  256. context.builder().CreateLoad(context.GetType(result_type), value);
  257. break;
  258. case SemIR::ExprCategory::Mixed:
  259. case SemIR::ExprCategory::RefTagged:
  260. case SemIR::ExprCategory::NotExpr:
  261. case SemIR::ExprCategory::Error:
  262. case SemIR::ExprCategory::Pattern:
  263. case SemIR::ExprCategory::Dependent:
  264. CARBON_FATAL("Unexpected category for `return` expression");
  265. }
  266. context.builder().CreateRet(value);
  267. return;
  268. }
  269. case SemIR::InitRepr::Abstract:
  270. CARBON_FATAL("Lowering return of abstract type {0}",
  271. result_type.file->types().GetAsInst(result_type.type_id));
  272. case SemIR::InitRepr::Incomplete:
  273. CARBON_FATAL("Lowering return of incomplete type {0}",
  274. result_type.file->types().GetAsInst(result_type.type_id));
  275. case SemIR::InitRepr::Dependent:
  276. CARBON_FATAL("Lowering return of dependent type {0}",
  277. result_type.file->types().GetAsInst(result_type.type_id));
  278. }
  279. }
  280. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  281. SemIR::SpecificFunction /*inst*/) -> void {
  282. // Nothing to do. This value should never be consumed.
  283. }
  284. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  285. SemIR::SpecificImplFunction /*inst*/) -> void {
  286. // Nothing to do. This value should never be consumed.
  287. }
  288. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  289. SemIR::SpliceBlock inst) -> void {
  290. context.LowerBlockContents(inst.block_id);
  291. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  292. }
  293. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  294. SemIR::SpliceInst /*inst*/) -> void {
  295. // TODO: Get the constant value of the spliced instruction from the current
  296. // specific, and lower the instruction in that constant value.
  297. CARBON_FATAL("Template lowering not implemented yet");
  298. }
  299. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  300. SemIR::TypeLiteral inst) -> void {
  301. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  302. }
  303. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  304. SemIR::UnaryOperatorNot inst) -> void {
  305. context.SetLocal(
  306. inst_id, context.builder().CreateNot(context.GetValue(inst.operand_id)));
  307. }
  308. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  309. SemIR::UpdateInit inst) -> void {
  310. // Ensure that our subordinate initializations have been performed. They may
  311. // have been skipped if they were constant.
  312. context.InitializeStorage(inst.base_init_id);
  313. context.InitializeStorage(inst.update_init_id);
  314. // TODO: Add a helper to poison a value slot.
  315. context.SetLocal(inst_id,
  316. llvm::PoisonValue::get(context.GetTypeOfInst(inst_id)));
  317. }
  318. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  319. SemIR::VarStorage /* inst */) -> void {
  320. context.SetLocal(inst_id,
  321. context.CreateAlloca(context.GetTypeOfInst(inst_id)));
  322. }
  323. } // namespace Carbon::Lower