call.cpp 16 KB

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