handle.cpp 12 KB

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