call.cpp 9.3 KB

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