diff --git a/examples/interop/cpp/hello_world.carbon b/examples/interop/cpp/hello_world.carbon index b39477f415ed8..27cee9662595c 100644 --- a/examples/interop/cpp/hello_world.carbon +++ b/examples/interop/cpp/hello_world.carbon @@ -2,27 +2,12 @@ // Exceptions. See /LICENSE for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -import Cpp inline "#include "; - -fn Run() { - // TODO: Requires class with virtual bases (`basic_ostream`). - // Cpp.std.cout << "Hello world!\n"; - - // TODO: Requires variadic function. - // Cpp.printf("Hello world!\n"); - - // TODO: Requires nullable pointer. - // Cpp.puts("Hello world!\n"); - - // TODO: Requires nullable void pointer. - // Cpp.write(1, "Hello world!\n", 13); - - // TODO: Requires Core.String API. - // let message: str = "Hello world!\n\n"; - // for (c: char in message) { - // Cpp.putchar((c as u8) as i32); - // } +import Cpp library ""; +import Cpp library ""; +import Cpp library ""; +import Cpp library ""; +fn HelloArrayOfChars() { let message: array(char, 13) = ('H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'); for (c: char in message) { @@ -30,3 +15,42 @@ fn Run() { Cpp.putchar((c as u8) as i32); } } + +fn HelloStringAsArrayOfChars() { + // TODO: Requires IndexWith support for str. + // let message: str = "Hello world!\n\n"; + // for (c: char in message) { + // Cpp.putchar((c as u8) as i32); + // } +} + +fn HelloPuts() { + // TODO: Requires mapping from Optional(const char*) into C++. + // TODO: There should be a better way to interact with functions that expect a + // null-terminated string. + // Cpp.puts(Cpp.std.data("Hello world!\n\0")); +} + +fn HelloWrite() { + // TODO: Requires mapping from Optional(const char*) into C++. + // let s: str = "Hello world!\n"; + // Cpp.write(1, Cpp.std.data(s), Cpp.std.size(s)); +} + +fn HelloPrintf() { + // TODO: Requires variadic function. + // Cpp.printf("Hello world!\n"); +} + +fn HelloIostreams() { + Cpp.std.cout << "Hello world!\n"; +} + +fn Run() { + HelloArrayOfChars(); + HelloStringAsArrayOfChars(); + HelloPuts(); + HelloWrite(); + HelloPrintf(); + HelloIostreams(); +} diff --git a/toolchain/check/cpp/call.cpp b/toolchain/check/cpp/call.cpp index ecde9c8f09718..465531b3a26db 100644 --- a/toolchain/check/cpp/call.cpp +++ b/toolchain/check/cpp/call.cpp @@ -15,10 +15,14 @@ namespace Carbon::Check { // Returns whether the function is an imported C++ operator member function. -static auto IsCppOperatorMethod(Context& context, SemIR::FunctionId function_id) - -> bool { +auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool { + auto function_type = context.types().TryGetAs( + context.insts().Get(inst_id).type_id()); + if (!function_type) { + return false; + } SemIR::ClangDeclId clang_decl_id = - context.functions().Get(function_id).clang_decl_id; + context.functions().Get(function_type->function_id).clang_decl_id; return clang_decl_id.has_value() && IsCppOperatorMethodDecl( context.clang_decls().Get(clang_decl_id).key.decl); @@ -41,9 +45,6 @@ auto PerformCallToCppFunction(Context& context, SemIR::LocId loc_id, if (self_id.has_value()) { // Preserve the `self` argument from the original callee. fn.self_id = self_id; - } else if (IsCppOperatorMethod(context, fn.function_id)) { - // Adjust `self` and args for C++ overloaded operator methods. - fn.self_id = arg_ids.consume_front(); } return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids); } diff --git a/toolchain/check/cpp/call.h b/toolchain/check/cpp/call.h index 02e8b79078396..50327da08edbc 100644 --- a/toolchain/check/cpp/call.h +++ b/toolchain/check/cpp/call.h @@ -10,6 +10,11 @@ namespace Carbon::Check { +// Returns whether the specified instruction refers to a C++ overloaded operator +// that is a method. If so, the first operand will be passed as `self` rather +// than as the first argument. +auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool; + // Checks and builds SemIR for a call to a C++ function in the given overload // set with self `self_id` and arguments `arg_ids`. // diff --git a/toolchain/check/cpp/import.cpp b/toolchain/check/cpp/import.cpp index 1680834529623..bd7876e6bcfc9 100644 --- a/toolchain/check/cpp/import.cpp +++ b/toolchain/check/cpp/import.cpp @@ -740,6 +740,13 @@ static auto GetInheritanceKind(clang::CXXRecordDecl* class_def) return SemIR::Class::Final; } + if (class_def->getNumVBases()) { + // TODO: We treat classes with virtual bases as final for now. We use the + // layout of the class including its virtual bases as its Carbon type + // layout, so we wouldn't behave correctly if we derived from it. + return SemIR::Class::Final; + } + if (class_def->isAbstract()) { // If the class has any abstract members, it's abstract. return SemIR::Class::Abstract; @@ -802,8 +809,15 @@ static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id, // Import bases. for (const auto& base : clang_def->bases()) { - CARBON_CHECK(!base.isVirtual(), - "Should not import definition for class with a virtual base"); + if (base.isVirtual()) { + // If the base is virtual, skip it from the layout. We don't know where it + // will actually appear within the complete object layout, as a pointer to + // this class might point to a derived type that puts the vbase in a + // different place. + // TODO: Track that the virtual base existed. Support derived-to-vbase + // conversions by generating a clang AST fragment. + continue; + } auto [base_type_inst_id, base_type_id] = ImportTypeAndDependencies(context, import_ir_inst_id, base.getType()); @@ -842,6 +856,10 @@ static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id, class_info.base_id = SemIR::InstId::None; } + // TODO: If the base class has virtual bases, the size of the type that we + // add to the layout here will be the full size of the class (including + // virtual bases), whereas the size actually occupied by this base class is + // only the nvsize (excluding virtual bases). auto base_offset = base.isVirtual() ? clang_layout.getVBaseClassOffset(base_class) : clang_layout.getBaseClassOffset(base_class); @@ -2413,17 +2431,6 @@ auto ImportClassDefinitionForClangDecl(Context& context, SemIR::LocId loc_id, auto* class_def = class_decl->getDefinition(); CARBON_CHECK(class_def, "Complete type has no definition"); - if (class_def->getNumVBases()) { - // TODO: Handle virtual bases. We don't actually know where they go in the - // layout. We may also want to use a different size in the layout for - // `partial C`, excluding the virtual base. It's also not entirely safe to - // just skip over the virtual base, as the type we would construct would - // have a misleading size. For now, treat a C++ class with vbases as - // incomplete in Carbon. - context.TODO(loc_id, "class with virtual bases"); - return false; - } - BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id, class_def); } else if (auto* enum_decl = dyn_cast(clang_decl)) { diff --git a/toolchain/check/cpp/operators.cpp b/toolchain/check/cpp/operators.cpp index d8aa1327a6cfe..c472cb9fdbc64 100644 --- a/toolchain/check/cpp/operators.cpp +++ b/toolchain/check/cpp/operators.cpp @@ -8,6 +8,7 @@ #include "clang/Sema/Sema.h" #include "toolchain/check/cpp/import.h" #include "toolchain/check/cpp/location.h" +#include "toolchain/check/cpp/overload_resolution.h" #include "toolchain/check/cpp/type_mapping.h" #include "toolchain/check/inst.h" #include "toolchain/check/type.h" @@ -190,31 +191,82 @@ auto LookupCppOperator(Context& context, SemIR::LocId loc_id, Operator op, } } - auto arg_exprs = InventClangArgs(context, arg_ids); - if (!arg_exprs.has_value()) { + auto maybe_arg_exprs = InventClangArgs(context, arg_ids); + if (!maybe_arg_exprs.has_value()) { return SemIR::ErrorInst::InstId; } + auto& arg_exprs = *maybe_arg_exprs; clang::SourceLocation loc = GetCppLocation(context, loc_id); clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info( *op_kind, loc, /*AllowRewritten=*/true); - clang::UnresolvedSet<4> functions; + clang::UnresolvedSet<0> functions; clang::OverloadCandidateSet candidate_set( loc, clang::OverloadCandidateSet::CSK_Operator, operator_rewrite_info); + + clang::Sema& sema = context.clang_sema(); + // This works for both unary and binary operators. - context.clang_sema().LookupOverloadedBinOp(candidate_set, *op_kind, functions, - *arg_exprs); + sema.LookupOverloadedBinOp(candidate_set, *op_kind, functions, arg_exprs); - for (auto& it : candidate_set) { - if (!it.Function) { - continue; + clang::OverloadCandidateSet::iterator best_viable_fn; + switch (candidate_set.BestViableFunction(sema, loc, best_viable_fn)) { + case clang::OverloadingResult::OR_Success: { + if (!best_viable_fn->Function) { + // The best viable candidate was a builtin. Let the Carbon operator + // machinery handle that. + return SemIR::InstId::None; + } + if (best_viable_fn->RewriteKind) { + context.TODO( + loc_id, + llvm::formatv("Rewriting operator{0} using {1} is not supported", + clang::getOperatorSpelling( + candidate_set.getRewriteInfo().OriginalOperator), + best_viable_fn->Function->getNameAsString())); + return SemIR::ErrorInst::InstId; + } + sema.MarkFunctionReferenced(loc, best_viable_fn->Function); + auto result_id = ImportCppFunctionDecl( + context, loc_id, best_viable_fn->Function, + // If this is an operator method, the first arg will be used as self. + arg_ids.size() - + (isa(best_viable_fn->Function) ? 1 : 0)); + CheckCppOverloadAccess(context, loc_id, best_viable_fn->FoundDecl, + result_id); + return result_id; } - functions.addDecl(it.Function, it.FoundDecl.getAccess()); + case clang::OverloadingResult::OR_No_Viable_Function: { + // OK, didn't find a viable C++ candidate, but this is not an error, as + // there might be a Carbon candidate. + return SemIR::InstId::None; + } + case clang::OverloadingResult::OR_Ambiguous: { + const char* spelling = clang::getOperatorSpelling(*op_kind); + candidate_set.NoteCandidates( + clang::PartialDiagnosticAt( + loc, sema.PDiag(clang::diag::err_ovl_ambiguous_oper_binary) + << spelling << arg_exprs[0]->getType() + << arg_exprs[1]->getType()), + sema, clang::OCD_AmbiguousCandidates, arg_exprs, spelling, loc); + return SemIR::ErrorInst::InstId; + } + case clang::OverloadingResult::OR_Deleted: + const char* spelling = clang::getOperatorSpelling(*op_kind); + auto* message = best_viable_fn->Function->getDeletedMessage(); + // The best viable function might be a different operator if the best + // candidate is a rewritten candidate, so use the operator kind of the + // candidate itself in the diagnostic. + candidate_set.NoteCandidates( + clang::PartialDiagnosticAt( + loc, sema.PDiag(clang::diag::err_ovl_deleted_oper) + << clang::getOperatorSpelling( + best_viable_fn->Function->getOverloadedOperator()) + << (message != nullptr) + << (message ? message->getString() : llvm::StringRef())), + sema, clang::OCD_AllCandidates, arg_exprs, spelling, loc); + return SemIR::ErrorInst::InstId; } - - return ImportCppOverloadSet( - context, loc_id, SemIR::NameScopeId::None, SemIR::NameId::CppOperator, - /*naming_class=*/nullptr, std::move(functions), operator_rewrite_info); } auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool { diff --git a/toolchain/check/cpp/overload_resolution.cpp b/toolchain/check/cpp/overload_resolution.cpp index 12f90b8b3b190..5906524002a20 100644 --- a/toolchain/check/cpp/overload_resolution.cpp +++ b/toolchain/check/cpp/overload_resolution.cpp @@ -84,22 +84,31 @@ static auto AddOverloadCandidates(clang::Sema& sema, } } -// Checks whether a selected overload is accessible and diagnoses if not. -static auto CheckOverloadAccess(Context& context, SemIR::LocId loc_id, - const SemIR::CppOverloadSet& overload_set, - clang::DeclAccessPair overload, - SemIR::InstId overload_inst_id) -> void { +auto CheckCppOverloadAccess(Context& context, SemIR::LocId loc_id, + clang::DeclAccessPair overload, + SemIR::InstId overload_inst_id, + SemIR::NameScopeId parent_scope_id) -> void { SemIR::AccessKind member_access_kind = MapCppAccess(overload); if (member_access_kind == SemIR::AccessKind::Public) { return; } + if (overload_inst_id == SemIR::ErrorInst::InstId) { + return; + } + + auto function_id = + context.insts().GetAs(overload_inst_id).function_id; + auto& function = context.functions().Get(function_id); + if (!parent_scope_id.has_value()) { + parent_scope_id = function.parent_scope_id; + } auto name_scope_const_id = context.constant_values().Get( - context.name_scopes().Get(overload_set.parent_scope_id).inst_id()); + context.name_scopes().Get(parent_scope_id).inst_id()); SemIR::AccessKind allowed_access_kind = GetHighestAllowedAccess(context, loc_id, name_scope_const_id); - CheckAccess(context, loc_id, SemIR::LocId(overload_inst_id), - overload_set.name_id, member_access_kind, + CheckAccess(context, loc_id, SemIR::LocId(overload_inst_id), function.name_id, + member_access_kind, /*is_parent_access=*/false, {.constant_id = name_scope_const_id, .highest_allowed_access = allowed_access_kind}); @@ -155,25 +164,13 @@ auto PerformCppOverloadResolution(Context& context, SemIR::LocId loc_id, switch (overloading_result) { case clang::OverloadingResult::OR_Success: { - // TODO: Handle the cases when Function is null. CARBON_CHECK(best_viable_fn->Function); - if (best_viable_fn->RewriteKind) { - context.TODO( - loc_id, - llvm::formatv("Rewriting operator{0} using {1} is not supported", - clang::getOperatorSpelling( - candidate_set.getRewriteInfo().OriginalOperator), - best_viable_fn->Function->getNameAsString())); - return SemIR::ErrorInst::InstId; - } + CARBON_CHECK(!best_viable_fn->RewriteKind); sema.MarkFunctionReferenced(loc, best_viable_fn->Function); SemIR::InstId result_id = ImportCppFunctionDecl( - context, loc_id, best_viable_fn->Function, - // If this is an operator method, the first arg will be used as self. - arg_exprs.size() - - (IsCppOperatorMethodDecl(best_viable_fn->Function) ? 1 : 0)); - CheckOverloadAccess(context, loc_id, overload_set, - best_viable_fn->FoundDecl, result_id); + context, loc_id, best_viable_fn->Function, arg_exprs.size()); + CheckCppOverloadAccess(context, loc_id, best_viable_fn->FoundDecl, + result_id, overload_set.parent_scope_id); return result_id; } case clang::OverloadingResult::OR_No_Viable_Function: { diff --git a/toolchain/check/cpp/overload_resolution.h b/toolchain/check/cpp/overload_resolution.h index c088316678872..63ffd40cfca1b 100644 --- a/toolchain/check/cpp/overload_resolution.h +++ b/toolchain/check/cpp/overload_resolution.h @@ -11,6 +11,15 @@ namespace Carbon::Check { +// Checks whether a selected overload is accessible and diagnoses if not. +// `parent_scope_id`, if specified, describes the scope that was named to find +// the overload. If unspecified, we assume the overload was found in the class +// that it is a direct member of, rather than a derived class. +auto CheckCppOverloadAccess( + Context& context, SemIR::LocId loc_id, clang::DeclAccessPair overload, + SemIR::InstId overload_inst_id, + SemIR::NameScopeId parent_scope_id = SemIR::NameScopeId::None) -> void; + // Resolves which function to call using Clang overloading resolution, or // returns an error instruction if overload resolution failed. // diff --git a/toolchain/check/operator.cpp b/toolchain/check/operator.cpp index 8eaebdbb7ab64..184d32401b5af 100644 --- a/toolchain/check/operator.cpp +++ b/toolchain/check/operator.cpp @@ -8,6 +8,7 @@ #include "toolchain/check/call.h" #include "toolchain/check/context.h" +#include "toolchain/check/cpp/call.h" #include "toolchain/check/cpp/operators.h" #include "toolchain/check/generic.h" #include "toolchain/check/member_access.h" @@ -67,27 +68,30 @@ auto BuildUnaryOperator(Context& context, SemIR::LocId loc_id, Operator op, // Operator operands don't require `ref` tags. context.ref_tags().Insert(operand_id, Context::RefTag::NotRequired); + SemIR::InstId op_fn_id = SemIR::InstId::None; + // For unary operators with a C++ class as the operand, try to import and call // the C++ operator. // TODO: Change impl lookup instead. See // https://github.com/carbon-language/carbon-lang/blob/db0a00d713015436844c55e7ac190a0f95556499/toolchain/check/operator.cpp#L76 if (IsCppClassType(context, operand_id)) { - SemIR::InstId cpp_inst_id = - LookupCppOperator(context, loc_id, op, {operand_id}); - if (cpp_inst_id.has_value()) { - if (cpp_inst_id == SemIR::ErrorInst::InstId) { - return SemIR::ErrorInst::InstId; - } - return PerformCall(context, loc_id, cpp_inst_id, {operand_id}); + op_fn_id = LookupCppOperator(context, loc_id, op, {operand_id}); + + // If C++ operator lookup found a non-method operator, call it with one call + // argument. Otherwise fall through to call it with a self argument. + if (op_fn_id.has_value() && !IsCppOperatorMethod(context, op_fn_id)) { + return PerformCall(context, loc_id, op_fn_id, {operand_id}); } } - // Look up the operator function. - auto op_fn = GetOperatorOpFunction(context, loc_id, op); + if (!op_fn_id.has_value()) { + // Look up the operator function. + op_fn_id = GetOperatorOpFunction(context, loc_id, op); + } // Form `operand.(Op)`. - auto bound_op_id = PerformCompoundMemberAccess(context, loc_id, operand_id, - op_fn, missing_impl_diagnoser); + auto bound_op_id = PerformCompoundMemberAccess( + context, loc_id, operand_id, op_fn_id, missing_impl_diagnoser); if (bound_op_id == SemIR::ErrorInst::InstId) { return SemIR::ErrorInst::InstId; } @@ -109,6 +113,8 @@ auto BuildBinaryOperator(Context& context, SemIR::LocId loc_id, Operator op, context.ref_tags().Insert(lhs_id, Context::RefTag::NotRequired); context.ref_tags().Insert(rhs_id, Context::RefTag::NotRequired); + SemIR::InstId op_fn_id = SemIR::InstId::None; + // For binary operators with a C++ class as at least one of the operands, try // to import and call the C++ operator. // TODO: Instead of hooking this here, change impl lookup, so that a generic @@ -118,22 +124,24 @@ auto BuildBinaryOperator(Context& context, SemIR::LocId loc_id, Operator op, // and // https://github.com/carbon-language/carbon-lang/pull/5996/files/5d01fa69511b76f87efbc0387f5e40abcf4c911a#r2308664536 if (IsCppClassType(context, lhs_id) || IsCppClassType(context, rhs_id)) { - SemIR::InstId cpp_inst_id = - LookupCppOperator(context, loc_id, op, {lhs_id, rhs_id}); - if (cpp_inst_id.has_value()) { - if (cpp_inst_id == SemIR::ErrorInst::InstId) { - return SemIR::ErrorInst::InstId; - } - return PerformCall(context, loc_id, cpp_inst_id, {lhs_id, rhs_id}); + op_fn_id = LookupCppOperator(context, loc_id, op, {lhs_id, rhs_id}); + + // If C++ operator lookup found a non-method operator, call it with two call + // arguments. Otherwise fall through to call it with a self argument and one + // call argument. + if (op_fn_id.has_value() && !IsCppOperatorMethod(context, op_fn_id)) { + return PerformCall(context, loc_id, op_fn_id, {lhs_id, rhs_id}); } } - // Look up the operator function. - auto op_fn = GetOperatorOpFunction(context, loc_id, op); + if (!op_fn_id.has_value()) { + // Look up the operator function. + op_fn_id = GetOperatorOpFunction(context, loc_id, op); + } // Form `lhs.(Op)`. - auto bound_op_id = PerformCompoundMemberAccess(context, loc_id, lhs_id, op_fn, - missing_impl_diagnoser); + auto bound_op_id = PerformCompoundMemberAccess( + context, loc_id, lhs_id, op_fn_id, missing_impl_diagnoser); if (bound_op_id == SemIR::ErrorInst::InstId) { return SemIR::ErrorInst::InstId; } diff --git a/toolchain/check/testdata/interop/cpp/class/base.carbon b/toolchain/check/testdata/interop/cpp/class/base.carbon index 9b2290e322ed4..254548da49c5c 100644 --- a/toolchain/check/testdata/interop/cpp/class/base.carbon +++ b/toolchain/check/testdata/interop/cpp/class/base.carbon @@ -298,30 +298,128 @@ library "[[@TEST_NAME]]"; import Cpp library "virtual_inheritance.h"; fn Convert(p: Cpp.B*) -> Cpp.A* { - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+21]]:3: error: semantics TODO: `class with virtual bases` [SemanticsTodo] + // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.B*` to `Cpp.A*` [ConversionFailure] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+18]]:3: note: while completing C++ type `Cpp.B` [InCppTypeCompletion] + // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+4]]:3: note: type `Cpp.B*` does not implement interface `Core.ImplicitAs(Cpp.A*)` [MissingImplInMemberAccessNote] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ // CHECK:STDERR: - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+14]]:3: error: semantics TODO: `class with virtual bases` [SemanticsTodo] + return p; +} + +// --- diamond.h + +struct A { + int a; +}; + +struct B : virtual A { + int b; +}; + +struct C : virtual A { + int c; +}; + +struct D : B, C { + int d; +}; + +// --- fail_todo_use_diamond.carbon + +library "[[@TEST_NAME]]"; + +import Cpp library "diamond.h"; + +fn ConvertBA(p: Cpp.B*) -> Cpp.A* { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.B*` to `Cpp.A*` [ConversionFailure] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+11]]:3: note: while completing C++ type `Cpp.B` [InCppTypeCompletion] + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:3: note: type `Cpp.B*` does not implement interface `Core.ImplicitAs(Cpp.A*)` [MissingImplInMemberAccessNote] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ // CHECK:STDERR: - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.B*` to `Cpp.A*` [ConversionFailure] + return p; +} + +fn ConvertCA(p: Cpp.C*) -> Cpp.A* { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.C*` to `Cpp.A*` [ConversionFailure] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ - // CHECK:STDERR: fail_todo_use_virtual_inheritance.carbon:[[@LINE+4]]:3: note: type `Cpp.B*` does not implement interface `Core.ImplicitAs(Cpp.A*)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:3: note: type `Cpp.C*` does not implement interface `Core.ImplicitAs(Cpp.A*)` [MissingImplInMemberAccessNote] // CHECK:STDERR: return p; // CHECK:STDERR: ^~~~~~~~~ // CHECK:STDERR: return p; } +fn ConvertDB(p: Cpp.D*) -> Cpp.B* { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.D*` to `Cpp.B*` [ConversionFailure] + // CHECK:STDERR: return p; + // CHECK:STDERR: ^~~~~~~~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:3: note: type `Cpp.D*` does not implement interface `Core.ImplicitAs(Cpp.B*)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return p; + // CHECK:STDERR: ^~~~~~~~~ + // CHECK:STDERR: + return p; +} + +fn ConvertDC(p: Cpp.D*) -> Cpp.C* { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:3: error: cannot implicitly convert expression of type `Cpp.D*` to `Cpp.C*` [ConversionFailure] + // CHECK:STDERR: return p; + // CHECK:STDERR: ^~~~~~~~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:3: note: type `Cpp.D*` does not implement interface `Core.ImplicitAs(Cpp.C*)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return p; + // CHECK:STDERR: ^~~~~~~~~ + // CHECK:STDERR: + return p; +} + +fn AccessBA(d: Cpp.D) -> i32 { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:11: error: cannot convert expression of type `Cpp.D` to `Cpp.B` with `as` [ConversionFailure] + // CHECK:STDERR: return (d as Cpp.B).b; + // CHECK:STDERR: ^~~~~~~~~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:11: note: type `Cpp.D` does not implement interface `Core.As(Cpp.B)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return (d as Cpp.B).b; + // CHECK:STDERR: ^~~~~~~~~~ + // CHECK:STDERR: + return (d as Cpp.B).b; +} + +fn AccessCA(d: Cpp.D) -> i32 { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:11: error: cannot convert expression of type `Cpp.D` to `Cpp.C` with `as` [ConversionFailure] + // CHECK:STDERR: return (d as Cpp.C).b; + // CHECK:STDERR: ^~~~~~~~~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:11: note: type `Cpp.D` does not implement interface `Core.As(Cpp.C)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return (d as Cpp.C).b; + // CHECK:STDERR: ^~~~~~~~~~ + // CHECK:STDERR: + return (d as Cpp.C).b; +} + +fn AccessDB(d: Cpp.D) -> i32 { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:10: error: cannot implicitly convert expression of type `Cpp.D` to `Cpp.B` [ConversionFailure] + // CHECK:STDERR: return d.b; + // CHECK:STDERR: ^~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:10: note: type `Cpp.D` does not implement interface `Core.ImplicitAs(Cpp.B)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return d.b; + // CHECK:STDERR: ^~~ + // CHECK:STDERR: + return d.b; +} + +fn AccessDC(d: Cpp.D) -> i32 { + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+7]]:10: error: cannot implicitly convert expression of type `Cpp.D` to `Cpp.C` [ConversionFailure] + // CHECK:STDERR: return d.c; + // CHECK:STDERR: ^~~ + // CHECK:STDERR: fail_todo_use_diamond.carbon:[[@LINE+4]]:10: note: type `Cpp.D` does not implement interface `Core.ImplicitAs(Cpp.C)` [MissingImplInMemberAccessNote] + // CHECK:STDERR: return d.c; + // CHECK:STDERR: ^~~ + // CHECK:STDERR: + return d.c; +} + // --- final.h struct A final {}; diff --git a/toolchain/check/testdata/interop/cpp/function/operators.carbon b/toolchain/check/testdata/interop/cpp/function/operators.carbon index a0bbe6827712d..bfd324dfd7d80 100644 --- a/toolchain/check/testdata/interop/cpp/function/operators.carbon +++ b/toolchain/check/testdata/interop/cpp/function/operators.carbon @@ -93,22 +93,14 @@ import Cpp library "postfix_inc_and_dec.h"; fn F() { var postfix: Cpp.Postfix = Cpp.Postfix.Postfix(); - // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE+8]]:3: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 16 | ++postfix; - // CHECK:STDERR: | ^ - // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE-7]]:10: in file included here [InCppInclude] - // CHECK:STDERR: ./postfix_inc_and_dec.h:3:6: note: candidate function not viable: requires 2 arguments, but 1 was provided [CppInteropParseNote] - // CHECK:STDERR: 3 | auto operator++(Postfix& operand, int) -> Postfix&; - // CHECK:STDERR: | ^ ~~~~~~~~~~~~~~~~~~~~~ + // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE+4]]:3: error: cannot access member of interface `Core.Inc` in type `Cpp.Postfix` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: ++postfix; + // CHECK:STDERR: ^~~~~~~~~ // CHECK:STDERR: ++postfix; - // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE+8]]:3: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 25 | --postfix; - // CHECK:STDERR: | ^ - // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE-16]]:10: in file included here [InCppInclude] - // CHECK:STDERR: ./postfix_inc_and_dec.h:4:6: note: candidate function not viable: requires 2 arguments, but 1 was provided [CppInteropParseNote] - // CHECK:STDERR: 4 | auto operator--(Postfix& operand, int) -> Postfix&; - // CHECK:STDERR: | ^ ~~~~~~~~~~~~~~~~~~~~~ + // CHECK:STDERR: fail_postfix_calling_prefix.carbon:[[@LINE+4]]:3: error: cannot access member of interface `Core.Dec` in type `Cpp.Postfix` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: --postfix; + // CHECK:STDERR: ^~~~~~~~~ // CHECK:STDERR: --postfix; } @@ -230,26 +222,70 @@ import Cpp library "binary_operators.h"; fn F() { let c1: Cpp.C = Cpp.C.C(); - // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE+8]]:22: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 16 | let c2: Cpp.C = c1 + 5; - // CHECK:STDERR: | ^ - // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE-7]]:10: in file included here [InCppInclude] - // CHECK:STDERR: ./binary_operators.h:5:6: note: candidate function not viable: no known conversion from 'int' to 'C' for 2nd argument [CppInteropParseNote] - // CHECK:STDERR: 5 | auto operator+(C lhs, C rhs) -> C; - // CHECK:STDERR: | ^ ~~~~~ + // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE+4]]:19: error: cannot access member of interface `Core.AddWith(Core.IntLiteral)` in type `Cpp.C` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: let c2: Cpp.C = c1 + 5; + // CHECK:STDERR: ^~~~~~ // CHECK:STDERR: let c2: Cpp.C = c1 + 5; - // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE+8]]:21: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 25 | let c3: Cpp.C = 6 + c1; - // CHECK:STDERR: | ^ - // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE-16]]:10: in file included here [InCppInclude] - // CHECK:STDERR: ./binary_operators.h:5:6: note: candidate function not viable: no known conversion from 'int' to 'C' for 1st argument [CppInteropParseNote] - // CHECK:STDERR: 5 | auto operator+(C lhs, C rhs) -> C; - // CHECK:STDERR: | ^ ~~~~~ + // CHECK:STDERR: fail_call_with_wrong_type.carbon:[[@LINE+4]]:19: error: cannot access member of interface `Core.AddWith(Cpp.C)` in type `Core.IntLiteral` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: let c3: Cpp.C = 6 + c1; + // CHECK:STDERR: ^~~~~~ // CHECK:STDERR: let c3: Cpp.C = 6 + c1; } +// ============================================================================ +// Overload resolution failures +// ============================================================================ + +// --- fail_ambiguous.carbon + +library "[[@TEST_NAME]]"; + +import Cpp inline ''' +class C {}; +void operator+(C, char); +void operator+(C, short); +'''; + +fn Test(c: Cpp.C) { + // CHECK:STDERR: fail_ambiguous.carbon:[[@LINE+10]]:5: error: use of overloaded operator '+' is ambiguous (with operand types 'C' and 'int') [CppInteropParseError] + // CHECK:STDERR: 21 | c + 1; + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_ambiguous.carbon:[[@LINE-8]]:6: note: candidate function [CppInteropParseNote] + // CHECK:STDERR: 6 | void operator+(C, char); + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_ambiguous.carbon:[[@LINE-10]]:6: note: candidate function [CppInteropParseNote] + // CHECK:STDERR: 7 | void operator+(C, short); + // CHECK:STDERR: | ^ + // CHECK:STDERR: + c + 1; +} + +// --- fail_deleted.carbon + +library "[[@TEST_NAME]]"; + +import Cpp inline ''' +class C {}; +void operator+(C, int) = delete; +void operator+(C, void*) = delete; +'''; + +fn Test(c: Cpp.C) { + // CHECK:STDERR: fail_deleted.carbon:[[@LINE+10]]:5: error: overload resolution selected deleted operator '+' [CppInteropParseError] + // CHECK:STDERR: 21 | c + 1; + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_deleted.carbon:[[@LINE-8]]:6: note: candidate function has been explicitly deleted [CppInteropParseNote] + // CHECK:STDERR: 6 | void operator+(C, int) = delete; + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_deleted.carbon:[[@LINE-10]]:6: note: candidate function not viable: no known conversion from 'int' to 'void *' for 2nd argument [CppInteropParseNote] + // CHECK:STDERR: 7 | void operator+(C, void*) = delete; + // CHECK:STDERR: | ^ ~~~~~ + // CHECK:STDERR: + c + 1; +} + // ============================================================================ // Rewrite using the spaceship operator // ============================================================================ @@ -294,6 +330,34 @@ fn F() { //@dump-sem-ir-end } +// --- fail_rewrite_deleted.carbon + +library "[[@TEST_NAME]]"; + +import Cpp inline ''' +class B {}; +class C : public B {}; + +namespace std { class strong_ordering {}; } +auto operator<=>(C lhs, C rhs) -> std::strong_ordering = delete; +auto operator<(C lhs, B rhs) -> bool; +'''; + +fn F(c: Cpp.C) -> bool { + // Note that we mention `operator '<=>'` in the diagnostic. + // CHECK:STDERR: fail_rewrite_deleted.carbon:[[@LINE+10]]:12: error: overload resolution selected deleted operator '<=>' [CppInteropParseError] + // CHECK:STDERR: 25 | return c < c; + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_rewrite_deleted.carbon:[[@LINE-9]]:6: note: candidate function has been explicitly deleted [CppInteropParseNote] + // CHECK:STDERR: 9 | auto operator<=>(C lhs, C rhs) -> std::strong_ordering = delete; + // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_rewrite_deleted.carbon:[[@LINE-11]]:6: note: candidate function [CppInteropParseNote] + // CHECK:STDERR: 10 | auto operator<(C lhs, B rhs) -> bool; + // CHECK:STDERR: | ^ + // CHECK:STDERR: + return c < c; +} + // ============================================================================ // Rewrite using the equal operator // ============================================================================ @@ -655,9 +719,9 @@ fn F() { //@dump-sem-ir-begin let c1: Cpp.N.C = Cpp.N.C.C(); let c2: Cpp.N.C = Cpp.N.C.C(); - // CHECK:STDERR: fail_todo_import_operands_in_namespace_operator_in_global.carbon:[[@LINE+4]]:24: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 14 | let c3: Cpp.N.C = c1 + c2; - // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_todo_import_operands_in_namespace_operator_in_global.carbon:[[@LINE+4]]:21: error: cannot access member of interface `Core.AddWith(Cpp.N.C)` in type `Cpp.N.C` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: let c3: Cpp.N.C = c1 + c2; + // CHECK:STDERR: ^~~~~~~ // CHECK:STDERR: let c3: Cpp.N.C = c1 + c2; //@dump-sem-ir-end @@ -793,9 +857,9 @@ import Cpp library "not_found.h"; fn F() { let c1: Cpp.C = Cpp.C.C(); let c2: Cpp.C = Cpp.C.C(); - // CHECK:STDERR: fail_import_not_found.carbon:[[@LINE+4]]:22: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 13 | let c3: Cpp.C = c1 + c2; - // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_import_not_found.carbon:[[@LINE+4]]:19: error: cannot access member of interface `Core.AddWith(Cpp.C)` in type `Cpp.C` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: let c3: Cpp.C = c1 + c2; + // CHECK:STDERR: ^~~~~~~ // CHECK:STDERR: let c3: Cpp.C = c1 + c2; } @@ -877,54 +941,6 @@ fn F() { let result: i32 = *CreateIncomplete() + complete; } -// ============================================================================ -// Unsupported operand type in instantiation -// ============================================================================ - -// --- unsupported_in_instantiation.h - -struct Supported {}; - -template -struct Unsupported : public virtual Supported {}; -using UnsupportedAlias = Unsupported; -extern UnsupportedAlias unsupported; - -// --- fail_import_unsupported_in_instantiation_unary.carbon - -library "[[@TEST_NAME]]"; - -import Cpp library "unsupported_in_instantiation.h"; - -fn F() { - // CHECK:STDERR: fail_import_unsupported_in_instantiation_unary.carbon:[[@LINE+7]]:21: error: semantics TODO: `class with virtual bases` [SemanticsTodo] - // CHECK:STDERR: let result: i32 = -Cpp.unsupported; - // CHECK:STDERR: ^~~~~~~~~~~~~~~~ - // CHECK:STDERR: fail_import_unsupported_in_instantiation_unary.carbon:[[@LINE+4]]:21: note: while completing C++ type `Cpp.Unsupported` [InCppTypeCompletion] - // CHECK:STDERR: let result: i32 = -Cpp.unsupported; - // CHECK:STDERR: ^~~~~~~~~~~~~~~~ - // CHECK:STDERR: - let result: i32 = -Cpp.unsupported; -} - -// --- fail_import_unsupported_in_instantiation_binary.carbon - -library "[[@TEST_NAME]]"; - -import Cpp library "unsupported_in_instantiation.h"; - -fn F() { - var supported: Cpp.Supported = Cpp.Supported.Supported(); - // CHECK:STDERR: fail_import_unsupported_in_instantiation_binary.carbon:[[@LINE+7]]:21: error: semantics TODO: `class with virtual bases` [SemanticsTodo] - // CHECK:STDERR: let result: i32 = supported + Cpp.unsupported; - // CHECK:STDERR: ^~~~~~~~~~~~~~~~~~~~~~~~~~~ - // CHECK:STDERR: fail_import_unsupported_in_instantiation_binary.carbon:[[@LINE+4]]:21: note: while completing C++ type `Cpp.Unsupported` [InCppTypeCompletion] - // CHECK:STDERR: let result: i32 = supported + Cpp.unsupported; - // CHECK:STDERR: ^~~~~~~~~~~~~~~~~~~~~~~~~~~ - // CHECK:STDERR: - let result: i32 = supported + Cpp.unsupported; -} - // ============================================================================ // Indirect template instantiation // ============================================================================ @@ -947,10 +963,6 @@ fn F(x: Cpp.X) -> i32 { //@dump-sem-ir-end } -// ============================================================================ -// Indirect template instantiation error -// ============================================================================ - // --- fail_indirect_template_instantiation_error.carbon library "[[@TEST_NAME]]"; @@ -972,13 +984,33 @@ fn F(x: Cpp.X) -> i32 { // CHECK:STDERR: 25 | return x + x; // CHECK:STDERR: | ^ // CHECK:STDERR: - // CHECK:STDERR: fail_indirect_template_instantiation_error.carbon:[[@LINE+4]]:12: error: no matching function for call to '' [CppInteropParseError] - // CHECK:STDERR: 25 | return x + x; - // CHECK:STDERR: | ^ + // CHECK:STDERR: fail_indirect_template_instantiation_error.carbon:[[@LINE+4]]:10: error: cannot access member of interface `Core.AddWith(Cpp.B)` in type `Cpp.B` that does not implement that interface [MissingImplInMemberAccess] + // CHECK:STDERR: return x + x; + // CHECK:STDERR: ^~~~~ // CHECK:STDERR: return x + x; } +// ============================================================================ +// Templated operators +// ============================================================================ + +// --- templated_operator.h + +template struct X {}; +template X operator+(X, X); +using Xint = X; + +// --- templated_operator.carbon + +library "[[@TEST_NAME]]"; + +import Cpp library "templated_operator.h"; + +fn Test(x: Cpp.Xint) -> Cpp.Xint { + return x + x; +} + // ============================================================================ // Operator overloading // ============================================================================ @@ -2961,8 +2993,12 @@ fn F() { // CHECK:STDOUT: %ptr.d9e: type = ptr_type %C [concrete] // CHECK:STDOUT: %C__carbon_thunk.type: type = fn_type @C__carbon_thunk [concrete] // CHECK:STDOUT: %C__carbon_thunk: %C__carbon_thunk.type = struct_value () [concrete] +// CHECK:STDOUT: %C.cpp_operator.type.dab96a.1: type = fn_type @C.cpp_operator.1 [concrete] +// CHECK:STDOUT: %C.cpp_operator.d21c75.1: %C.cpp_operator.type.dab96a.1 = struct_value () [concrete] // CHECK:STDOUT: %operator-__carbon_thunk.type: type = fn_type @operator-__carbon_thunk [concrete] // CHECK:STDOUT: %operator-__carbon_thunk: %operator-__carbon_thunk.type = struct_value () [concrete] +// CHECK:STDOUT: %C.cpp_operator.type.dab96a.2: type = fn_type @C.cpp_operator.2 [concrete] +// CHECK:STDOUT: %C.cpp_operator.d21c75.2: %C.cpp_operator.type.dab96a.2 = struct_value () [concrete] // CHECK:STDOUT: %operator+__carbon_thunk.type: type = fn_type @operator+__carbon_thunk [concrete] // CHECK:STDOUT: %operator+__carbon_thunk: %operator+__carbon_thunk.type = struct_value () [concrete] // CHECK:STDOUT: %type_where: type = facet_type > [concrete] @@ -2983,11 +3019,29 @@ fn F() { // CHECK:STDOUT: } { // CHECK:STDOUT: // CHECK:STDOUT: } +// CHECK:STDOUT: %C.cpp_operator.decl.828f43.1: %C.cpp_operator.type.dab96a.1 = fn_decl @C.cpp_operator.1 [concrete = constants.%C.cpp_operator.d21c75.1] { +// CHECK:STDOUT: %self.patt: %pattern_type.217 = ref_binding_pattern self [concrete] +// CHECK:STDOUT: %self.param_patt: %pattern_type.217 = ref_param_pattern %self.patt, call_param0 [concrete] +// CHECK:STDOUT: +// CHECK:STDOUT: } { +// CHECK:STDOUT: %self.param: ref %C = ref_param call_param0 +// CHECK:STDOUT: %self: ref %C = ref_binding self, %self.param +// CHECK:STDOUT: +// CHECK:STDOUT: } // CHECK:STDOUT: %operator-__carbon_thunk.decl: %operator-__carbon_thunk.type = fn_decl @operator-__carbon_thunk [concrete = constants.%operator-__carbon_thunk] { // CHECK:STDOUT: // CHECK:STDOUT: } { // CHECK:STDOUT: // CHECK:STDOUT: } +// CHECK:STDOUT: %C.cpp_operator.decl.828f43.2: %C.cpp_operator.type.dab96a.2 = fn_decl @C.cpp_operator.2 [concrete = constants.%C.cpp_operator.d21c75.2] { +// CHECK:STDOUT: %self.patt: %pattern_type.217 = ref_binding_pattern self [concrete] +// CHECK:STDOUT: %self.param_patt: %pattern_type.217 = ref_param_pattern %self.patt, call_param0 [concrete] +// CHECK:STDOUT: +// CHECK:STDOUT: } { +// CHECK:STDOUT: %self.param: ref %C = ref_param call_param0 +// CHECK:STDOUT: %self: ref %C = ref_binding self, %self.param +// CHECK:STDOUT: +// CHECK:STDOUT: } // CHECK:STDOUT: %operator+__carbon_thunk.decl: %operator+__carbon_thunk.type = fn_decl @operator+__carbon_thunk [concrete = constants.%operator+__carbon_thunk] { // CHECK:STDOUT: // CHECK:STDOUT: } { @@ -3021,6 +3075,7 @@ fn F() { // CHECK:STDOUT: } // CHECK:STDOUT: %c2.var: ref %C = var %c2.var_patt // CHECK:STDOUT: %c1.ref.loc9: ref %C = name_ref c1, %c1 +// CHECK:STDOUT: %C.cpp_operator.bound.loc9: = bound_method %c1.ref.loc9, imports.%C.cpp_operator.decl.828f43.1 // CHECK:STDOUT: %.loc9_3: ref %C = splice_block %c2.var {} // CHECK:STDOUT: %addr.loc9: %ptr.d9e = addr_of %.loc9_3 // CHECK:STDOUT: %operator-__carbon_thunk.call: init %empty_tuple.type = call imports.%operator-__carbon_thunk.decl(%c1.ref.loc9, %addr.loc9) @@ -3038,6 +3093,7 @@ fn F() { // CHECK:STDOUT: %c3.var: ref %C = var %c3.var_patt // CHECK:STDOUT: %c1.ref.loc10: ref %C = name_ref c1, %c1 // CHECK:STDOUT: %c2.ref: ref %C = name_ref c2, %c2 +// CHECK:STDOUT: %C.cpp_operator.bound.loc10: = bound_method %c1.ref.loc10, imports.%C.cpp_operator.decl.828f43.2 // CHECK:STDOUT: %.loc10_3: ref %C = splice_block %c3.var {} // CHECK:STDOUT: %.loc10_24.1: %C = acquire_value %c2.ref // CHECK:STDOUT: %.loc10_24.2: ref %C = value_as_ref %.loc10_24.1 diff --git a/toolchain/lower/testdata/interop/cpp/virtual_base.carbon b/toolchain/lower/testdata/interop/cpp/virtual_base.carbon new file mode 100644 index 0000000000000..9b29436bacd22 --- /dev/null +++ b/toolchain/lower/testdata/interop/cpp/virtual_base.carbon @@ -0,0 +1,195 @@ +// Part of the Carbon Language project, under the Apache License v2.0 with LLVM +// Exceptions. See /LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/int.carbon +// +// AUTOUPDATE +// TIP: To test this file alone, run: +// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/lower/testdata/interop/cpp/virtual_base.carbon +// TIP: To dump output, run: +// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/lower/testdata/interop/cpp/virtual_base.carbon + +// --- diamond.h + +struct A { + A(); + int a; +}; + +struct B : virtual A { + B(); + int b; +}; + +struct C : virtual A { + C(); + int c; +}; + +struct D : B, C { + int d; +}; + +// Layout of D (x86_64): +// +// 0: B | 0: vptr +// 8: | 8: int B::b +// 12: (4 bytes padding) +// 16: C | 0: vptr +// 24: | 8: int C::c +// 28: int D::d +// 32: A | 0: int A::a +// 36: (4 bytes padding) +// 40: (end of D) + +// --- use_diamond.carbon + +library "[[@TEST_NAME]]"; + +import Cpp library "diamond.h"; + +fn Make() { + // This should construct a 40-byte object, using the `...C1` constructor, + // which should call the `...C2` constructors for A, B, and C. + var d: Cpp.D = Cpp.D.D(); +} + +fn AccessD(d: Cpp.D) -> i32 { + // This should read an i32 at offset 28. + return d.d; +} + +// CHECK:STDOUT: ; ModuleID = 'use_diamond.carbon' +// CHECK:STDOUT: source_filename = "use_diamond.carbon" +// CHECK:STDOUT: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128" +// CHECK:STDOUT: target triple = "x86_64-unknown-linux-gnu" +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZN1DC1Ev = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTV1D = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTT1D = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTC1D0_1B = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTI1B = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTS1B = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTI1A = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTS1A = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTC1D16_1C = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTI1C = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTS1C = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTI1D = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: $_ZTS1D = comdat any +// CHECK:STDOUT: +// CHECK:STDOUT: @_ZTV1D = linkonce_odr dso_local unnamed_addr constant { [3 x ptr], [3 x ptr] } { [3 x ptr] [ptr inttoptr (i64 32 to ptr), ptr null, ptr @_ZTI1D], [3 x ptr] [ptr inttoptr (i64 16 to ptr), ptr inttoptr (i64 -16 to ptr), ptr @_ZTI1D] }, comdat, align 8 +// CHECK:STDOUT: @_ZTT1D = linkonce_odr dso_local unnamed_addr constant [4 x ptr] [ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 0, i32 3), ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr] }, ptr @_ZTC1D0_1B, i32 0, i32 0, i32 3), ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr] }, ptr @_ZTC1D16_1C, i32 0, i32 0, i32 3), ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 1, i32 3)], comdat, align 8 +// CHECK:STDOUT: @_ZTC1D0_1B = linkonce_odr dso_local unnamed_addr constant { [3 x ptr] } { [3 x ptr] [ptr inttoptr (i64 32 to ptr), ptr null, ptr @_ZTI1B] }, comdat, align 8 +// CHECK:STDOUT: @_ZTI1B = linkonce_odr dso_local constant { ptr, ptr, i32, i32, ptr, i64 } { ptr getelementptr inbounds (ptr, ptr @_ZTVN10__cxxabiv121__vmi_class_type_infoE, i64 2), ptr @_ZTS1B, i32 0, i32 1, ptr @_ZTI1A, i64 -6141 }, comdat, align 8 +// CHECK:STDOUT: @_ZTVN10__cxxabiv121__vmi_class_type_infoE = external global [0 x ptr] +// CHECK:STDOUT: @_ZTS1B = linkonce_odr dso_local constant [3 x i8] c"1B\00", comdat, align 1 +// CHECK:STDOUT: @_ZTI1A = linkonce_odr dso_local constant { ptr, ptr } { ptr getelementptr inbounds (ptr, ptr @_ZTVN10__cxxabiv117__class_type_infoE, i64 2), ptr @_ZTS1A }, comdat, align 8 +// CHECK:STDOUT: @_ZTVN10__cxxabiv117__class_type_infoE = external global [0 x ptr] +// CHECK:STDOUT: @_ZTS1A = linkonce_odr dso_local constant [3 x i8] c"1A\00", comdat, align 1 +// CHECK:STDOUT: @_ZTC1D16_1C = linkonce_odr dso_local unnamed_addr constant { [3 x ptr] } { [3 x ptr] [ptr inttoptr (i64 16 to ptr), ptr null, ptr @_ZTI1C] }, comdat, align 8 +// CHECK:STDOUT: @_ZTI1C = linkonce_odr dso_local constant { ptr, ptr, i32, i32, ptr, i64 } { ptr getelementptr inbounds (ptr, ptr @_ZTVN10__cxxabiv121__vmi_class_type_infoE, i64 2), ptr @_ZTS1C, i32 0, i32 1, ptr @_ZTI1A, i64 -6141 }, comdat, align 8 +// CHECK:STDOUT: @_ZTS1C = linkonce_odr dso_local constant [3 x i8] c"1C\00", comdat, align 1 +// CHECK:STDOUT: @_ZTI1D = linkonce_odr dso_local constant { ptr, ptr, i32, i32, ptr, i64, ptr, i64 } { ptr getelementptr inbounds (ptr, ptr @_ZTVN10__cxxabiv121__vmi_class_type_infoE, i64 2), ptr @_ZTS1D, i32 2, i32 2, ptr @_ZTI1B, i64 2, ptr @_ZTI1C, i64 4098 }, comdat, align 8 +// CHECK:STDOUT: @_ZTS1D = linkonce_odr dso_local constant [3 x i8] c"1D\00", comdat, align 1 +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: nounwind +// CHECK:STDOUT: define void @_CMake.Main() #0 !dbg !7 { +// CHECK:STDOUT: entry: +// CHECK:STDOUT: %d.var = alloca [40 x i8], align 1, !dbg !10 +// CHECK:STDOUT: call void @llvm.lifetime.start.p0(ptr %d.var), !dbg !10 +// CHECK:STDOUT: call void @_ZN1DC1Ev.carbon_thunk(ptr %d.var), !dbg !11 +// CHECK:STDOUT: ret void, !dbg !12 +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: nounwind +// CHECK:STDOUT: define i32 @_CAccessD.Main(ptr %d) #0 !dbg !13 { +// CHECK:STDOUT: entry: +// CHECK:STDOUT: %.loc14_11.1.d = getelementptr inbounds nuw [40 x i8], ptr %d, i32 0, i32 28, !dbg !14 +// CHECK:STDOUT: %.loc14_11.2 = load i32, ptr %.loc14_11.1.d, align 4, !dbg !14 +// CHECK:STDOUT: ret i32 %.loc14_11.2, !dbg !15 +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: readwrite) +// CHECK:STDOUT: declare void @llvm.lifetime.start.p0(ptr captures(none)) #1 +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: alwaysinline mustprogress +// CHECK:STDOUT: define dso_local void @_ZN1DC1Ev.carbon_thunk(ptr %return) #2 { +// CHECK:STDOUT: entry: +// CHECK:STDOUT: %return.addr = alloca ptr, align 8 +// CHECK:STDOUT: store ptr %return, ptr %return.addr, align 8 +// CHECK:STDOUT: %0 = load ptr, ptr %return.addr, align 8 +// CHECK:STDOUT: call void @_ZN1DC1Ev(ptr nonnull align 8 dereferenceable(32) %0) +// CHECK:STDOUT: ret void +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: mustprogress noinline optnone +// CHECK:STDOUT: define linkonce_odr dso_local void @_ZN1DC1Ev(ptr nonnull align 8 dereferenceable(32) %this) unnamed_addr #3 comdat align 2 { +// CHECK:STDOUT: entry: +// CHECK:STDOUT: %this.addr = alloca ptr, align 8 +// CHECK:STDOUT: store ptr %this, ptr %this.addr, align 8 +// CHECK:STDOUT: %this1 = load ptr, ptr %this.addr, align 8 +// CHECK:STDOUT: %0 = getelementptr inbounds i8, ptr %this1, i64 32 +// CHECK:STDOUT: call void @_ZN1AC2Ev(ptr nonnull align 4 dereferenceable(4) %0) +// CHECK:STDOUT: call void @_ZN1BC2Ev(ptr nonnull align 8 dereferenceable(12) %this1, ptr getelementptr inbounds ([4 x ptr], ptr @_ZTT1D, i64 0, i64 1)) +// CHECK:STDOUT: %1 = getelementptr inbounds i8, ptr %this1, i64 16 +// CHECK:STDOUT: call void @_ZN1CC2Ev(ptr nonnull align 8 dereferenceable(12) %1, ptr getelementptr inbounds ([4 x ptr], ptr @_ZTT1D, i64 0, i64 2)) +// CHECK:STDOUT: store ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 0, i32 3), ptr %this1, align 8 +// CHECK:STDOUT: %add.ptr = getelementptr inbounds i8, ptr %this1, i64 16 +// CHECK:STDOUT: store ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 1, i32 3), ptr %add.ptr, align 8 +// CHECK:STDOUT: ret void +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: declare void @_ZN1AC2Ev(ptr nonnull align 4 dereferenceable(4)) unnamed_addr #4 +// CHECK:STDOUT: +// CHECK:STDOUT: declare void @_ZN1BC2Ev(ptr nonnull align 8 dereferenceable(12), ptr) unnamed_addr #4 +// CHECK:STDOUT: +// CHECK:STDOUT: declare void @_ZN1CC2Ev(ptr nonnull align 8 dereferenceable(12), ptr) unnamed_addr #4 +// CHECK:STDOUT: +// CHECK:STDOUT: ; uselistorder directives +// CHECK:STDOUT: uselistorder ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 0, i32 3), { 1, 0 } +// CHECK:STDOUT: uselistorder ptr getelementptr inbounds inrange(-24, 0) ({ [3 x ptr], [3 x ptr] }, ptr @_ZTV1D, i32 0, i32 1, i32 3), { 1, 0 } +// CHECK:STDOUT: uselistorder ptr getelementptr inbounds (ptr, ptr @_ZTVN10__cxxabiv121__vmi_class_type_infoE, i64 2), { 2, 1, 0 } +// CHECK:STDOUT: uselistorder ptr @_ZTI1B, { 1, 0 } +// CHECK:STDOUT: uselistorder ptr @_ZTI1A, { 1, 0 } +// CHECK:STDOUT: uselistorder ptr @_ZTI1C, { 1, 0 } +// CHECK:STDOUT: uselistorder ptr @_ZTI1D, { 1, 0 } +// CHECK:STDOUT: +// CHECK:STDOUT: attributes #0 = { nounwind } +// CHECK:STDOUT: attributes #1 = { nocallback nofree nosync nounwind willreturn memory(argmem: readwrite) } +// CHECK:STDOUT: attributes #2 = { alwaysinline mustprogress "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="0" "target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" } +// CHECK:STDOUT: attributes #3 = { mustprogress noinline optnone "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="0" "target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" } +// CHECK:STDOUT: attributes #4 = { "no-trapping-math"="true" "stack-protector-buffer-size"="0" "target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" } +// CHECK:STDOUT: +// CHECK:STDOUT: !llvm.module.flags = !{!0, !1, !2, !3, !4} +// CHECK:STDOUT: !llvm.dbg.cu = !{!5} +// CHECK:STDOUT: +// CHECK:STDOUT: !0 = !{i32 7, !"Dwarf Version", i32 5} +// CHECK:STDOUT: !1 = !{i32 2, !"Debug Info Version", i32 3} +// CHECK:STDOUT: !2 = !{i32 1, !"wchar_size", i32 4} +// CHECK:STDOUT: !3 = !{i32 8, !"PIC Level", i32 0} +// CHECK:STDOUT: !4 = !{i32 7, !"PIE Level", i32 2} +// CHECK:STDOUT: !5 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !6, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug) +// CHECK:STDOUT: !6 = !DIFile(filename: "use_diamond.carbon", directory: "") +// CHECK:STDOUT: !7 = distinct !DISubprogram(name: "Make", linkageName: "_CMake.Main", scope: null, file: !6, line: 6, type: !8, spFlags: DISPFlagDefinition, unit: !5) +// CHECK:STDOUT: !8 = !DISubroutineType(types: !9) +// CHECK:STDOUT: !9 = !{} +// CHECK:STDOUT: !10 = !DILocation(line: 9, column: 3, scope: !7) +// CHECK:STDOUT: !11 = !DILocation(line: 9, column: 18, scope: !7) +// CHECK:STDOUT: !12 = !DILocation(line: 6, column: 1, scope: !7) +// CHECK:STDOUT: !13 = distinct !DISubprogram(name: "AccessD", linkageName: "_CAccessD.Main", scope: null, file: !6, line: 12, type: !8, spFlags: DISPFlagDefinition, unit: !5) +// CHECK:STDOUT: !14 = !DILocation(line: 14, column: 10, scope: !13) +// CHECK:STDOUT: !15 = !DILocation(line: 14, column: 3, scope: !13)