handle.cpp 13 KB

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