handle.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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/Type.h"
  10. #include "llvm/IR/Value.h"
  11. #include "llvm/Support/Casting.h"
  12. #include "toolchain/lower/function_context.h"
  13. #include "toolchain/sem_ir/function.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Lower {
  17. template <typename InstT>
  18. static auto FatalErrorIfEncountered(InstT inst) -> void {
  19. CARBON_FATAL()
  20. << "Encountered an instruction that isn't expected to lower. It's "
  21. "possible that logic needs to be changed in order to stop "
  22. "showing this instruction in lowered contexts. Instruction: "
  23. << inst;
  24. }
  25. auto HandleAddrOf(FunctionContext& context, SemIR::InstId inst_id,
  26. SemIR::AddrOf inst) -> void {
  27. context.SetLocal(inst_id, context.GetValue(inst.lvalue_id));
  28. }
  29. auto HandleAddrPattern(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  30. SemIR::AddrPattern /*inst*/) -> void {
  31. CARBON_FATAL() << "`addr` should be lowered by `BuildFunctionDefinition`";
  32. }
  33. auto HandleArrayIndex(FunctionContext& context, SemIR::InstId inst_id,
  34. SemIR::ArrayIndex inst) -> void {
  35. auto* array_value = context.GetValue(inst.array_id);
  36. auto* llvm_type =
  37. context.GetType(context.sem_ir().insts().Get(inst.array_id).type_id());
  38. llvm::Value* indexes[2] = {
  39. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  40. context.GetValue(inst.index_id)};
  41. context.SetLocal(inst_id,
  42. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  43. indexes, "array.index"));
  44. }
  45. auto HandleArrayInit(FunctionContext& context, SemIR::InstId inst_id,
  46. SemIR::ArrayInit inst) -> void {
  47. // The result of initialization is the return slot of the initializer.
  48. context.SetLocal(inst_id, context.GetValue(inst.dest_id));
  49. }
  50. auto HandleAssign(FunctionContext& context, SemIR::InstId /*inst_id*/,
  51. SemIR::Assign inst) -> void {
  52. auto storage_type_id = context.sem_ir().insts().Get(inst.lhs_id).type_id();
  53. context.FinishInit(storage_type_id, inst.lhs_id, inst.rhs_id);
  54. }
  55. auto HandleAssociatedConstantDecl(FunctionContext& /*context*/,
  56. SemIR::InstId /*inst_id*/,
  57. SemIR::AssociatedConstantDecl inst) -> void {
  58. FatalErrorIfEncountered(inst);
  59. }
  60. auto HandleAssociatedEntity(FunctionContext& /*context*/,
  61. SemIR::InstId /*inst_id*/,
  62. SemIR::AssociatedEntity inst) -> void {
  63. FatalErrorIfEncountered(inst);
  64. }
  65. auto HandleBindAlias(FunctionContext& context, SemIR::InstId inst_id,
  66. SemIR::BindAlias inst) -> void {
  67. auto type_inst_id = context.sem_ir().types().GetInstId(inst.type_id);
  68. if (type_inst_id == SemIR::InstId::BuiltinNamespaceType) {
  69. return;
  70. }
  71. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  72. }
  73. auto HandleBindName(FunctionContext& context, SemIR::InstId inst_id,
  74. SemIR::BindName inst) -> void {
  75. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  76. }
  77. auto HandleBindSymbolicName(FunctionContext& context, SemIR::InstId inst_id,
  78. SemIR::BindSymbolicName inst) -> void {
  79. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  80. }
  81. auto HandleBlockArg(FunctionContext& context, SemIR::InstId inst_id,
  82. SemIR::BlockArg inst) -> void {
  83. context.SetLocal(inst_id, context.GetBlockArg(inst.block_id, inst.type_id));
  84. }
  85. auto HandleBoolLiteral(FunctionContext& context, SemIR::InstId inst_id,
  86. SemIR::BoolLiteral inst) -> void {
  87. llvm::Value* v =
  88. llvm::ConstantInt::get(context.builder().getInt1Ty(), inst.value.index);
  89. context.SetLocal(inst_id, v);
  90. }
  91. auto HandleBoundMethod(FunctionContext& context, SemIR::InstId inst_id,
  92. SemIR::BoundMethod inst) -> void {
  93. // Propagate just the function; the object is separately provided to the
  94. // enclosing call as an implicit argument.
  95. context.SetLocal(inst_id, context.GetValue(inst.function_id));
  96. }
  97. auto HandleBranch(FunctionContext& context, SemIR::InstId /*inst_id*/,
  98. SemIR::Branch inst) -> void {
  99. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  100. // TODO: Don't do this if it would remove a loop preheader block.
  101. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  102. if (block->empty() && context.TryToReuseBlock(inst.target_id, block)) {
  103. // Reuse this block as the branch target.
  104. } else {
  105. context.builder().CreateBr(context.GetBlock(inst.target_id));
  106. }
  107. context.builder().ClearInsertionPoint();
  108. }
  109. auto HandleBranchIf(FunctionContext& context, SemIR::InstId /*inst_id*/,
  110. SemIR::BranchIf inst) -> void {
  111. llvm::Value* cond = context.GetValue(inst.cond_id);
  112. llvm::BasicBlock* then_block = context.GetBlock(inst.target_id);
  113. llvm::BasicBlock* else_block = context.MakeSyntheticBlock();
  114. context.builder().CreateCondBr(cond, then_block, else_block);
  115. context.builder().SetInsertPoint(else_block);
  116. }
  117. auto HandleBranchWithArg(FunctionContext& context, SemIR::InstId /*inst_id*/,
  118. SemIR::BranchWithArg inst) -> void {
  119. llvm::Value* arg = context.GetValue(inst.arg_id);
  120. SemIR::TypeId arg_type_id =
  121. context.sem_ir().insts().Get(inst.arg_id).type_id();
  122. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  123. // We only do this for a block that we know will only have a single
  124. // predecessor, so that we can correctly populate the predecessors of the
  125. // PHINode.
  126. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  127. llvm::BasicBlock* phi_predecessor = block;
  128. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  129. context.TryToReuseBlock(inst.target_id, block)) {
  130. // Reuse this block as the branch target.
  131. phi_predecessor = block->getSinglePredecessor();
  132. CARBON_CHECK(phi_predecessor)
  133. << "Synthetic block did not have a single predecessor";
  134. } else {
  135. context.builder().CreateBr(context.GetBlock(inst.target_id));
  136. }
  137. context.GetBlockArg(inst.target_id, arg_type_id)
  138. ->addIncoming(arg, phi_predecessor);
  139. context.builder().ClearInsertionPoint();
  140. }
  141. auto HandleBuiltin(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  142. SemIR::Builtin inst) -> void {
  143. CARBON_FATAL() << "TODO: Add support: " << inst;
  144. }
  145. // Returns the builtin function kind of the callee in a function call, or None
  146. // if the call is not to a builtin.
  147. static auto GetCalleeBuiltinFunctionKind(const SemIR::File& sem_ir,
  148. SemIR::InstId callee_id)
  149. -> SemIR::BuiltinFunctionKind {
  150. if (auto bound_method =
  151. sem_ir.insts().TryGetAs<SemIR::BoundMethod>(callee_id)) {
  152. callee_id = bound_method->function_id;
  153. }
  154. callee_id = sem_ir.constant_values().Get(callee_id).inst_id();
  155. if (!callee_id.is_valid()) {
  156. return SemIR::BuiltinFunctionKind::None;
  157. }
  158. if (auto callee = sem_ir.insts().TryGetAs<SemIR::FunctionDecl>(callee_id)) {
  159. const auto& function = sem_ir.functions().Get(callee->function_id);
  160. return function.builtin_kind;
  161. }
  162. return SemIR::BuiltinFunctionKind::None;
  163. }
  164. // Handles a call to a builtin function.
  165. static auto HandleBuiltinCall(FunctionContext& context, SemIR::InstId inst_id,
  166. SemIR::BuiltinFunctionKind builtin_kind,
  167. llvm::ArrayRef<SemIR::InstId> arg_ids) -> void {
  168. switch (builtin_kind) {
  169. case SemIR::BuiltinFunctionKind::None:
  170. CARBON_FATAL() << "No callee in function call.";
  171. case SemIR::BuiltinFunctionKind::IntAdd: {
  172. // TODO: Move type checking to the point where we make the call.
  173. if (arg_ids.size() != 2) {
  174. break;
  175. }
  176. auto lhs_type = context.sem_ir().insts().Get(arg_ids[0]).type_id();
  177. auto rhs_type = context.sem_ir().insts().Get(arg_ids[1]).type_id();
  178. auto result_type = context.sem_ir().insts().Get(inst_id).type_id();
  179. if (lhs_type != rhs_type || lhs_type != result_type ||
  180. context.sem_ir().types().GetInstId(lhs_type) !=
  181. SemIR::InstId::BuiltinIntType) {
  182. break;
  183. }
  184. constexpr bool SignedOverflowIsUB = false;
  185. context.SetLocal(inst_id, context.builder().CreateAdd(
  186. context.GetValue(arg_ids[0]),
  187. context.GetValue(arg_ids[1]), "add",
  188. /*HasNUW=*/false,
  189. /*HasNSW=*/SignedOverflowIsUB));
  190. return;
  191. }
  192. }
  193. CARBON_FATAL() << "Unsupported builtin call.";
  194. }
  195. auto HandleCall(FunctionContext& context, SemIR::InstId inst_id,
  196. SemIR::Call inst) -> void {
  197. llvm::ArrayRef<SemIR::InstId> arg_ids =
  198. context.sem_ir().inst_blocks().Get(inst.args_id);
  199. auto* callee_value = context.GetValue(inst.callee_id);
  200. // A null callee pointer value indicates this isn't a real function.
  201. if (!callee_value) {
  202. auto builtin_kind =
  203. GetCalleeBuiltinFunctionKind(context.sem_ir(), inst.callee_id);
  204. HandleBuiltinCall(context, inst_id, builtin_kind, arg_ids);
  205. return;
  206. }
  207. auto* callee = llvm::cast<llvm::Function>(callee_value);
  208. std::vector<llvm::Value*> args;
  209. if (SemIR::GetInitRepr(context.sem_ir(), inst.type_id).has_return_slot()) {
  210. args.push_back(context.GetValue(arg_ids.back()));
  211. arg_ids = arg_ids.drop_back();
  212. }
  213. for (auto arg_id : arg_ids) {
  214. auto arg_type_id = context.sem_ir().insts().Get(arg_id).type_id();
  215. if (SemIR::GetValueRepr(context.sem_ir(), arg_type_id).kind !=
  216. SemIR::ValueRepr::None) {
  217. args.push_back(context.GetValue(arg_id));
  218. }
  219. }
  220. auto* call = context.builder().CreateCall(callee, args);
  221. context.SetLocal(inst_id, call);
  222. // Name the call's result the same as the callee.
  223. // TODO: Is this a helpful name?
  224. if (!call->getType()->isVoidTy()) {
  225. call->setName(callee->getName());
  226. }
  227. }
  228. auto HandleConverted(FunctionContext& context, SemIR::InstId inst_id,
  229. SemIR::Converted inst) -> void {
  230. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  231. }
  232. auto HandleDeref(FunctionContext& context, SemIR::InstId inst_id,
  233. SemIR::Deref inst) -> void {
  234. context.SetLocal(inst_id, context.GetValue(inst.pointer_id));
  235. }
  236. auto HandleFunctionDecl(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  237. SemIR::FunctionDecl inst) -> void {
  238. FatalErrorIfEncountered(inst);
  239. }
  240. auto HandleImplDecl(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  241. SemIR::ImplDecl inst) -> void {
  242. FatalErrorIfEncountered(inst);
  243. }
  244. auto HandleImportRefUnused(FunctionContext& /*context*/,
  245. SemIR::InstId /*inst_id*/,
  246. SemIR::ImportRefUnused inst) -> void {
  247. FatalErrorIfEncountered(inst);
  248. }
  249. auto HandleImportRefUsed(FunctionContext& /*context*/,
  250. SemIR::InstId /*inst_id*/, SemIR::ImportRefUsed inst)
  251. -> void {
  252. FatalErrorIfEncountered(inst);
  253. }
  254. auto HandleInitializeFrom(FunctionContext& context, SemIR::InstId /*inst_id*/,
  255. SemIR::InitializeFrom inst) -> void {
  256. auto storage_type_id = context.sem_ir().insts().Get(inst.dest_id).type_id();
  257. context.FinishInit(storage_type_id, inst.dest_id, inst.src_id);
  258. }
  259. auto HandleInterfaceDecl(FunctionContext& /*context*/,
  260. SemIR::InstId /*inst_id*/, SemIR::InterfaceDecl inst)
  261. -> void {
  262. FatalErrorIfEncountered(inst);
  263. }
  264. auto HandleInterfaceWitness(FunctionContext& /*context*/,
  265. SemIR::InstId /*inst_id*/,
  266. SemIR::InterfaceWitness inst) -> void {
  267. FatalErrorIfEncountered(inst);
  268. }
  269. auto HandleInterfaceWitnessAccess(FunctionContext& context,
  270. SemIR::InstId inst_id,
  271. SemIR::InterfaceWitnessAccess inst) -> void {
  272. // TODO: Add general constant lowering.
  273. auto const_id = context.sem_ir().constant_values().Get(inst_id);
  274. CARBON_CHECK(const_id.is_constant())
  275. << "Lowering non-constant witness access " << inst;
  276. context.SetLocal(inst_id, context.GetValue(const_id.inst_id()));
  277. }
  278. auto HandleIntLiteral(FunctionContext& context, SemIR::InstId inst_id,
  279. SemIR::IntLiteral inst) -> void {
  280. const llvm::APInt& i = context.sem_ir().ints().Get(inst.int_id);
  281. // TODO: This won't offer correct semantics, but seems close enough for now.
  282. llvm::Value* v =
  283. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue());
  284. context.SetLocal(inst_id, v);
  285. }
  286. auto HandleNameRef(FunctionContext& context, SemIR::InstId inst_id,
  287. SemIR::NameRef inst) -> void {
  288. auto type_inst_id = context.sem_ir().types().GetInstId(inst.type_id);
  289. if (type_inst_id == SemIR::InstId::BuiltinNamespaceType) {
  290. return;
  291. }
  292. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  293. }
  294. auto HandleNamespace(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  295. SemIR::Namespace inst) -> void {
  296. FatalErrorIfEncountered(inst);
  297. }
  298. auto HandleParam(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  299. SemIR::Param /*inst*/) -> void {
  300. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  301. }
  302. auto HandleRealLiteral(FunctionContext& context, SemIR::InstId inst_id,
  303. SemIR::RealLiteral inst) -> void {
  304. const Real& real = context.sem_ir().reals().Get(inst.real_id);
  305. // TODO: This will probably have overflow issues, and should be fixed.
  306. double val =
  307. real.mantissa.getZExtValue() *
  308. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  309. llvm::APFloat llvm_val(val);
  310. context.SetLocal(inst_id, llvm::ConstantFP::get(
  311. context.builder().getDoubleTy(), llvm_val));
  312. }
  313. auto HandleReturn(FunctionContext& context, SemIR::InstId /*inst_id*/,
  314. SemIR::Return /*inst*/) -> void {
  315. context.builder().CreateRetVoid();
  316. }
  317. auto HandleReturnExpr(FunctionContext& context, SemIR::InstId /*inst_id*/,
  318. SemIR::ReturnExpr inst) -> void {
  319. switch (
  320. SemIR::GetInitRepr(context.sem_ir(),
  321. context.sem_ir().insts().Get(inst.expr_id).type_id())
  322. .kind) {
  323. case SemIR::InitRepr::None:
  324. case SemIR::InitRepr::InPlace:
  325. // Nothing to return.
  326. context.builder().CreateRetVoid();
  327. return;
  328. case SemIR::InitRepr::ByCopy:
  329. // The expression produces the value representation for the type.
  330. context.builder().CreateRet(context.GetValue(inst.expr_id));
  331. return;
  332. }
  333. }
  334. auto HandleSpliceBlock(FunctionContext& context, SemIR::InstId inst_id,
  335. SemIR::SpliceBlock inst) -> void {
  336. context.LowerBlock(inst.block_id);
  337. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  338. }
  339. auto HandleStringLiteral(FunctionContext& /*context*/,
  340. SemIR::InstId /*inst_id*/, SemIR::StringLiteral inst)
  341. -> void {
  342. CARBON_FATAL() << "TODO: Add support: " << inst;
  343. }
  344. auto HandleUnaryOperatorNot(FunctionContext& context, SemIR::InstId inst_id,
  345. SemIR::UnaryOperatorNot inst) -> void {
  346. context.SetLocal(
  347. inst_id, context.builder().CreateNot(context.GetValue(inst.operand_id)));
  348. }
  349. auto HandleVarStorage(FunctionContext& context, SemIR::InstId inst_id,
  350. SemIR::VarStorage inst) -> void {
  351. // TODO: Eventually this name will be optional, and we'll want to provide
  352. // something like `var` as a default. However, that's not possible right now
  353. // so cannot be tested.
  354. auto name = context.sem_ir().names().GetIRBaseName(inst.name_id);
  355. auto* alloca = context.builder().CreateAlloca(context.GetType(inst.type_id),
  356. /*ArraySize=*/nullptr, name);
  357. context.SetLocal(inst_id, alloca);
  358. }
  359. } // namespace Carbon::Lower