operators.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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/operators.h"
  5. #include "clang/Sema/Initialization.h"
  6. #include "clang/Sema/Overload.h"
  7. #include "clang/Sema/Sema.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/core_identifier.h"
  10. #include "toolchain/check/cpp/import.h"
  11. #include "toolchain/check/cpp/location.h"
  12. #include "toolchain/check/cpp/overload_resolution.h"
  13. #include "toolchain/check/cpp/type_mapping.h"
  14. #include "toolchain/check/function.h"
  15. #include "toolchain/check/inst.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/sem_ir/builtin_function_kind.h"
  19. #include "toolchain/sem_ir/cpp_initializer_list.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/inst.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Check {
  24. // Maps Carbon operator interface and operator names to Clang operator kinds.
  25. static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
  26. CoreIdentifier interface_name,
  27. CoreIdentifier op_name)
  28. -> std::optional<clang::OverloadedOperatorKind> {
  29. switch (interface_name) {
  30. // Unary operators.
  31. case CoreIdentifier::Destroy:
  32. case CoreIdentifier::As:
  33. case CoreIdentifier::ImplicitAs:
  34. case CoreIdentifier::UnsafeAs:
  35. case CoreIdentifier::Copy: {
  36. // TODO: Support destructors and conversions.
  37. return std::nullopt;
  38. }
  39. // Increment and decrement.
  40. case CoreIdentifier::Inc: {
  41. CARBON_CHECK(op_name == CoreIdentifier::Op);
  42. return clang::OO_PlusPlus;
  43. }
  44. case CoreIdentifier::Dec: {
  45. CARBON_CHECK(op_name == CoreIdentifier::Op);
  46. return clang::OO_MinusMinus;
  47. }
  48. // Arithmetic.
  49. case CoreIdentifier::Negate: {
  50. CARBON_CHECK(op_name == CoreIdentifier::Op);
  51. return clang::OO_Minus;
  52. }
  53. // Bitwise.
  54. case CoreIdentifier::BitComplement: {
  55. CARBON_CHECK(op_name == CoreIdentifier::Op);
  56. return clang::OO_Tilde;
  57. }
  58. // Binary operators.
  59. // Arithmetic operators.
  60. case CoreIdentifier::AddWith: {
  61. CARBON_CHECK(op_name == CoreIdentifier::Op);
  62. return clang::OO_Plus;
  63. }
  64. case CoreIdentifier::SubWith: {
  65. CARBON_CHECK(op_name == CoreIdentifier::Op);
  66. return clang::OO_Minus;
  67. }
  68. case CoreIdentifier::MulWith: {
  69. CARBON_CHECK(op_name == CoreIdentifier::Op);
  70. return clang::OO_Star;
  71. }
  72. case CoreIdentifier::DivWith: {
  73. CARBON_CHECK(op_name == CoreIdentifier::Op);
  74. return clang::OO_Slash;
  75. }
  76. case CoreIdentifier::ModWith: {
  77. CARBON_CHECK(op_name == CoreIdentifier::Op);
  78. return clang::OO_Percent;
  79. }
  80. // Bitwise operators.
  81. case CoreIdentifier::BitAndWith: {
  82. CARBON_CHECK(op_name == CoreIdentifier::Op);
  83. return clang::OO_Amp;
  84. }
  85. case CoreIdentifier::BitOrWith: {
  86. CARBON_CHECK(op_name == CoreIdentifier::Op);
  87. return clang::OO_Pipe;
  88. }
  89. case CoreIdentifier::BitXorWith: {
  90. CARBON_CHECK(op_name == CoreIdentifier::Op);
  91. return clang::OO_Caret;
  92. }
  93. case CoreIdentifier::LeftShiftWith: {
  94. CARBON_CHECK(op_name == CoreIdentifier::Op);
  95. return clang::OO_LessLess;
  96. }
  97. case CoreIdentifier::RightShiftWith: {
  98. CARBON_CHECK(op_name == CoreIdentifier::Op);
  99. return clang::OO_GreaterGreater;
  100. }
  101. // Assignment.
  102. case CoreIdentifier::AssignWith: {
  103. // TODO: This is not yet reached because we don't use the `AssignWith`
  104. // interface for assignment yet.
  105. CARBON_CHECK(op_name == CoreIdentifier::Op);
  106. return clang::OO_Equal;
  107. }
  108. // Compound assignment arithmetic operators.
  109. case CoreIdentifier::AddAssignWith: {
  110. CARBON_CHECK(op_name == CoreIdentifier::Op);
  111. return clang::OO_PlusEqual;
  112. }
  113. case CoreIdentifier::SubAssignWith: {
  114. CARBON_CHECK(op_name == CoreIdentifier::Op);
  115. return clang::OO_MinusEqual;
  116. }
  117. case CoreIdentifier::MulAssignWith: {
  118. CARBON_CHECK(op_name == CoreIdentifier::Op);
  119. return clang::OO_StarEqual;
  120. }
  121. case CoreIdentifier::DivAssignWith: {
  122. CARBON_CHECK(op_name == CoreIdentifier::Op);
  123. return clang::OO_SlashEqual;
  124. }
  125. case CoreIdentifier::ModAssignWith: {
  126. CARBON_CHECK(op_name == CoreIdentifier::Op);
  127. return clang::OO_PercentEqual;
  128. }
  129. // Compound assignment bitwise operators.
  130. case CoreIdentifier::BitAndAssignWith: {
  131. CARBON_CHECK(op_name == CoreIdentifier::Op);
  132. return clang::OO_AmpEqual;
  133. }
  134. case CoreIdentifier::BitOrAssignWith: {
  135. CARBON_CHECK(op_name == CoreIdentifier::Op);
  136. return clang::OO_PipeEqual;
  137. }
  138. case CoreIdentifier::BitXorAssignWith: {
  139. CARBON_CHECK(op_name == CoreIdentifier::Op);
  140. return clang::OO_CaretEqual;
  141. }
  142. case CoreIdentifier::LeftShiftAssignWith: {
  143. CARBON_CHECK(op_name == CoreIdentifier::Op);
  144. return clang::OO_LessLessEqual;
  145. }
  146. case CoreIdentifier::RightShiftAssignWith: {
  147. CARBON_CHECK(op_name == CoreIdentifier::Op);
  148. return clang::OO_GreaterGreaterEqual;
  149. }
  150. // Relational operators.
  151. case CoreIdentifier::EqWith: {
  152. if (op_name == CoreIdentifier::Equal) {
  153. return clang::OO_EqualEqual;
  154. }
  155. CARBON_CHECK(op_name == CoreIdentifier::NotEqual);
  156. return clang::OO_ExclaimEqual;
  157. }
  158. case CoreIdentifier::OrderedWith: {
  159. switch (op_name) {
  160. case CoreIdentifier::Less:
  161. return clang::OO_Less;
  162. case CoreIdentifier::Greater:
  163. return clang::OO_Greater;
  164. case CoreIdentifier::LessOrEquivalent:
  165. return clang::OO_LessEqual;
  166. case CoreIdentifier::GreaterOrEquivalent:
  167. return clang::OO_GreaterEqual;
  168. default:
  169. CARBON_FATAL("Unexpected OrderedWith op `{0}`", op_name);
  170. }
  171. }
  172. // Array indexing.
  173. case CoreIdentifier::IndexWith: {
  174. CARBON_CHECK(op_name == CoreIdentifier::At);
  175. return clang::OO_Subscript;
  176. }
  177. default: {
  178. context.TODO(loc_id, llvm::formatv("Unsupported operator interface `{0}`",
  179. interface_name));
  180. return std::nullopt;
  181. }
  182. }
  183. }
  184. // Creates and returns a function that can be used to construct a
  185. // std::initializer_list from an array.
  186. //
  187. // TODO: This should ideally be implemented in Carbon code rather than by
  188. // synthesizing a function.
  189. // TODO: We should cache and reuse the generated function.
  190. static auto MakeCppStdInitializerListMake(Context& context, SemIR::LocId loc_id,
  191. clang::QualType init_list_type,
  192. int32_t size) -> SemIR::InstId {
  193. // Extract the element type `T` from the `std::initializer_list<T>` type.
  194. clang::QualType element_type;
  195. bool is_std_initializer_list =
  196. context.clang_sema().isStdInitializerList(init_list_type, &element_type);
  197. CARBON_CHECK(is_std_initializer_list);
  198. auto element_type_inst_id =
  199. ImportCppType(context, loc_id, element_type).inst_id;
  200. if (element_type_inst_id == SemIR::ErrorInst::InstId) {
  201. return SemIR::ErrorInst::InstId;
  202. }
  203. // Import the `std::initializer_list<T>` type and check we recognize its
  204. // layout.
  205. auto [init_list_type_inst_id, init_list_type_id] =
  206. ImportCppType(context, loc_id, init_list_type);
  207. if (init_list_type_id == SemIR::ErrorInst::TypeId) {
  208. return SemIR::ErrorInst::InstId;
  209. }
  210. auto layout =
  211. SemIR::GetStdInitializerListLayout(context.sem_ir(), init_list_type_id);
  212. if (layout.kind == SemIR::StdInitializerListLayout::None) {
  213. context.TODO(loc_id, "Unsupported layout for std::initializer_list");
  214. return SemIR::ErrorInst::InstId;
  215. }
  216. auto init_list_class_id = context.sem_ir()
  217. .types()
  218. .GetAs<SemIR::ClassType>(init_list_type_id)
  219. .class_id;
  220. auto& init_list_class = context.classes().Get(init_list_class_id);
  221. // Build the array type `T[size]` that we use as the parameter type.
  222. // TODO: This will eventually be called from impl lookup, possibly while
  223. // forming a specific, so we should not be adding instructions here.
  224. auto bound_id = AddInst(
  225. context, SemIR::LocIdAndInst(
  226. loc_id, SemIR::IntValue{
  227. .type_id = GetSingletonType(
  228. context, SemIR::IntLiteralType::TypeInstId),
  229. .int_id = context.ints().Add(size)}));
  230. auto array_type_inst_id = AddTypeInst(
  231. context, SemIR::LocIdAndInst::UncheckedLoc(
  232. loc_id, SemIR::ArrayType{
  233. .type_id = SemIR::TypeType::TypeId,
  234. .bound_id = bound_id,
  235. .element_type_inst_id = element_type_inst_id}));
  236. auto array_type_id =
  237. context.types().GetTypeIdForTypeInstId(array_type_inst_id);
  238. // Create a builtin function to perform the conversion from array type to
  239. // initializer list type. We name the synthesized function as if it were a
  240. // constructor of std::initializer_list.
  241. return MakeBuiltinFunction(
  242. context, loc_id, SemIR::BuiltinFunctionKind::CppStdInitializerListMake,
  243. init_list_class.scope_id, init_list_class.name_id,
  244. {.param_type_ids = {array_type_id}, .return_type_id = init_list_type_id});
  245. }
  246. // Returns information about the Carbon signature to import when importing a C++
  247. // constructor or conversion operator.
  248. static auto GetConversionSignatureToImport(
  249. Context& context, SemIR::InstId source_id,
  250. clang::InitializationSequence::StepKind step_kind,
  251. clang::FunctionDecl* function_decl) -> SemIR::ClangDeclKey::Signature {
  252. // If we're performing a constructor initialization from a list, form a
  253. // function signature that takes a single tuple or struct pattern
  254. // instead of a function signature with one parameter per C++ parameter.
  255. if (step_kind ==
  256. clang::InitializationSequence::SK_ConstructorInitializationFromList) {
  257. // The source type should always be a tuple type, because we don't support
  258. // C++ initialization from struct types.
  259. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(
  260. context.insts().Get(source_id).type_id());
  261. CARBON_CHECK(tuple_type, "List initialization from non-tuple type");
  262. // Initialization from a tuple `(a, b, c)` results in a constructor
  263. // function that takes a tuple pattern:
  264. //
  265. // fn Class.Class((a: A, b: B, c: C)) -> Class;
  266. return {
  267. .kind = SemIR::ClangDeclKey::Signature::Kind::TuplePattern,
  268. .num_params = static_cast<int32_t>(
  269. context.inst_blocks().Get(tuple_type->type_elements_id).size())};
  270. }
  271. // Any other initialization using a constructor is calling a converting
  272. // constructor:
  273. //
  274. // fn Class.Class(a: A) -> Class;
  275. if (isa<clang::CXXConstructorDecl>(function_decl)) {
  276. return {.kind = SemIR::ClangDeclKey::Signature::Kind::Normal,
  277. .num_params = 1};
  278. }
  279. // Otherwise, the initialization is calling a conversion function
  280. // `Source::operator Dest`:
  281. //
  282. // fn Source.<conversion function>[self: Source]() -> Dest;
  283. CARBON_CHECK(isa<clang::CXXConversionDecl>(function_decl));
  284. return {.kind = SemIR::ClangDeclKey::Signature::Kind::Normal,
  285. .num_params = 0};
  286. }
  287. static auto LookupCppConversion(Context& context, SemIR::LocId loc_id,
  288. SemIR::InstId source_id,
  289. SemIR::TypeId dest_type_id, bool allow_explicit)
  290. -> SemIR::InstId {
  291. if (context.types().Is<SemIR::StructType>(
  292. context.insts().Get(source_id).type_id())) {
  293. // Structs can only be used to initialize C++ aggregates. That case is
  294. // handled by Convert, not here.
  295. return SemIR::InstId::None;
  296. }
  297. auto dest_type = MapToCppType(context, dest_type_id);
  298. if (dest_type.isNull()) {
  299. return SemIR::InstId::None;
  300. }
  301. auto* arg_expr = InventClangArg(context, source_id);
  302. // If we can't map the argument, we can't perform the conversion.
  303. if (!arg_expr) {
  304. return SemIR::InstId::None;
  305. }
  306. auto loc = GetCppLocation(context, loc_id);
  307. // Form a Clang initialization sequence.
  308. auto& sema = context.clang_sema();
  309. clang::InitializedEntity entity =
  310. clang::InitializedEntity::InitializeTemporary(dest_type);
  311. clang::InitializationKind kind =
  312. allow_explicit ? clang::InitializationKind::CreateDirect(
  313. loc, /*LParenLoc=*/clang::SourceLocation(),
  314. /*RParenLoc=*/clang::SourceLocation())
  315. : clang::InitializationKind::CreateCopy(
  316. loc, /*EqualLoc=*/clang::SourceLocation());
  317. clang::MultiExprArg args(arg_expr);
  318. // `(a, b) as T` uses `T{a, b}`, not `T({a, b})`. The latter would introduce
  319. // a redundant extra copy.
  320. // TODO: We need to communicate this back to the caller so they know to call
  321. // the constructor with an exploded argument list somehow.
  322. if (allow_explicit && isa<clang::InitListExpr>(arg_expr)) {
  323. kind = clang::InitializationKind::CreateDirectList(loc);
  324. }
  325. clang::InitializationSequence init(sema, entity, kind, args);
  326. if (init.Failed()) {
  327. // TODO: Are there initialization failures that we should translate into
  328. // errors rather than a missing conversion?
  329. return SemIR::InstId::None;
  330. }
  331. // Scan the steps looking for user-defined conversions. For now we just find
  332. // and return the first such conversion function. We skip over standard
  333. // conversions; we'll perform those using the Carbon rules as part of calling
  334. // the C++ conversion function.
  335. for (const auto& step : init.steps()) {
  336. switch (step.Kind) {
  337. case clang::InitializationSequence::SK_UserConversion:
  338. case clang::InitializationSequence::SK_ConstructorInitialization:
  339. case clang::InitializationSequence::SK_StdInitializerListConstructorCall:
  340. case clang::InitializationSequence::
  341. SK_ConstructorInitializationFromList: {
  342. if (auto* ctor =
  343. dyn_cast<clang::CXXConstructorDecl>(step.Function.Function);
  344. ctor && ctor->isCopyOrMoveConstructor()) {
  345. // Skip copy / move constructor calls. They shouldn't be performed
  346. // this way because they're not considered conversions in Carbon, and
  347. // will frequently lead to infinite recursion because we'll end up
  348. // back here when attempting to convert the argument.
  349. continue;
  350. }
  351. if (sema.DiagnoseUseOfOverloadedDecl(step.Function.Function, loc)) {
  352. return SemIR::ErrorInst::InstId;
  353. }
  354. sema.MarkFunctionReferenced(loc, step.Function.Function);
  355. auto signature = GetConversionSignatureToImport(
  356. context, source_id, step.Kind, step.Function.Function);
  357. auto result_id = ImportCppFunctionDecl(
  358. context, loc_id, step.Function.Function, signature);
  359. if (auto fn_decl = context.insts().TryGetAsWithId<SemIR::FunctionDecl>(
  360. result_id)) {
  361. CheckCppOverloadAccess(context, loc_id, step.Function.FoundDecl,
  362. fn_decl->inst_id);
  363. } else {
  364. CARBON_CHECK(result_id == SemIR::ErrorInst::InstId);
  365. }
  366. // TODO: There may be other conversions later in the sequence that we
  367. // need to model; we've only applied the first one here.
  368. return result_id;
  369. }
  370. case clang::InitializationSequence::SK_StdInitializerList: {
  371. return MakeCppStdInitializerListMake(
  372. context, loc_id, step.Type,
  373. cast<clang::InitListExpr>(arg_expr)->getNumInits());
  374. }
  375. case clang::InitializationSequence::SK_ListInitialization: {
  376. // Aggregate initialization is handled by the normal Carbon conversion
  377. // logic, so we ignore it here.
  378. // TODO: So far we only support aggregate initialization for arrays and
  379. // empty classes.
  380. continue;
  381. }
  382. case clang::InitializationSequence::SK_ConversionSequence:
  383. case clang::InitializationSequence::SK_ConversionSequenceNoNarrowing: {
  384. // Implicit conversions are handled by the normal Carbon conversion
  385. // logic, so we ignore them here.
  386. continue;
  387. }
  388. default: {
  389. // TODO: Handle other kinds of initialization steps. For now we assume
  390. // they will be handled by our function call logic and we can skip them.
  391. RawStringOstream os;
  392. os << "Unsupported initialization sequence:\n";
  393. init.dump(os);
  394. context.TODO(loc_id, os.TakeStr());
  395. return SemIR::ErrorInst::InstId;
  396. }
  397. }
  398. }
  399. return SemIR::InstId::None;
  400. }
  401. auto LookupCppOperator(Context& context, SemIR::LocId loc_id, Operator op,
  402. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  403. // Register an annotation scope to flush any Clang diagnostics when we return.
  404. // This is important to ensure that Clang diagnostics are properly interleaved
  405. // with Carbon diagnostics.
  406. Diagnostics::AnnotationScope annotate_diagnostics(&context.emitter(),
  407. [](auto& /*builder*/) {});
  408. // Handle `ImplicitAs` and `As`.
  409. if (op.interface_name == CoreIdentifier::ImplicitAs ||
  410. op.interface_name == CoreIdentifier::As) {
  411. if (op.interface_args_ref.size() != 1 || arg_ids.size() != 1) {
  412. return SemIR::InstId::None;
  413. }
  414. // The argument is the destination type for both interfaces.
  415. auto dest_const_id =
  416. context.constant_values().Get(op.interface_args_ref[0]);
  417. auto dest_type_id =
  418. context.types().TryGetTypeIdForTypeConstantId(dest_const_id);
  419. if (!dest_type_id.has_value()) {
  420. return SemIR::InstId::None;
  421. }
  422. return LookupCppConversion(
  423. context, loc_id, arg_ids[0], dest_type_id,
  424. /*allow_explicit=*/op.interface_name == CoreIdentifier::As);
  425. }
  426. auto op_kind =
  427. GetClangOperatorKind(context, loc_id, op.interface_name, op.op_name);
  428. if (!op_kind) {
  429. return SemIR::InstId::None;
  430. }
  431. // Make sure all operands are complete before lookup.
  432. for (SemIR::InstId arg_id : arg_ids) {
  433. SemIR::TypeId arg_type_id = context.insts().Get(arg_id).type_id();
  434. if (!RequireCompleteType(context, arg_type_id, loc_id, [&] {
  435. CARBON_DIAGNOSTIC(
  436. IncompleteOperandTypeInCppOperatorLookup, Error,
  437. "looking up a C++ operator with incomplete operand type {0}",
  438. SemIR::TypeId);
  439. return context.emitter().Build(
  440. loc_id, IncompleteOperandTypeInCppOperatorLookup, arg_type_id);
  441. })) {
  442. return SemIR::ErrorInst::InstId;
  443. }
  444. }
  445. auto maybe_arg_exprs = InventClangArgs(context, arg_ids);
  446. if (!maybe_arg_exprs.has_value()) {
  447. return SemIR::ErrorInst::InstId;
  448. }
  449. auto& arg_exprs = *maybe_arg_exprs;
  450. clang::SourceLocation loc = GetCppLocation(context, loc_id);
  451. clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info(
  452. *op_kind, loc, /*AllowRewritten=*/true);
  453. clang::OverloadCandidateSet candidate_set(
  454. loc, clang::OverloadCandidateSet::CSK_Operator, operator_rewrite_info);
  455. clang::Sema& sema = context.clang_sema();
  456. // This works for both unary and binary operators.
  457. sema.LookupOverloadedBinOp(candidate_set, *op_kind, clang::UnresolvedSet<0>{},
  458. arg_exprs);
  459. clang::OverloadCandidateSet::iterator best_viable_fn;
  460. switch (candidate_set.BestViableFunction(sema, loc, best_viable_fn)) {
  461. case clang::OverloadingResult::OR_Success: {
  462. if (!best_viable_fn->Function) {
  463. // The best viable candidate was a builtin. Let the Carbon operator
  464. // machinery handle that.
  465. return SemIR::InstId::None;
  466. }
  467. if (best_viable_fn->RewriteKind) {
  468. context.TODO(
  469. loc_id,
  470. llvm::formatv("Rewriting operator{0} using {1} is not supported",
  471. clang::getOperatorSpelling(
  472. candidate_set.getRewriteInfo().OriginalOperator),
  473. best_viable_fn->Function->getNameAsString()));
  474. return SemIR::ErrorInst::InstId;
  475. }
  476. sema.MarkFunctionReferenced(loc, best_viable_fn->Function);
  477. // If this is an operator method, the first arg will be used as self.
  478. int32_t num_params = arg_ids.size();
  479. if (isa<clang::CXXMethodDecl>(best_viable_fn->Function)) {
  480. --num_params;
  481. }
  482. auto result_id =
  483. ImportCppFunctionDecl(context, loc_id, best_viable_fn->Function,
  484. {.num_params = num_params});
  485. if (result_id != SemIR::ErrorInst::InstId) {
  486. CheckCppOverloadAccess(
  487. context, loc_id, best_viable_fn->FoundDecl,
  488. context.insts().GetAsKnownInstId<SemIR::FunctionDecl>(result_id));
  489. }
  490. return result_id;
  491. }
  492. case clang::OverloadingResult::OR_No_Viable_Function: {
  493. // OK, didn't find a viable C++ candidate, but this is not an error, as
  494. // there might be a Carbon candidate.
  495. return SemIR::InstId::None;
  496. }
  497. case clang::OverloadingResult::OR_Ambiguous: {
  498. const char* spelling = clang::getOperatorSpelling(*op_kind);
  499. candidate_set.NoteCandidates(
  500. clang::PartialDiagnosticAt(
  501. loc, sema.PDiag(clang::diag::err_ovl_ambiguous_oper_binary)
  502. << spelling << arg_exprs[0]->getType()
  503. << arg_exprs[1]->getType()),
  504. sema, clang::OCD_AmbiguousCandidates, arg_exprs, spelling, loc);
  505. return SemIR::ErrorInst::InstId;
  506. }
  507. case clang::OverloadingResult::OR_Deleted:
  508. const char* spelling = clang::getOperatorSpelling(*op_kind);
  509. auto* message = best_viable_fn->Function->getDeletedMessage();
  510. // The best viable function might be a different operator if the best
  511. // candidate is a rewritten candidate, so use the operator kind of the
  512. // candidate itself in the diagnostic.
  513. candidate_set.NoteCandidates(
  514. clang::PartialDiagnosticAt(
  515. loc, sema.PDiag(clang::diag::err_ovl_deleted_oper)
  516. << clang::getOperatorSpelling(
  517. best_viable_fn->Function->getOverloadedOperator())
  518. << (message != nullptr)
  519. << (message ? message->getString() : llvm::StringRef())),
  520. sema, clang::OCD_AllCandidates, arg_exprs, spelling, loc);
  521. return SemIR::ErrorInst::InstId;
  522. }
  523. }
  524. auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool {
  525. auto* clang_method_decl = dyn_cast<clang::CXXMethodDecl>(decl);
  526. return clang_method_decl &&
  527. (clang_method_decl->isOverloadedOperator() ||
  528. isa<clang::CXXConversionDecl>(clang_method_decl));
  529. }
  530. static auto GetAsCppFunctionDecl(Context& context, SemIR::InstId inst_id)
  531. -> clang::FunctionDecl* {
  532. if (inst_id == SemIR::InstId::None) {
  533. return nullptr;
  534. }
  535. auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  536. context.insts().Get(inst_id).type_id());
  537. if (!function_type) {
  538. return nullptr;
  539. }
  540. SemIR::ClangDeclId clang_decl_id =
  541. context.functions().Get(function_type->function_id).clang_decl_id;
  542. return clang_decl_id.has_value()
  543. ? dyn_cast<clang::FunctionDecl>(
  544. context.clang_decls().Get(clang_decl_id).key.decl)
  545. : nullptr;
  546. }
  547. auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool {
  548. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  549. return function_decl && IsCppOperatorMethodDecl(function_decl);
  550. }
  551. auto IsCppConstructorOrNonMethodOperator(Context& context,
  552. SemIR::InstId inst_id) -> bool {
  553. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  554. if (!function_decl) {
  555. return false;
  556. }
  557. if (isa<clang::CXXConstructorDecl>(function_decl)) {
  558. return true;
  559. }
  560. return !isa<clang::CXXMethodDecl>(function_decl) &&
  561. function_decl->isOverloadedOperator();
  562. }
  563. } // namespace Carbon::Check