operators.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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,
  232. SemIR::LocIdAndInst::RuntimeVerified(
  233. context.sem_ir(), loc_id,
  234. SemIR::ArrayType{.type_id = SemIR::TypeType::TypeId,
  235. .bound_id = bound_id,
  236. .element_type_inst_id = element_type_inst_id}));
  237. auto array_type_id =
  238. context.types().GetTypeIdForTypeInstId(array_type_inst_id);
  239. // Create a builtin function to perform the conversion from array type to
  240. // initializer list type. We name the synthesized function as if it were a
  241. // constructor of std::initializer_list.
  242. // TODO: Find a better way to handle this. Ideally we should stop using this
  243. // function entirely and declare the necessary builtin in the prelude.
  244. auto [decl_id, function_id] =
  245. MakeGeneratedFunctionDecl(context, loc_id,
  246. {.parent_scope_id = init_list_class.scope_id,
  247. .name_id = init_list_class.name_id,
  248. .param_type_ids = {array_type_id},
  249. .return_type_id = init_list_type_id});
  250. auto& function = context.functions().Get(function_id);
  251. CARBON_CHECK(IsValidBuiltinDeclaration(
  252. context, function,
  253. SemIR::BuiltinFunctionKind::CppStdInitializerListMake));
  254. function.SetBuiltinFunction(
  255. SemIR::BuiltinFunctionKind::CppStdInitializerListMake);
  256. return decl_id;
  257. }
  258. // Returns information about the Carbon signature to import when importing a C++
  259. // constructor or conversion operator.
  260. static auto GetConversionSignatureToImport(
  261. Context& context, SemIR::InstId source_id,
  262. clang::InitializationSequence::StepKind step_kind,
  263. clang::FunctionDecl* function_decl) -> SemIR::ClangDeclKey::Signature {
  264. // If we're performing a constructor initialization from a list, form a
  265. // function signature that takes a single tuple or struct pattern
  266. // instead of a function signature with one parameter per C++ parameter.
  267. if (step_kind ==
  268. clang::InitializationSequence::SK_ConstructorInitializationFromList) {
  269. // The source type should always be a tuple type, because we don't support
  270. // C++ initialization from struct types.
  271. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(
  272. context.insts().Get(source_id).type_id());
  273. CARBON_CHECK(tuple_type, "List initialization from non-tuple type");
  274. // Initialization from a tuple `(a, b, c)` results in a constructor
  275. // function that takes a tuple pattern:
  276. //
  277. // fn Class.Class((a: A, b: B, c: C)) -> Class;
  278. return {
  279. .kind = SemIR::ClangDeclKey::Signature::Kind::TuplePattern,
  280. .num_params = static_cast<int32_t>(
  281. context.inst_blocks().Get(tuple_type->type_elements_id).size())};
  282. }
  283. // Any other initialization using a constructor is calling a converting
  284. // constructor:
  285. //
  286. // fn Class.Class(a: A) -> Class;
  287. if (isa<clang::CXXConstructorDecl>(function_decl)) {
  288. return {.kind = SemIR::ClangDeclKey::Signature::Kind::Normal,
  289. .num_params = 1};
  290. }
  291. // Otherwise, the initialization is calling a conversion function
  292. // `Source::operator Dest`:
  293. //
  294. // fn Source.<conversion function>[self: Source]() -> Dest;
  295. CARBON_CHECK(isa<clang::CXXConversionDecl>(function_decl));
  296. return {.kind = SemIR::ClangDeclKey::Signature::Kind::Normal,
  297. .num_params = 0};
  298. }
  299. static auto LookupCppConversion(Context& context, SemIR::LocId loc_id,
  300. SemIR::InstId source_id,
  301. SemIR::TypeId dest_type_id, bool allow_explicit)
  302. -> SemIR::InstId {
  303. if (context.types().Is<SemIR::StructType>(
  304. context.insts().Get(source_id).type_id())) {
  305. // Structs can only be used to initialize C++ aggregates. That case is
  306. // handled by Convert, not here.
  307. return SemIR::InstId::None;
  308. }
  309. auto dest_type = MapToCppType(context, dest_type_id);
  310. if (dest_type.isNull()) {
  311. return SemIR::InstId::None;
  312. }
  313. auto* arg_expr = InventClangArg(context, source_id);
  314. // If we can't map the argument, we can't perform the conversion.
  315. if (!arg_expr) {
  316. return SemIR::InstId::None;
  317. }
  318. auto loc = GetCppLocation(context, loc_id);
  319. // Form a Clang initialization sequence.
  320. auto& sema = context.clang_sema();
  321. clang::InitializedEntity entity =
  322. clang::InitializedEntity::InitializeTemporary(dest_type);
  323. clang::InitializationKind kind =
  324. allow_explicit ? clang::InitializationKind::CreateDirect(
  325. loc, /*LParenLoc=*/clang::SourceLocation(),
  326. /*RParenLoc=*/clang::SourceLocation())
  327. : clang::InitializationKind::CreateCopy(
  328. loc, /*EqualLoc=*/clang::SourceLocation());
  329. clang::MultiExprArg args(arg_expr);
  330. // `(a, b) as T` uses `T{a, b}`, not `T({a, b})`. The latter would introduce
  331. // a redundant extra copy.
  332. // TODO: We need to communicate this back to the caller so they know to call
  333. // the constructor with an exploded argument list somehow.
  334. if (allow_explicit && isa<clang::InitListExpr>(arg_expr)) {
  335. kind = clang::InitializationKind::CreateDirectList(loc);
  336. }
  337. clang::InitializationSequence init(sema, entity, kind, args);
  338. if (init.Failed()) {
  339. // TODO: Are there initialization failures that we should translate into
  340. // errors rather than a missing conversion?
  341. return SemIR::InstId::None;
  342. }
  343. // Scan the steps looking for user-defined conversions. For now we just find
  344. // and return the first such conversion function. We skip over standard
  345. // conversions; we'll perform those using the Carbon rules as part of calling
  346. // the C++ conversion function.
  347. for (const auto& step : init.steps()) {
  348. switch (step.Kind) {
  349. case clang::InitializationSequence::SK_UserConversion:
  350. case clang::InitializationSequence::SK_ConstructorInitialization:
  351. case clang::InitializationSequence::SK_StdInitializerListConstructorCall:
  352. case clang::InitializationSequence::
  353. SK_ConstructorInitializationFromList: {
  354. if (auto* ctor =
  355. dyn_cast<clang::CXXConstructorDecl>(step.Function.Function);
  356. ctor && ctor->isCopyOrMoveConstructor()) {
  357. // Skip copy / move constructor calls. They shouldn't be performed
  358. // this way because they're not considered conversions in Carbon, and
  359. // will frequently lead to infinite recursion because we'll end up
  360. // back here when attempting to convert the argument.
  361. continue;
  362. }
  363. if (sema.DiagnoseUseOfOverloadedDecl(step.Function.Function, loc)) {
  364. return SemIR::ErrorInst::InstId;
  365. }
  366. sema.MarkFunctionReferenced(loc, step.Function.Function);
  367. auto signature = GetConversionSignatureToImport(
  368. context, source_id, step.Kind, step.Function.Function);
  369. auto result_id = ImportCppFunctionDecl(
  370. context, loc_id, step.Function.Function, signature);
  371. if (auto fn_decl = context.insts().TryGetAsWithId<SemIR::FunctionDecl>(
  372. result_id)) {
  373. CheckCppOverloadAccess(context, loc_id, step.Function.FoundDecl,
  374. fn_decl->inst_id);
  375. } else {
  376. CARBON_CHECK(result_id == SemIR::ErrorInst::InstId);
  377. }
  378. // TODO: There may be other conversions later in the sequence that we
  379. // need to model; we've only applied the first one here.
  380. return result_id;
  381. }
  382. case clang::InitializationSequence::SK_StdInitializerList: {
  383. return MakeCppStdInitializerListMake(
  384. context, loc_id, step.Type,
  385. cast<clang::InitListExpr>(arg_expr)->getNumInits());
  386. }
  387. case clang::InitializationSequence::SK_ListInitialization: {
  388. // Aggregate initialization is handled by the normal Carbon conversion
  389. // logic, so we ignore it here.
  390. // TODO: So far we only support aggregate initialization for arrays and
  391. // empty classes.
  392. continue;
  393. }
  394. case clang::InitializationSequence::SK_ConversionSequence:
  395. case clang::InitializationSequence::SK_ConversionSequenceNoNarrowing: {
  396. // Implicit conversions are handled by the normal Carbon conversion
  397. // logic, so we ignore them here.
  398. continue;
  399. }
  400. default: {
  401. // TODO: Handle other kinds of initialization steps. For now we assume
  402. // they will be handled by our function call logic and we can skip them.
  403. RawStringOstream os;
  404. os << "Unsupported initialization sequence:\n";
  405. init.dump(os);
  406. context.TODO(loc_id, os.TakeStr());
  407. return SemIR::ErrorInst::InstId;
  408. }
  409. }
  410. }
  411. return SemIR::InstId::None;
  412. }
  413. static auto FindClangOperator(Context& context, SemIR::LocId loc_id,
  414. clang::OverloadedOperatorKind op_kind,
  415. llvm::ArrayRef<clang::Expr*> arg_exprs)
  416. -> SemIR::InstId;
  417. namespace {
  418. struct DiagnoseIncompleteOperandTypeInCppOperatorLookup {
  419. Context& context;
  420. SemIR::TypeId arg_type_id;
  421. SemIR::LocId loc_id;
  422. void operator()(auto& builder) const {
  423. CARBON_DIAGNOSTIC(
  424. IncompleteOperandTypeInCppOperatorLookup, Context,
  425. "looking up a C++ operator with incomplete operand type {0}",
  426. SemIR::TypeId);
  427. builder.Context(loc_id, IncompleteOperandTypeInCppOperatorLookup,
  428. arg_type_id);
  429. }
  430. };
  431. } // namespace
  432. auto LookupCppOperator(Context& context, SemIR::LocId loc_id, Operator op,
  433. llvm::ArrayRef<SemIR::TypeId> arg_type_ids)
  434. -> SemIR::InstId {
  435. // Register an annotation scope to flush any Clang diagnostics when we return.
  436. // This is important to ensure that Clang diagnostics are properly interleaved
  437. // with Carbon diagnostics.
  438. Diagnostics::AnnotationScope annotate_diagnostics(&context.emitter(),
  439. [](auto& /*builder*/) {});
  440. if (op.interface_name == CoreIdentifier::ImplicitAs ||
  441. op.interface_name == CoreIdentifier::As) {
  442. context.TODO(loc_id, "handle `as` operator when passed a type");
  443. return SemIR::ErrorInst::InstId;
  444. }
  445. auto op_kind =
  446. GetClangOperatorKind(context, loc_id, op.interface_name, op.op_name);
  447. if (!op_kind) {
  448. return SemIR::ErrorInst::InstId;
  449. }
  450. for (SemIR::TypeId arg_type_id : arg_type_ids) {
  451. if (!RequireCompleteType(context, arg_type_id, loc_id,
  452. DiagnoseIncompleteOperandTypeInCppOperatorLookup{
  453. .context = context,
  454. .arg_type_id = arg_type_id,
  455. .loc_id = loc_id})) {
  456. return SemIR::ErrorInst::InstId;
  457. }
  458. }
  459. struct Operand {
  460. using enum clang::ExprValueKind;
  461. explicit Operand(clang::QualType type)
  462. : type(type),
  463. expression({}, type,
  464. type->isLValueReferenceType() ? VK_LValue
  465. : type->isRValueReferenceType() ? VK_XValue
  466. : VK_PRValue) {}
  467. clang::QualType type;
  468. clang::OpaqueValueExpr expression;
  469. };
  470. auto cpp_type = MapToCppType(context, arg_type_ids[0]);
  471. if (cpp_type.isNull()) {
  472. return SemIR::InstId::None;
  473. }
  474. auto arg0 = Operand(cpp_type);
  475. if (arg_type_ids.size() == 1) {
  476. return FindClangOperator(context, loc_id, *op_kind, {&arg0.expression});
  477. }
  478. CARBON_CHECK(arg_type_ids.size() == 2);
  479. cpp_type = MapToCppType(context, arg_type_ids[1]);
  480. if (cpp_type.isNull()) {
  481. return SemIR::InstId::None;
  482. }
  483. auto arg1 = Operand(cpp_type);
  484. return FindClangOperator(context, loc_id, *op_kind,
  485. {&arg0.expression, &arg1.expression});
  486. }
  487. auto LookupCppOperator(Context& context, SemIR::LocId loc_id, Operator op,
  488. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  489. // Register an annotation scope to flush any Clang diagnostics when we return.
  490. // This is important to ensure that Clang diagnostics are properly interleaved
  491. // with Carbon diagnostics.
  492. Diagnostics::AnnotationScope annotate_diagnostics(&context.emitter(),
  493. [](auto& /*builder*/) {});
  494. // We can only handle concrete types in LookupCppOperator.
  495. for (auto arg_id : arg_ids) {
  496. auto type_id = context.insts().Get(arg_id).type_id();
  497. if (type_id.is_symbolic()) {
  498. return SemIR::InstId::None;
  499. }
  500. }
  501. // Handle `ImplicitAs` and `As`.
  502. if (op.interface_name == CoreIdentifier::ImplicitAs ||
  503. op.interface_name == CoreIdentifier::As) {
  504. if (op.interface_args_ref.size() != 1 || arg_ids.size() != 1) {
  505. return SemIR::InstId::None;
  506. }
  507. // The argument is the destination type for both interfaces.
  508. auto dest_const_id =
  509. context.constant_values().Get(op.interface_args_ref[0]);
  510. auto dest_type_id =
  511. context.types().TryGetTypeIdForTypeConstantId(dest_const_id);
  512. if (!dest_type_id.has_value()) {
  513. return SemIR::InstId::None;
  514. }
  515. return LookupCppConversion(
  516. context, loc_id, arg_ids[0], dest_type_id,
  517. /*allow_explicit=*/op.interface_name == CoreIdentifier::As);
  518. }
  519. auto op_kind =
  520. GetClangOperatorKind(context, loc_id, op.interface_name, op.op_name);
  521. if (!op_kind) {
  522. return SemIR::InstId::None;
  523. }
  524. // Make sure all operands are complete before lookup.
  525. for (SemIR::InstId arg_id : arg_ids) {
  526. SemIR::TypeId arg_type_id = context.insts().Get(arg_id).type_id();
  527. if (!RequireCompleteType(context, arg_type_id, loc_id,
  528. DiagnoseIncompleteOperandTypeInCppOperatorLookup{
  529. .context = context,
  530. .arg_type_id = arg_type_id,
  531. .loc_id = loc_id})) {
  532. return SemIR::ErrorInst::InstId;
  533. }
  534. }
  535. auto maybe_arg_exprs = InventClangArgs(context, arg_ids);
  536. if (!maybe_arg_exprs.has_value()) {
  537. return SemIR::ErrorInst::InstId;
  538. }
  539. return FindClangOperator(context, loc_id, *op_kind, *maybe_arg_exprs);
  540. }
  541. static auto FindClangOperator(Context& context, SemIR::LocId loc_id,
  542. clang::OverloadedOperatorKind op_kind,
  543. llvm::ArrayRef<clang::Expr*> arg_exprs)
  544. -> SemIR::InstId {
  545. clang::SourceLocation loc = GetCppLocation(context, loc_id);
  546. clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info(
  547. op_kind, loc, /*AllowRewritten=*/true);
  548. clang::OverloadCandidateSet candidate_set(
  549. loc, clang::OverloadCandidateSet::CSK_Operator, operator_rewrite_info);
  550. clang::Sema& sema = context.clang_sema();
  551. // This works for both unary and binary operators.
  552. sema.LookupOverloadedBinOp(candidate_set, op_kind, clang::UnresolvedSet<0>{},
  553. arg_exprs);
  554. clang::OverloadCandidateSet::iterator best_viable_fn;
  555. switch (candidate_set.BestViableFunction(sema, loc, best_viable_fn)) {
  556. case clang::OverloadingResult::OR_Success: {
  557. if (!best_viable_fn->Function) {
  558. // The best viable candidate was a builtin. Let the Carbon operator
  559. // machinery handle that.
  560. return SemIR::InstId::None;
  561. }
  562. if (best_viable_fn->RewriteKind) {
  563. context.TODO(
  564. loc_id,
  565. llvm::formatv("Rewriting operator{0} using {1} is not supported",
  566. clang::getOperatorSpelling(
  567. candidate_set.getRewriteInfo().OriginalOperator),
  568. best_viable_fn->Function->getNameAsString()));
  569. return SemIR::ErrorInst::InstId;
  570. }
  571. sema.MarkFunctionReferenced(loc, best_viable_fn->Function);
  572. // If this is an operator method, the first arg will be used as self.
  573. int32_t num_params = arg_exprs.size();
  574. if (isa<clang::CXXMethodDecl>(best_viable_fn->Function)) {
  575. --num_params;
  576. }
  577. auto result_id =
  578. ImportCppFunctionDecl(context, loc_id, best_viable_fn->Function,
  579. {.num_params = num_params});
  580. if (result_id != SemIR::ErrorInst::InstId) {
  581. CheckCppOverloadAccess(
  582. context, loc_id, best_viable_fn->FoundDecl,
  583. context.insts().GetAsKnownInstId<SemIR::FunctionDecl>(result_id));
  584. }
  585. return result_id;
  586. }
  587. case clang::OverloadingResult::OR_No_Viable_Function: {
  588. // OK, didn't find a viable C++ candidate, but this is not an error, as
  589. // there might be a Carbon candidate.
  590. return SemIR::InstId::None;
  591. }
  592. case clang::OverloadingResult::OR_Ambiguous: {
  593. const char* spelling = clang::getOperatorSpelling(op_kind);
  594. candidate_set.NoteCandidates(
  595. clang::PartialDiagnosticAt(
  596. loc, sema.PDiag(clang::diag::err_ovl_ambiguous_oper_binary)
  597. << spelling << arg_exprs[0]->getType()
  598. << arg_exprs[1]->getType()),
  599. sema, clang::OCD_AmbiguousCandidates, arg_exprs, spelling, loc);
  600. return SemIR::ErrorInst::InstId;
  601. }
  602. case clang::OverloadingResult::OR_Deleted:
  603. const char* spelling = clang::getOperatorSpelling(op_kind);
  604. auto* message = best_viable_fn->Function->getDeletedMessage();
  605. // The best viable function might be a different operator if the best
  606. // candidate is a rewritten candidate, so use the operator kind of the
  607. // candidate itself in the diagnostic.
  608. candidate_set.NoteCandidates(
  609. clang::PartialDiagnosticAt(
  610. loc, sema.PDiag(clang::diag::err_ovl_deleted_oper)
  611. << clang::getOperatorSpelling(
  612. best_viable_fn->Function->getOverloadedOperator())
  613. << (message != nullptr)
  614. << (message ? message->getString() : llvm::StringRef())),
  615. sema, clang::OCD_AllCandidates, arg_exprs, spelling, loc);
  616. return SemIR::ErrorInst::InstId;
  617. }
  618. }
  619. auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool {
  620. auto* clang_method_decl = dyn_cast<clang::CXXMethodDecl>(decl);
  621. return clang_method_decl &&
  622. (clang_method_decl->isOverloadedOperator() ||
  623. isa<clang::CXXConversionDecl>(clang_method_decl));
  624. }
  625. static auto GetAsCppFunctionDecl(Context& context, SemIR::InstId inst_id)
  626. -> clang::FunctionDecl* {
  627. if (inst_id == SemIR::InstId::None) {
  628. return nullptr;
  629. }
  630. auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  631. context.insts().Get(inst_id).type_id());
  632. if (!function_type) {
  633. return nullptr;
  634. }
  635. SemIR::ClangDeclId clang_decl_id =
  636. context.functions().Get(function_type->function_id).clang_decl_id;
  637. return clang_decl_id.has_value()
  638. ? dyn_cast<clang::FunctionDecl>(
  639. context.clang_decls().Get(clang_decl_id).key.decl)
  640. : nullptr;
  641. }
  642. auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool {
  643. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  644. return function_decl && IsCppOperatorMethodDecl(function_decl);
  645. }
  646. auto IsCppConstructorOrNonMethodOperator(Context& context,
  647. SemIR::InstId inst_id) -> bool {
  648. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  649. if (!function_decl) {
  650. return false;
  651. }
  652. if (isa<clang::CXXConstructorDecl>(function_decl)) {
  653. return true;
  654. }
  655. return !isa<clang::CXXMethodDecl>(function_decl) &&
  656. function_decl->isOverloadedOperator();
  657. }
  658. } // namespace Carbon::Check