handle.cpp 12 KB

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