call.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/cpp/call.h"
  5. #include "clang/Sema/Sema.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/call.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/cpp/location.h"
  10. #include "toolchain/check/cpp/operators.h"
  11. #include "toolchain/check/cpp/overload_resolution.h"
  12. #include "toolchain/check/cpp/type_mapping.h"
  13. #include "toolchain/check/literal.h"
  14. #include "toolchain/sem_ir/function.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. auto PerformCallToCppFunction(Context& context, SemIR::LocId loc_id,
  19. SemIR::CppOverloadSetId overload_set_id,
  20. SemIR::InstId self_id,
  21. llvm::ArrayRef<SemIR::InstId> arg_ids,
  22. bool is_operator_syntax) -> SemIR::InstId {
  23. SemIR::InstId callee_id = PerformCppOverloadResolution(
  24. context, loc_id, overload_set_id, self_id, arg_ids);
  25. SemIR::Callee callee = GetCallee(context.sem_ir(), callee_id);
  26. CARBON_KIND_SWITCH(callee) {
  27. case CARBON_KIND(SemIR::CalleeError _): {
  28. return SemIR::ErrorInst::InstId;
  29. }
  30. case CARBON_KIND(SemIR::CalleeFunction fn): {
  31. CARBON_CHECK(!fn.self_id.has_value());
  32. if (self_id.has_value()) {
  33. // Preserve the `self` argument from the original callee.
  34. fn.self_id = self_id;
  35. }
  36. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids,
  37. is_operator_syntax);
  38. }
  39. case CARBON_KIND(SemIR::CalleeCppOverloadSet _): {
  40. CARBON_FATAL("overloads can't be recursive");
  41. }
  42. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  43. CARBON_FATAL("overloads should produce functions");
  44. }
  45. }
  46. }
  47. // Synthesize a placeholder `void{}` template argument, that will never be a
  48. // valid argument for any template parameter. This is used in order to get Clang
  49. // to diagnose invalid template argument errors for us. The location of the
  50. // Carbon expression is used as the location of the C++ expression, so
  51. // Clang's diagnostics will point into the Carbon code.
  52. //
  53. // TODO: If Clang ever tries to print the type of the expression or to
  54. // pretty-print the expression itself, it would print the wrong thing. Currently
  55. // this doesn't appear to happen, but in principle it could. Ideally we'd add an
  56. // extension point to Clang to represent a "foreign expression" and use it here
  57. // instead of creating a bogus placeholder expression.
  58. static auto MakePlaceholderTemplateArg(Context& context, SemIR::InstId arg_id)
  59. -> clang::TemplateArgumentLoc {
  60. auto arg_loc = GetCppLocation(context, SemIR::LocId(arg_id));
  61. auto void_type = context.ast_context().VoidTy;
  62. auto* arg = new (context.ast_context()) clang::CXXScalarValueInitExpr(
  63. void_type,
  64. context.ast_context().getTrivialTypeSourceInfo(void_type, arg_loc),
  65. arg_loc);
  66. return clang::TemplateArgumentLoc(
  67. clang::TemplateArgument(arg, /*IsCanonical=*/false), arg);
  68. }
  69. // Converts an argument in a call to a C++ template name into a corresponding
  70. // clang template argument, given the template parameter it will be matched
  71. // against.
  72. static auto ConvertArgToTemplateArg(Context& context,
  73. const clang::NamedDecl* param_decl,
  74. SemIR::InstId arg_id)
  75. -> std::optional<clang::TemplateArgumentLoc> {
  76. if (isa<clang::TemplateTypeParmDecl>(param_decl)) {
  77. auto type = ExprAsType(context, SemIR::LocId(arg_id), arg_id);
  78. if (type.type_id == SemIR::ErrorInst::TypeId) {
  79. return std::nullopt;
  80. }
  81. auto clang_type = MapToCppType(context, type.type_id);
  82. if (clang_type.isNull()) {
  83. context.TODO(arg_id, "unsupported type used as template argument");
  84. return std::nullopt;
  85. }
  86. return clang::TemplateArgumentLoc(
  87. clang_type,
  88. context.ast_context().getTrivialTypeSourceInfo(
  89. clang_type, GetCppLocation(context, SemIR::LocId(arg_id))));
  90. }
  91. if (isa<clang::TemplateTemplateParmDecl>(param_decl)) {
  92. auto inst = context.sem_ir().insts().Get(arg_id);
  93. if (auto template_name_type =
  94. context.types().TryGetAs<SemIR::CppTemplateNameType>(
  95. inst.type_id())) {
  96. clang::TemplateName name(cast<clang::TemplateDecl>(
  97. context.clang_decls().Get(template_name_type->decl_id).key.decl));
  98. return clang::TemplateArgumentLoc(
  99. context.ast_context(), clang::TemplateArgument(name),
  100. /*TemplateKWLoc=*/clang::SourceLocation(),
  101. clang::NestedNameSpecifierLoc(),
  102. GetCppLocation(context, SemIR::LocId(arg_id)));
  103. }
  104. // TODO: Eventually we should also support passing Carbon generics as
  105. // template template arguments.
  106. return MakePlaceholderTemplateArg(context, arg_id);
  107. }
  108. if (isa<clang::NonTypeTemplateParmDecl>(param_decl)) {
  109. // TODO: Check the argument has a concrete constant value, and convert it to
  110. // a Clang constant value.
  111. context.TODO(arg_id, "argument for non-type template parameter");
  112. return std::nullopt;
  113. }
  114. CARBON_FATAL("Unknown declaration kind for template parameter");
  115. }
  116. // Converts a call argument list into a Clang template argument list for a given
  117. // template. Returns true on success, or false if an error was diagnosed.
  118. static auto ConvertArgsToTemplateArgs(Context& context,
  119. clang::TemplateDecl* template_decl,
  120. llvm::ArrayRef<SemIR::InstId> arg_ids,
  121. clang::TemplateArgumentListInfo& arg_list)
  122. -> bool {
  123. for (auto* param_decl : template_decl->getTemplateParameters()->asArray()) {
  124. if (arg_ids.empty()) {
  125. return true;
  126. }
  127. // A parameter pack consumes all remaining arguments; otherwise, it consumes
  128. // a single argument.
  129. // TODO: Handle expanded template parameter packs, which have a known, fixed
  130. // arity.
  131. llvm::ArrayRef<SemIR::InstId> args_for_param =
  132. param_decl->isTemplateParameterPack() ? std::exchange(arg_ids, {})
  133. : arg_ids.consume_front();
  134. for (auto arg_id : args_for_param) {
  135. if (auto arg = ConvertArgToTemplateArg(context, param_decl, arg_id)) {
  136. arg_list.addArgument(*arg);
  137. } else {
  138. return false;
  139. }
  140. }
  141. }
  142. // If there are any remaining arguments, that's an error; convert them to
  143. // placeholder template arguments so that Clang will diagnose it for us.
  144. for (auto arg_id : arg_ids) {
  145. // Synthesize a placeholder `void{}` template argument.
  146. arg_list.addArgument(MakePlaceholderTemplateArg(context, arg_id));
  147. }
  148. return true;
  149. }
  150. // Given a template and an template argument list, builds a Carbon value
  151. // describing the corresponding C++ template-id.
  152. static auto BuildTemplateId(Context& context, SemIR::LocId loc_id,
  153. clang::SourceLocation loc,
  154. clang::TemplateDecl* template_decl,
  155. clang::TemplateArgumentListInfo& arg_list)
  156. -> SemIR::InstId {
  157. if (auto* var_template_decl =
  158. dyn_cast<clang::VarTemplateDecl>(template_decl)) {
  159. auto decl_result = context.clang_sema().CheckVarTemplateId(
  160. var_template_decl, /*TemplateLoc=*/clang::SourceLocation(), loc,
  161. arg_list, /*SetWrittenArgs=*/false);
  162. return decl_result.isInvalid()
  163. ? SemIR::ErrorInst::InstId
  164. : ImportCppDecl(context, loc_id,
  165. SemIR::ClangDeclKey::ForNonFunctionDecl(
  166. decl_result.get()));
  167. }
  168. if (auto* concept_decl = dyn_cast<clang::ConceptDecl>(template_decl)) {
  169. auto expr_result = context.clang_sema().CheckConceptTemplateId(
  170. clang::CXXScopeSpec(), /*TemplateKWLoc=*/clang::SourceLocation(),
  171. clang::DeclarationNameInfo(concept_decl->getDeclName(), loc),
  172. concept_decl, concept_decl, &arg_list);
  173. if (expr_result.isInvalid()) {
  174. return SemIR::ErrorInst::InstId;
  175. }
  176. auto* expr = expr_result.getAs<clang::ConceptSpecializationExpr>();
  177. return MakeBoolLiteral(context, loc_id,
  178. SemIR::BoolValue::From(expr->isSatisfied()));
  179. }
  180. clang::TemplateName template_name(template_decl);
  181. auto clang_type = context.clang_sema().CheckTemplateIdType(
  182. clang::ElaboratedTypeKeyword::None, template_name, loc, arg_list,
  183. /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
  184. if (clang_type.isNull()) {
  185. return SemIR::ErrorInst::InstId;
  186. }
  187. return ImportCppType(context, loc_id, clang_type).inst_id;
  188. }
  189. auto PerformCallToCppTemplateName(Context& context, SemIR::LocId loc_id,
  190. SemIR::ClangDeclId template_decl_id,
  191. llvm::ArrayRef<SemIR::InstId> arg_ids)
  192. -> SemIR::InstId {
  193. auto* template_decl = dyn_cast<clang::TemplateDecl>(
  194. context.clang_decls().Get(template_decl_id).key.decl);
  195. auto loc = GetCppLocation(context, loc_id);
  196. // Form a template argument list for this template.
  197. clang::TemplateArgumentListInfo arg_list(loc, loc);
  198. if (!ConvertArgsToTemplateArgs(context, template_decl, arg_ids, arg_list)) {
  199. return SemIR::ErrorInst::InstId;
  200. }
  201. return BuildTemplateId(context, loc_id, loc, template_decl, arg_list);
  202. }
  203. } // namespace Carbon::Check