call.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 "toolchain/check/call.h"
  5. #include <optional>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/control_flow.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/cpp_thunk.h"
  11. #include "toolchain/check/deduce.h"
  12. #include "toolchain/check/facet_type.h"
  13. #include "toolchain/check/function.h"
  14. #include "toolchain/check/import_ref.h"
  15. #include "toolchain/check/inst.h"
  16. #include "toolchain/check/name_ref.h"
  17. #include "toolchain/check/thunk.h"
  18. #include "toolchain/check/type.h"
  19. #include "toolchain/diagnostics/format_providers.h"
  20. #include "toolchain/sem_ir/builtin_function_kind.h"
  21. #include "toolchain/sem_ir/entity_with_params_base.h"
  22. #include "toolchain/sem_ir/function.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/inst.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. namespace {
  28. // Entity kinds, for diagnostics. Converted to an int for a select.
  29. enum class EntityKind : uint8_t {
  30. Function = 0,
  31. GenericClass = 1,
  32. GenericInterface = 2,
  33. };
  34. } // namespace
  35. // Resolves the callee expression in a call to a specific callee, or diagnoses
  36. // if no specific callee can be identified. This verifies the arity of the
  37. // callee and determines any compile-time arguments, but doesn't check that the
  38. // runtime arguments are convertible to the parameter types.
  39. //
  40. // `self_id` and `arg_ids` are the self argument and explicit arguments in the
  41. // call.
  42. //
  43. // Returns a `SpecificId` for the specific callee, `SpecificId::None` if the
  44. // callee is not generic, or `nullopt` if an error has been diagnosed.
  45. static auto ResolveCalleeInCall(Context& context, SemIR::LocId loc_id,
  46. const SemIR::EntityWithParamsBase& entity,
  47. EntityKind entity_kind_for_diagnostic,
  48. SemIR::SpecificId enclosing_specific_id,
  49. SemIR::InstId self_type_id,
  50. SemIR::InstId self_id,
  51. llvm::ArrayRef<SemIR::InstId> arg_ids)
  52. -> std::optional<SemIR::SpecificId> {
  53. // Check that the arity matches.
  54. auto params = context.inst_blocks().GetOrEmpty(entity.param_patterns_id);
  55. if (arg_ids.size() != params.size()) {
  56. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  57. "{0} argument{0:s} passed to "
  58. "{1:=0:function|=1:generic class|=2:generic interface}"
  59. " expecting {2} argument{2:s}",
  60. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect,
  61. Diagnostics::IntAsSelect);
  62. CARBON_DIAGNOSTIC(
  63. InCallToEntity, Note,
  64. "calling {0:=0:function|=1:generic class|=2:generic interface}"
  65. " declared here",
  66. Diagnostics::IntAsSelect);
  67. context.emitter()
  68. .Build(loc_id, CallArgCountMismatch, arg_ids.size(),
  69. static_cast<int>(entity_kind_for_diagnostic), params.size())
  70. .Note(entity.latest_decl_id(), InCallToEntity,
  71. static_cast<int>(entity_kind_for_diagnostic))
  72. .Emit();
  73. return std::nullopt;
  74. }
  75. // Perform argument deduction.
  76. auto specific_id = SemIR::SpecificId::None;
  77. if (entity.generic_id.has_value()) {
  78. specific_id = DeduceGenericCallArguments(
  79. context, loc_id, entity.generic_id, enclosing_specific_id, self_type_id,
  80. entity.implicit_param_patterns_id, entity.param_patterns_id, self_id,
  81. arg_ids);
  82. if (!specific_id.has_value()) {
  83. return std::nullopt;
  84. }
  85. }
  86. return specific_id;
  87. }
  88. // Performs a call where the callee is the name of a generic class, such as
  89. // `Vector(i32)`.
  90. static auto PerformCallToGenericClass(Context& context, SemIR::LocId loc_id,
  91. SemIR::ClassId class_id,
  92. SemIR::SpecificId enclosing_specific_id,
  93. llvm::ArrayRef<SemIR::InstId> arg_ids)
  94. -> SemIR::InstId {
  95. const auto& generic_class = context.classes().Get(class_id);
  96. auto callee_specific_id =
  97. ResolveCalleeInCall(context, loc_id, generic_class,
  98. EntityKind::GenericClass, enclosing_specific_id,
  99. /*self_type_id=*/SemIR::InstId::None,
  100. /*self_id=*/SemIR::InstId::None, arg_ids);
  101. if (!callee_specific_id) {
  102. return SemIR::ErrorInst::InstId;
  103. }
  104. return GetOrAddInst<SemIR::ClassType>(context, loc_id,
  105. {.type_id = SemIR::TypeType::TypeId,
  106. .class_id = class_id,
  107. .specific_id = *callee_specific_id});
  108. }
  109. // Performs a call where the callee is the name of a generic interface, such as
  110. // `AddWith(i32)`.
  111. static auto PerformCallToGenericInterface(
  112. Context& context, SemIR::LocId loc_id, SemIR::InterfaceId interface_id,
  113. SemIR::SpecificId enclosing_specific_id,
  114. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  115. const auto& interface = context.interfaces().Get(interface_id);
  116. auto callee_specific_id =
  117. ResolveCalleeInCall(context, loc_id, interface,
  118. EntityKind::GenericInterface, enclosing_specific_id,
  119. /*self_type_id=*/SemIR::InstId::None,
  120. /*self_id=*/SemIR::InstId::None, arg_ids);
  121. if (!callee_specific_id) {
  122. return SemIR::ErrorInst::InstId;
  123. }
  124. return GetOrAddInst(
  125. context, loc_id,
  126. FacetTypeFromInterface(context, interface_id, *callee_specific_id));
  127. }
  128. // Builds an appropriate specific function for the callee, also handling
  129. // instance binding.
  130. static auto BuildCalleeSpecificFunction(
  131. Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  132. SemIR::InstId callee_function_self_type_id,
  133. SemIR::SpecificId callee_specific_id) -> SemIR::InstId {
  134. auto generic_callee_id = callee_id;
  135. // Strip off a bound_method so that we can form a constant specific callee.
  136. auto bound_method = context.insts().TryGetAs<SemIR::BoundMethod>(callee_id);
  137. if (bound_method) {
  138. generic_callee_id = bound_method->function_decl_id;
  139. }
  140. // Form a specific callee.
  141. if (callee_function_self_type_id.has_value()) {
  142. // This is an associated function in an interface; the callee is the
  143. // specific function in the impl that corresponds to the specific function
  144. // we deduced.
  145. callee_id =
  146. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  147. SemIR::SpecificImplFunction{
  148. .type_id = GetSingletonType(
  149. context, SemIR::SpecificFunctionType::TypeInstId),
  150. .callee_id = generic_callee_id,
  151. .specific_id = callee_specific_id});
  152. } else {
  153. // This is a regular generic function. The callee is the specific function
  154. // we deduced.
  155. callee_id =
  156. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  157. SemIR::SpecificFunction{
  158. .type_id = GetSingletonType(
  159. context, SemIR::SpecificFunctionType::TypeInstId),
  160. .callee_id = generic_callee_id,
  161. .specific_id = callee_specific_id});
  162. }
  163. // Add the `self` argument back if there was one.
  164. if (bound_method) {
  165. callee_id =
  166. GetOrAddInst<SemIR::BoundMethod>(context, loc_id,
  167. {.type_id = bound_method->type_id,
  168. .object_id = bound_method->object_id,
  169. .function_decl_id = callee_id});
  170. }
  171. return callee_id;
  172. }
  173. // Returns the return type, with a scoped annotation for any diagnostics.
  174. static auto CheckCalleeFunctionReturnType(Context& context, SemIR::LocId loc_id,
  175. SemIR::FunctionId callee_function_id,
  176. SemIR::SpecificId callee_specific_id)
  177. -> SemIR::ReturnTypeInfo {
  178. auto& function = context.functions().Get(callee_function_id);
  179. Diagnostics::AnnotationScope annotate_diagnostics(
  180. &context.emitter(), [&](auto& builder) {
  181. CARBON_DIAGNOSTIC(IncompleteReturnTypeHere, Note,
  182. "return type declared here");
  183. builder.Note(function.return_slot_pattern_id, IncompleteReturnTypeHere);
  184. });
  185. return CheckFunctionReturnType(context, loc_id, function, callee_specific_id);
  186. }
  187. // Performs a call where the callee is a function.
  188. static auto PerformCallToFunction(Context& context, SemIR::LocId loc_id,
  189. SemIR::InstId callee_id,
  190. const SemIR::CalleeFunction& callee_function,
  191. llvm::ArrayRef<SemIR::InstId> arg_ids)
  192. -> SemIR::InstId {
  193. // If the callee is a generic function, determine the generic argument values
  194. // for the call.
  195. auto callee_specific_id = ResolveCalleeInCall(
  196. context, loc_id, context.functions().Get(callee_function.function_id),
  197. EntityKind::Function, callee_function.enclosing_specific_id,
  198. callee_function.self_type_id, callee_function.self_id, arg_ids);
  199. if (!callee_specific_id) {
  200. return SemIR::ErrorInst::InstId;
  201. }
  202. if (callee_specific_id->has_value()) {
  203. callee_id = BuildCalleeSpecificFunction(context, loc_id, callee_id,
  204. callee_function.self_type_id,
  205. *callee_specific_id);
  206. }
  207. // If there is a return slot, build storage for the result.
  208. SemIR::ReturnTypeInfo return_info = CheckCalleeFunctionReturnType(
  209. context, loc_id, callee_function.function_id, *callee_specific_id);
  210. SemIR::InstId return_slot_arg_id = SemIR::InstId::None;
  211. switch (return_info.init_repr.kind) {
  212. case SemIR::InitRepr::InPlace:
  213. // Tentatively put storage for a temporary in the function's return slot.
  214. // This will be replaced if necessary when we perform initialization.
  215. return_slot_arg_id = AddInst<SemIR::TemporaryStorage>(
  216. context, loc_id, {.type_id = return_info.type_id});
  217. break;
  218. case SemIR::InitRepr::None:
  219. // For functions with an implicit return type, the return type is the
  220. // empty tuple type.
  221. if (!return_info.type_id.has_value()) {
  222. return_info.type_id = GetTupleType(context, {});
  223. }
  224. break;
  225. case SemIR::InitRepr::ByCopy:
  226. break;
  227. case SemIR::InitRepr::Incomplete:
  228. // Don't form an initializing expression with an incomplete type.
  229. // CheckFunctionReturnType will have diagnosed this for us if needed.
  230. return_info.type_id = SemIR::ErrorInst::TypeId;
  231. break;
  232. }
  233. auto& callee = context.functions().Get(callee_function.function_id);
  234. // Convert the arguments to match the parameters.
  235. auto converted_args_id =
  236. ConvertCallArgs(context, loc_id, callee_function.self_id, arg_ids,
  237. return_slot_arg_id, callee, *callee_specific_id);
  238. switch (callee.special_function_kind) {
  239. case SemIR::Function::SpecialFunctionKind::Thunk: {
  240. // If we're about to form a direct call to a thunk, inline it.
  241. LoadImportRef(context, callee.thunk_decl_id());
  242. // Name the thunk target within the enclosing scope of the thunk.
  243. auto thunk_ref_id =
  244. BuildNameRef(context, loc_id, callee.name_id, callee.thunk_decl_id(),
  245. callee_function.enclosing_specific_id);
  246. // This recurses back into `PerformCall`. However, we never form a thunk
  247. // to a thunk, so we only recurse once.
  248. return PerformThunkCall(context, loc_id, callee_function.function_id,
  249. context.inst_blocks().Get(converted_args_id),
  250. thunk_ref_id);
  251. }
  252. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  253. // This recurses back into `PerformCall`. However, we never form a C++
  254. // thunk to a C++ thunk, so we only recurse once.
  255. return PerformCppThunkCall(context, loc_id, callee_function.function_id,
  256. context.inst_blocks().Get(converted_args_id),
  257. callee.cpp_thunk_decl_id());
  258. }
  259. case SemIR::Function::SpecialFunctionKind::None:
  260. case SemIR::Function::SpecialFunctionKind::Builtin: {
  261. return GetOrAddInst<SemIR::Call>(context, loc_id,
  262. {.type_id = return_info.type_id,
  263. .callee_id = callee_id,
  264. .args_id = converted_args_id});
  265. }
  266. }
  267. }
  268. auto PerformCall(Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  269. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  270. // Try treating the callee as a function first.
  271. auto callee_function = GetCalleeFunction(context.sem_ir(), callee_id);
  272. if (callee_function.is_error) {
  273. return SemIR::ErrorInst::InstId;
  274. }
  275. if (callee_function.function_id.has_value()) {
  276. return PerformCallToFunction(context, loc_id, callee_id, callee_function,
  277. arg_ids);
  278. }
  279. // Callee isn't a function, so try treating it as a generic type.
  280. auto type_inst =
  281. context.types().GetAsInst(context.insts().Get(callee_id).type_id());
  282. CARBON_KIND_SWITCH(type_inst) {
  283. case CARBON_KIND(SemIR::GenericClassType generic_class): {
  284. return PerformCallToGenericClass(context, loc_id, generic_class.class_id,
  285. generic_class.enclosing_specific_id,
  286. arg_ids);
  287. }
  288. case CARBON_KIND(SemIR::GenericInterfaceType generic_interface): {
  289. return PerformCallToGenericInterface(
  290. context, loc_id, generic_interface.interface_id,
  291. generic_interface.enclosing_specific_id, arg_ids);
  292. }
  293. default: {
  294. CARBON_DIAGNOSTIC(CallToNonCallable, Error,
  295. "value of type {0} is not callable", TypeOfInstId);
  296. context.emitter().Emit(loc_id, CallToNonCallable, callee_id);
  297. return SemIR::ErrorInst::InstId;
  298. }
  299. }
  300. }
  301. } // namespace Carbon::Check