handle.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Lower {
  16. template <typename InstT>
  17. static auto FatalErrorIfEncountered(InstT inst) -> void {
  18. CARBON_FATAL()
  19. << "Encountered an instruction that isn't expected to lower. It's "
  20. "possible that logic needs to be changed in order to stop "
  21. "showing this instruction in lowered contexts. Instruction: "
  22. << inst;
  23. }
  24. auto HandleAddressOf(FunctionContext& context, SemIR::InstId inst_id,
  25. SemIR::AddressOf inst) -> void {
  26. context.SetLocal(inst_id, context.GetValue(inst.lvalue_id));
  27. }
  28. auto HandleArrayIndex(FunctionContext& context, SemIR::InstId inst_id,
  29. SemIR::ArrayIndex inst) -> void {
  30. auto* array_value = context.GetValue(inst.array_id);
  31. auto* llvm_type =
  32. context.GetType(context.sem_ir().insts().Get(inst.array_id).type_id());
  33. llvm::Value* indexes[2] = {
  34. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  35. context.GetValue(inst.index_id)};
  36. context.SetLocal(inst_id,
  37. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  38. indexes, "array.index"));
  39. }
  40. auto HandleArrayInit(FunctionContext& context, SemIR::InstId inst_id,
  41. SemIR::ArrayInit inst) -> void {
  42. // The result of initialization is the return slot of the initializer.
  43. context.SetLocal(inst_id, context.GetValue(inst.dest_id));
  44. }
  45. auto HandleAssign(FunctionContext& context, SemIR::InstId /*inst_id*/,
  46. SemIR::Assign inst) -> void {
  47. auto storage_type_id = context.sem_ir().insts().Get(inst.lhs_id).type_id();
  48. context.FinishInit(storage_type_id, inst.lhs_id, inst.rhs_id);
  49. }
  50. auto HandleBindName(FunctionContext& context, SemIR::InstId inst_id,
  51. SemIR::BindName inst) -> void {
  52. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  53. }
  54. auto HandleBlockArg(FunctionContext& context, SemIR::InstId inst_id,
  55. SemIR::BlockArg inst) -> void {
  56. context.SetLocal(inst_id, context.GetBlockArg(inst.block_id, inst.type_id));
  57. }
  58. auto HandleBoolLiteral(FunctionContext& context, SemIR::InstId inst_id,
  59. SemIR::BoolLiteral inst) -> void {
  60. llvm::Value* v =
  61. llvm::ConstantInt::get(context.builder().getInt1Ty(), inst.value.index);
  62. context.SetLocal(inst_id, v);
  63. }
  64. auto HandleBoundMethod(FunctionContext& context, SemIR::InstId inst_id,
  65. SemIR::BoundMethod inst) -> void {
  66. // Propagate just the function; the object is separately provided to the
  67. // enclosing call as an implicit argument.
  68. context.SetLocal(inst_id, context.GetValue(inst.function_id));
  69. }
  70. auto HandleBranch(FunctionContext& context, SemIR::InstId /*inst_id*/,
  71. SemIR::Branch inst) -> void {
  72. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  73. // TODO: Don't do this if it would remove a loop preheader block.
  74. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  75. if (block->empty() && context.TryToReuseBlock(inst.target_id, block)) {
  76. // Reuse this block as the branch target.
  77. } else {
  78. context.builder().CreateBr(context.GetBlock(inst.target_id));
  79. }
  80. context.builder().ClearInsertionPoint();
  81. }
  82. auto HandleBranchIf(FunctionContext& context, SemIR::InstId /*inst_id*/,
  83. SemIR::BranchIf inst) -> void {
  84. llvm::Value* cond = context.GetValue(inst.cond_id);
  85. llvm::BasicBlock* then_block = context.GetBlock(inst.target_id);
  86. llvm::BasicBlock* else_block = context.CreateSyntheticBlock();
  87. context.builder().CreateCondBr(cond, then_block, else_block);
  88. context.builder().SetInsertPoint(else_block);
  89. }
  90. auto HandleBranchWithArg(FunctionContext& context, SemIR::InstId /*inst_id*/,
  91. SemIR::BranchWithArg inst) -> void {
  92. llvm::Value* arg = context.GetValue(inst.arg_id);
  93. SemIR::TypeId arg_type_id =
  94. context.sem_ir().insts().Get(inst.arg_id).type_id();
  95. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  96. // We only do this for a block that we know will only have a single
  97. // predecessor, so that we can correctly populate the predecessors of the
  98. // PHINode.
  99. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  100. llvm::BasicBlock* phi_predecessor = block;
  101. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  102. context.TryToReuseBlock(inst.target_id, block)) {
  103. // Reuse this block as the branch target.
  104. phi_predecessor = block->getSinglePredecessor();
  105. CARBON_CHECK(phi_predecessor)
  106. << "Synthetic block did not have a single predecessor";
  107. } else {
  108. context.builder().CreateBr(context.GetBlock(inst.target_id));
  109. }
  110. context.GetBlockArg(inst.target_id, arg_type_id)
  111. ->addIncoming(arg, phi_predecessor);
  112. context.builder().ClearInsertionPoint();
  113. }
  114. auto HandleBuiltin(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  115. SemIR::Builtin inst) -> void {
  116. CARBON_FATAL() << "TODO: Add support: " << inst;
  117. }
  118. auto HandleCall(FunctionContext& context, SemIR::InstId inst_id,
  119. SemIR::Call inst) -> void {
  120. auto* callee = llvm::cast<llvm::Function>(context.GetValue(inst.callee_id));
  121. std::vector<llvm::Value*> args;
  122. llvm::ArrayRef<SemIR::InstId> arg_ids =
  123. context.sem_ir().inst_blocks().Get(inst.args_id);
  124. if (SemIR::GetInitRepr(context.sem_ir(), inst.type_id).has_return_slot()) {
  125. args.push_back(context.GetValue(arg_ids.back()));
  126. arg_ids = arg_ids.drop_back();
  127. }
  128. for (auto arg_id : arg_ids) {
  129. auto arg_type_id = context.sem_ir().insts().Get(arg_id).type_id();
  130. if (SemIR::GetValueRepr(context.sem_ir(), arg_type_id).kind !=
  131. SemIR::ValueRepr::None) {
  132. args.push_back(context.GetValue(arg_id));
  133. }
  134. }
  135. auto* call = context.builder().CreateCall(callee, args);
  136. context.SetLocal(inst_id, call);
  137. // Name the call's result the same as the callee.
  138. // TODO: Is this a helpful name?
  139. if (!call->getType()->isVoidTy()) {
  140. call->setName(callee->getName());
  141. }
  142. }
  143. auto HandleConverted(FunctionContext& context, SemIR::InstId inst_id,
  144. SemIR::Converted inst) -> void {
  145. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  146. }
  147. auto HandleCrossRef(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  148. SemIR::CrossRef inst) -> void {
  149. FatalErrorIfEncountered(inst);
  150. }
  151. auto HandleDeref(FunctionContext& context, SemIR::InstId inst_id,
  152. SemIR::Deref inst) -> void {
  153. context.SetLocal(inst_id, context.GetValue(inst.pointer_id));
  154. }
  155. auto HandleFunctionDecl(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  156. SemIR::FunctionDecl inst) -> void {
  157. FatalErrorIfEncountered(inst);
  158. }
  159. auto HandleImport(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  160. SemIR::Import inst) -> void {
  161. FatalErrorIfEncountered(inst);
  162. }
  163. auto HandleInitializeFrom(FunctionContext& context, SemIR::InstId /*inst_id*/,
  164. SemIR::InitializeFrom inst) -> void {
  165. auto storage_type_id = context.sem_ir().insts().Get(inst.dest_id).type_id();
  166. context.FinishInit(storage_type_id, inst.dest_id, inst.src_id);
  167. }
  168. auto HandleInterfaceDecl(FunctionContext& /*context*/,
  169. SemIR::InstId /*inst_id*/,
  170. SemIR::InterfaceDecl /*inst*/) -> void {
  171. // No action to perform.
  172. }
  173. auto HandleIntLiteral(FunctionContext& context, SemIR::InstId inst_id,
  174. SemIR::IntLiteral inst) -> void {
  175. const llvm::APInt& i = context.sem_ir().ints().Get(inst.int_id);
  176. // TODO: This won't offer correct semantics, but seems close enough for now.
  177. llvm::Value* v =
  178. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue());
  179. context.SetLocal(inst_id, v);
  180. }
  181. auto HandleLazyImportRef(FunctionContext& /*context*/,
  182. SemIR::InstId /*inst_id*/, SemIR::LazyImportRef inst)
  183. -> void {
  184. FatalErrorIfEncountered(inst);
  185. }
  186. auto HandleNameRef(FunctionContext& context, SemIR::InstId inst_id,
  187. SemIR::NameRef inst) -> void {
  188. auto type_inst_id = context.sem_ir().types().GetInstId(inst.type_id);
  189. if (type_inst_id == SemIR::InstId::BuiltinNamespaceType) {
  190. return;
  191. }
  192. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  193. }
  194. auto HandleNamespace(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  195. SemIR::Namespace inst) -> void {
  196. FatalErrorIfEncountered(inst);
  197. }
  198. auto HandleNoOp(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  199. SemIR::NoOp /*inst*/) -> void {
  200. // No action to take.
  201. }
  202. auto HandleParam(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  203. SemIR::Param /*inst*/) -> void {
  204. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  205. }
  206. auto HandleRealLiteral(FunctionContext& context, SemIR::InstId inst_id,
  207. SemIR::RealLiteral inst) -> void {
  208. const Real& real = context.sem_ir().reals().Get(inst.real_id);
  209. // TODO: This will probably have overflow issues, and should be fixed.
  210. double val =
  211. real.mantissa.getZExtValue() *
  212. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  213. llvm::APFloat llvm_val(val);
  214. context.SetLocal(inst_id, llvm::ConstantFP::get(
  215. context.builder().getDoubleTy(), llvm_val));
  216. }
  217. auto HandleReturn(FunctionContext& context, SemIR::InstId /*inst_id*/,
  218. SemIR::Return /*inst*/) -> void {
  219. context.builder().CreateRetVoid();
  220. }
  221. auto HandleReturnExpr(FunctionContext& context, SemIR::InstId /*inst_id*/,
  222. SemIR::ReturnExpr inst) -> void {
  223. switch (
  224. SemIR::GetInitRepr(context.sem_ir(),
  225. context.sem_ir().insts().Get(inst.expr_id).type_id())
  226. .kind) {
  227. case SemIR::InitRepr::None:
  228. case SemIR::InitRepr::InPlace:
  229. // Nothing to return.
  230. context.builder().CreateRetVoid();
  231. return;
  232. case SemIR::InitRepr::ByCopy:
  233. // The expression produces the value representation for the type.
  234. context.builder().CreateRet(context.GetValue(inst.expr_id));
  235. return;
  236. }
  237. }
  238. auto HandleSelfParam(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  239. SemIR::SelfParam /*inst*/) -> void {
  240. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  241. }
  242. auto HandleSpliceBlock(FunctionContext& context, SemIR::InstId inst_id,
  243. SemIR::SpliceBlock inst) -> void {
  244. context.LowerBlock(inst.block_id);
  245. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  246. }
  247. auto HandleStringLiteral(FunctionContext& /*context*/,
  248. SemIR::InstId /*inst_id*/, SemIR::StringLiteral inst)
  249. -> void {
  250. CARBON_FATAL() << "TODO: Add support: " << inst;
  251. }
  252. auto HandleUnaryOperatorNot(FunctionContext& context, SemIR::InstId inst_id,
  253. SemIR::UnaryOperatorNot inst) -> void {
  254. context.SetLocal(
  255. inst_id, context.builder().CreateNot(context.GetValue(inst.operand_id)));
  256. }
  257. auto HandleVarStorage(FunctionContext& context, SemIR::InstId inst_id,
  258. SemIR::VarStorage inst) -> void {
  259. // TODO: Eventually this name will be optional, and we'll want to provide
  260. // something like `var` as a default. However, that's not possible right now
  261. // so cannot be tested.
  262. auto name = context.sem_ir().names().GetIRBaseName(inst.name_id);
  263. auto* alloca = context.builder().CreateAlloca(context.GetType(inst.type_id),
  264. /*ArraySize=*/nullptr, name);
  265. context.SetLocal(inst_id, alloca);
  266. }
  267. } // namespace Carbon::Lower