1 | //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file provides Sema routines for C++ overloading. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "clang/AST/ASTContext.h" |
14 | #include "clang/AST/ASTLambda.h" |
15 | #include "clang/AST/CXXInheritance.h" |
16 | #include "clang/AST/DeclCXX.h" |
17 | #include "clang/AST/DeclObjC.h" |
18 | #include "clang/AST/DependenceFlags.h" |
19 | #include "clang/AST/Expr.h" |
20 | #include "clang/AST/ExprCXX.h" |
21 | #include "clang/AST/ExprObjC.h" |
22 | #include "clang/AST/Type.h" |
23 | #include "clang/AST/TypeOrdering.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/DiagnosticOptions.h" |
26 | #include "clang/Basic/OperatorKinds.h" |
27 | #include "clang/Basic/PartialDiagnostic.h" |
28 | #include "clang/Basic/SourceManager.h" |
29 | #include "clang/Basic/TargetInfo.h" |
30 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
31 | #include "clang/Sema/Initialization.h" |
32 | #include "clang/Sema/Lookup.h" |
33 | #include "clang/Sema/Overload.h" |
34 | #include "clang/Sema/SemaInternal.h" |
35 | #include "clang/Sema/Template.h" |
36 | #include "clang/Sema/TemplateDeduction.h" |
37 | #include "llvm/ADT/DenseSet.h" |
38 | #include "llvm/ADT/STLExtras.h" |
39 | #include "llvm/ADT/SmallPtrSet.h" |
40 | #include "llvm/ADT/SmallString.h" |
41 | #include "llvm/ADT/SmallVector.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include <algorithm> |
44 | #include <cstddef> |
45 | #include <cstdlib> |
46 | #include <optional> |
47 | |
48 | using namespace clang; |
49 | using namespace sema; |
50 | |
51 | using AllowedExplicit = Sema::AllowedExplicit; |
52 | |
53 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { |
54 | return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) { |
55 | return P->hasAttr<PassObjectSizeAttr>(); |
56 | }); |
57 | } |
58 | |
59 | /// A convenience routine for creating a decayed reference to a function. |
60 | static ExprResult CreateFunctionRefExpr( |
61 | Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, |
62 | bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), |
63 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { |
64 | if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc)) |
65 | return ExprError(); |
66 | // If FoundDecl is different from Fn (such as if one is a template |
67 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
68 | // called on both. |
69 | // FIXME: This would be more comprehensively addressed by modifying |
70 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
71 | // being used. |
72 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) |
73 | return ExprError(); |
74 | DeclRefExpr *DRE = new (S.Context) |
75 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); |
76 | if (HadMultipleCandidates) |
77 | DRE->setHadMultipleCandidates(true); |
78 | |
79 | S.MarkDeclRefReferenced(E: DRE, Base); |
80 | if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { |
81 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { |
82 | S.ResolveExceptionSpec(Loc, FPT: FPT); |
83 | DRE->setType(Fn->getType()); |
84 | } |
85 | } |
86 | return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(DRE->getType()), |
87 | CK: CK_FunctionToPointerDecay); |
88 | } |
89 | |
90 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
91 | bool InOverloadResolution, |
92 | StandardConversionSequence &SCS, |
93 | bool CStyle, |
94 | bool AllowObjCWritebackConversion); |
95 | |
96 | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
97 | QualType &ToType, |
98 | bool InOverloadResolution, |
99 | StandardConversionSequence &SCS, |
100 | bool CStyle); |
101 | static OverloadingResult |
102 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
103 | UserDefinedConversionSequence& User, |
104 | OverloadCandidateSet& Conversions, |
105 | AllowedExplicit AllowExplicit, |
106 | bool AllowObjCConversionOnExplicit); |
107 | |
108 | static ImplicitConversionSequence::CompareKind |
109 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
110 | const StandardConversionSequence& SCS1, |
111 | const StandardConversionSequence& SCS2); |
112 | |
113 | static ImplicitConversionSequence::CompareKind |
114 | CompareQualificationConversions(Sema &S, |
115 | const StandardConversionSequence& SCS1, |
116 | const StandardConversionSequence& SCS2); |
117 | |
118 | static ImplicitConversionSequence::CompareKind |
119 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
120 | const StandardConversionSequence& SCS1, |
121 | const StandardConversionSequence& SCS2); |
122 | |
123 | /// GetConversionRank - Retrieve the implicit conversion rank |
124 | /// corresponding to the given implicit conversion kind. |
125 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { |
126 | static const ImplicitConversionRank |
127 | Rank[] = { |
128 | ICR_Exact_Match, |
129 | ICR_Exact_Match, |
130 | ICR_Exact_Match, |
131 | ICR_Exact_Match, |
132 | ICR_Exact_Match, |
133 | ICR_Exact_Match, |
134 | ICR_Promotion, |
135 | ICR_Promotion, |
136 | ICR_Promotion, |
137 | ICR_Conversion, |
138 | ICR_Conversion, |
139 | ICR_Conversion, |
140 | ICR_Conversion, |
141 | ICR_Conversion, |
142 | ICR_Conversion, |
143 | ICR_Conversion, |
144 | ICR_Conversion, |
145 | ICR_Conversion, |
146 | ICR_Conversion, |
147 | ICR_Conversion, |
148 | ICR_Conversion, |
149 | ICR_OCL_Scalar_Widening, |
150 | ICR_Complex_Real_Conversion, |
151 | ICR_Conversion, |
152 | ICR_Conversion, |
153 | ICR_Writeback_Conversion, |
154 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- |
155 | // it was omitted by the patch that added |
156 | // ICK_Zero_Event_Conversion |
157 | ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- |
158 | // it was omitted by the patch that added |
159 | // ICK_Zero_Queue_Conversion |
160 | ICR_C_Conversion, |
161 | ICR_C_Conversion_Extension, |
162 | ICR_Conversion, |
163 | }; |
164 | static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); |
165 | return Rank[(int)Kind]; |
166 | } |
167 | |
168 | /// GetImplicitConversionName - Return the name of this kind of |
169 | /// implicit conversion. |
170 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { |
171 | static const char* const Name[] = { |
172 | "No conversion" , |
173 | "Lvalue-to-rvalue" , |
174 | "Array-to-pointer" , |
175 | "Function-to-pointer" , |
176 | "Function pointer conversion" , |
177 | "Qualification" , |
178 | "Integral promotion" , |
179 | "Floating point promotion" , |
180 | "Complex promotion" , |
181 | "Integral conversion" , |
182 | "Floating conversion" , |
183 | "Complex conversion" , |
184 | "Floating-integral conversion" , |
185 | "Pointer conversion" , |
186 | "Pointer-to-member conversion" , |
187 | "Boolean conversion" , |
188 | "Compatible-types conversion" , |
189 | "Derived-to-base conversion" , |
190 | "Vector conversion" , |
191 | "SVE Vector conversion" , |
192 | "RVV Vector conversion" , |
193 | "Vector splat" , |
194 | "Complex-real conversion" , |
195 | "Block Pointer conversion" , |
196 | "Transparent Union Conversion" , |
197 | "Writeback conversion" , |
198 | "OpenCL Zero Event Conversion" , |
199 | "OpenCL Zero Queue Conversion" , |
200 | "C specific type conversion" , |
201 | "Incompatible pointer conversion" , |
202 | "Fixed point conversion" , |
203 | }; |
204 | static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); |
205 | return Name[Kind]; |
206 | } |
207 | |
208 | /// StandardConversionSequence - Set the standard conversion |
209 | /// sequence to the identity conversion. |
210 | void StandardConversionSequence::setAsIdentityConversion() { |
211 | First = ICK_Identity; |
212 | Second = ICK_Identity; |
213 | Third = ICK_Identity; |
214 | DeprecatedStringLiteralToCharPtr = false; |
215 | QualificationIncludesObjCLifetime = false; |
216 | ReferenceBinding = false; |
217 | DirectBinding = false; |
218 | IsLvalueReference = true; |
219 | BindsToFunctionLvalue = false; |
220 | BindsToRvalue = false; |
221 | BindsImplicitObjectArgumentWithoutRefQualifier = false; |
222 | ObjCLifetimeConversionBinding = false; |
223 | CopyConstructor = nullptr; |
224 | } |
225 | |
226 | /// getRank - Retrieve the rank of this standard conversion sequence |
227 | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the |
228 | /// implicit conversions. |
229 | ImplicitConversionRank StandardConversionSequence::getRank() const { |
230 | ImplicitConversionRank Rank = ICR_Exact_Match; |
231 | if (GetConversionRank(Kind: First) > Rank) |
232 | Rank = GetConversionRank(Kind: First); |
233 | if (GetConversionRank(Kind: Second) > Rank) |
234 | Rank = GetConversionRank(Kind: Second); |
235 | if (GetConversionRank(Kind: Third) > Rank) |
236 | Rank = GetConversionRank(Kind: Third); |
237 | return Rank; |
238 | } |
239 | |
240 | /// isPointerConversionToBool - Determines whether this conversion is |
241 | /// a conversion of a pointer or pointer-to-member to bool. This is |
242 | /// used as part of the ranking of standard conversion sequences |
243 | /// (C++ 13.3.3.2p4). |
244 | bool StandardConversionSequence::isPointerConversionToBool() const { |
245 | // Note that FromType has not necessarily been transformed by the |
246 | // array-to-pointer or function-to-pointer implicit conversions, so |
247 | // check for their presence as well as checking whether FromType is |
248 | // a pointer. |
249 | if (getToType(Idx: 1)->isBooleanType() && |
250 | (getFromType()->isPointerType() || |
251 | getFromType()->isMemberPointerType() || |
252 | getFromType()->isObjCObjectPointerType() || |
253 | getFromType()->isBlockPointerType() || |
254 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) |
255 | return true; |
256 | |
257 | return false; |
258 | } |
259 | |
260 | /// isPointerConversionToVoidPointer - Determines whether this |
261 | /// conversion is a conversion of a pointer to a void pointer. This is |
262 | /// used as part of the ranking of standard conversion sequences (C++ |
263 | /// 13.3.3.2p4). |
264 | bool |
265 | StandardConversionSequence:: |
266 | isPointerConversionToVoidPointer(ASTContext& Context) const { |
267 | QualType FromType = getFromType(); |
268 | QualType ToType = getToType(Idx: 1); |
269 | |
270 | // Note that FromType has not necessarily been transformed by the |
271 | // array-to-pointer implicit conversion, so check for its presence |
272 | // and redo the conversion to get a pointer. |
273 | if (First == ICK_Array_To_Pointer) |
274 | FromType = Context.getArrayDecayedType(T: FromType); |
275 | |
276 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) |
277 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) |
278 | return ToPtrType->getPointeeType()->isVoidType(); |
279 | |
280 | return false; |
281 | } |
282 | |
283 | /// Skip any implicit casts which could be either part of a narrowing conversion |
284 | /// or after one in an implicit conversion. |
285 | static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, |
286 | const Expr *Converted) { |
287 | // We can have cleanups wrapping the converted expression; these need to be |
288 | // preserved so that destructors run if necessary. |
289 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) { |
290 | Expr *Inner = |
291 | const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); |
292 | return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(), |
293 | objects: EWC->getObjects()); |
294 | } |
295 | |
296 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) { |
297 | switch (ICE->getCastKind()) { |
298 | case CK_NoOp: |
299 | case CK_IntegralCast: |
300 | case CK_IntegralToBoolean: |
301 | case CK_IntegralToFloating: |
302 | case CK_BooleanToSignedIntegral: |
303 | case CK_FloatingToIntegral: |
304 | case CK_FloatingToBoolean: |
305 | case CK_FloatingCast: |
306 | Converted = ICE->getSubExpr(); |
307 | continue; |
308 | |
309 | default: |
310 | return Converted; |
311 | } |
312 | } |
313 | |
314 | return Converted; |
315 | } |
316 | |
317 | /// Check if this standard conversion sequence represents a narrowing |
318 | /// conversion, according to C++11 [dcl.init.list]p7. |
319 | /// |
320 | /// \param Ctx The AST context. |
321 | /// \param Converted The result of applying this standard conversion sequence. |
322 | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the |
323 | /// value of the expression prior to the narrowing conversion. |
324 | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the |
325 | /// type of the expression prior to the narrowing conversion. |
326 | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions |
327 | /// from floating point types to integral types should be ignored. |
328 | NarrowingKind StandardConversionSequence::getNarrowingKind( |
329 | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, |
330 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { |
331 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++" ); |
332 | |
333 | // C++11 [dcl.init.list]p7: |
334 | // A narrowing conversion is an implicit conversion ... |
335 | QualType FromType = getToType(Idx: 0); |
336 | QualType ToType = getToType(Idx: 1); |
337 | |
338 | // A conversion to an enumeration type is narrowing if the conversion to |
339 | // the underlying type is narrowing. This only arises for expressions of |
340 | // the form 'Enum{init}'. |
341 | if (auto *ET = ToType->getAs<EnumType>()) |
342 | ToType = ET->getDecl()->getIntegerType(); |
343 | |
344 | switch (Second) { |
345 | // 'bool' is an integral type; dispatch to the right place to handle it. |
346 | case ICK_Boolean_Conversion: |
347 | if (FromType->isRealFloatingType()) |
348 | goto FloatingIntegralConversion; |
349 | if (FromType->isIntegralOrUnscopedEnumerationType()) |
350 | goto IntegralConversion; |
351 | // -- from a pointer type or pointer-to-member type to bool, or |
352 | return NK_Type_Narrowing; |
353 | |
354 | // -- from a floating-point type to an integer type, or |
355 | // |
356 | // -- from an integer type or unscoped enumeration type to a floating-point |
357 | // type, except where the source is a constant expression and the actual |
358 | // value after conversion will fit into the target type and will produce |
359 | // the original value when converted back to the original type, or |
360 | case ICK_Floating_Integral: |
361 | FloatingIntegralConversion: |
362 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { |
363 | return NK_Type_Narrowing; |
364 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
365 | ToType->isRealFloatingType()) { |
366 | if (IgnoreFloatToIntegralConversion) |
367 | return NK_Not_Narrowing; |
368 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
369 | assert(Initializer && "Unknown conversion expression" ); |
370 | |
371 | // If it's value-dependent, we can't tell whether it's narrowing. |
372 | if (Initializer->isValueDependent()) |
373 | return NK_Dependent_Narrowing; |
374 | |
375 | if (std::optional<llvm::APSInt> IntConstantValue = |
376 | Initializer->getIntegerConstantExpr(Ctx)) { |
377 | // Convert the integer to the floating type. |
378 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType)); |
379 | Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(), |
380 | RM: llvm::APFloat::rmNearestTiesToEven); |
381 | // And back. |
382 | llvm::APSInt ConvertedValue = *IntConstantValue; |
383 | bool ignored; |
384 | Result.convertToInteger(Result&: ConvertedValue, |
385 | RM: llvm::APFloat::rmTowardZero, IsExact: &ignored); |
386 | // If the resulting value is different, this was a narrowing conversion. |
387 | if (*IntConstantValue != ConvertedValue) { |
388 | ConstantValue = APValue(*IntConstantValue); |
389 | ConstantType = Initializer->getType(); |
390 | return NK_Constant_Narrowing; |
391 | } |
392 | } else { |
393 | // Variables are always narrowings. |
394 | return NK_Variable_Narrowing; |
395 | } |
396 | } |
397 | return NK_Not_Narrowing; |
398 | |
399 | // -- from long double to double or float, or from double to float, except |
400 | // where the source is a constant expression and the actual value after |
401 | // conversion is within the range of values that can be represented (even |
402 | // if it cannot be represented exactly), or |
403 | case ICK_Floating_Conversion: |
404 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && |
405 | Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) { |
406 | // FromType is larger than ToType. |
407 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
408 | |
409 | // If it's value-dependent, we can't tell whether it's narrowing. |
410 | if (Initializer->isValueDependent()) |
411 | return NK_Dependent_Narrowing; |
412 | |
413 | if (Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)) { |
414 | // Constant! |
415 | assert(ConstantValue.isFloat()); |
416 | llvm::APFloat FloatVal = ConstantValue.getFloat(); |
417 | // Convert the source value into the target type. |
418 | bool ignored; |
419 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( |
420 | ToSemantics: Ctx.getFloatTypeSemantics(T: ToType), |
421 | RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored); |
422 | // If there was no overflow, the source value is within the range of |
423 | // values that can be represented. |
424 | if (ConvertStatus & llvm::APFloat::opOverflow) { |
425 | ConstantType = Initializer->getType(); |
426 | return NK_Constant_Narrowing; |
427 | } |
428 | } else { |
429 | return NK_Variable_Narrowing; |
430 | } |
431 | } |
432 | return NK_Not_Narrowing; |
433 | |
434 | // -- from an integer type or unscoped enumeration type to an integer type |
435 | // that cannot represent all the values of the original type, except where |
436 | // the source is a constant expression and the actual value after |
437 | // conversion will fit into the target type and will produce the original |
438 | // value when converted back to the original type. |
439 | case ICK_Integral_Conversion: |
440 | IntegralConversion: { |
441 | assert(FromType->isIntegralOrUnscopedEnumerationType()); |
442 | assert(ToType->isIntegralOrUnscopedEnumerationType()); |
443 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); |
444 | const unsigned FromWidth = Ctx.getIntWidth(T: FromType); |
445 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); |
446 | const unsigned ToWidth = Ctx.getIntWidth(T: ToType); |
447 | |
448 | if (FromWidth > ToWidth || |
449 | (FromWidth == ToWidth && FromSigned != ToSigned) || |
450 | (FromSigned && !ToSigned)) { |
451 | // Not all values of FromType can be represented in ToType. |
452 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
453 | |
454 | // If it's value-dependent, we can't tell whether it's narrowing. |
455 | if (Initializer->isValueDependent()) |
456 | return NK_Dependent_Narrowing; |
457 | |
458 | std::optional<llvm::APSInt> OptInitializerValue; |
459 | if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { |
460 | // Such conversions on variables are always narrowing. |
461 | return NK_Variable_Narrowing; |
462 | } |
463 | llvm::APSInt &InitializerValue = *OptInitializerValue; |
464 | bool Narrowing = false; |
465 | if (FromWidth < ToWidth) { |
466 | // Negative -> unsigned is narrowing. Otherwise, more bits is never |
467 | // narrowing. |
468 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) |
469 | Narrowing = true; |
470 | } else { |
471 | // Add a bit to the InitializerValue so we don't have to worry about |
472 | // signed vs. unsigned comparisons. |
473 | InitializerValue = InitializerValue.extend( |
474 | width: InitializerValue.getBitWidth() + 1); |
475 | // Convert the initializer to and from the target width and signed-ness. |
476 | llvm::APSInt ConvertedValue = InitializerValue; |
477 | ConvertedValue = ConvertedValue.trunc(width: ToWidth); |
478 | ConvertedValue.setIsSigned(ToSigned); |
479 | ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth()); |
480 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); |
481 | // If the result is different, this was a narrowing conversion. |
482 | if (ConvertedValue != InitializerValue) |
483 | Narrowing = true; |
484 | } |
485 | if (Narrowing) { |
486 | ConstantType = Initializer->getType(); |
487 | ConstantValue = APValue(InitializerValue); |
488 | return NK_Constant_Narrowing; |
489 | } |
490 | } |
491 | return NK_Not_Narrowing; |
492 | } |
493 | |
494 | default: |
495 | // Other kinds of conversions are not narrowings. |
496 | return NK_Not_Narrowing; |
497 | } |
498 | } |
499 | |
500 | /// dump - Print this standard conversion sequence to standard |
501 | /// error. Useful for debugging overloading issues. |
502 | LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { |
503 | raw_ostream &OS = llvm::errs(); |
504 | bool PrintedSomething = false; |
505 | if (First != ICK_Identity) { |
506 | OS << GetImplicitConversionName(Kind: First); |
507 | PrintedSomething = true; |
508 | } |
509 | |
510 | if (Second != ICK_Identity) { |
511 | if (PrintedSomething) { |
512 | OS << " -> " ; |
513 | } |
514 | OS << GetImplicitConversionName(Kind: Second); |
515 | |
516 | if (CopyConstructor) { |
517 | OS << " (by copy constructor)" ; |
518 | } else if (DirectBinding) { |
519 | OS << " (direct reference binding)" ; |
520 | } else if (ReferenceBinding) { |
521 | OS << " (reference binding)" ; |
522 | } |
523 | PrintedSomething = true; |
524 | } |
525 | |
526 | if (Third != ICK_Identity) { |
527 | if (PrintedSomething) { |
528 | OS << " -> " ; |
529 | } |
530 | OS << GetImplicitConversionName(Kind: Third); |
531 | PrintedSomething = true; |
532 | } |
533 | |
534 | if (!PrintedSomething) { |
535 | OS << "No conversions required" ; |
536 | } |
537 | } |
538 | |
539 | /// dump - Print this user-defined conversion sequence to standard |
540 | /// error. Useful for debugging overloading issues. |
541 | void UserDefinedConversionSequence::dump() const { |
542 | raw_ostream &OS = llvm::errs(); |
543 | if (Before.First || Before.Second || Before.Third) { |
544 | Before.dump(); |
545 | OS << " -> " ; |
546 | } |
547 | if (ConversionFunction) |
548 | OS << '\'' << *ConversionFunction << '\''; |
549 | else |
550 | OS << "aggregate initialization" ; |
551 | if (After.First || After.Second || After.Third) { |
552 | OS << " -> " ; |
553 | After.dump(); |
554 | } |
555 | } |
556 | |
557 | /// dump - Print this implicit conversion sequence to standard |
558 | /// error. Useful for debugging overloading issues. |
559 | void ImplicitConversionSequence::dump() const { |
560 | raw_ostream &OS = llvm::errs(); |
561 | if (hasInitializerListContainerType()) |
562 | OS << "Worst list element conversion: " ; |
563 | switch (ConversionKind) { |
564 | case StandardConversion: |
565 | OS << "Standard conversion: " ; |
566 | Standard.dump(); |
567 | break; |
568 | case UserDefinedConversion: |
569 | OS << "User-defined conversion: " ; |
570 | UserDefined.dump(); |
571 | break; |
572 | case EllipsisConversion: |
573 | OS << "Ellipsis conversion" ; |
574 | break; |
575 | case AmbiguousConversion: |
576 | OS << "Ambiguous conversion" ; |
577 | break; |
578 | case BadConversion: |
579 | OS << "Bad conversion" ; |
580 | break; |
581 | } |
582 | |
583 | OS << "\n" ; |
584 | } |
585 | |
586 | void AmbiguousConversionSequence::construct() { |
587 | new (&conversions()) ConversionSet(); |
588 | } |
589 | |
590 | void AmbiguousConversionSequence::destruct() { |
591 | conversions().~ConversionSet(); |
592 | } |
593 | |
594 | void |
595 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { |
596 | FromTypePtr = O.FromTypePtr; |
597 | ToTypePtr = O.ToTypePtr; |
598 | new (&conversions()) ConversionSet(O.conversions()); |
599 | } |
600 | |
601 | namespace { |
602 | // Structure used by DeductionFailureInfo to store |
603 | // template argument information. |
604 | struct DFIArguments { |
605 | TemplateArgument FirstArg; |
606 | TemplateArgument SecondArg; |
607 | }; |
608 | // Structure used by DeductionFailureInfo to store |
609 | // template parameter and template argument information. |
610 | struct DFIParamWithArguments : DFIArguments { |
611 | TemplateParameter Param; |
612 | }; |
613 | // Structure used by DeductionFailureInfo to store template argument |
614 | // information and the index of the problematic call argument. |
615 | struct DFIDeducedMismatchArgs : DFIArguments { |
616 | TemplateArgumentList *TemplateArgs; |
617 | unsigned CallArgIndex; |
618 | }; |
619 | // Structure used by DeductionFailureInfo to store information about |
620 | // unsatisfied constraints. |
621 | struct CNSInfo { |
622 | TemplateArgumentList *TemplateArgs; |
623 | ConstraintSatisfaction Satisfaction; |
624 | }; |
625 | } |
626 | |
627 | /// Convert from Sema's representation of template deduction information |
628 | /// to the form used in overload-candidate information. |
629 | DeductionFailureInfo |
630 | clang::MakeDeductionFailureInfo(ASTContext &Context, |
631 | TemplateDeductionResult TDK, |
632 | TemplateDeductionInfo &Info) { |
633 | DeductionFailureInfo Result; |
634 | Result.Result = static_cast<unsigned>(TDK); |
635 | Result.HasDiagnostic = false; |
636 | switch (TDK) { |
637 | case TemplateDeductionResult::Invalid: |
638 | case TemplateDeductionResult::InstantiationDepth: |
639 | case TemplateDeductionResult::TooManyArguments: |
640 | case TemplateDeductionResult::TooFewArguments: |
641 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
642 | case TemplateDeductionResult::CUDATargetMismatch: |
643 | Result.Data = nullptr; |
644 | break; |
645 | |
646 | case TemplateDeductionResult::Incomplete: |
647 | case TemplateDeductionResult::InvalidExplicitArguments: |
648 | Result.Data = Info.Param.getOpaqueValue(); |
649 | break; |
650 | |
651 | case TemplateDeductionResult::DeducedMismatch: |
652 | case TemplateDeductionResult::DeducedMismatchNested: { |
653 | // FIXME: Should allocate from normal heap so that we can free this later. |
654 | auto *Saved = new (Context) DFIDeducedMismatchArgs; |
655 | Saved->FirstArg = Info.FirstArg; |
656 | Saved->SecondArg = Info.SecondArg; |
657 | Saved->TemplateArgs = Info.takeSugared(); |
658 | Saved->CallArgIndex = Info.CallArgIndex; |
659 | Result.Data = Saved; |
660 | break; |
661 | } |
662 | |
663 | case TemplateDeductionResult::NonDeducedMismatch: { |
664 | // FIXME: Should allocate from normal heap so that we can free this later. |
665 | DFIArguments *Saved = new (Context) DFIArguments; |
666 | Saved->FirstArg = Info.FirstArg; |
667 | Saved->SecondArg = Info.SecondArg; |
668 | Result.Data = Saved; |
669 | break; |
670 | } |
671 | |
672 | case TemplateDeductionResult::IncompletePack: |
673 | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. |
674 | case TemplateDeductionResult::Inconsistent: |
675 | case TemplateDeductionResult::Underqualified: { |
676 | // FIXME: Should allocate from normal heap so that we can free this later. |
677 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; |
678 | Saved->Param = Info.Param; |
679 | Saved->FirstArg = Info.FirstArg; |
680 | Saved->SecondArg = Info.SecondArg; |
681 | Result.Data = Saved; |
682 | break; |
683 | } |
684 | |
685 | case TemplateDeductionResult::SubstitutionFailure: |
686 | Result.Data = Info.takeSugared(); |
687 | if (Info.hasSFINAEDiagnostic()) { |
688 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( |
689 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); |
690 | Info.takeSFINAEDiagnostic(PD&: *Diag); |
691 | Result.HasDiagnostic = true; |
692 | } |
693 | break; |
694 | |
695 | case TemplateDeductionResult::ConstraintsNotSatisfied: { |
696 | CNSInfo *Saved = new (Context) CNSInfo; |
697 | Saved->TemplateArgs = Info.takeSugared(); |
698 | Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; |
699 | Result.Data = Saved; |
700 | break; |
701 | } |
702 | |
703 | case TemplateDeductionResult::Success: |
704 | case TemplateDeductionResult::NonDependentConversionFailure: |
705 | case TemplateDeductionResult::AlreadyDiagnosed: |
706 | llvm_unreachable("not a deduction failure" ); |
707 | } |
708 | |
709 | return Result; |
710 | } |
711 | |
712 | void DeductionFailureInfo::Destroy() { |
713 | switch (static_cast<TemplateDeductionResult>(Result)) { |
714 | case TemplateDeductionResult::Success: |
715 | case TemplateDeductionResult::Invalid: |
716 | case TemplateDeductionResult::InstantiationDepth: |
717 | case TemplateDeductionResult::Incomplete: |
718 | case TemplateDeductionResult::TooManyArguments: |
719 | case TemplateDeductionResult::TooFewArguments: |
720 | case TemplateDeductionResult::InvalidExplicitArguments: |
721 | case TemplateDeductionResult::CUDATargetMismatch: |
722 | case TemplateDeductionResult::NonDependentConversionFailure: |
723 | break; |
724 | |
725 | case TemplateDeductionResult::IncompletePack: |
726 | case TemplateDeductionResult::Inconsistent: |
727 | case TemplateDeductionResult::Underqualified: |
728 | case TemplateDeductionResult::DeducedMismatch: |
729 | case TemplateDeductionResult::DeducedMismatchNested: |
730 | case TemplateDeductionResult::NonDeducedMismatch: |
731 | // FIXME: Destroy the data? |
732 | Data = nullptr; |
733 | break; |
734 | |
735 | case TemplateDeductionResult::SubstitutionFailure: |
736 | // FIXME: Destroy the template argument list? |
737 | Data = nullptr; |
738 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
739 | Diag->~PartialDiagnosticAt(); |
740 | HasDiagnostic = false; |
741 | } |
742 | break; |
743 | |
744 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
745 | // FIXME: Destroy the template argument list? |
746 | Data = nullptr; |
747 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
748 | Diag->~PartialDiagnosticAt(); |
749 | HasDiagnostic = false; |
750 | } |
751 | break; |
752 | |
753 | // Unhandled |
754 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
755 | case TemplateDeductionResult::AlreadyDiagnosed: |
756 | break; |
757 | } |
758 | } |
759 | |
760 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { |
761 | if (HasDiagnostic) |
762 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); |
763 | return nullptr; |
764 | } |
765 | |
766 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { |
767 | switch (static_cast<TemplateDeductionResult>(Result)) { |
768 | case TemplateDeductionResult::Success: |
769 | case TemplateDeductionResult::Invalid: |
770 | case TemplateDeductionResult::InstantiationDepth: |
771 | case TemplateDeductionResult::TooManyArguments: |
772 | case TemplateDeductionResult::TooFewArguments: |
773 | case TemplateDeductionResult::SubstitutionFailure: |
774 | case TemplateDeductionResult::DeducedMismatch: |
775 | case TemplateDeductionResult::DeducedMismatchNested: |
776 | case TemplateDeductionResult::NonDeducedMismatch: |
777 | case TemplateDeductionResult::CUDATargetMismatch: |
778 | case TemplateDeductionResult::NonDependentConversionFailure: |
779 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
780 | return TemplateParameter(); |
781 | |
782 | case TemplateDeductionResult::Incomplete: |
783 | case TemplateDeductionResult::InvalidExplicitArguments: |
784 | return TemplateParameter::getFromOpaqueValue(VP: Data); |
785 | |
786 | case TemplateDeductionResult::IncompletePack: |
787 | case TemplateDeductionResult::Inconsistent: |
788 | case TemplateDeductionResult::Underqualified: |
789 | return static_cast<DFIParamWithArguments*>(Data)->Param; |
790 | |
791 | // Unhandled |
792 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
793 | case TemplateDeductionResult::AlreadyDiagnosed: |
794 | break; |
795 | } |
796 | |
797 | return TemplateParameter(); |
798 | } |
799 | |
800 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { |
801 | switch (static_cast<TemplateDeductionResult>(Result)) { |
802 | case TemplateDeductionResult::Success: |
803 | case TemplateDeductionResult::Invalid: |
804 | case TemplateDeductionResult::InstantiationDepth: |
805 | case TemplateDeductionResult::TooManyArguments: |
806 | case TemplateDeductionResult::TooFewArguments: |
807 | case TemplateDeductionResult::Incomplete: |
808 | case TemplateDeductionResult::IncompletePack: |
809 | case TemplateDeductionResult::InvalidExplicitArguments: |
810 | case TemplateDeductionResult::Inconsistent: |
811 | case TemplateDeductionResult::Underqualified: |
812 | case TemplateDeductionResult::NonDeducedMismatch: |
813 | case TemplateDeductionResult::CUDATargetMismatch: |
814 | case TemplateDeductionResult::NonDependentConversionFailure: |
815 | return nullptr; |
816 | |
817 | case TemplateDeductionResult::DeducedMismatch: |
818 | case TemplateDeductionResult::DeducedMismatchNested: |
819 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; |
820 | |
821 | case TemplateDeductionResult::SubstitutionFailure: |
822 | return static_cast<TemplateArgumentList*>(Data); |
823 | |
824 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
825 | return static_cast<CNSInfo*>(Data)->TemplateArgs; |
826 | |
827 | // Unhandled |
828 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
829 | case TemplateDeductionResult::AlreadyDiagnosed: |
830 | break; |
831 | } |
832 | |
833 | return nullptr; |
834 | } |
835 | |
836 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { |
837 | switch (static_cast<TemplateDeductionResult>(Result)) { |
838 | case TemplateDeductionResult::Success: |
839 | case TemplateDeductionResult::Invalid: |
840 | case TemplateDeductionResult::InstantiationDepth: |
841 | case TemplateDeductionResult::Incomplete: |
842 | case TemplateDeductionResult::TooManyArguments: |
843 | case TemplateDeductionResult::TooFewArguments: |
844 | case TemplateDeductionResult::InvalidExplicitArguments: |
845 | case TemplateDeductionResult::SubstitutionFailure: |
846 | case TemplateDeductionResult::CUDATargetMismatch: |
847 | case TemplateDeductionResult::NonDependentConversionFailure: |
848 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
849 | return nullptr; |
850 | |
851 | case TemplateDeductionResult::IncompletePack: |
852 | case TemplateDeductionResult::Inconsistent: |
853 | case TemplateDeductionResult::Underqualified: |
854 | case TemplateDeductionResult::DeducedMismatch: |
855 | case TemplateDeductionResult::DeducedMismatchNested: |
856 | case TemplateDeductionResult::NonDeducedMismatch: |
857 | return &static_cast<DFIArguments*>(Data)->FirstArg; |
858 | |
859 | // Unhandled |
860 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
861 | case TemplateDeductionResult::AlreadyDiagnosed: |
862 | break; |
863 | } |
864 | |
865 | return nullptr; |
866 | } |
867 | |
868 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { |
869 | switch (static_cast<TemplateDeductionResult>(Result)) { |
870 | case TemplateDeductionResult::Success: |
871 | case TemplateDeductionResult::Invalid: |
872 | case TemplateDeductionResult::InstantiationDepth: |
873 | case TemplateDeductionResult::Incomplete: |
874 | case TemplateDeductionResult::IncompletePack: |
875 | case TemplateDeductionResult::TooManyArguments: |
876 | case TemplateDeductionResult::TooFewArguments: |
877 | case TemplateDeductionResult::InvalidExplicitArguments: |
878 | case TemplateDeductionResult::SubstitutionFailure: |
879 | case TemplateDeductionResult::CUDATargetMismatch: |
880 | case TemplateDeductionResult::NonDependentConversionFailure: |
881 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
882 | return nullptr; |
883 | |
884 | case TemplateDeductionResult::Inconsistent: |
885 | case TemplateDeductionResult::Underqualified: |
886 | case TemplateDeductionResult::DeducedMismatch: |
887 | case TemplateDeductionResult::DeducedMismatchNested: |
888 | case TemplateDeductionResult::NonDeducedMismatch: |
889 | return &static_cast<DFIArguments*>(Data)->SecondArg; |
890 | |
891 | // Unhandled |
892 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
893 | case TemplateDeductionResult::AlreadyDiagnosed: |
894 | break; |
895 | } |
896 | |
897 | return nullptr; |
898 | } |
899 | |
900 | std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { |
901 | switch (static_cast<TemplateDeductionResult>(Result)) { |
902 | case TemplateDeductionResult::DeducedMismatch: |
903 | case TemplateDeductionResult::DeducedMismatchNested: |
904 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; |
905 | |
906 | default: |
907 | return std::nullopt; |
908 | } |
909 | } |
910 | |
911 | static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, |
912 | const FunctionDecl *Y) { |
913 | if (!X || !Y) |
914 | return false; |
915 | if (X->getNumParams() != Y->getNumParams()) |
916 | return false; |
917 | // FIXME: when do rewritten comparison operators |
918 | // with explicit object parameters correspond? |
919 | // https://cplusplus.github.io/CWG/issues/2797.html |
920 | for (unsigned I = 0; I < X->getNumParams(); ++I) |
921 | if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(), |
922 | T2: Y->getParamDecl(i: I)->getType())) |
923 | return false; |
924 | if (auto *FTX = X->getDescribedFunctionTemplate()) { |
925 | auto *FTY = Y->getDescribedFunctionTemplate(); |
926 | if (!FTY) |
927 | return false; |
928 | if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(), |
929 | Y: FTY->getTemplateParameters())) |
930 | return false; |
931 | } |
932 | return true; |
933 | } |
934 | |
935 | static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, |
936 | Expr *FirstOperand, FunctionDecl *EqFD) { |
937 | assert(EqFD->getOverloadedOperator() == |
938 | OverloadedOperatorKind::OO_EqualEqual); |
939 | // C++2a [over.match.oper]p4: |
940 | // A non-template function or function template F named operator== is a |
941 | // rewrite target with first operand o unless a search for the name operator!= |
942 | // in the scope S from the instantiation context of the operator expression |
943 | // finds a function or function template that would correspond |
944 | // ([basic.scope.scope]) to F if its name were operator==, where S is the |
945 | // scope of the class type of o if F is a class member, and the namespace |
946 | // scope of which F is a member otherwise. A function template specialization |
947 | // named operator== is a rewrite target if its function template is a rewrite |
948 | // target. |
949 | DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( |
950 | Op: OverloadedOperatorKind::OO_ExclaimEqual); |
951 | if (isa<CXXMethodDecl>(Val: EqFD)) { |
952 | // If F is a class member, search scope is class type of first operand. |
953 | QualType RHS = FirstOperand->getType(); |
954 | auto *RHSRec = RHS->getAs<RecordType>(); |
955 | if (!RHSRec) |
956 | return true; |
957 | LookupResult Members(S, NotEqOp, OpLoc, |
958 | Sema::LookupNameKind::LookupMemberName); |
959 | S.LookupQualifiedName(Members, RHSRec->getDecl()); |
960 | Members.suppressAccessDiagnostics(); |
961 | for (NamedDecl *Op : Members) |
962 | if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) |
963 | return false; |
964 | return true; |
965 | } |
966 | // Otherwise the search scope is the namespace scope of which F is a member. |
967 | for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) { |
968 | auto *NotEqFD = Op->getAsFunction(); |
969 | if (auto *UD = dyn_cast<UsingShadowDecl>(Op)) |
970 | NotEqFD = UD->getUnderlyingDecl()->getAsFunction(); |
971 | if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) && |
972 | declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()), |
973 | cast<Decl>(Op->getLexicalDeclContext()))) |
974 | return false; |
975 | } |
976 | return true; |
977 | } |
978 | |
979 | bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( |
980 | OverloadedOperatorKind Op) { |
981 | if (!AllowRewrittenCandidates) |
982 | return false; |
983 | return Op == OO_EqualEqual || Op == OO_Spaceship; |
984 | } |
985 | |
986 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( |
987 | Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { |
988 | auto Op = FD->getOverloadedOperator(); |
989 | if (!allowsReversed(Op)) |
990 | return false; |
991 | if (Op == OverloadedOperatorKind::OO_EqualEqual) { |
992 | assert(OriginalArgs.size() == 2); |
993 | if (!shouldAddReversedEqEq( |
994 | S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD)) |
995 | return false; |
996 | } |
997 | // Don't bother adding a reversed candidate that can never be a better |
998 | // match than the non-reversed version. |
999 | return FD->getNumNonObjectParams() != 2 || |
1000 | !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(), |
1001 | T2: FD->getParamDecl(i: 1)->getType()) || |
1002 | FD->hasAttr<EnableIfAttr>(); |
1003 | } |
1004 | |
1005 | void OverloadCandidateSet::destroyCandidates() { |
1006 | for (iterator i = begin(), e = end(); i != e; ++i) { |
1007 | for (auto &C : i->Conversions) |
1008 | C.~ImplicitConversionSequence(); |
1009 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) |
1010 | i->DeductionFailure.Destroy(); |
1011 | } |
1012 | } |
1013 | |
1014 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { |
1015 | destroyCandidates(); |
1016 | SlabAllocator.Reset(); |
1017 | NumInlineBytesUsed = 0; |
1018 | Candidates.clear(); |
1019 | Functions.clear(); |
1020 | Kind = CSK; |
1021 | } |
1022 | |
1023 | namespace { |
1024 | class UnbridgedCastsSet { |
1025 | struct Entry { |
1026 | Expr **Addr; |
1027 | Expr *Saved; |
1028 | }; |
1029 | SmallVector<Entry, 2> Entries; |
1030 | |
1031 | public: |
1032 | void save(Sema &S, Expr *&E) { |
1033 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); |
1034 | Entry entry = { .Addr: &E, .Saved: E }; |
1035 | Entries.push_back(Elt: entry); |
1036 | E = S.stripARCUnbridgedCast(e: E); |
1037 | } |
1038 | |
1039 | void restore() { |
1040 | for (SmallVectorImpl<Entry>::iterator |
1041 | i = Entries.begin(), e = Entries.end(); i != e; ++i) |
1042 | *i->Addr = i->Saved; |
1043 | } |
1044 | }; |
1045 | } |
1046 | |
1047 | /// checkPlaceholderForOverload - Do any interesting placeholder-like |
1048 | /// preprocessing on the given expression. |
1049 | /// |
1050 | /// \param unbridgedCasts a collection to which to add unbridged casts; |
1051 | /// without this, they will be immediately diagnosed as errors |
1052 | /// |
1053 | /// Return true on unrecoverable error. |
1054 | static bool |
1055 | checkPlaceholderForOverload(Sema &S, Expr *&E, |
1056 | UnbridgedCastsSet *unbridgedCasts = nullptr) { |
1057 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { |
1058 | // We can't handle overloaded expressions here because overload |
1059 | // resolution might reasonably tweak them. |
1060 | if (placeholder->getKind() == BuiltinType::Overload) return false; |
1061 | |
1062 | // If the context potentially accepts unbridged ARC casts, strip |
1063 | // the unbridged cast and add it to the collection for later restoration. |
1064 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && |
1065 | unbridgedCasts) { |
1066 | unbridgedCasts->save(S, E); |
1067 | return false; |
1068 | } |
1069 | |
1070 | // Go ahead and check everything else. |
1071 | ExprResult result = S.CheckPlaceholderExpr(E); |
1072 | if (result.isInvalid()) |
1073 | return true; |
1074 | |
1075 | E = result.get(); |
1076 | return false; |
1077 | } |
1078 | |
1079 | // Nothing to do. |
1080 | return false; |
1081 | } |
1082 | |
1083 | /// checkArgPlaceholdersForOverload - Check a set of call operands for |
1084 | /// placeholders. |
1085 | static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, |
1086 | UnbridgedCastsSet &unbridged) { |
1087 | for (unsigned i = 0, e = Args.size(); i != e; ++i) |
1088 | if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged)) |
1089 | return true; |
1090 | |
1091 | return false; |
1092 | } |
1093 | |
1094 | /// Determine whether the given New declaration is an overload of the |
1095 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if |
1096 | /// New and Old cannot be overloaded, e.g., if New has the same signature as |
1097 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't |
1098 | /// functions (or function templates) at all. When it does return Ovl_Match or |
1099 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be |
1100 | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying |
1101 | /// declaration. |
1102 | /// |
1103 | /// Example: Given the following input: |
1104 | /// |
1105 | /// void f(int, float); // #1 |
1106 | /// void f(int, int); // #2 |
1107 | /// int f(int, int); // #3 |
1108 | /// |
1109 | /// When we process #1, there is no previous declaration of "f", so IsOverload |
1110 | /// will not be used. |
1111 | /// |
1112 | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing |
1113 | /// the parameter types, we see that #1 and #2 are overloaded (since they have |
1114 | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is |
1115 | /// unchanged. |
1116 | /// |
1117 | /// When we process #3, Old is an overload set containing #1 and #2. We compare |
1118 | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then |
1119 | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of |
1120 | /// functions are not part of the signature), IsOverload returns Ovl_Match and |
1121 | /// MatchedDecl will be set to point to the FunctionDecl for #2. |
1122 | /// |
1123 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class |
1124 | /// by a using declaration. The rules for whether to hide shadow declarations |
1125 | /// ignore some properties which otherwise figure into a function template's |
1126 | /// signature. |
1127 | Sema::OverloadKind |
1128 | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, |
1129 | NamedDecl *&Match, bool NewIsUsingDecl) { |
1130 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); |
1131 | I != E; ++I) { |
1132 | NamedDecl *OldD = *I; |
1133 | |
1134 | bool OldIsUsingDecl = false; |
1135 | if (isa<UsingShadowDecl>(Val: OldD)) { |
1136 | OldIsUsingDecl = true; |
1137 | |
1138 | // We can always introduce two using declarations into the same |
1139 | // context, even if they have identical signatures. |
1140 | if (NewIsUsingDecl) continue; |
1141 | |
1142 | OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl(); |
1143 | } |
1144 | |
1145 | // A using-declaration does not conflict with another declaration |
1146 | // if one of them is hidden. |
1147 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I)) |
1148 | continue; |
1149 | |
1150 | // If either declaration was introduced by a using declaration, |
1151 | // we'll need to use slightly different rules for matching. |
1152 | // Essentially, these rules are the normal rules, except that |
1153 | // function templates hide function templates with different |
1154 | // return types or template parameter lists. |
1155 | bool UseMemberUsingDeclRules = |
1156 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && |
1157 | !New->getFriendObjectKind(); |
1158 | |
1159 | if (FunctionDecl *OldF = OldD->getAsFunction()) { |
1160 | if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) { |
1161 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { |
1162 | HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I)); |
1163 | continue; |
1164 | } |
1165 | |
1166 | if (!isa<FunctionTemplateDecl>(Val: OldD) && |
1167 | !shouldLinkPossiblyHiddenDecl(*I, New)) |
1168 | continue; |
1169 | |
1170 | Match = *I; |
1171 | return Ovl_Match; |
1172 | } |
1173 | |
1174 | // Builtins that have custom typechecking or have a reference should |
1175 | // not be overloadable or redeclarable. |
1176 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { |
1177 | Match = *I; |
1178 | return Ovl_NonFunction; |
1179 | } |
1180 | } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) { |
1181 | // We can overload with these, which can show up when doing |
1182 | // redeclaration checks for UsingDecls. |
1183 | assert(Old.getLookupKind() == LookupUsingDeclName); |
1184 | } else if (isa<TagDecl>(Val: OldD)) { |
1185 | // We can always overload with tags by hiding them. |
1186 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) { |
1187 | // Optimistically assume that an unresolved using decl will |
1188 | // overload; if it doesn't, we'll have to diagnose during |
1189 | // template instantiation. |
1190 | // |
1191 | // Exception: if the scope is dependent and this is not a class |
1192 | // member, the using declaration can only introduce an enumerator. |
1193 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { |
1194 | Match = *I; |
1195 | return Ovl_NonFunction; |
1196 | } |
1197 | } else { |
1198 | // (C++ 13p1): |
1199 | // Only function declarations can be overloaded; object and type |
1200 | // declarations cannot be overloaded. |
1201 | Match = *I; |
1202 | return Ovl_NonFunction; |
1203 | } |
1204 | } |
1205 | |
1206 | // C++ [temp.friend]p1: |
1207 | // For a friend function declaration that is not a template declaration: |
1208 | // -- if the name of the friend is a qualified or unqualified template-id, |
1209 | // [...], otherwise |
1210 | // -- if the name of the friend is a qualified-id and a matching |
1211 | // non-template function is found in the specified class or namespace, |
1212 | // the friend declaration refers to that function, otherwise, |
1213 | // -- if the name of the friend is a qualified-id and a matching function |
1214 | // template is found in the specified class or namespace, the friend |
1215 | // declaration refers to the deduced specialization of that function |
1216 | // template, otherwise |
1217 | // -- the name shall be an unqualified-id [...] |
1218 | // If we get here for a qualified friend declaration, we've just reached the |
1219 | // third bullet. If the type of the friend is dependent, skip this lookup |
1220 | // until instantiation. |
1221 | if (New->getFriendObjectKind() && New->getQualifier() && |
1222 | !New->getDescribedFunctionTemplate() && |
1223 | !New->getDependentSpecializationInfo() && |
1224 | !New->getType()->isDependentType()) { |
1225 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); |
1226 | TemplateSpecResult.addAllDecls(Other: Old); |
1227 | if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult, |
1228 | /*QualifiedFriend*/true)) { |
1229 | New->setInvalidDecl(); |
1230 | return Ovl_Overload; |
1231 | } |
1232 | |
1233 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); |
1234 | return Ovl_Match; |
1235 | } |
1236 | |
1237 | return Ovl_Overload; |
1238 | } |
1239 | |
1240 | static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, |
1241 | FunctionDecl *Old, |
1242 | bool UseMemberUsingDeclRules, |
1243 | bool ConsiderCudaAttrs, |
1244 | bool UseOverrideRules = false) { |
1245 | // C++ [basic.start.main]p2: This function shall not be overloaded. |
1246 | if (New->isMain()) |
1247 | return false; |
1248 | |
1249 | // MSVCRT user defined entry points cannot be overloaded. |
1250 | if (New->isMSVCRTEntryPoint()) |
1251 | return false; |
1252 | |
1253 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); |
1254 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); |
1255 | |
1256 | // C++ [temp.fct]p2: |
1257 | // A function template can be overloaded with other function templates |
1258 | // and with normal (non-template) functions. |
1259 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) |
1260 | return true; |
1261 | |
1262 | // Is the function New an overload of the function Old? |
1263 | QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType()); |
1264 | QualType NewQType = SemaRef.Context.getCanonicalType(New->getType()); |
1265 | |
1266 | // Compare the signatures (C++ 1.3.10) of the two functions to |
1267 | // determine whether they are overloads. If we find any mismatch |
1268 | // in the signature, they are overloads. |
1269 | |
1270 | // If either of these functions is a K&R-style function (no |
1271 | // prototype), then we consider them to have matching signatures. |
1272 | if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) || |
1273 | isa<FunctionNoProtoType>(Val: NewQType.getTypePtr())) |
1274 | return false; |
1275 | |
1276 | const auto *OldType = cast<FunctionProtoType>(Val&: OldQType); |
1277 | const auto *NewType = cast<FunctionProtoType>(Val&: NewQType); |
1278 | |
1279 | // The signature of a function includes the types of its |
1280 | // parameters (C++ 1.3.10), which includes the presence or absence |
1281 | // of the ellipsis; see C++ DR 357). |
1282 | if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic()) |
1283 | return true; |
1284 | |
1285 | // For member-like friends, the enclosing class is part of the signature. |
1286 | if ((New->isMemberLikeConstrainedFriend() || |
1287 | Old->isMemberLikeConstrainedFriend()) && |
1288 | !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) |
1289 | return true; |
1290 | |
1291 | // Compare the parameter lists. |
1292 | // This can only be done once we have establish that friend functions |
1293 | // inhabit the same context, otherwise we might tried to instantiate |
1294 | // references to non-instantiated entities during constraint substitution. |
1295 | // GH78101. |
1296 | if (NewTemplate) { |
1297 | // C++ [temp.over.link]p4: |
1298 | // The signature of a function template consists of its function |
1299 | // signature, its return type and its template parameter list. The names |
1300 | // of the template parameters are significant only for establishing the |
1301 | // relationship between the template parameters and the rest of the |
1302 | // signature. |
1303 | // |
1304 | // We check the return type and template parameter lists for function |
1305 | // templates first; the remaining checks follow. |
1306 | bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual( |
1307 | NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, |
1308 | OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch); |
1309 | bool SameReturnType = SemaRef.Context.hasSameType( |
1310 | T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType()); |
1311 | // FIXME(GH58571): Match template parameter list even for non-constrained |
1312 | // template heads. This currently ensures that the code prior to C++20 is |
1313 | // not newly broken. |
1314 | bool ConstraintsInTemplateHead = |
1315 | NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || |
1316 | OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); |
1317 | // C++ [namespace.udecl]p11: |
1318 | // The set of declarations named by a using-declarator that inhabits a |
1319 | // class C does not include member functions and member function |
1320 | // templates of a base class that "correspond" to (and thus would |
1321 | // conflict with) a declaration of a function or function template in |
1322 | // C. |
1323 | // Comparing return types is not required for the "correspond" check to |
1324 | // decide whether a member introduced by a shadow declaration is hidden. |
1325 | if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && |
1326 | !SameTemplateParameterList) |
1327 | return true; |
1328 | if (!UseMemberUsingDeclRules && |
1329 | (!SameTemplateParameterList || !SameReturnType)) |
1330 | return true; |
1331 | } |
1332 | |
1333 | const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old); |
1334 | const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New); |
1335 | |
1336 | int OldParamsOffset = 0; |
1337 | int NewParamsOffset = 0; |
1338 | |
1339 | // When determining if a method is an overload from a base class, act as if |
1340 | // the implicit object parameter are of the same type. |
1341 | |
1342 | auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) { |
1343 | if (M->isExplicitObjectMemberFunction()) |
1344 | return Q; |
1345 | |
1346 | // We do not allow overloading based off of '__restrict'. |
1347 | Q.removeRestrict(); |
1348 | |
1349 | // We may not have applied the implicit const for a constexpr member |
1350 | // function yet (because we haven't yet resolved whether this is a static |
1351 | // or non-static member function). Add it now, on the assumption that this |
1352 | // is a redeclaration of OldMethod. |
1353 | if (!SemaRef.getLangOpts().CPlusPlus14 && |
1354 | (M->isConstexpr() || M->isConsteval()) && |
1355 | !isa<CXXConstructorDecl>(Val: NewMethod)) |
1356 | Q.addConst(); |
1357 | return Q; |
1358 | }; |
1359 | |
1360 | auto CompareType = [&](QualType Base, QualType D) { |
1361 | auto BS = Base.getNonReferenceType().getCanonicalType().split(); |
1362 | BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals); |
1363 | |
1364 | auto DS = D.getNonReferenceType().getCanonicalType().split(); |
1365 | DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals); |
1366 | |
1367 | if (BS.Quals != DS.Quals) |
1368 | return false; |
1369 | |
1370 | if (OldMethod->isImplicitObjectMemberFunction() && |
1371 | OldMethod->getParent() != NewMethod->getParent()) { |
1372 | QualType ParentType = |
1373 | SemaRef.Context.getTypeDeclType(OldMethod->getParent()) |
1374 | .getCanonicalType(); |
1375 | if (ParentType.getTypePtr() != BS.Ty) |
1376 | return false; |
1377 | BS.Ty = DS.Ty; |
1378 | } |
1379 | |
1380 | // FIXME: should we ignore some type attributes here? |
1381 | if (BS.Ty != DS.Ty) |
1382 | return false; |
1383 | |
1384 | if (Base->isLValueReferenceType()) |
1385 | return D->isLValueReferenceType(); |
1386 | return Base->isRValueReferenceType() == D->isRValueReferenceType(); |
1387 | }; |
1388 | |
1389 | // If the function is a class member, its signature includes the |
1390 | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. |
1391 | auto DiagnoseInconsistentRefQualifiers = [&]() { |
1392 | if (SemaRef.LangOpts.CPlusPlus23) |
1393 | return false; |
1394 | if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier()) |
1395 | return false; |
1396 | if (OldMethod->isExplicitObjectMemberFunction() || |
1397 | NewMethod->isExplicitObjectMemberFunction()) |
1398 | return false; |
1399 | if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None || |
1400 | NewMethod->getRefQualifier() == RQ_None)) { |
1401 | SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) |
1402 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); |
1403 | SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration); |
1404 | return true; |
1405 | } |
1406 | return false; |
1407 | }; |
1408 | |
1409 | if (OldMethod && OldMethod->isExplicitObjectMemberFunction()) |
1410 | OldParamsOffset++; |
1411 | if (NewMethod && NewMethod->isExplicitObjectMemberFunction()) |
1412 | NewParamsOffset++; |
1413 | |
1414 | if (OldType->getNumParams() - OldParamsOffset != |
1415 | NewType->getNumParams() - NewParamsOffset || |
1416 | !SemaRef.FunctionParamTypesAreEqual( |
1417 | {OldType->param_type_begin() + OldParamsOffset, |
1418 | OldType->param_type_end()}, |
1419 | {NewType->param_type_begin() + NewParamsOffset, |
1420 | NewType->param_type_end()}, |
1421 | nullptr)) { |
1422 | return true; |
1423 | } |
1424 | |
1425 | if (OldMethod && NewMethod && !OldMethod->isStatic() && |
1426 | !OldMethod->isStatic()) { |
1427 | bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old, |
1428 | const CXXMethodDecl *New) { |
1429 | auto NewObjectType = New->getFunctionObjectParameterReferenceType(); |
1430 | auto OldObjectType = Old->getFunctionObjectParameterReferenceType(); |
1431 | |
1432 | auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) { |
1433 | return F->getRefQualifier() == RQ_None && |
1434 | !F->isExplicitObjectMemberFunction(); |
1435 | }; |
1436 | |
1437 | if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) && |
1438 | CompareType(OldObjectType.getNonReferenceType(), |
1439 | NewObjectType.getNonReferenceType())) |
1440 | return true; |
1441 | return CompareType(OldObjectType, NewObjectType); |
1442 | }(OldMethod, NewMethod); |
1443 | |
1444 | if (!HaveCorrespondingObjectParameters) { |
1445 | if (DiagnoseInconsistentRefQualifiers()) |
1446 | return true; |
1447 | // CWG2554 |
1448 | // and, if at least one is an explicit object member function, ignoring |
1449 | // object parameters |
1450 | if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() && |
1451 | !OldMethod->isExplicitObjectMemberFunction())) |
1452 | return true; |
1453 | } |
1454 | } |
1455 | |
1456 | if (!UseOverrideRules) { |
1457 | Expr *NewRC = New->getTrailingRequiresClause(), |
1458 | *OldRC = Old->getTrailingRequiresClause(); |
1459 | if ((NewRC != nullptr) != (OldRC != nullptr)) |
1460 | return true; |
1461 | |
1462 | if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC)) |
1463 | return true; |
1464 | } |
1465 | |
1466 | if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() && |
1467 | NewMethod->isImplicitObjectMemberFunction()) { |
1468 | if (DiagnoseInconsistentRefQualifiers()) |
1469 | return true; |
1470 | } |
1471 | |
1472 | // Though pass_object_size is placed on parameters and takes an argument, we |
1473 | // consider it to be a function-level modifier for the sake of function |
1474 | // identity. Either the function has one or more parameters with |
1475 | // pass_object_size or it doesn't. |
1476 | if (functionHasPassObjectSizeParams(FD: New) != |
1477 | functionHasPassObjectSizeParams(FD: Old)) |
1478 | return true; |
1479 | |
1480 | // enable_if attributes are an order-sensitive part of the signature. |
1481 | for (specific_attr_iterator<EnableIfAttr> |
1482 | NewI = New->specific_attr_begin<EnableIfAttr>(), |
1483 | NewE = New->specific_attr_end<EnableIfAttr>(), |
1484 | OldI = Old->specific_attr_begin<EnableIfAttr>(), |
1485 | OldE = Old->specific_attr_end<EnableIfAttr>(); |
1486 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { |
1487 | if (NewI == NewE || OldI == OldE) |
1488 | return true; |
1489 | llvm::FoldingSetNodeID NewID, OldID; |
1490 | NewI->getCond()->Profile(NewID, SemaRef.Context, true); |
1491 | OldI->getCond()->Profile(OldID, SemaRef.Context, true); |
1492 | if (NewID != OldID) |
1493 | return true; |
1494 | } |
1495 | |
1496 | if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) { |
1497 | // Don't allow overloading of destructors. (In theory we could, but it |
1498 | // would be a giant change to clang.) |
1499 | if (!isa<CXXDestructorDecl>(Val: New)) { |
1500 | Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(D: New), |
1501 | OldTarget = SemaRef.IdentifyCUDATarget(D: Old); |
1502 | if (NewTarget != Sema::CFT_InvalidTarget) { |
1503 | assert((OldTarget != Sema::CFT_InvalidTarget) && |
1504 | "Unexpected invalid target." ); |
1505 | |
1506 | // Allow overloading of functions with same signature and different CUDA |
1507 | // target attributes. |
1508 | if (NewTarget != OldTarget) |
1509 | return true; |
1510 | } |
1511 | } |
1512 | } |
1513 | |
1514 | // The signatures match; this is not an overload. |
1515 | return false; |
1516 | } |
1517 | |
1518 | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, |
1519 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { |
1520 | return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules, |
1521 | ConsiderCudaAttrs); |
1522 | } |
1523 | |
1524 | bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, |
1525 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { |
1526 | return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD, |
1527 | /*UseMemberUsingDeclRules=*/false, |
1528 | /*ConsiderCudaAttrs=*/true, |
1529 | /*UseOverrideRules=*/true); |
1530 | } |
1531 | |
1532 | /// Tries a user-defined conversion from From to ToType. |
1533 | /// |
1534 | /// Produces an implicit conversion sequence for when a standard conversion |
1535 | /// is not an option. See TryImplicitConversion for more information. |
1536 | static ImplicitConversionSequence |
1537 | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
1538 | bool SuppressUserConversions, |
1539 | AllowedExplicit AllowExplicit, |
1540 | bool InOverloadResolution, |
1541 | bool CStyle, |
1542 | bool AllowObjCWritebackConversion, |
1543 | bool AllowObjCConversionOnExplicit) { |
1544 | ImplicitConversionSequence ICS; |
1545 | |
1546 | if (SuppressUserConversions) { |
1547 | // We're not in the case above, so there is no conversion that |
1548 | // we can perform. |
1549 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType); |
1550 | return ICS; |
1551 | } |
1552 | |
1553 | // Attempt user-defined conversion. |
1554 | OverloadCandidateSet Conversions(From->getExprLoc(), |
1555 | OverloadCandidateSet::CSK_Normal); |
1556 | switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined, |
1557 | Conversions, AllowExplicit, |
1558 | AllowObjCConversionOnExplicit)) { |
1559 | case OR_Success: |
1560 | case OR_Deleted: |
1561 | ICS.setUserDefined(); |
1562 | // C++ [over.ics.user]p4: |
1563 | // A conversion of an expression of class type to the same class |
1564 | // type is given Exact Match rank, and a conversion of an |
1565 | // expression of class type to a base class of that type is |
1566 | // given Conversion rank, in spite of the fact that a copy |
1567 | // constructor (i.e., a user-defined conversion function) is |
1568 | // called for those cases. |
1569 | if (CXXConstructorDecl *Constructor |
1570 | = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) { |
1571 | QualType FromCanon |
1572 | = S.Context.getCanonicalType(T: From->getType().getUnqualifiedType()); |
1573 | QualType ToCanon |
1574 | = S.Context.getCanonicalType(T: ToType).getUnqualifiedType(); |
1575 | if (Constructor->isCopyConstructor() && |
1576 | (FromCanon == ToCanon || |
1577 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { |
1578 | // Turn this into a "standard" conversion sequence, so that it |
1579 | // gets ranked with standard conversion sequences. |
1580 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; |
1581 | ICS.setStandard(); |
1582 | ICS.Standard.setAsIdentityConversion(); |
1583 | ICS.Standard.setFromType(From->getType()); |
1584 | ICS.Standard.setAllToTypes(ToType); |
1585 | ICS.Standard.CopyConstructor = Constructor; |
1586 | ICS.Standard.FoundCopyConstructor = Found; |
1587 | if (ToCanon != FromCanon) |
1588 | ICS.Standard.Second = ICK_Derived_To_Base; |
1589 | } |
1590 | } |
1591 | break; |
1592 | |
1593 | case OR_Ambiguous: |
1594 | ICS.setAmbiguous(); |
1595 | ICS.Ambiguous.setFromType(From->getType()); |
1596 | ICS.Ambiguous.setToType(ToType); |
1597 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); |
1598 | Cand != Conversions.end(); ++Cand) |
1599 | if (Cand->Best) |
1600 | ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function); |
1601 | break; |
1602 | |
1603 | // Fall through. |
1604 | case OR_No_Viable_Function: |
1605 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType); |
1606 | break; |
1607 | } |
1608 | |
1609 | return ICS; |
1610 | } |
1611 | |
1612 | /// TryImplicitConversion - Attempt to perform an implicit conversion |
1613 | /// from the given expression (Expr) to the given type (ToType). This |
1614 | /// function returns an implicit conversion sequence that can be used |
1615 | /// to perform the initialization. Given |
1616 | /// |
1617 | /// void f(float f); |
1618 | /// void g(int i) { f(i); } |
1619 | /// |
1620 | /// this routine would produce an implicit conversion sequence to |
1621 | /// describe the initialization of f from i, which will be a standard |
1622 | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ |
1623 | /// 4.1) followed by a floating-integral conversion (C++ 4.9). |
1624 | // |
1625 | /// Note that this routine only determines how the conversion can be |
1626 | /// performed; it does not actually perform the conversion. As such, |
1627 | /// it will not produce any diagnostics if no conversion is available, |
1628 | /// but will instead return an implicit conversion sequence of kind |
1629 | /// "BadConversion". |
1630 | /// |
1631 | /// If @p SuppressUserConversions, then user-defined conversions are |
1632 | /// not permitted. |
1633 | /// If @p AllowExplicit, then explicit user-defined conversions are |
1634 | /// permitted. |
1635 | /// |
1636 | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C |
1637 | /// writeback conversion, which allows __autoreleasing id* parameters to |
1638 | /// be initialized with __strong id* or __weak id* arguments. |
1639 | static ImplicitConversionSequence |
1640 | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, |
1641 | bool SuppressUserConversions, |
1642 | AllowedExplicit AllowExplicit, |
1643 | bool InOverloadResolution, |
1644 | bool CStyle, |
1645 | bool AllowObjCWritebackConversion, |
1646 | bool AllowObjCConversionOnExplicit) { |
1647 | ImplicitConversionSequence ICS; |
1648 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, |
1649 | SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){ |
1650 | ICS.setStandard(); |
1651 | return ICS; |
1652 | } |
1653 | |
1654 | if (!S.getLangOpts().CPlusPlus) { |
1655 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType); |
1656 | return ICS; |
1657 | } |
1658 | |
1659 | // C++ [over.ics.user]p4: |
1660 | // A conversion of an expression of class type to the same class |
1661 | // type is given Exact Match rank, and a conversion of an |
1662 | // expression of class type to a base class of that type is |
1663 | // given Conversion rank, in spite of the fact that a copy/move |
1664 | // constructor (i.e., a user-defined conversion function) is |
1665 | // called for those cases. |
1666 | QualType FromType = From->getType(); |
1667 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && |
1668 | (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) || |
1669 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { |
1670 | ICS.setStandard(); |
1671 | ICS.Standard.setAsIdentityConversion(); |
1672 | ICS.Standard.setFromType(FromType); |
1673 | ICS.Standard.setAllToTypes(ToType); |
1674 | |
1675 | // We don't actually check at this point whether there is a valid |
1676 | // copy/move constructor, since overloading just assumes that it |
1677 | // exists. When we actually perform initialization, we'll find the |
1678 | // appropriate constructor to copy the returned object, if needed. |
1679 | ICS.Standard.CopyConstructor = nullptr; |
1680 | |
1681 | // Determine whether this is considered a derived-to-base conversion. |
1682 | if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) |
1683 | ICS.Standard.Second = ICK_Derived_To_Base; |
1684 | |
1685 | return ICS; |
1686 | } |
1687 | |
1688 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
1689 | AllowExplicit, InOverloadResolution, CStyle, |
1690 | AllowObjCWritebackConversion, |
1691 | AllowObjCConversionOnExplicit); |
1692 | } |
1693 | |
1694 | ImplicitConversionSequence |
1695 | Sema::TryImplicitConversion(Expr *From, QualType ToType, |
1696 | bool SuppressUserConversions, |
1697 | AllowedExplicit AllowExplicit, |
1698 | bool InOverloadResolution, |
1699 | bool CStyle, |
1700 | bool AllowObjCWritebackConversion) { |
1701 | return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions, |
1702 | AllowExplicit, InOverloadResolution, CStyle, |
1703 | AllowObjCWritebackConversion, |
1704 | /*AllowObjCConversionOnExplicit=*/false); |
1705 | } |
1706 | |
1707 | /// PerformImplicitConversion - Perform an implicit conversion of the |
1708 | /// expression From to the type ToType. Returns the |
1709 | /// converted expression. Flavor is the kind of conversion we're |
1710 | /// performing, used in the error message. If @p AllowExplicit, |
1711 | /// explicit user-defined conversions are permitted. |
1712 | ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
1713 | AssignmentAction Action, |
1714 | bool AllowExplicit) { |
1715 | if (checkPlaceholderForOverload(S&: *this, E&: From)) |
1716 | return ExprError(); |
1717 | |
1718 | // Objective-C ARC: Determine whether we will allow the writeback conversion. |
1719 | bool AllowObjCWritebackConversion |
1720 | = getLangOpts().ObjCAutoRefCount && |
1721 | (Action == AA_Passing || Action == AA_Sending); |
1722 | if (getLangOpts().ObjC) |
1723 | CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType, |
1724 | SrcType: From->getType(), SrcExpr&: From); |
1725 | ImplicitConversionSequence ICS = ::TryImplicitConversion( |
1726 | S&: *this, From, ToType, |
1727 | /*SuppressUserConversions=*/false, |
1728 | AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, |
1729 | /*InOverloadResolution=*/false, |
1730 | /*CStyle=*/false, AllowObjCWritebackConversion, |
1731 | /*AllowObjCConversionOnExplicit=*/false); |
1732 | return PerformImplicitConversion(From, ToType, ICS, Action); |
1733 | } |
1734 | |
1735 | /// Determine whether the conversion from FromType to ToType is a valid |
1736 | /// conversion that strips "noexcept" or "noreturn" off the nested function |
1737 | /// type. |
1738 | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, |
1739 | QualType &ResultTy) { |
1740 | if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) |
1741 | return false; |
1742 | |
1743 | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) |
1744 | // or F(t noexcept) -> F(t) |
1745 | // where F adds one of the following at most once: |
1746 | // - a pointer |
1747 | // - a member pointer |
1748 | // - a block pointer |
1749 | // Changes here need matching changes in FindCompositePointerType. |
1750 | CanQualType CanTo = Context.getCanonicalType(T: ToType); |
1751 | CanQualType CanFrom = Context.getCanonicalType(T: FromType); |
1752 | Type::TypeClass TyClass = CanTo->getTypeClass(); |
1753 | if (TyClass != CanFrom->getTypeClass()) return false; |
1754 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { |
1755 | if (TyClass == Type::Pointer) { |
1756 | CanTo = CanTo.castAs<PointerType>()->getPointeeType(); |
1757 | CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); |
1758 | } else if (TyClass == Type::BlockPointer) { |
1759 | CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); |
1760 | CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); |
1761 | } else if (TyClass == Type::MemberPointer) { |
1762 | auto ToMPT = CanTo.castAs<MemberPointerType>(); |
1763 | auto FromMPT = CanFrom.castAs<MemberPointerType>(); |
1764 | // A function pointer conversion cannot change the class of the function. |
1765 | if (ToMPT->getClass() != FromMPT->getClass()) |
1766 | return false; |
1767 | CanTo = ToMPT->getPointeeType(); |
1768 | CanFrom = FromMPT->getPointeeType(); |
1769 | } else { |
1770 | return false; |
1771 | } |
1772 | |
1773 | TyClass = CanTo->getTypeClass(); |
1774 | if (TyClass != CanFrom->getTypeClass()) return false; |
1775 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) |
1776 | return false; |
1777 | } |
1778 | |
1779 | const auto *FromFn = cast<FunctionType>(Val&: CanFrom); |
1780 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
1781 | |
1782 | const auto *ToFn = cast<FunctionType>(Val&: CanTo); |
1783 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
1784 | |
1785 | bool Changed = false; |
1786 | |
1787 | // Drop 'noreturn' if not present in target type. |
1788 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { |
1789 | FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false)); |
1790 | Changed = true; |
1791 | } |
1792 | |
1793 | // Drop 'noexcept' if not present in target type. |
1794 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn)) { |
1795 | const auto *ToFPT = cast<FunctionProtoType>(Val: ToFn); |
1796 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { |
1797 | FromFn = cast<FunctionType>( |
1798 | Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0), |
1799 | ESI: EST_None) |
1800 | .getTypePtr()); |
1801 | Changed = true; |
1802 | } |
1803 | |
1804 | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid |
1805 | // only if the ExtParameterInfo lists of the two function prototypes can be |
1806 | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. |
1807 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
1808 | bool CanUseToFPT, CanUseFromFPT; |
1809 | if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT, |
1810 | CanUseSecond&: CanUseFromFPT, NewParamInfos) && |
1811 | CanUseToFPT && !CanUseFromFPT) { |
1812 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); |
1813 | ExtInfo.ExtParameterInfos = |
1814 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); |
1815 | QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(), |
1816 | Args: FromFPT->getParamTypes(), EPI: ExtInfo); |
1817 | FromFn = QT->getAs<FunctionType>(); |
1818 | Changed = true; |
1819 | } |
1820 | } |
1821 | |
1822 | if (!Changed) |
1823 | return false; |
1824 | |
1825 | assert(QualType(FromFn, 0).isCanonical()); |
1826 | if (QualType(FromFn, 0) != CanTo) return false; |
1827 | |
1828 | ResultTy = ToType; |
1829 | return true; |
1830 | } |
1831 | |
1832 | /// Determine whether the conversion from FromType to ToType is a valid |
1833 | /// vector conversion. |
1834 | /// |
1835 | /// \param ICK Will be set to the vector conversion kind, if this is a vector |
1836 | /// conversion. |
1837 | static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, |
1838 | ImplicitConversionKind &ICK, Expr *From, |
1839 | bool InOverloadResolution, bool CStyle) { |
1840 | // We need at least one of these types to be a vector type to have a vector |
1841 | // conversion. |
1842 | if (!ToType->isVectorType() && !FromType->isVectorType()) |
1843 | return false; |
1844 | |
1845 | // Identical types require no conversions. |
1846 | if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) |
1847 | return false; |
1848 | |
1849 | // There are no conversions between extended vector types, only identity. |
1850 | if (ToType->isExtVectorType()) { |
1851 | // There are no conversions between extended vector types other than the |
1852 | // identity conversion. |
1853 | if (FromType->isExtVectorType()) |
1854 | return false; |
1855 | |
1856 | // Vector splat from any arithmetic type to a vector. |
1857 | if (FromType->isArithmeticType()) { |
1858 | ICK = ICK_Vector_Splat; |
1859 | return true; |
1860 | } |
1861 | } |
1862 | |
1863 | if (ToType->isSVESizelessBuiltinType() || |
1864 | FromType->isSVESizelessBuiltinType()) |
1865 | if (S.Context.areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) || |
1866 | S.Context.areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) { |
1867 | ICK = ICK_SVE_Vector_Conversion; |
1868 | return true; |
1869 | } |
1870 | |
1871 | if (ToType->isRVVSizelessBuiltinType() || |
1872 | FromType->isRVVSizelessBuiltinType()) |
1873 | if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) || |
1874 | S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) { |
1875 | ICK = ICK_RVV_Vector_Conversion; |
1876 | return true; |
1877 | } |
1878 | |
1879 | // We can perform the conversion between vector types in the following cases: |
1880 | // 1)vector types are equivalent AltiVec and GCC vector types |
1881 | // 2)lax vector conversions are permitted and the vector types are of the |
1882 | // same size |
1883 | // 3)the destination type does not have the ARM MVE strict-polymorphism |
1884 | // attribute, which inhibits lax vector conversion for overload resolution |
1885 | // only |
1886 | if (ToType->isVectorType() && FromType->isVectorType()) { |
1887 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || |
1888 | (S.isLaxVectorConversion(FromType, ToType) && |
1889 | !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { |
1890 | if (S.getASTContext().getTargetInfo().getTriple().isPPC() && |
1891 | S.isLaxVectorConversion(srcType: FromType, destType: ToType) && |
1892 | S.anyAltivecTypes(srcType: FromType, destType: ToType) && |
1893 | !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) && |
1894 | !InOverloadResolution && !CStyle) { |
1895 | S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) |
1896 | << FromType << ToType; |
1897 | } |
1898 | ICK = ICK_Vector_Conversion; |
1899 | return true; |
1900 | } |
1901 | } |
1902 | |
1903 | return false; |
1904 | } |
1905 | |
1906 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
1907 | bool InOverloadResolution, |
1908 | StandardConversionSequence &SCS, |
1909 | bool CStyle); |
1910 | |
1911 | /// IsStandardConversion - Determines whether there is a standard |
1912 | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the |
1913 | /// expression From to the type ToType. Standard conversion sequences |
1914 | /// only consider non-class types; for conversions that involve class |
1915 | /// types, use TryImplicitConversion. If a conversion exists, SCS will |
1916 | /// contain the standard conversion sequence required to perform this |
1917 | /// conversion and this routine will return true. Otherwise, this |
1918 | /// routine will return false and the value of SCS is unspecified. |
1919 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
1920 | bool InOverloadResolution, |
1921 | StandardConversionSequence &SCS, |
1922 | bool CStyle, |
1923 | bool AllowObjCWritebackConversion) { |
1924 | QualType FromType = From->getType(); |
1925 | |
1926 | // Standard conversions (C++ [conv]) |
1927 | SCS.setAsIdentityConversion(); |
1928 | SCS.IncompatibleObjC = false; |
1929 | SCS.setFromType(FromType); |
1930 | SCS.CopyConstructor = nullptr; |
1931 | |
1932 | // There are no standard conversions for class types in C++, so |
1933 | // abort early. When overloading in C, however, we do permit them. |
1934 | if (S.getLangOpts().CPlusPlus && |
1935 | (FromType->isRecordType() || ToType->isRecordType())) |
1936 | return false; |
1937 | |
1938 | // The first conversion can be an lvalue-to-rvalue conversion, |
1939 | // array-to-pointer conversion, or function-to-pointer conversion |
1940 | // (C++ 4p1). |
1941 | |
1942 | if (FromType == S.Context.OverloadTy) { |
1943 | DeclAccessPair AccessPair; |
1944 | if (FunctionDecl *Fn |
1945 | = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false, |
1946 | Found&: AccessPair)) { |
1947 | // We were able to resolve the address of the overloaded function, |
1948 | // so we can convert to the type of that function. |
1949 | FromType = Fn->getType(); |
1950 | SCS.setFromType(FromType); |
1951 | |
1952 | // we can sometimes resolve &foo<int> regardless of ToType, so check |
1953 | // if the type matches (identity) or we are converting to bool |
1954 | if (!S.Context.hasSameUnqualifiedType( |
1955 | T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) { |
1956 | QualType resultTy; |
1957 | // if the function type matches except for [[noreturn]], it's ok |
1958 | if (!S.IsFunctionConversion(FromType, |
1959 | ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), ResultTy&: resultTy)) |
1960 | // otherwise, only a boolean conversion is standard |
1961 | if (!ToType->isBooleanType()) |
1962 | return false; |
1963 | } |
1964 | |
1965 | // Check if the "from" expression is taking the address of an overloaded |
1966 | // function and recompute the FromType accordingly. Take advantage of the |
1967 | // fact that non-static member functions *must* have such an address-of |
1968 | // expression. |
1969 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn); |
1970 | if (Method && !Method->isStatic() && |
1971 | !Method->isExplicitObjectMemberFunction()) { |
1972 | assert(isa<UnaryOperator>(From->IgnoreParens()) && |
1973 | "Non-unary operator on non-static member address" ); |
1974 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() |
1975 | == UO_AddrOf && |
1976 | "Non-address-of operator on non-static member address" ); |
1977 | const Type *ClassType |
1978 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); |
1979 | FromType = S.Context.getMemberPointerType(T: FromType, Cls: ClassType); |
1980 | } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) { |
1981 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == |
1982 | UO_AddrOf && |
1983 | "Non-address-of operator for overloaded function expression" ); |
1984 | FromType = S.Context.getPointerType(T: FromType); |
1985 | } |
1986 | } else { |
1987 | return false; |
1988 | } |
1989 | } |
1990 | // Lvalue-to-rvalue conversion (C++11 4.1): |
1991 | // A glvalue (3.10) of a non-function, non-array type T can |
1992 | // be converted to a prvalue. |
1993 | bool argIsLValue = From->isGLValue(); |
1994 | if (argIsLValue && |
1995 | !FromType->isFunctionType() && !FromType->isArrayType() && |
1996 | S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) { |
1997 | SCS.First = ICK_Lvalue_To_Rvalue; |
1998 | |
1999 | // C11 6.3.2.1p2: |
2000 | // ... if the lvalue has atomic type, the value has the non-atomic version |
2001 | // of the type of the lvalue ... |
2002 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) |
2003 | FromType = Atomic->getValueType(); |
2004 | |
2005 | // If T is a non-class type, the type of the rvalue is the |
2006 | // cv-unqualified version of T. Otherwise, the type of the rvalue |
2007 | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we |
2008 | // just strip the qualifiers because they don't matter. |
2009 | FromType = FromType.getUnqualifiedType(); |
2010 | } else if (FromType->isArrayType()) { |
2011 | // Array-to-pointer conversion (C++ 4.2) |
2012 | SCS.First = ICK_Array_To_Pointer; |
2013 | |
2014 | // An lvalue or rvalue of type "array of N T" or "array of unknown |
2015 | // bound of T" can be converted to an rvalue of type "pointer to |
2016 | // T" (C++ 4.2p1). |
2017 | FromType = S.Context.getArrayDecayedType(T: FromType); |
2018 | |
2019 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { |
2020 | // This conversion is deprecated in C++03 (D.4) |
2021 | SCS.DeprecatedStringLiteralToCharPtr = true; |
2022 | |
2023 | // For the purpose of ranking in overload resolution |
2024 | // (13.3.3.1.1), this conversion is considered an |
2025 | // array-to-pointer conversion followed by a qualification |
2026 | // conversion (4.4). (C++ 4.2p2) |
2027 | SCS.Second = ICK_Identity; |
2028 | SCS.Third = ICK_Qualification; |
2029 | SCS.QualificationIncludesObjCLifetime = false; |
2030 | SCS.setAllToTypes(FromType); |
2031 | return true; |
2032 | } |
2033 | } else if (FromType->isFunctionType() && argIsLValue) { |
2034 | // Function-to-pointer conversion (C++ 4.3). |
2035 | SCS.First = ICK_Function_To_Pointer; |
2036 | |
2037 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts())) |
2038 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) |
2039 | if (!S.checkAddressOfFunctionIsAvailable(Function: FD)) |
2040 | return false; |
2041 | |
2042 | // An lvalue of function type T can be converted to an rvalue of |
2043 | // type "pointer to T." The result is a pointer to the |
2044 | // function. (C++ 4.3p1). |
2045 | FromType = S.Context.getPointerType(T: FromType); |
2046 | } else { |
2047 | // We don't require any conversions for the first step. |
2048 | SCS.First = ICK_Identity; |
2049 | } |
2050 | SCS.setToType(Idx: 0, T: FromType); |
2051 | |
2052 | // The second conversion can be an integral promotion, floating |
2053 | // point promotion, integral conversion, floating point conversion, |
2054 | // floating-integral conversion, pointer conversion, |
2055 | // pointer-to-member conversion, or boolean conversion (C++ 4p1). |
2056 | // For overloading in C, this can also be a "compatible-type" |
2057 | // conversion. |
2058 | bool IncompatibleObjC = false; |
2059 | ImplicitConversionKind SecondICK = ICK_Identity; |
2060 | if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) { |
2061 | // The unqualified versions of the types are the same: there's no |
2062 | // conversion to do. |
2063 | SCS.Second = ICK_Identity; |
2064 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { |
2065 | // Integral promotion (C++ 4.5). |
2066 | SCS.Second = ICK_Integral_Promotion; |
2067 | FromType = ToType.getUnqualifiedType(); |
2068 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { |
2069 | // Floating point promotion (C++ 4.6). |
2070 | SCS.Second = ICK_Floating_Promotion; |
2071 | FromType = ToType.getUnqualifiedType(); |
2072 | } else if (S.IsComplexPromotion(FromType, ToType)) { |
2073 | // Complex promotion (Clang extension) |
2074 | SCS.Second = ICK_Complex_Promotion; |
2075 | FromType = ToType.getUnqualifiedType(); |
2076 | } else if (ToType->isBooleanType() && |
2077 | (FromType->isArithmeticType() || |
2078 | FromType->isAnyPointerType() || |
2079 | FromType->isBlockPointerType() || |
2080 | FromType->isMemberPointerType())) { |
2081 | // Boolean conversions (C++ 4.12). |
2082 | SCS.Second = ICK_Boolean_Conversion; |
2083 | FromType = S.Context.BoolTy; |
2084 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
2085 | ToType->isIntegralType(Ctx: S.Context)) { |
2086 | // Integral conversions (C++ 4.7). |
2087 | SCS.Second = ICK_Integral_Conversion; |
2088 | FromType = ToType.getUnqualifiedType(); |
2089 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { |
2090 | // Complex conversions (C99 6.3.1.6) |
2091 | SCS.Second = ICK_Complex_Conversion; |
2092 | FromType = ToType.getUnqualifiedType(); |
2093 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || |
2094 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { |
2095 | // Complex-real conversions (C99 6.3.1.7) |
2096 | SCS.Second = ICK_Complex_Real; |
2097 | FromType = ToType.getUnqualifiedType(); |
2098 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { |
2099 | // FIXME: disable conversions between long double, __ibm128 and __float128 |
2100 | // if their representation is different until there is back end support |
2101 | // We of course allow this conversion if long double is really double. |
2102 | |
2103 | // Conversions between bfloat16 and float16 are currently not supported. |
2104 | if ((FromType->isBFloat16Type() && |
2105 | (ToType->isFloat16Type() || ToType->isHalfType())) || |
2106 | (ToType->isBFloat16Type() && |
2107 | (FromType->isFloat16Type() || FromType->isHalfType()))) |
2108 | return false; |
2109 | |
2110 | // Conversions between IEEE-quad and IBM-extended semantics are not |
2111 | // permitted. |
2112 | const llvm::fltSemantics &FromSem = |
2113 | S.Context.getFloatTypeSemantics(T: FromType); |
2114 | const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType); |
2115 | if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && |
2116 | &ToSem == &llvm::APFloat::IEEEquad()) || |
2117 | (&FromSem == &llvm::APFloat::IEEEquad() && |
2118 | &ToSem == &llvm::APFloat::PPCDoubleDouble())) |
2119 | return false; |
2120 | |
2121 | // Floating point conversions (C++ 4.8). |
2122 | SCS.Second = ICK_Floating_Conversion; |
2123 | FromType = ToType.getUnqualifiedType(); |
2124 | } else if ((FromType->isRealFloatingType() && |
2125 | ToType->isIntegralType(Ctx: S.Context)) || |
2126 | (FromType->isIntegralOrUnscopedEnumerationType() && |
2127 | ToType->isRealFloatingType())) { |
2128 | |
2129 | // Floating-integral conversions (C++ 4.9). |
2130 | SCS.Second = ICK_Floating_Integral; |
2131 | FromType = ToType.getUnqualifiedType(); |
2132 | } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) { |
2133 | SCS.Second = ICK_Block_Pointer_Conversion; |
2134 | } else if (AllowObjCWritebackConversion && |
2135 | S.isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) { |
2136 | SCS.Second = ICK_Writeback_Conversion; |
2137 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, |
2138 | ConvertedType&: FromType, IncompatibleObjC)) { |
2139 | // Pointer conversions (C++ 4.10). |
2140 | SCS.Second = ICK_Pointer_Conversion; |
2141 | SCS.IncompatibleObjC = IncompatibleObjC; |
2142 | FromType = FromType.getUnqualifiedType(); |
2143 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, |
2144 | InOverloadResolution, ConvertedType&: FromType)) { |
2145 | // Pointer to member conversions (4.11). |
2146 | SCS.Second = ICK_Pointer_Member; |
2147 | } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, From, |
2148 | InOverloadResolution, CStyle)) { |
2149 | SCS.Second = SecondICK; |
2150 | FromType = ToType.getUnqualifiedType(); |
2151 | } else if (!S.getLangOpts().CPlusPlus && |
2152 | S.Context.typesAreCompatible(T1: ToType, T2: FromType)) { |
2153 | // Compatible conversions (Clang extension for C function overloading) |
2154 | SCS.Second = ICK_Compatible_Conversion; |
2155 | FromType = ToType.getUnqualifiedType(); |
2156 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, |
2157 | InOverloadResolution, |
2158 | SCS, CStyle)) { |
2159 | SCS.Second = ICK_TransparentUnionConversion; |
2160 | FromType = ToType; |
2161 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, |
2162 | CStyle)) { |
2163 | // tryAtomicConversion has updated the standard conversion sequence |
2164 | // appropriately. |
2165 | return true; |
2166 | } else if (ToType->isEventT() && |
2167 | From->isIntegerConstantExpr(Ctx: S.getASTContext()) && |
2168 | From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) { |
2169 | SCS.Second = ICK_Zero_Event_Conversion; |
2170 | FromType = ToType; |
2171 | } else if (ToType->isQueueT() && |
2172 | From->isIntegerConstantExpr(Ctx: S.getASTContext()) && |
2173 | (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) { |
2174 | SCS.Second = ICK_Zero_Queue_Conversion; |
2175 | FromType = ToType; |
2176 | } else if (ToType->isSamplerT() && |
2177 | From->isIntegerConstantExpr(Ctx: S.getASTContext())) { |
2178 | SCS.Second = ICK_Compatible_Conversion; |
2179 | FromType = ToType; |
2180 | } else if ((ToType->isFixedPointType() && |
2181 | FromType->isConvertibleToFixedPointType()) || |
2182 | (FromType->isFixedPointType() && |
2183 | ToType->isConvertibleToFixedPointType())) { |
2184 | SCS.Second = ICK_Fixed_Point_Conversion; |
2185 | FromType = ToType; |
2186 | } else { |
2187 | // No second conversion required. |
2188 | SCS.Second = ICK_Identity; |
2189 | } |
2190 | SCS.setToType(Idx: 1, T: FromType); |
2191 | |
2192 | // The third conversion can be a function pointer conversion or a |
2193 | // qualification conversion (C++ [conv.fctptr], [conv.qual]). |
2194 | bool ObjCLifetimeConversion; |
2195 | if (S.IsFunctionConversion(FromType, ToType, ResultTy&: FromType)) { |
2196 | // Function pointer conversions (removing 'noexcept') including removal of |
2197 | // 'noreturn' (Clang extension). |
2198 | SCS.Third = ICK_Function_Conversion; |
2199 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, |
2200 | ObjCLifetimeConversion)) { |
2201 | SCS.Third = ICK_Qualification; |
2202 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; |
2203 | FromType = ToType; |
2204 | } else { |
2205 | // No conversion required |
2206 | SCS.Third = ICK_Identity; |
2207 | } |
2208 | |
2209 | // C++ [over.best.ics]p6: |
2210 | // [...] Any difference in top-level cv-qualification is |
2211 | // subsumed by the initialization itself and does not constitute |
2212 | // a conversion. [...] |
2213 | QualType CanonFrom = S.Context.getCanonicalType(T: FromType); |
2214 | QualType CanonTo = S.Context.getCanonicalType(T: ToType); |
2215 | if (CanonFrom.getLocalUnqualifiedType() |
2216 | == CanonTo.getLocalUnqualifiedType() && |
2217 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { |
2218 | FromType = ToType; |
2219 | CanonFrom = CanonTo; |
2220 | } |
2221 | |
2222 | SCS.setToType(Idx: 2, T: FromType); |
2223 | |
2224 | if (CanonFrom == CanonTo) |
2225 | return true; |
2226 | |
2227 | // If we have not converted the argument type to the parameter type, |
2228 | // this is a bad conversion sequence, unless we're resolving an overload in C. |
2229 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) |
2230 | return false; |
2231 | |
2232 | ExprResult ER = ExprResult{From}; |
2233 | Sema::AssignConvertType Conv = |
2234 | S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER, |
2235 | /*Diagnose=*/false, |
2236 | /*DiagnoseCFAudited=*/false, |
2237 | /*ConvertRHS=*/false); |
2238 | ImplicitConversionKind SecondConv; |
2239 | switch (Conv) { |
2240 | case Sema::Compatible: |
2241 | SecondConv = ICK_C_Only_Conversion; |
2242 | break; |
2243 | // For our purposes, discarding qualifiers is just as bad as using an |
2244 | // incompatible pointer. Note that an IncompatiblePointer conversion can drop |
2245 | // qualifiers, as well. |
2246 | case Sema::CompatiblePointerDiscardsQualifiers: |
2247 | case Sema::IncompatiblePointer: |
2248 | case Sema::IncompatiblePointerSign: |
2249 | SecondConv = ICK_Incompatible_Pointer_Conversion; |
2250 | break; |
2251 | default: |
2252 | return false; |
2253 | } |
2254 | |
2255 | // First can only be an lvalue conversion, so we pretend that this was the |
2256 | // second conversion. First should already be valid from earlier in the |
2257 | // function. |
2258 | SCS.Second = SecondConv; |
2259 | SCS.setToType(Idx: 1, T: ToType); |
2260 | |
2261 | // Third is Identity, because Second should rank us worse than any other |
2262 | // conversion. This could also be ICK_Qualification, but it's simpler to just |
2263 | // lump everything in with the second conversion, and we don't gain anything |
2264 | // from making this ICK_Qualification. |
2265 | SCS.Third = ICK_Identity; |
2266 | SCS.setToType(Idx: 2, T: ToType); |
2267 | return true; |
2268 | } |
2269 | |
2270 | static bool |
2271 | IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
2272 | QualType &ToType, |
2273 | bool InOverloadResolution, |
2274 | StandardConversionSequence &SCS, |
2275 | bool CStyle) { |
2276 | |
2277 | const RecordType *UT = ToType->getAsUnionType(); |
2278 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
2279 | return false; |
2280 | // The field to initialize within the transparent union. |
2281 | RecordDecl *UD = UT->getDecl(); |
2282 | // It's compatible if the expression matches any of the fields. |
2283 | for (const auto *it : UD->fields()) { |
2284 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, |
2285 | CStyle, /*AllowObjCWritebackConversion=*/false)) { |
2286 | ToType = it->getType(); |
2287 | return true; |
2288 | } |
2289 | } |
2290 | return false; |
2291 | } |
2292 | |
2293 | /// IsIntegralPromotion - Determines whether the conversion from the |
2294 | /// expression From (whose potentially-adjusted type is FromType) to |
2295 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and |
2296 | /// sets PromotedType to the promoted type. |
2297 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { |
2298 | const BuiltinType *To = ToType->getAs<BuiltinType>(); |
2299 | // All integers are built-in. |
2300 | if (!To) { |
2301 | return false; |
2302 | } |
2303 | |
2304 | // An rvalue of type char, signed char, unsigned char, short int, or |
2305 | // unsigned short int can be converted to an rvalue of type int if |
2306 | // int can represent all the values of the source type; otherwise, |
2307 | // the source rvalue can be converted to an rvalue of type unsigned |
2308 | // int (C++ 4.5p1). |
2309 | if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() && |
2310 | !FromType->isEnumeralType()) { |
2311 | if ( // We can promote any signed, promotable integer type to an int |
2312 | (FromType->isSignedIntegerType() || |
2313 | // We can promote any unsigned integer type whose size is |
2314 | // less than int to an int. |
2315 | Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) { |
2316 | return To->getKind() == BuiltinType::Int; |
2317 | } |
2318 | |
2319 | return To->getKind() == BuiltinType::UInt; |
2320 | } |
2321 | |
2322 | // C++11 [conv.prom]p3: |
2323 | // A prvalue of an unscoped enumeration type whose underlying type is not |
2324 | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the |
2325 | // following types that can represent all the values of the enumeration |
2326 | // (i.e., the values in the range bmin to bmax as described in 7.2): int, |
2327 | // unsigned int, long int, unsigned long int, long long int, or unsigned |
2328 | // long long int. If none of the types in that list can represent all the |
2329 | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration |
2330 | // type can be converted to an rvalue a prvalue of the extended integer type |
2331 | // with lowest integer conversion rank (4.13) greater than the rank of long |
2332 | // long in which all the values of the enumeration can be represented. If |
2333 | // there are two such extended types, the signed one is chosen. |
2334 | // C++11 [conv.prom]p4: |
2335 | // A prvalue of an unscoped enumeration type whose underlying type is fixed |
2336 | // can be converted to a prvalue of its underlying type. Moreover, if |
2337 | // integral promotion can be applied to its underlying type, a prvalue of an |
2338 | // unscoped enumeration type whose underlying type is fixed can also be |
2339 | // converted to a prvalue of the promoted underlying type. |
2340 | if (const EnumType * = FromType->getAs<EnumType>()) { |
2341 | // C++0x 7.2p9: Note that this implicit enum to int conversion is not |
2342 | // provided for a scoped enumeration. |
2343 | if (FromEnumType->getDecl()->isScoped()) |
2344 | return false; |
2345 | |
2346 | // We can perform an integral promotion to the underlying type of the enum, |
2347 | // even if that's not the promoted type. Note that the check for promoting |
2348 | // the underlying type is based on the type alone, and does not consider |
2349 | // the bitfield-ness of the actual source expression. |
2350 | if (FromEnumType->getDecl()->isFixed()) { |
2351 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); |
2352 | return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) || |
2353 | IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType); |
2354 | } |
2355 | |
2356 | // We have already pre-calculated the promotion type, so this is trivial. |
2357 | if (ToType->isIntegerType() && |
2358 | isCompleteType(Loc: From->getBeginLoc(), T: FromType)) |
2359 | return Context.hasSameUnqualifiedType( |
2360 | T1: ToType, T2: FromEnumType->getDecl()->getPromotionType()); |
2361 | |
2362 | // C++ [conv.prom]p5: |
2363 | // If the bit-field has an enumerated type, it is treated as any other |
2364 | // value of that type for promotion purposes. |
2365 | // |
2366 | // ... so do not fall through into the bit-field checks below in C++. |
2367 | if (getLangOpts().CPlusPlus) |
2368 | return false; |
2369 | } |
2370 | |
2371 | // C++0x [conv.prom]p2: |
2372 | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted |
2373 | // to an rvalue a prvalue of the first of the following types that can |
2374 | // represent all the values of its underlying type: int, unsigned int, |
2375 | // long int, unsigned long int, long long int, or unsigned long long int. |
2376 | // If none of the types in that list can represent all the values of its |
2377 | // underlying type, an rvalue a prvalue of type char16_t, char32_t, |
2378 | // or wchar_t can be converted to an rvalue a prvalue of its underlying |
2379 | // type. |
2380 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && |
2381 | ToType->isIntegerType()) { |
2382 | // Determine whether the type we're converting from is signed or |
2383 | // unsigned. |
2384 | bool FromIsSigned = FromType->isSignedIntegerType(); |
2385 | uint64_t FromSize = Context.getTypeSize(T: FromType); |
2386 | |
2387 | // The types we'll try to promote to, in the appropriate |
2388 | // order. Try each of these types. |
2389 | QualType PromoteTypes[6] = { |
2390 | Context.IntTy, Context.UnsignedIntTy, |
2391 | Context.LongTy, Context.UnsignedLongTy , |
2392 | Context.LongLongTy, Context.UnsignedLongLongTy |
2393 | }; |
2394 | for (int Idx = 0; Idx < 6; ++Idx) { |
2395 | uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]); |
2396 | if (FromSize < ToSize || |
2397 | (FromSize == ToSize && |
2398 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { |
2399 | // We found the type that we can promote to. If this is the |
2400 | // type we wanted, we have a promotion. Otherwise, no |
2401 | // promotion. |
2402 | return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]); |
2403 | } |
2404 | } |
2405 | } |
2406 | |
2407 | // An rvalue for an integral bit-field (9.6) can be converted to an |
2408 | // rvalue of type int if int can represent all the values of the |
2409 | // bit-field; otherwise, it can be converted to unsigned int if |
2410 | // unsigned int can represent all the values of the bit-field. If |
2411 | // the bit-field is larger yet, no integral promotion applies to |
2412 | // it. If the bit-field has an enumerated type, it is treated as any |
2413 | // other value of that type for promotion purposes (C++ 4.5p3). |
2414 | // FIXME: We should delay checking of bit-fields until we actually perform the |
2415 | // conversion. |
2416 | // |
2417 | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be |
2418 | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum |
2419 | // bit-fields and those whose underlying type is larger than int) for GCC |
2420 | // compatibility. |
2421 | if (From) { |
2422 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { |
2423 | std::optional<llvm::APSInt> BitWidth; |
2424 | if (FromType->isIntegralType(Ctx: Context) && |
2425 | (BitWidth = |
2426 | MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) { |
2427 | llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); |
2428 | ToSize = Context.getTypeSize(T: ToType); |
2429 | |
2430 | // Are we promoting to an int from a bitfield that fits in an int? |
2431 | if (*BitWidth < ToSize || |
2432 | (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { |
2433 | return To->getKind() == BuiltinType::Int; |
2434 | } |
2435 | |
2436 | // Are we promoting to an unsigned int from an unsigned bitfield |
2437 | // that fits into an unsigned int? |
2438 | if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { |
2439 | return To->getKind() == BuiltinType::UInt; |
2440 | } |
2441 | |
2442 | return false; |
2443 | } |
2444 | } |
2445 | } |
2446 | |
2447 | // An rvalue of type bool can be converted to an rvalue of type int, |
2448 | // with false becoming zero and true becoming one (C++ 4.5p4). |
2449 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { |
2450 | return true; |
2451 | } |
2452 | |
2453 | return false; |
2454 | } |
2455 | |
2456 | /// IsFloatingPointPromotion - Determines whether the conversion from |
2457 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, |
2458 | /// returns true and sets PromotedType to the promoted type. |
2459 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { |
2460 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) |
2461 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { |
2462 | /// An rvalue of type float can be converted to an rvalue of type |
2463 | /// double. (C++ 4.6p1). |
2464 | if (FromBuiltin->getKind() == BuiltinType::Float && |
2465 | ToBuiltin->getKind() == BuiltinType::Double) |
2466 | return true; |
2467 | |
2468 | // C99 6.3.1.5p1: |
2469 | // When a float is promoted to double or long double, or a |
2470 | // double is promoted to long double [...]. |
2471 | if (!getLangOpts().CPlusPlus && |
2472 | (FromBuiltin->getKind() == BuiltinType::Float || |
2473 | FromBuiltin->getKind() == BuiltinType::Double) && |
2474 | (ToBuiltin->getKind() == BuiltinType::LongDouble || |
2475 | ToBuiltin->getKind() == BuiltinType::Float128 || |
2476 | ToBuiltin->getKind() == BuiltinType::Ibm128)) |
2477 | return true; |
2478 | |
2479 | // Half can be promoted to float. |
2480 | if (!getLangOpts().NativeHalfType && |
2481 | FromBuiltin->getKind() == BuiltinType::Half && |
2482 | ToBuiltin->getKind() == BuiltinType::Float) |
2483 | return true; |
2484 | } |
2485 | |
2486 | return false; |
2487 | } |
2488 | |
2489 | /// Determine if a conversion is a complex promotion. |
2490 | /// |
2491 | /// A complex promotion is defined as a complex -> complex conversion |
2492 | /// where the conversion between the underlying real types is a |
2493 | /// floating-point or integral promotion. |
2494 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { |
2495 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); |
2496 | if (!FromComplex) |
2497 | return false; |
2498 | |
2499 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); |
2500 | if (!ToComplex) |
2501 | return false; |
2502 | |
2503 | return IsFloatingPointPromotion(FromType: FromComplex->getElementType(), |
2504 | ToType: ToComplex->getElementType()) || |
2505 | IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(), |
2506 | ToType: ToComplex->getElementType()); |
2507 | } |
2508 | |
2509 | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from |
2510 | /// the pointer type FromPtr to a pointer to type ToPointee, with the |
2511 | /// same type qualifiers as FromPtr has on its pointee type. ToType, |
2512 | /// if non-empty, will be a pointer to ToType that may or may not have |
2513 | /// the right set of qualifiers on its pointee. |
2514 | /// |
2515 | static QualType |
2516 | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, |
2517 | QualType ToPointee, QualType ToType, |
2518 | ASTContext &Context, |
2519 | bool StripObjCLifetime = false) { |
2520 | assert((FromPtr->getTypeClass() == Type::Pointer || |
2521 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) && |
2522 | "Invalid similarly-qualified pointer type" ); |
2523 | |
2524 | /// Conversions to 'id' subsume cv-qualifier conversions. |
2525 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) |
2526 | return ToType.getUnqualifiedType(); |
2527 | |
2528 | QualType CanonFromPointee |
2529 | = Context.getCanonicalType(T: FromPtr->getPointeeType()); |
2530 | QualType CanonToPointee = Context.getCanonicalType(T: ToPointee); |
2531 | Qualifiers Quals = CanonFromPointee.getQualifiers(); |
2532 | |
2533 | if (StripObjCLifetime) |
2534 | Quals.removeObjCLifetime(); |
2535 | |
2536 | // Exact qualifier match -> return the pointer type we're converting to. |
2537 | if (CanonToPointee.getLocalQualifiers() == Quals) { |
2538 | // ToType is exactly what we need. Return it. |
2539 | if (!ToType.isNull()) |
2540 | return ToType.getUnqualifiedType(); |
2541 | |
2542 | // Build a pointer to ToPointee. It has the right qualifiers |
2543 | // already. |
2544 | if (isa<ObjCObjectPointerType>(Val: ToType)) |
2545 | return Context.getObjCObjectPointerType(OIT: ToPointee); |
2546 | return Context.getPointerType(T: ToPointee); |
2547 | } |
2548 | |
2549 | // Just build a canonical type that has the right qualifiers. |
2550 | QualType QualifiedCanonToPointee |
2551 | = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals); |
2552 | |
2553 | if (isa<ObjCObjectPointerType>(Val: ToType)) |
2554 | return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee); |
2555 | return Context.getPointerType(T: QualifiedCanonToPointee); |
2556 | } |
2557 | |
2558 | static bool isNullPointerConstantForConversion(Expr *Expr, |
2559 | bool InOverloadResolution, |
2560 | ASTContext &Context) { |
2561 | // Handle value-dependent integral null pointer constants correctly. |
2562 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
2563 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && |
2564 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) |
2565 | return !InOverloadResolution; |
2566 | |
2567 | return Expr->isNullPointerConstant(Ctx&: Context, |
2568 | NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
2569 | : Expr::NPC_ValueDependentIsNull); |
2570 | } |
2571 | |
2572 | /// IsPointerConversion - Determines whether the conversion of the |
2573 | /// expression From, which has the (possibly adjusted) type FromType, |
2574 | /// can be converted to the type ToType via a pointer conversion (C++ |
2575 | /// 4.10). If so, returns true and places the converted type (that |
2576 | /// might differ from ToType in its cv-qualifiers at some level) into |
2577 | /// ConvertedType. |
2578 | /// |
2579 | /// This routine also supports conversions to and from block pointers |
2580 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and |
2581 | /// pointers to interfaces. FIXME: Once we've determined the |
2582 | /// appropriate overloading rules for Objective-C, we may want to |
2583 | /// split the Objective-C checks into a different routine; however, |
2584 | /// GCC seems to consider all of these conversions to be pointer |
2585 | /// conversions, so for now they live here. IncompatibleObjC will be |
2586 | /// set if the conversion is an allowed Objective-C conversion that |
2587 | /// should result in a warning. |
2588 | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2589 | bool InOverloadResolution, |
2590 | QualType& ConvertedType, |
2591 | bool &IncompatibleObjC) { |
2592 | IncompatibleObjC = false; |
2593 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, |
2594 | IncompatibleObjC)) |
2595 | return true; |
2596 | |
2597 | // Conversion from a null pointer constant to any Objective-C pointer type. |
2598 | if (ToType->isObjCObjectPointerType() && |
2599 | isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) { |
2600 | ConvertedType = ToType; |
2601 | return true; |
2602 | } |
2603 | |
2604 | // Blocks: Block pointers can be converted to void*. |
2605 | if (FromType->isBlockPointerType() && ToType->isPointerType() && |
2606 | ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
2607 | ConvertedType = ToType; |
2608 | return true; |
2609 | } |
2610 | // Blocks: A null pointer constant can be converted to a block |
2611 | // pointer type. |
2612 | if (ToType->isBlockPointerType() && |
2613 | isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) { |
2614 | ConvertedType = ToType; |
2615 | return true; |
2616 | } |
2617 | |
2618 | // If the left-hand-side is nullptr_t, the right side can be a null |
2619 | // pointer constant. |
2620 | if (ToType->isNullPtrType() && |
2621 | isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) { |
2622 | ConvertedType = ToType; |
2623 | return true; |
2624 | } |
2625 | |
2626 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); |
2627 | if (!ToTypePtr) |
2628 | return false; |
2629 | |
2630 | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). |
2631 | if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) { |
2632 | ConvertedType = ToType; |
2633 | return true; |
2634 | } |
2635 | |
2636 | // Beyond this point, both types need to be pointers |
2637 | // , including objective-c pointers. |
2638 | QualType ToPointeeType = ToTypePtr->getPointeeType(); |
2639 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && |
2640 | !getLangOpts().ObjCAutoRefCount) { |
2641 | ConvertedType = BuildSimilarlyQualifiedPointerType( |
2642 | FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, |
2643 | Context); |
2644 | return true; |
2645 | } |
2646 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); |
2647 | if (!FromTypePtr) |
2648 | return false; |
2649 | |
2650 | QualType FromPointeeType = FromTypePtr->getPointeeType(); |
2651 | |
2652 | // If the unqualified pointee types are the same, this can't be a |
2653 | // pointer conversion, so don't do all of the work below. |
2654 | if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) |
2655 | return false; |
2656 | |
2657 | // An rvalue of type "pointer to cv T," where T is an object type, |
2658 | // can be converted to an rvalue of type "pointer to cv void" (C++ |
2659 | // 4.10p2). |
2660 | if (FromPointeeType->isIncompleteOrObjectType() && |
2661 | ToPointeeType->isVoidType()) { |
2662 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2663 | ToPointeeType, |
2664 | ToType, Context, |
2665 | /*StripObjCLifetime=*/true); |
2666 | return true; |
2667 | } |
2668 | |
2669 | // MSVC allows implicit function to void* type conversion. |
2670 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && |
2671 | ToPointeeType->isVoidType()) { |
2672 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2673 | ToPointeeType, |
2674 | ToType, Context); |
2675 | return true; |
2676 | } |
2677 | |
2678 | // When we're overloading in C, we allow a special kind of pointer |
2679 | // conversion for compatible-but-not-identical pointee types. |
2680 | if (!getLangOpts().CPlusPlus && |
2681 | Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) { |
2682 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2683 | ToPointeeType, |
2684 | ToType, Context); |
2685 | return true; |
2686 | } |
2687 | |
2688 | // C++ [conv.ptr]p3: |
2689 | // |
2690 | // An rvalue of type "pointer to cv D," where D is a class type, |
2691 | // can be converted to an rvalue of type "pointer to cv B," where |
2692 | // B is a base class (clause 10) of D. If B is an inaccessible |
2693 | // (clause 11) or ambiguous (10.2) base class of D, a program that |
2694 | // necessitates this conversion is ill-formed. The result of the |
2695 | // conversion is a pointer to the base class sub-object of the |
2696 | // derived class object. The null pointer value is converted to |
2697 | // the null pointer value of the destination type. |
2698 | // |
2699 | // Note that we do not check for ambiguity or inaccessibility |
2700 | // here. That is handled by CheckPointerConversion. |
2701 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && |
2702 | ToPointeeType->isRecordType() && |
2703 | !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) && |
2704 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { |
2705 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2706 | ToPointeeType, |
2707 | ToType, Context); |
2708 | return true; |
2709 | } |
2710 | |
2711 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && |
2712 | Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) { |
2713 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2714 | ToPointeeType, |
2715 | ToType, Context); |
2716 | return true; |
2717 | } |
2718 | |
2719 | return false; |
2720 | } |
2721 | |
2722 | /// Adopt the given qualifiers for the given type. |
2723 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ |
2724 | Qualifiers TQs = T.getQualifiers(); |
2725 | |
2726 | // Check whether qualifiers already match. |
2727 | if (TQs == Qs) |
2728 | return T; |
2729 | |
2730 | if (Qs.compatiblyIncludes(other: TQs)) |
2731 | return Context.getQualifiedType(T, Qs); |
2732 | |
2733 | return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs); |
2734 | } |
2735 | |
2736 | /// isObjCPointerConversion - Determines whether this is an |
2737 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, |
2738 | /// with the same arguments and return values. |
2739 | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, |
2740 | QualType& ConvertedType, |
2741 | bool &IncompatibleObjC) { |
2742 | if (!getLangOpts().ObjC) |
2743 | return false; |
2744 | |
2745 | // The set of qualifiers on the type we're converting from. |
2746 | Qualifiers FromQualifiers = FromType.getQualifiers(); |
2747 | |
2748 | // First, we handle all conversions on ObjC object pointer types. |
2749 | const ObjCObjectPointerType* ToObjCPtr = |
2750 | ToType->getAs<ObjCObjectPointerType>(); |
2751 | const ObjCObjectPointerType *FromObjCPtr = |
2752 | FromType->getAs<ObjCObjectPointerType>(); |
2753 | |
2754 | if (ToObjCPtr && FromObjCPtr) { |
2755 | // If the pointee types are the same (ignoring qualifications), |
2756 | // then this is not a pointer conversion. |
2757 | if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(), |
2758 | T2: FromObjCPtr->getPointeeType())) |
2759 | return false; |
2760 | |
2761 | // Conversion between Objective-C pointers. |
2762 | if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) { |
2763 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); |
2764 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); |
2765 | if (getLangOpts().CPlusPlus && LHS && RHS && |
2766 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( |
2767 | other: FromObjCPtr->getPointeeType())) |
2768 | return false; |
2769 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2770 | ToObjCPtr->getPointeeType(), |
2771 | ToType, Context); |
2772 | ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers); |
2773 | return true; |
2774 | } |
2775 | |
2776 | if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) { |
2777 | // Okay: this is some kind of implicit downcast of Objective-C |
2778 | // interfaces, which is permitted. However, we're going to |
2779 | // complain about it. |
2780 | IncompatibleObjC = true; |
2781 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2782 | ToObjCPtr->getPointeeType(), |
2783 | ToType, Context); |
2784 | ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers); |
2785 | return true; |
2786 | } |
2787 | } |
2788 | // Beyond this point, both types need to be C pointers or block pointers. |
2789 | QualType ToPointeeType; |
2790 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) |
2791 | ToPointeeType = ToCPtr->getPointeeType(); |
2792 | else if (const BlockPointerType *ToBlockPtr = |
2793 | ToType->getAs<BlockPointerType>()) { |
2794 | // Objective C++: We're able to convert from a pointer to any object |
2795 | // to a block pointer type. |
2796 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { |
2797 | ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers); |
2798 | return true; |
2799 | } |
2800 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2801 | } |
2802 | else if (FromType->getAs<BlockPointerType>() && |
2803 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { |
2804 | // Objective C++: We're able to convert from a block pointer type to a |
2805 | // pointer to any object. |
2806 | ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers); |
2807 | return true; |
2808 | } |
2809 | else |
2810 | return false; |
2811 | |
2812 | QualType FromPointeeType; |
2813 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) |
2814 | FromPointeeType = FromCPtr->getPointeeType(); |
2815 | else if (const BlockPointerType *FromBlockPtr = |
2816 | FromType->getAs<BlockPointerType>()) |
2817 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2818 | else |
2819 | return false; |
2820 | |
2821 | // If we have pointers to pointers, recursively check whether this |
2822 | // is an Objective-C conversion. |
2823 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && |
2824 | isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType, |
2825 | IncompatibleObjC)) { |
2826 | // We always complain about this conversion. |
2827 | IncompatibleObjC = true; |
2828 | ConvertedType = Context.getPointerType(T: ConvertedType); |
2829 | ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers); |
2830 | return true; |
2831 | } |
2832 | // Allow conversion of pointee being objective-c pointer to another one; |
2833 | // as in I* to id. |
2834 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && |
2835 | ToPointeeType->getAs<ObjCObjectPointerType>() && |
2836 | isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType, |
2837 | IncompatibleObjC)) { |
2838 | |
2839 | ConvertedType = Context.getPointerType(T: ConvertedType); |
2840 | ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers); |
2841 | return true; |
2842 | } |
2843 | |
2844 | // If we have pointers to functions or blocks, check whether the only |
2845 | // differences in the argument and result types are in Objective-C |
2846 | // pointer conversions. If so, we permit the conversion (but |
2847 | // complain about it). |
2848 | const FunctionProtoType *FromFunctionType |
2849 | = FromPointeeType->getAs<FunctionProtoType>(); |
2850 | const FunctionProtoType *ToFunctionType |
2851 | = ToPointeeType->getAs<FunctionProtoType>(); |
2852 | if (FromFunctionType && ToFunctionType) { |
2853 | // If the function types are exactly the same, this isn't an |
2854 | // Objective-C pointer conversion. |
2855 | if (Context.getCanonicalType(T: FromPointeeType) |
2856 | == Context.getCanonicalType(T: ToPointeeType)) |
2857 | return false; |
2858 | |
2859 | // Perform the quick checks that will tell us whether these |
2860 | // function types are obviously different. |
2861 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2862 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || |
2863 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) |
2864 | return false; |
2865 | |
2866 | bool HasObjCConversion = false; |
2867 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == |
2868 | Context.getCanonicalType(ToFunctionType->getReturnType())) { |
2869 | // Okay, the types match exactly. Nothing to do. |
2870 | } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(), |
2871 | ToType: ToFunctionType->getReturnType(), |
2872 | ConvertedType, IncompatibleObjC)) { |
2873 | // Okay, we have an Objective-C pointer conversion. |
2874 | HasObjCConversion = true; |
2875 | } else { |
2876 | // Function types are too different. Abort. |
2877 | return false; |
2878 | } |
2879 | |
2880 | // Check argument types. |
2881 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2882 | ArgIdx != NumArgs; ++ArgIdx) { |
2883 | QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx); |
2884 | QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx); |
2885 | if (Context.getCanonicalType(T: FromArgType) |
2886 | == Context.getCanonicalType(T: ToArgType)) { |
2887 | // Okay, the types match exactly. Nothing to do. |
2888 | } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType, |
2889 | ConvertedType, IncompatibleObjC)) { |
2890 | // Okay, we have an Objective-C pointer conversion. |
2891 | HasObjCConversion = true; |
2892 | } else { |
2893 | // Argument types are too different. Abort. |
2894 | return false; |
2895 | } |
2896 | } |
2897 | |
2898 | if (HasObjCConversion) { |
2899 | // We had an Objective-C conversion. Allow this pointer |
2900 | // conversion, but complain about it. |
2901 | ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers); |
2902 | IncompatibleObjC = true; |
2903 | return true; |
2904 | } |
2905 | } |
2906 | |
2907 | return false; |
2908 | } |
2909 | |
2910 | /// Determine whether this is an Objective-C writeback conversion, |
2911 | /// used for parameter passing when performing automatic reference counting. |
2912 | /// |
2913 | /// \param FromType The type we're converting form. |
2914 | /// |
2915 | /// \param ToType The type we're converting to. |
2916 | /// |
2917 | /// \param ConvertedType The type that will be produced after applying |
2918 | /// this conversion. |
2919 | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, |
2920 | QualType &ConvertedType) { |
2921 | if (!getLangOpts().ObjCAutoRefCount || |
2922 | Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) |
2923 | return false; |
2924 | |
2925 | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). |
2926 | QualType ToPointee; |
2927 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) |
2928 | ToPointee = ToPointer->getPointeeType(); |
2929 | else |
2930 | return false; |
2931 | |
2932 | Qualifiers ToQuals = ToPointee.getQualifiers(); |
2933 | if (!ToPointee->isObjCLifetimeType() || |
2934 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || |
2935 | !ToQuals.withoutObjCLifetime().empty()) |
2936 | return false; |
2937 | |
2938 | // Argument must be a pointer to __strong to __weak. |
2939 | QualType FromPointee; |
2940 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) |
2941 | FromPointee = FromPointer->getPointeeType(); |
2942 | else |
2943 | return false; |
2944 | |
2945 | Qualifiers FromQuals = FromPointee.getQualifiers(); |
2946 | if (!FromPointee->isObjCLifetimeType() || |
2947 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && |
2948 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) |
2949 | return false; |
2950 | |
2951 | // Make sure that we have compatible qualifiers. |
2952 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); |
2953 | if (!ToQuals.compatiblyIncludes(other: FromQuals)) |
2954 | return false; |
2955 | |
2956 | // Remove qualifiers from the pointee type we're converting from; they |
2957 | // aren't used in the compatibility check belong, and we'll be adding back |
2958 | // qualifiers (with __autoreleasing) if the compatibility check succeeds. |
2959 | FromPointee = FromPointee.getUnqualifiedType(); |
2960 | |
2961 | // The unqualified form of the pointee types must be compatible. |
2962 | ToPointee = ToPointee.getUnqualifiedType(); |
2963 | bool IncompatibleObjC; |
2964 | if (Context.typesAreCompatible(T1: FromPointee, T2: ToPointee)) |
2965 | FromPointee = ToPointee; |
2966 | else if (!isObjCPointerConversion(FromType: FromPointee, ToType: ToPointee, ConvertedType&: FromPointee, |
2967 | IncompatibleObjC)) |
2968 | return false; |
2969 | |
2970 | /// Construct the type we're converting to, which is a pointer to |
2971 | /// __autoreleasing pointee. |
2972 | FromPointee = Context.getQualifiedType(T: FromPointee, Qs: FromQuals); |
2973 | ConvertedType = Context.getPointerType(T: FromPointee); |
2974 | return true; |
2975 | } |
2976 | |
2977 | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, |
2978 | QualType& ConvertedType) { |
2979 | QualType ToPointeeType; |
2980 | if (const BlockPointerType *ToBlockPtr = |
2981 | ToType->getAs<BlockPointerType>()) |
2982 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2983 | else |
2984 | return false; |
2985 | |
2986 | QualType FromPointeeType; |
2987 | if (const BlockPointerType *FromBlockPtr = |
2988 | FromType->getAs<BlockPointerType>()) |
2989 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2990 | else |
2991 | return false; |
2992 | // We have pointer to blocks, check whether the only |
2993 | // differences in the argument and result types are in Objective-C |
2994 | // pointer conversions. If so, we permit the conversion. |
2995 | |
2996 | const FunctionProtoType *FromFunctionType |
2997 | = FromPointeeType->getAs<FunctionProtoType>(); |
2998 | const FunctionProtoType *ToFunctionType |
2999 | = ToPointeeType->getAs<FunctionProtoType>(); |
3000 | |
3001 | if (!FromFunctionType || !ToFunctionType) |
3002 | return false; |
3003 | |
3004 | if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType)) |
3005 | return true; |
3006 | |
3007 | // Perform the quick checks that will tell us whether these |
3008 | // function types are obviously different. |
3009 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
3010 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) |
3011 | return false; |
3012 | |
3013 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); |
3014 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); |
3015 | if (FromEInfo != ToEInfo) |
3016 | return false; |
3017 | |
3018 | bool IncompatibleObjC = false; |
3019 | if (Context.hasSameType(FromFunctionType->getReturnType(), |
3020 | ToFunctionType->getReturnType())) { |
3021 | // Okay, the types match exactly. Nothing to do. |
3022 | } else { |
3023 | QualType RHS = FromFunctionType->getReturnType(); |
3024 | QualType LHS = ToFunctionType->getReturnType(); |
3025 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && |
3026 | !RHS.hasQualifiers() && LHS.hasQualifiers()) |
3027 | LHS = LHS.getUnqualifiedType(); |
3028 | |
3029 | if (Context.hasSameType(T1: RHS,T2: LHS)) { |
3030 | // OK exact match. |
3031 | } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS, |
3032 | ConvertedType, IncompatibleObjC)) { |
3033 | if (IncompatibleObjC) |
3034 | return false; |
3035 | // Okay, we have an Objective-C pointer conversion. |
3036 | } |
3037 | else |
3038 | return false; |
3039 | } |
3040 | |
3041 | // Check argument types. |
3042 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
3043 | ArgIdx != NumArgs; ++ArgIdx) { |
3044 | IncompatibleObjC = false; |
3045 | QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx); |
3046 | QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx); |
3047 | if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) { |
3048 | // Okay, the types match exactly. Nothing to do. |
3049 | } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType, |
3050 | ConvertedType, IncompatibleObjC)) { |
3051 | if (IncompatibleObjC) |
3052 | return false; |
3053 | // Okay, we have an Objective-C pointer conversion. |
3054 | } else |
3055 | // Argument types are too different. Abort. |
3056 | return false; |
3057 | } |
3058 | |
3059 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
3060 | bool CanUseToFPT, CanUseFromFPT; |
3061 | if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType, |
3062 | CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT, |
3063 | NewParamInfos)) |
3064 | return false; |
3065 | |
3066 | ConvertedType = ToType; |
3067 | return true; |
3068 | } |
3069 | |
3070 | enum { |
3071 | ft_default, |
3072 | ft_different_class, |
3073 | ft_parameter_arity, |
3074 | ft_parameter_mismatch, |
3075 | ft_return_type, |
3076 | ft_qualifer_mismatch, |
3077 | ft_noexcept |
3078 | }; |
3079 | |
3080 | /// Attempts to get the FunctionProtoType from a Type. Handles |
3081 | /// MemberFunctionPointers properly. |
3082 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { |
3083 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) |
3084 | return FPT; |
3085 | |
3086 | if (auto *MPT = FromType->getAs<MemberPointerType>()) |
3087 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); |
3088 | |
3089 | return nullptr; |
3090 | } |
3091 | |
3092 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing |
3093 | /// function types. Catches different number of parameter, mismatch in |
3094 | /// parameter types, and different return types. |
3095 | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
3096 | QualType FromType, QualType ToType) { |
3097 | // If either type is not valid, include no extra info. |
3098 | if (FromType.isNull() || ToType.isNull()) { |
3099 | PDiag << ft_default; |
3100 | return; |
3101 | } |
3102 | |
3103 | // Get the function type from the pointers. |
3104 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { |
3105 | const auto *FromMember = FromType->castAs<MemberPointerType>(), |
3106 | *ToMember = ToType->castAs<MemberPointerType>(); |
3107 | if (!Context.hasSameType(T1: FromMember->getClass(), T2: ToMember->getClass())) { |
3108 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) |
3109 | << QualType(FromMember->getClass(), 0); |
3110 | return; |
3111 | } |
3112 | FromType = FromMember->getPointeeType(); |
3113 | ToType = ToMember->getPointeeType(); |
3114 | } |
3115 | |
3116 | if (FromType->isPointerType()) |
3117 | FromType = FromType->getPointeeType(); |
3118 | if (ToType->isPointerType()) |
3119 | ToType = ToType->getPointeeType(); |
3120 | |
3121 | // Remove references. |
3122 | FromType = FromType.getNonReferenceType(); |
3123 | ToType = ToType.getNonReferenceType(); |
3124 | |
3125 | // Don't print extra info for non-specialized template functions. |
3126 | if (FromType->isInstantiationDependentType() && |
3127 | !FromType->getAs<TemplateSpecializationType>()) { |
3128 | PDiag << ft_default; |
3129 | return; |
3130 | } |
3131 | |
3132 | // No extra info for same types. |
3133 | if (Context.hasSameType(T1: FromType, T2: ToType)) { |
3134 | PDiag << ft_default; |
3135 | return; |
3136 | } |
3137 | |
3138 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), |
3139 | *ToFunction = tryGetFunctionProtoType(FromType: ToType); |
3140 | |
3141 | // Both types need to be function types. |
3142 | if (!FromFunction || !ToFunction) { |
3143 | PDiag << ft_default; |
3144 | return; |
3145 | } |
3146 | |
3147 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { |
3148 | PDiag << ft_parameter_arity << ToFunction->getNumParams() |
3149 | << FromFunction->getNumParams(); |
3150 | return; |
3151 | } |
3152 | |
3153 | // Handle different parameter types. |
3154 | unsigned ArgPos; |
3155 | if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) { |
3156 | PDiag << ft_parameter_mismatch << ArgPos + 1 |
3157 | << ToFunction->getParamType(i: ArgPos) |
3158 | << FromFunction->getParamType(i: ArgPos); |
3159 | return; |
3160 | } |
3161 | |
3162 | // Handle different return type. |
3163 | if (!Context.hasSameType(FromFunction->getReturnType(), |
3164 | ToFunction->getReturnType())) { |
3165 | PDiag << ft_return_type << ToFunction->getReturnType() |
3166 | << FromFunction->getReturnType(); |
3167 | return; |
3168 | } |
3169 | |
3170 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { |
3171 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() |
3172 | << FromFunction->getMethodQuals(); |
3173 | return; |
3174 | } |
3175 | |
3176 | // Handle exception specification differences on canonical type (in C++17 |
3177 | // onwards). |
3178 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) |
3179 | ->isNothrow() != |
3180 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) |
3181 | ->isNothrow()) { |
3182 | PDiag << ft_noexcept; |
3183 | return; |
3184 | } |
3185 | |
3186 | // Unable to find a difference, so add no extra info. |
3187 | PDiag << ft_default; |
3188 | } |
3189 | |
3190 | /// FunctionParamTypesAreEqual - This routine checks two function proto types |
3191 | /// for equality of their parameter types. Caller has already checked that |
3192 | /// they have same number of parameters. If the parameters are different, |
3193 | /// ArgPos will have the parameter index of the first different parameter. |
3194 | /// If `Reversed` is true, the parameters of `NewType` will be compared in |
3195 | /// reverse order. That's useful if one of the functions is being used as a C++20 |
3196 | /// synthesized operator overload with a reversed parameter order. |
3197 | bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old, |
3198 | ArrayRef<QualType> New, unsigned *ArgPos, |
3199 | bool Reversed) { |
3200 | assert(llvm::size(Old) == llvm::size(New) && |
3201 | "Can't compare parameters of functions with different number of " |
3202 | "parameters!" ); |
3203 | |
3204 | for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) { |
3205 | // Reverse iterate over the parameters of `OldType` if `Reversed` is true. |
3206 | size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx; |
3207 | |
3208 | // Ignore address spaces in pointee type. This is to disallow overloading |
3209 | // on __ptr32/__ptr64 address spaces. |
3210 | QualType OldType = |
3211 | Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType()); |
3212 | QualType NewType = |
3213 | Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType()); |
3214 | |
3215 | if (!Context.hasSameType(T1: OldType, T2: NewType)) { |
3216 | if (ArgPos) |
3217 | *ArgPos = Idx; |
3218 | return false; |
3219 | } |
3220 | } |
3221 | return true; |
3222 | } |
3223 | |
3224 | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
3225 | const FunctionProtoType *NewType, |
3226 | unsigned *ArgPos, bool Reversed) { |
3227 | return FunctionParamTypesAreEqual(Old: OldType->param_types(), |
3228 | New: NewType->param_types(), ArgPos, Reversed); |
3229 | } |
3230 | |
3231 | bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, |
3232 | const FunctionDecl *NewFunction, |
3233 | unsigned *ArgPos, |
3234 | bool Reversed) { |
3235 | |
3236 | if (OldFunction->getNumNonObjectParams() != |
3237 | NewFunction->getNumNonObjectParams()) |
3238 | return false; |
3239 | |
3240 | unsigned OldIgnore = |
3241 | unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter()); |
3242 | unsigned NewIgnore = |
3243 | unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter()); |
3244 | |
3245 | auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType()); |
3246 | auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType()); |
3247 | |
3248 | return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore), |
3249 | NewPT->param_types().slice(NewIgnore), |
3250 | ArgPos, Reversed); |
3251 | } |
3252 | |
3253 | /// CheckPointerConversion - Check the pointer conversion from the |
3254 | /// expression From to the type ToType. This routine checks for |
3255 | /// ambiguous or inaccessible derived-to-base pointer |
3256 | /// conversions for which IsPointerConversion has already returned |
3257 | /// true. It returns true and produces a diagnostic if there was an |
3258 | /// error, or returns false otherwise. |
3259 | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, |
3260 | CastKind &Kind, |
3261 | CXXCastPath& BasePath, |
3262 | bool IgnoreBaseAccess, |
3263 | bool Diagnose) { |
3264 | QualType FromType = From->getType(); |
3265 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; |
3266 | |
3267 | Kind = CK_BitCast; |
3268 | |
3269 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && |
3270 | From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) == |
3271 | Expr::NPCK_ZeroExpression) { |
3272 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) |
3273 | DiagRuntimeBehavior(From->getExprLoc(), From, |
3274 | PDiag(diag::warn_impcast_bool_to_null_pointer) |
3275 | << ToType << From->getSourceRange()); |
3276 | else if (!isUnevaluatedContext()) |
3277 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) |
3278 | << ToType << From->getSourceRange(); |
3279 | } |
3280 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { |
3281 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { |
3282 | QualType FromPointeeType = FromPtrType->getPointeeType(), |
3283 | ToPointeeType = ToPtrType->getPointeeType(); |
3284 | |
3285 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && |
3286 | !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) { |
3287 | // We must have a derived-to-base conversion. Check an |
3288 | // ambiguous or inaccessible conversion. |
3289 | unsigned InaccessibleID = 0; |
3290 | unsigned AmbiguousID = 0; |
3291 | if (Diagnose) { |
3292 | InaccessibleID = diag::err_upcast_to_inaccessible_base; |
3293 | AmbiguousID = diag::err_ambiguous_derived_to_base_conv; |
3294 | } |
3295 | if (CheckDerivedToBaseConversion( |
3296 | FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, |
3297 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), |
3298 | &BasePath, IgnoreBaseAccess)) |
3299 | return true; |
3300 | |
3301 | // The conversion was successful. |
3302 | Kind = CK_DerivedToBase; |
3303 | } |
3304 | |
3305 | if (Diagnose && !IsCStyleOrFunctionalCast && |
3306 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { |
3307 | assert(getLangOpts().MSVCCompat && |
3308 | "this should only be possible with MSVCCompat!" ); |
3309 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) |
3310 | << From->getSourceRange(); |
3311 | } |
3312 | } |
3313 | } else if (const ObjCObjectPointerType *ToPtrType = |
3314 | ToType->getAs<ObjCObjectPointerType>()) { |
3315 | if (const ObjCObjectPointerType *FromPtrType = |
3316 | FromType->getAs<ObjCObjectPointerType>()) { |
3317 | // Objective-C++ conversions are always okay. |
3318 | // FIXME: We should have a different class of conversions for the |
3319 | // Objective-C++ implicit conversions. |
3320 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) |
3321 | return false; |
3322 | } else if (FromType->isBlockPointerType()) { |
3323 | Kind = CK_BlockPointerToObjCPointerCast; |
3324 | } else { |
3325 | Kind = CK_CPointerToObjCPointerCast; |
3326 | } |
3327 | } else if (ToType->isBlockPointerType()) { |
3328 | if (!FromType->isBlockPointerType()) |
3329 | Kind = CK_AnyPointerToBlockPointerCast; |
3330 | } |
3331 | |
3332 | // We shouldn't fall into this case unless it's valid for other |
3333 | // reasons. |
3334 | if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) |
3335 | Kind = CK_NullToPointer; |
3336 | |
3337 | return false; |
3338 | } |
3339 | |
3340 | /// IsMemberPointerConversion - Determines whether the conversion of the |
3341 | /// expression From, which has the (possibly adjusted) type FromType, can be |
3342 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). |
3343 | /// If so, returns true and places the converted type (that might differ from |
3344 | /// ToType in its cv-qualifiers at some level) into ConvertedType. |
3345 | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, |
3346 | QualType ToType, |
3347 | bool InOverloadResolution, |
3348 | QualType &ConvertedType) { |
3349 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); |
3350 | if (!ToTypePtr) |
3351 | return false; |
3352 | |
3353 | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) |
3354 | if (From->isNullPointerConstant(Ctx&: Context, |
3355 | NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
3356 | : Expr::NPC_ValueDependentIsNull)) { |
3357 | ConvertedType = ToType; |
3358 | return true; |
3359 | } |
3360 | |
3361 | // Otherwise, both types have to be member pointers. |
3362 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); |
3363 | if (!FromTypePtr) |
3364 | return false; |
3365 | |
3366 | // A pointer to member of B can be converted to a pointer to member of D, |
3367 | // where D is derived from B (C++ 4.11p2). |
3368 | QualType FromClass(FromTypePtr->getClass(), 0); |
3369 | QualType ToClass(ToTypePtr->getClass(), 0); |
3370 | |
3371 | if (!Context.hasSameUnqualifiedType(T1: FromClass, T2: ToClass) && |
3372 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { |
3373 | ConvertedType = Context.getMemberPointerType(T: FromTypePtr->getPointeeType(), |
3374 | Cls: ToClass.getTypePtr()); |
3375 | return true; |
3376 | } |
3377 | |
3378 | return false; |
3379 | } |
3380 | |
3381 | /// CheckMemberPointerConversion - Check the member pointer conversion from the |
3382 | /// expression From to the type ToType. This routine checks for ambiguous or |
3383 | /// virtual or inaccessible base-to-derived member pointer conversions |
3384 | /// for which IsMemberPointerConversion has already returned true. It returns |
3385 | /// true and produces a diagnostic if there was an error, or returns false |
3386 | /// otherwise. |
3387 | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, |
3388 | CastKind &Kind, |
3389 | CXXCastPath &BasePath, |
3390 | bool IgnoreBaseAccess) { |
3391 | QualType FromType = From->getType(); |
3392 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); |
3393 | if (!FromPtrType) { |
3394 | // This must be a null pointer to member pointer conversion |
3395 | assert(From->isNullPointerConstant(Context, |
3396 | Expr::NPC_ValueDependentIsNull) && |
3397 | "Expr must be null pointer constant!" ); |
3398 | Kind = CK_NullToMemberPointer; |
3399 | return false; |
3400 | } |
3401 | |
3402 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); |
3403 | assert(ToPtrType && "No member pointer cast has a target type " |
3404 | "that is not a member pointer." ); |
3405 | |
3406 | QualType FromClass = QualType(FromPtrType->getClass(), 0); |
3407 | QualType ToClass = QualType(ToPtrType->getClass(), 0); |
3408 | |
3409 | // FIXME: What about dependent types? |
3410 | assert(FromClass->isRecordType() && "Pointer into non-class." ); |
3411 | assert(ToClass->isRecordType() && "Pointer into non-class." ); |
3412 | |
3413 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3414 | /*DetectVirtual=*/true); |
3415 | bool DerivationOkay = |
3416 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); |
3417 | assert(DerivationOkay && |
3418 | "Should not have been called if derivation isn't OK." ); |
3419 | (void)DerivationOkay; |
3420 | |
3421 | if (Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: FromClass). |
3422 | getUnqualifiedType())) { |
3423 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3424 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) |
3425 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); |
3426 | return true; |
3427 | } |
3428 | |
3429 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { |
3430 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) |
3431 | << FromClass << ToClass << QualType(VBase, 0) |
3432 | << From->getSourceRange(); |
3433 | return true; |
3434 | } |
3435 | |
3436 | if (!IgnoreBaseAccess) |
3437 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, |
3438 | Paths.front(), |
3439 | diag::err_downcast_from_inaccessible_base); |
3440 | |
3441 | // Must be a base to derived member conversion. |
3442 | BuildBasePathArray(Paths, BasePath); |
3443 | Kind = CK_BaseToDerivedMemberPointer; |
3444 | return false; |
3445 | } |
3446 | |
3447 | /// Determine whether the lifetime conversion between the two given |
3448 | /// qualifiers sets is nontrivial. |
3449 | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, |
3450 | Qualifiers ToQuals) { |
3451 | // Converting anything to const __unsafe_unretained is trivial. |
3452 | if (ToQuals.hasConst() && |
3453 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) |
3454 | return false; |
3455 | |
3456 | return true; |
3457 | } |
3458 | |
3459 | /// Perform a single iteration of the loop for checking if a qualification |
3460 | /// conversion is valid. |
3461 | /// |
3462 | /// Specifically, check whether any change between the qualifiers of \p |
3463 | /// FromType and \p ToType is permissible, given knowledge about whether every |
3464 | /// outer layer is const-qualified. |
3465 | static bool isQualificationConversionStep(QualType FromType, QualType ToType, |
3466 | bool CStyle, bool IsTopLevel, |
3467 | bool &PreviousToQualsIncludeConst, |
3468 | bool &ObjCLifetimeConversion) { |
3469 | Qualifiers FromQuals = FromType.getQualifiers(); |
3470 | Qualifiers ToQuals = ToType.getQualifiers(); |
3471 | |
3472 | // Ignore __unaligned qualifier. |
3473 | FromQuals.removeUnaligned(); |
3474 | |
3475 | // Objective-C ARC: |
3476 | // Check Objective-C lifetime conversions. |
3477 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { |
3478 | if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) { |
3479 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) |
3480 | ObjCLifetimeConversion = true; |
3481 | FromQuals.removeObjCLifetime(); |
3482 | ToQuals.removeObjCLifetime(); |
3483 | } else { |
3484 | // Qualification conversions cannot cast between different |
3485 | // Objective-C lifetime qualifiers. |
3486 | return false; |
3487 | } |
3488 | } |
3489 | |
3490 | // Allow addition/removal of GC attributes but not changing GC attributes. |
3491 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && |
3492 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { |
3493 | FromQuals.removeObjCGCAttr(); |
3494 | ToQuals.removeObjCGCAttr(); |
3495 | } |
3496 | |
3497 | // -- for every j > 0, if const is in cv 1,j then const is in cv |
3498 | // 2,j, and similarly for volatile. |
3499 | if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals)) |
3500 | return false; |
3501 | |
3502 | // If address spaces mismatch: |
3503 | // - in top level it is only valid to convert to addr space that is a |
3504 | // superset in all cases apart from C-style casts where we allow |
3505 | // conversions between overlapping address spaces. |
3506 | // - in non-top levels it is not a valid conversion. |
3507 | if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && |
3508 | (!IsTopLevel || |
3509 | !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals) || |
3510 | (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals))))) |
3511 | return false; |
3512 | |
3513 | // -- if the cv 1,j and cv 2,j are different, then const is in |
3514 | // every cv for 0 < k < j. |
3515 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && |
3516 | !PreviousToQualsIncludeConst) |
3517 | return false; |
3518 | |
3519 | // The following wording is from C++20, where the result of the conversion |
3520 | // is T3, not T2. |
3521 | // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is |
3522 | // "array of unknown bound of" |
3523 | if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) |
3524 | return false; |
3525 | |
3526 | // -- if the resulting P3,i is different from P1,i [...], then const is |
3527 | // added to every cv 3_k for 0 < k < i. |
3528 | if (!CStyle && FromType->isConstantArrayType() && |
3529 | ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) |
3530 | return false; |
3531 | |
3532 | // Keep track of whether all prior cv-qualifiers in the "to" type |
3533 | // include const. |
3534 | PreviousToQualsIncludeConst = |
3535 | PreviousToQualsIncludeConst && ToQuals.hasConst(); |
3536 | return true; |
3537 | } |
3538 | |
3539 | /// IsQualificationConversion - Determines whether the conversion from |
3540 | /// an rvalue of type FromType to ToType is a qualification conversion |
3541 | /// (C++ 4.4). |
3542 | /// |
3543 | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate |
3544 | /// when the qualification conversion involves a change in the Objective-C |
3545 | /// object lifetime. |
3546 | bool |
3547 | Sema::IsQualificationConversion(QualType FromType, QualType ToType, |
3548 | bool CStyle, bool &ObjCLifetimeConversion) { |
3549 | FromType = Context.getCanonicalType(T: FromType); |
3550 | ToType = Context.getCanonicalType(T: ToType); |
3551 | ObjCLifetimeConversion = false; |
3552 | |
3553 | // If FromType and ToType are the same type, this is not a |
3554 | // qualification conversion. |
3555 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) |
3556 | return false; |
3557 | |
3558 | // (C++ 4.4p4): |
3559 | // A conversion can add cv-qualifiers at levels other than the first |
3560 | // in multi-level pointers, subject to the following rules: [...] |
3561 | bool PreviousToQualsIncludeConst = true; |
3562 | bool UnwrappedAnyPointer = false; |
3563 | while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) { |
3564 | if (!isQualificationConversionStep( |
3565 | FromType, ToType, CStyle, IsTopLevel: !UnwrappedAnyPointer, |
3566 | PreviousToQualsIncludeConst, ObjCLifetimeConversion)) |
3567 | return false; |
3568 | UnwrappedAnyPointer = true; |
3569 | } |
3570 | |
3571 | // We are left with FromType and ToType being the pointee types |
3572 | // after unwrapping the original FromType and ToType the same number |
3573 | // of times. If we unwrapped any pointers, and if FromType and |
3574 | // ToType have the same unqualified type (since we checked |
3575 | // qualifiers above), then this is a qualification conversion. |
3576 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType); |
3577 | } |
3578 | |
3579 | /// - Determine whether this is a conversion from a scalar type to an |
3580 | /// atomic type. |
3581 | /// |
3582 | /// If successful, updates \c SCS's second and third steps in the conversion |
3583 | /// sequence to finish the conversion. |
3584 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
3585 | bool InOverloadResolution, |
3586 | StandardConversionSequence &SCS, |
3587 | bool CStyle) { |
3588 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); |
3589 | if (!ToAtomic) |
3590 | return false; |
3591 | |
3592 | StandardConversionSequence InnerSCS; |
3593 | if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(), |
3594 | InOverloadResolution, SCS&: InnerSCS, |
3595 | CStyle, /*AllowObjCWritebackConversion=*/false)) |
3596 | return false; |
3597 | |
3598 | SCS.Second = InnerSCS.Second; |
3599 | SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1)); |
3600 | SCS.Third = InnerSCS.Third; |
3601 | SCS.QualificationIncludesObjCLifetime |
3602 | = InnerSCS.QualificationIncludesObjCLifetime; |
3603 | SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2)); |
3604 | return true; |
3605 | } |
3606 | |
3607 | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, |
3608 | CXXConstructorDecl *Constructor, |
3609 | QualType Type) { |
3610 | const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); |
3611 | if (CtorType->getNumParams() > 0) { |
3612 | QualType FirstArg = CtorType->getParamType(0); |
3613 | if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType())) |
3614 | return true; |
3615 | } |
3616 | return false; |
3617 | } |
3618 | |
3619 | static OverloadingResult |
3620 | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, |
3621 | CXXRecordDecl *To, |
3622 | UserDefinedConversionSequence &User, |
3623 | OverloadCandidateSet &CandidateSet, |
3624 | bool AllowExplicit) { |
3625 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3626 | for (auto *D : S.LookupConstructors(Class: To)) { |
3627 | auto Info = getConstructorInfo(ND: D); |
3628 | if (!Info) |
3629 | continue; |
3630 | |
3631 | bool Usable = !Info.Constructor->isInvalidDecl() && |
3632 | S.isInitListConstructor(Info.Constructor); |
3633 | if (Usable) { |
3634 | bool SuppressUserConversions = false; |
3635 | if (Info.ConstructorTmpl) |
3636 | S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
3637 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From, |
3638 | CandidateSet, SuppressUserConversions, |
3639 | /*PartialOverloading*/ false, |
3640 | AllowExplicit); |
3641 | else |
3642 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, |
3643 | CandidateSet, SuppressUserConversions, |
3644 | /*PartialOverloading*/ false, AllowExplicit); |
3645 | } |
3646 | } |
3647 | |
3648 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3649 | |
3650 | OverloadCandidateSet::iterator Best; |
3651 | switch (auto Result = |
3652 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3653 | case OR_Deleted: |
3654 | case OR_Success: { |
3655 | // Record the standard conversion we used and the conversion function. |
3656 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function); |
3657 | QualType ThisType = Constructor->getFunctionObjectParameterType(); |
3658 | // Initializer lists don't have conversions as such. |
3659 | User.Before.setAsIdentityConversion(); |
3660 | User.HadMultipleCandidates = HadMultipleCandidates; |
3661 | User.ConversionFunction = Constructor; |
3662 | User.FoundConversionFunction = Best->FoundDecl; |
3663 | User.After.setAsIdentityConversion(); |
3664 | User.After.setFromType(ThisType); |
3665 | User.After.setAllToTypes(ToType); |
3666 | return Result; |
3667 | } |
3668 | |
3669 | case OR_No_Viable_Function: |
3670 | return OR_No_Viable_Function; |
3671 | case OR_Ambiguous: |
3672 | return OR_Ambiguous; |
3673 | } |
3674 | |
3675 | llvm_unreachable("Invalid OverloadResult!" ); |
3676 | } |
3677 | |
3678 | /// Determines whether there is a user-defined conversion sequence |
3679 | /// (C++ [over.ics.user]) that converts expression From to the type |
3680 | /// ToType. If such a conversion exists, User will contain the |
3681 | /// user-defined conversion sequence that performs such a conversion |
3682 | /// and this routine will return true. Otherwise, this routine returns |
3683 | /// false and User is unspecified. |
3684 | /// |
3685 | /// \param AllowExplicit true if the conversion should consider C++0x |
3686 | /// "explicit" conversion functions as well as non-explicit conversion |
3687 | /// functions (C++0x [class.conv.fct]p2). |
3688 | /// |
3689 | /// \param AllowObjCConversionOnExplicit true if the conversion should |
3690 | /// allow an extra Objective-C pointer conversion on uses of explicit |
3691 | /// constructors. Requires \c AllowExplicit to also be set. |
3692 | static OverloadingResult |
3693 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
3694 | UserDefinedConversionSequence &User, |
3695 | OverloadCandidateSet &CandidateSet, |
3696 | AllowedExplicit AllowExplicit, |
3697 | bool AllowObjCConversionOnExplicit) { |
3698 | assert(AllowExplicit != AllowedExplicit::None || |
3699 | !AllowObjCConversionOnExplicit); |
3700 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3701 | |
3702 | // Whether we will only visit constructors. |
3703 | bool ConstructorsOnly = false; |
3704 | |
3705 | // If the type we are conversion to is a class type, enumerate its |
3706 | // constructors. |
3707 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { |
3708 | // C++ [over.match.ctor]p1: |
3709 | // When objects of class type are direct-initialized (8.5), or |
3710 | // copy-initialized from an expression of the same or a |
3711 | // derived class type (8.5), overload resolution selects the |
3712 | // constructor. [...] For copy-initialization, the candidate |
3713 | // functions are all the converting constructors (12.3.1) of |
3714 | // that class. The argument list is the expression-list within |
3715 | // the parentheses of the initializer. |
3716 | if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) || |
3717 | (From->getType()->getAs<RecordType>() && |
3718 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) |
3719 | ConstructorsOnly = true; |
3720 | |
3721 | if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) { |
3722 | // We're not going to find any constructors. |
3723 | } else if (CXXRecordDecl *ToRecordDecl |
3724 | = dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) { |
3725 | |
3726 | Expr **Args = &From; |
3727 | unsigned NumArgs = 1; |
3728 | bool ListInitializing = false; |
3729 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) { |
3730 | // But first, see if there is an init-list-constructor that will work. |
3731 | OverloadingResult Result = IsInitializerListConstructorConversion( |
3732 | S, From, ToType, To: ToRecordDecl, User, CandidateSet, |
3733 | AllowExplicit: AllowExplicit == AllowedExplicit::All); |
3734 | if (Result != OR_No_Viable_Function) |
3735 | return Result; |
3736 | // Never mind. |
3737 | CandidateSet.clear( |
3738 | CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3739 | |
3740 | // If we're list-initializing, we pass the individual elements as |
3741 | // arguments, not the entire list. |
3742 | Args = InitList->getInits(); |
3743 | NumArgs = InitList->getNumInits(); |
3744 | ListInitializing = true; |
3745 | } |
3746 | |
3747 | for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) { |
3748 | auto Info = getConstructorInfo(ND: D); |
3749 | if (!Info) |
3750 | continue; |
3751 | |
3752 | bool Usable = !Info.Constructor->isInvalidDecl(); |
3753 | if (!ListInitializing) |
3754 | Usable = Usable && Info.Constructor->isConvertingConstructor( |
3755 | /*AllowExplicit*/ true); |
3756 | if (Usable) { |
3757 | bool SuppressUserConversions = !ConstructorsOnly; |
3758 | // C++20 [over.best.ics.general]/4.5: |
3759 | // if the target is the first parameter of a constructor [of class |
3760 | // X] and the constructor [...] is a candidate by [...] the second |
3761 | // phase of [over.match.list] when the initializer list has exactly |
3762 | // one element that is itself an initializer list, [...] and the |
3763 | // conversion is to X or reference to cv X, user-defined conversion |
3764 | // sequences are not cnosidered. |
3765 | if (SuppressUserConversions && ListInitializing) { |
3766 | SuppressUserConversions = |
3767 | NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) && |
3768 | isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor, |
3769 | Type: ToType); |
3770 | } |
3771 | if (Info.ConstructorTmpl) |
3772 | S.AddTemplateOverloadCandidate( |
3773 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
3774 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs), |
3775 | CandidateSet, SuppressUserConversions, |
3776 | /*PartialOverloading*/ false, |
3777 | AllowExplicit: AllowExplicit == AllowedExplicit::All); |
3778 | else |
3779 | // Allow one user-defined conversion when user specifies a |
3780 | // From->ToType conversion via an static cast (c-style, etc). |
3781 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, |
3782 | llvm::ArrayRef(Args, NumArgs), CandidateSet, |
3783 | SuppressUserConversions, |
3784 | /*PartialOverloading*/ false, |
3785 | AllowExplicit == AllowedExplicit::All); |
3786 | } |
3787 | } |
3788 | } |
3789 | } |
3790 | |
3791 | // Enumerate conversion functions, if we're allowed to. |
3792 | if (ConstructorsOnly || isa<InitListExpr>(Val: From)) { |
3793 | } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) { |
3794 | // No conversion functions from incomplete types. |
3795 | } else if (const RecordType *FromRecordType = |
3796 | From->getType()->getAs<RecordType>()) { |
3797 | if (CXXRecordDecl *FromRecordDecl |
3798 | = dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) { |
3799 | // Add all of the conversion functions as candidates. |
3800 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); |
3801 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
3802 | DeclAccessPair FoundDecl = I.getPair(); |
3803 | NamedDecl *D = FoundDecl.getDecl(); |
3804 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
3805 | if (isa<UsingShadowDecl>(Val: D)) |
3806 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
3807 | |
3808 | CXXConversionDecl *Conv; |
3809 | FunctionTemplateDecl *ConvTemplate; |
3810 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D))) |
3811 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
3812 | else |
3813 | Conv = cast<CXXConversionDecl>(Val: D); |
3814 | |
3815 | if (ConvTemplate) |
3816 | S.AddTemplateConversionCandidate( |
3817 | FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, |
3818 | CandidateSet, AllowObjCConversionOnExplicit, |
3819 | AllowExplicit: AllowExplicit != AllowedExplicit::None); |
3820 | else |
3821 | S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType, |
3822 | CandidateSet, AllowObjCConversionOnExplicit, |
3823 | AllowExplicit: AllowExplicit != AllowedExplicit::None); |
3824 | } |
3825 | } |
3826 | } |
3827 | |
3828 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3829 | |
3830 | OverloadCandidateSet::iterator Best; |
3831 | switch (auto Result = |
3832 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3833 | case OR_Success: |
3834 | case OR_Deleted: |
3835 | // Record the standard conversion we used and the conversion function. |
3836 | if (CXXConstructorDecl *Constructor |
3837 | = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) { |
3838 | // C++ [over.ics.user]p1: |
3839 | // If the user-defined conversion is specified by a |
3840 | // constructor (12.3.1), the initial standard conversion |
3841 | // sequence converts the source type to the type required by |
3842 | // the argument of the constructor. |
3843 | // |
3844 | if (isa<InitListExpr>(Val: From)) { |
3845 | // Initializer lists don't have conversions as such. |
3846 | User.Before.setAsIdentityConversion(); |
3847 | } else { |
3848 | if (Best->Conversions[0].isEllipsis()) |
3849 | User.EllipsisConversion = true; |
3850 | else { |
3851 | User.Before = Best->Conversions[0].Standard; |
3852 | User.EllipsisConversion = false; |
3853 | } |
3854 | } |
3855 | User.HadMultipleCandidates = HadMultipleCandidates; |
3856 | User.ConversionFunction = Constructor; |
3857 | User.FoundConversionFunction = Best->FoundDecl; |
3858 | User.After.setAsIdentityConversion(); |
3859 | User.After.setFromType(Constructor->getFunctionObjectParameterType()); |
3860 | User.After.setAllToTypes(ToType); |
3861 | return Result; |
3862 | } |
3863 | if (CXXConversionDecl *Conversion |
3864 | = dyn_cast<CXXConversionDecl>(Val: Best->Function)) { |
3865 | // C++ [over.ics.user]p1: |
3866 | // |
3867 | // [...] If the user-defined conversion is specified by a |
3868 | // conversion function (12.3.2), the initial standard |
3869 | // conversion sequence converts the source type to the |
3870 | // implicit object parameter of the conversion function. |
3871 | User.Before = Best->Conversions[0].Standard; |
3872 | User.HadMultipleCandidates = HadMultipleCandidates; |
3873 | User.ConversionFunction = Conversion; |
3874 | User.FoundConversionFunction = Best->FoundDecl; |
3875 | User.EllipsisConversion = false; |
3876 | |
3877 | // C++ [over.ics.user]p2: |
3878 | // The second standard conversion sequence converts the |
3879 | // result of the user-defined conversion to the target type |
3880 | // for the sequence. Since an implicit conversion sequence |
3881 | // is an initialization, the special rules for |
3882 | // initialization by user-defined conversion apply when |
3883 | // selecting the best user-defined conversion for a |
3884 | // user-defined conversion sequence (see 13.3.3 and |
3885 | // 13.3.3.1). |
3886 | User.After = Best->FinalConversion; |
3887 | return Result; |
3888 | } |
3889 | llvm_unreachable("Not a constructor or conversion function?" ); |
3890 | |
3891 | case OR_No_Viable_Function: |
3892 | return OR_No_Viable_Function; |
3893 | |
3894 | case OR_Ambiguous: |
3895 | return OR_Ambiguous; |
3896 | } |
3897 | |
3898 | llvm_unreachable("Invalid OverloadResult!" ); |
3899 | } |
3900 | |
3901 | bool |
3902 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { |
3903 | ImplicitConversionSequence ICS; |
3904 | OverloadCandidateSet CandidateSet(From->getExprLoc(), |
3905 | OverloadCandidateSet::CSK_Normal); |
3906 | OverloadingResult OvResult = |
3907 | IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined, |
3908 | CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false); |
3909 | |
3910 | if (!(OvResult == OR_Ambiguous || |
3911 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) |
3912 | return false; |
3913 | |
3914 | auto Cands = CandidateSet.CompleteCandidates( |
3915 | S&: *this, |
3916 | OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, |
3917 | Args: From); |
3918 | if (OvResult == OR_Ambiguous) |
3919 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) |
3920 | << From->getType() << ToType << From->getSourceRange(); |
3921 | else { // OR_No_Viable_Function && !CandidateSet.empty() |
3922 | if (!RequireCompleteType(From->getBeginLoc(), ToType, |
3923 | diag::err_typecheck_nonviable_condition_incomplete, |
3924 | From->getType(), From->getSourceRange())) |
3925 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) |
3926 | << false << From->getType() << From->getSourceRange() << ToType; |
3927 | } |
3928 | |
3929 | CandidateSet.NoteCandidates( |
3930 | S&: *this, Args: From, Cands); |
3931 | return true; |
3932 | } |
3933 | |
3934 | // Helper for compareConversionFunctions that gets the FunctionType that the |
3935 | // conversion-operator return value 'points' to, or nullptr. |
3936 | static const FunctionType * |
3937 | getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { |
3938 | const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); |
3939 | const PointerType *RetPtrTy = |
3940 | ConvFuncTy->getReturnType()->getAs<PointerType>(); |
3941 | |
3942 | if (!RetPtrTy) |
3943 | return nullptr; |
3944 | |
3945 | return RetPtrTy->getPointeeType()->getAs<FunctionType>(); |
3946 | } |
3947 | |
3948 | /// Compare the user-defined conversion functions or constructors |
3949 | /// of two user-defined conversion sequences to determine whether any ordering |
3950 | /// is possible. |
3951 | static ImplicitConversionSequence::CompareKind |
3952 | compareConversionFunctions(Sema &S, FunctionDecl *Function1, |
3953 | FunctionDecl *Function2) { |
3954 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1); |
3955 | CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2); |
3956 | if (!Conv1 || !Conv2) |
3957 | return ImplicitConversionSequence::Indistinguishable; |
3958 | |
3959 | if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) |
3960 | return ImplicitConversionSequence::Indistinguishable; |
3961 | |
3962 | // Objective-C++: |
3963 | // If both conversion functions are implicitly-declared conversions from |
3964 | // a lambda closure type to a function pointer and a block pointer, |
3965 | // respectively, always prefer the conversion to a function pointer, |
3966 | // because the function pointer is more lightweight and is more likely |
3967 | // to keep code working. |
3968 | if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { |
3969 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); |
3970 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); |
3971 | if (Block1 != Block2) |
3972 | return Block1 ? ImplicitConversionSequence::Worse |
3973 | : ImplicitConversionSequence::Better; |
3974 | } |
3975 | |
3976 | // In order to support multiple calling conventions for the lambda conversion |
3977 | // operator (such as when the free and member function calling convention is |
3978 | // different), prefer the 'free' mechanism, followed by the calling-convention |
3979 | // of operator(). The latter is in place to support the MSVC-like solution of |
3980 | // defining ALL of the possible conversions in regards to calling-convention. |
3981 | const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1); |
3982 | const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2); |
3983 | |
3984 | if (Conv1FuncRet && Conv2FuncRet && |
3985 | Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { |
3986 | CallingConv Conv1CC = Conv1FuncRet->getCallConv(); |
3987 | CallingConv Conv2CC = Conv2FuncRet->getCallConv(); |
3988 | |
3989 | CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); |
3990 | const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); |
3991 | |
3992 | CallingConv CallOpCC = |
3993 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
3994 | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( |
3995 | IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false); |
3996 | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( |
3997 | IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true); |
3998 | |
3999 | CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; |
4000 | for (CallingConv CC : PrefOrder) { |
4001 | if (Conv1CC == CC) |
4002 | return ImplicitConversionSequence::Better; |
4003 | if (Conv2CC == CC) |
4004 | return ImplicitConversionSequence::Worse; |
4005 | } |
4006 | } |
4007 | |
4008 | return ImplicitConversionSequence::Indistinguishable; |
4009 | } |
4010 | |
4011 | static bool hasDeprecatedStringLiteralToCharPtrConversion( |
4012 | const ImplicitConversionSequence &ICS) { |
4013 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || |
4014 | (ICS.isUserDefined() && |
4015 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); |
4016 | } |
4017 | |
4018 | /// CompareImplicitConversionSequences - Compare two implicit |
4019 | /// conversion sequences to determine whether one is better than the |
4020 | /// other or if they are indistinguishable (C++ 13.3.3.2). |
4021 | static ImplicitConversionSequence::CompareKind |
4022 | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, |
4023 | const ImplicitConversionSequence& ICS1, |
4024 | const ImplicitConversionSequence& ICS2) |
4025 | { |
4026 | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit |
4027 | // conversion sequences (as defined in 13.3.3.1) |
4028 | // -- a standard conversion sequence (13.3.3.1.1) is a better |
4029 | // conversion sequence than a user-defined conversion sequence or |
4030 | // an ellipsis conversion sequence, and |
4031 | // -- a user-defined conversion sequence (13.3.3.1.2) is a better |
4032 | // conversion sequence than an ellipsis conversion sequence |
4033 | // (13.3.3.1.3). |
4034 | // |
4035 | // C++0x [over.best.ics]p10: |
4036 | // For the purpose of ranking implicit conversion sequences as |
4037 | // described in 13.3.3.2, the ambiguous conversion sequence is |
4038 | // treated as a user-defined sequence that is indistinguishable |
4039 | // from any other user-defined conversion sequence. |
4040 | |
4041 | // String literal to 'char *' conversion has been deprecated in C++03. It has |
4042 | // been removed from C++11. We still accept this conversion, if it happens at |
4043 | // the best viable function. Otherwise, this conversion is considered worse |
4044 | // than ellipsis conversion. Consider this as an extension; this is not in the |
4045 | // standard. For example: |
4046 | // |
4047 | // int &f(...); // #1 |
4048 | // void f(char*); // #2 |
4049 | // void g() { int &r = f("foo"); } |
4050 | // |
4051 | // In C++03, we pick #2 as the best viable function. |
4052 | // In C++11, we pick #1 as the best viable function, because ellipsis |
4053 | // conversion is better than string-literal to char* conversion (since there |
4054 | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't |
4055 | // convert arguments, #2 would be the best viable function in C++11. |
4056 | // If the best viable function has this conversion, a warning will be issued |
4057 | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. |
4058 | |
4059 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
4060 | hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) != |
4061 | hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) && |
4062 | // Ill-formedness must not differ |
4063 | ICS1.isBad() == ICS2.isBad()) |
4064 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) |
4065 | ? ImplicitConversionSequence::Worse |
4066 | : ImplicitConversionSequence::Better; |
4067 | |
4068 | if (ICS1.getKindRank() < ICS2.getKindRank()) |
4069 | return ImplicitConversionSequence::Better; |
4070 | if (ICS2.getKindRank() < ICS1.getKindRank()) |
4071 | return ImplicitConversionSequence::Worse; |
4072 | |
4073 | // The following checks require both conversion sequences to be of |
4074 | // the same kind. |
4075 | if (ICS1.getKind() != ICS2.getKind()) |
4076 | return ImplicitConversionSequence::Indistinguishable; |
4077 | |
4078 | ImplicitConversionSequence::CompareKind Result = |
4079 | ImplicitConversionSequence::Indistinguishable; |
4080 | |
4081 | // Two implicit conversion sequences of the same form are |
4082 | // indistinguishable conversion sequences unless one of the |
4083 | // following rules apply: (C++ 13.3.3.2p3): |
4084 | |
4085 | // List-initialization sequence L1 is a better conversion sequence than |
4086 | // list-initialization sequence L2 if: |
4087 | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, |
4088 | // if not that, |
4089 | // — L1 and L2 convert to arrays of the same element type, and either the |
4090 | // number of elements n_1 initialized by L1 is less than the number of |
4091 | // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to |
4092 | // an array of unknown bound and L1 does not, |
4093 | // even if one of the other rules in this paragraph would otherwise apply. |
4094 | if (!ICS1.isBad()) { |
4095 | bool StdInit1 = false, StdInit2 = false; |
4096 | if (ICS1.hasInitializerListContainerType()) |
4097 | StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(), |
4098 | Element: nullptr); |
4099 | if (ICS2.hasInitializerListContainerType()) |
4100 | StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(), |
4101 | Element: nullptr); |
4102 | if (StdInit1 != StdInit2) |
4103 | return StdInit1 ? ImplicitConversionSequence::Better |
4104 | : ImplicitConversionSequence::Worse; |
4105 | |
4106 | if (ICS1.hasInitializerListContainerType() && |
4107 | ICS2.hasInitializerListContainerType()) |
4108 | if (auto *CAT1 = S.Context.getAsConstantArrayType( |
4109 | T: ICS1.getInitializerListContainerType())) |
4110 | if (auto *CAT2 = S.Context.getAsConstantArrayType( |
4111 | T: ICS2.getInitializerListContainerType())) { |
4112 | if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(), |
4113 | T2: CAT2->getElementType())) { |
4114 | // Both to arrays of the same element type |
4115 | if (CAT1->getSize() != CAT2->getSize()) |
4116 | // Different sized, the smaller wins |
4117 | return CAT1->getSize().ult(RHS: CAT2->getSize()) |
4118 | ? ImplicitConversionSequence::Better |
4119 | : ImplicitConversionSequence::Worse; |
4120 | if (ICS1.isInitializerListOfIncompleteArray() != |
4121 | ICS2.isInitializerListOfIncompleteArray()) |
4122 | // One is incomplete, it loses |
4123 | return ICS2.isInitializerListOfIncompleteArray() |
4124 | ? ImplicitConversionSequence::Better |
4125 | : ImplicitConversionSequence::Worse; |
4126 | } |
4127 | } |
4128 | } |
4129 | |
4130 | if (ICS1.isStandard()) |
4131 | // Standard conversion sequence S1 is a better conversion sequence than |
4132 | // standard conversion sequence S2 if [...] |
4133 | Result = CompareStandardConversionSequences(S, Loc, |
4134 | SCS1: ICS1.Standard, SCS2: ICS2.Standard); |
4135 | else if (ICS1.isUserDefined()) { |
4136 | // User-defined conversion sequence U1 is a better conversion |
4137 | // sequence than another user-defined conversion sequence U2 if |
4138 | // they contain the same user-defined conversion function or |
4139 | // constructor and if the second standard conversion sequence of |
4140 | // U1 is better than the second standard conversion sequence of |
4141 | // U2 (C++ 13.3.3.2p3). |
4142 | if (ICS1.UserDefined.ConversionFunction == |
4143 | ICS2.UserDefined.ConversionFunction) |
4144 | Result = CompareStandardConversionSequences(S, Loc, |
4145 | SCS1: ICS1.UserDefined.After, |
4146 | SCS2: ICS2.UserDefined.After); |
4147 | else |
4148 | Result = compareConversionFunctions(S, |
4149 | Function1: ICS1.UserDefined.ConversionFunction, |
4150 | Function2: ICS2.UserDefined.ConversionFunction); |
4151 | } |
4152 | |
4153 | return Result; |
4154 | } |
4155 | |
4156 | // Per 13.3.3.2p3, compare the given standard conversion sequences to |
4157 | // determine if one is a proper subset of the other. |
4158 | static ImplicitConversionSequence::CompareKind |
4159 | compareStandardConversionSubsets(ASTContext &Context, |
4160 | const StandardConversionSequence& SCS1, |
4161 | const StandardConversionSequence& SCS2) { |
4162 | ImplicitConversionSequence::CompareKind Result |
4163 | = ImplicitConversionSequence::Indistinguishable; |
4164 | |
4165 | // the identity conversion sequence is considered to be a subsequence of |
4166 | // any non-identity conversion sequence |
4167 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) |
4168 | return ImplicitConversionSequence::Better; |
4169 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) |
4170 | return ImplicitConversionSequence::Worse; |
4171 | |
4172 | if (SCS1.Second != SCS2.Second) { |
4173 | if (SCS1.Second == ICK_Identity) |
4174 | Result = ImplicitConversionSequence::Better; |
4175 | else if (SCS2.Second == ICK_Identity) |
4176 | Result = ImplicitConversionSequence::Worse; |
4177 | else |
4178 | return ImplicitConversionSequence::Indistinguishable; |
4179 | } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1))) |
4180 | return ImplicitConversionSequence::Indistinguishable; |
4181 | |
4182 | if (SCS1.Third == SCS2.Third) { |
4183 | return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result |
4184 | : ImplicitConversionSequence::Indistinguishable; |
4185 | } |
4186 | |
4187 | if (SCS1.Third == ICK_Identity) |
4188 | return Result == ImplicitConversionSequence::Worse |
4189 | ? ImplicitConversionSequence::Indistinguishable |
4190 | : ImplicitConversionSequence::Better; |
4191 | |
4192 | if (SCS2.Third == ICK_Identity) |
4193 | return Result == ImplicitConversionSequence::Better |
4194 | ? ImplicitConversionSequence::Indistinguishable |
4195 | : ImplicitConversionSequence::Worse; |
4196 | |
4197 | return ImplicitConversionSequence::Indistinguishable; |
4198 | } |
4199 | |
4200 | /// Determine whether one of the given reference bindings is better |
4201 | /// than the other based on what kind of bindings they are. |
4202 | static bool |
4203 | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, |
4204 | const StandardConversionSequence &SCS2) { |
4205 | // C++0x [over.ics.rank]p3b4: |
4206 | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an |
4207 | // implicit object parameter of a non-static member function declared |
4208 | // without a ref-qualifier, and *either* S1 binds an rvalue reference |
4209 | // to an rvalue and S2 binds an lvalue reference *or S1 binds an |
4210 | // lvalue reference to a function lvalue and S2 binds an rvalue |
4211 | // reference*. |
4212 | // |
4213 | // FIXME: Rvalue references. We're going rogue with the above edits, |
4214 | // because the semantics in the current C++0x working paper (N3225 at the |
4215 | // time of this writing) break the standard definition of std::forward |
4216 | // and std::reference_wrapper when dealing with references to functions. |
4217 | // Proposed wording changes submitted to CWG for consideration. |
4218 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || |
4219 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) |
4220 | return false; |
4221 | |
4222 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && |
4223 | SCS2.IsLvalueReference) || |
4224 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && |
4225 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); |
4226 | } |
4227 | |
4228 | enum class FixedEnumPromotion { |
4229 | None, |
4230 | ToUnderlyingType, |
4231 | ToPromotedUnderlyingType |
4232 | }; |
4233 | |
4234 | /// Returns kind of fixed enum promotion the \a SCS uses. |
4235 | static FixedEnumPromotion |
4236 | getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { |
4237 | |
4238 | if (SCS.Second != ICK_Integral_Promotion) |
4239 | return FixedEnumPromotion::None; |
4240 | |
4241 | QualType FromType = SCS.getFromType(); |
4242 | if (!FromType->isEnumeralType()) |
4243 | return FixedEnumPromotion::None; |
4244 | |
4245 | EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); |
4246 | if (!Enum->isFixed()) |
4247 | return FixedEnumPromotion::None; |
4248 | |
4249 | QualType UnderlyingType = Enum->getIntegerType(); |
4250 | if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType)) |
4251 | return FixedEnumPromotion::ToUnderlyingType; |
4252 | |
4253 | return FixedEnumPromotion::ToPromotedUnderlyingType; |
4254 | } |
4255 | |
4256 | /// CompareStandardConversionSequences - Compare two standard |
4257 | /// conversion sequences to determine whether one is better than the |
4258 | /// other or if they are indistinguishable (C++ 13.3.3.2p3). |
4259 | static ImplicitConversionSequence::CompareKind |
4260 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
4261 | const StandardConversionSequence& SCS1, |
4262 | const StandardConversionSequence& SCS2) |
4263 | { |
4264 | // Standard conversion sequence S1 is a better conversion sequence |
4265 | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): |
4266 | |
4267 | // -- S1 is a proper subsequence of S2 (comparing the conversion |
4268 | // sequences in the canonical form defined by 13.3.3.1.1, |
4269 | // excluding any Lvalue Transformation; the identity conversion |
4270 | // sequence is considered to be a subsequence of any |
4271 | // non-identity conversion sequence) or, if not that, |
4272 | if (ImplicitConversionSequence::CompareKind CK |
4273 | = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2)) |
4274 | return CK; |
4275 | |
4276 | // -- the rank of S1 is better than the rank of S2 (by the rules |
4277 | // defined below), or, if not that, |
4278 | ImplicitConversionRank Rank1 = SCS1.getRank(); |
4279 | ImplicitConversionRank Rank2 = SCS2.getRank(); |
4280 | if (Rank1 < Rank2) |
4281 | return ImplicitConversionSequence::Better; |
4282 | else if (Rank2 < Rank1) |
4283 | return ImplicitConversionSequence::Worse; |
4284 | |
4285 | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank |
4286 | // are indistinguishable unless one of the following rules |
4287 | // applies: |
4288 | |
4289 | // A conversion that is not a conversion of a pointer, or |
4290 | // pointer to member, to bool is better than another conversion |
4291 | // that is such a conversion. |
4292 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) |
4293 | return SCS2.isPointerConversionToBool() |
4294 | ? ImplicitConversionSequence::Better |
4295 | : ImplicitConversionSequence::Worse; |
4296 | |
4297 | // C++14 [over.ics.rank]p4b2: |
4298 | // This is retroactively applied to C++11 by CWG 1601. |
4299 | // |
4300 | // A conversion that promotes an enumeration whose underlying type is fixed |
4301 | // to its underlying type is better than one that promotes to the promoted |
4302 | // underlying type, if the two are different. |
4303 | FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1); |
4304 | FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2); |
4305 | if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && |
4306 | FEP1 != FEP2) |
4307 | return FEP1 == FixedEnumPromotion::ToUnderlyingType |
4308 | ? ImplicitConversionSequence::Better |
4309 | : ImplicitConversionSequence::Worse; |
4310 | |
4311 | // C++ [over.ics.rank]p4b2: |
4312 | // |
4313 | // If class B is derived directly or indirectly from class A, |
4314 | // conversion of B* to A* is better than conversion of B* to |
4315 | // void*, and conversion of A* to void* is better than conversion |
4316 | // of B* to void*. |
4317 | bool SCS1ConvertsToVoid |
4318 | = SCS1.isPointerConversionToVoidPointer(Context&: S.Context); |
4319 | bool SCS2ConvertsToVoid |
4320 | = SCS2.isPointerConversionToVoidPointer(Context&: S.Context); |
4321 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { |
4322 | // Exactly one of the conversion sequences is a conversion to |
4323 | // a void pointer; it's the worse conversion. |
4324 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better |
4325 | : ImplicitConversionSequence::Worse; |
4326 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { |
4327 | // Neither conversion sequence converts to a void pointer; compare |
4328 | // their derived-to-base conversions. |
4329 | if (ImplicitConversionSequence::CompareKind DerivedCK |
4330 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) |
4331 | return DerivedCK; |
4332 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && |
4333 | !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) { |
4334 | // Both conversion sequences are conversions to void |
4335 | // pointers. Compare the source types to determine if there's an |
4336 | // inheritance relationship in their sources. |
4337 | QualType FromType1 = SCS1.getFromType(); |
4338 | QualType FromType2 = SCS2.getFromType(); |
4339 | |
4340 | // Adjust the types we're converting from via the array-to-pointer |
4341 | // conversion, if we need to. |
4342 | if (SCS1.First == ICK_Array_To_Pointer) |
4343 | FromType1 = S.Context.getArrayDecayedType(T: FromType1); |
4344 | if (SCS2.First == ICK_Array_To_Pointer) |
4345 | FromType2 = S.Context.getArrayDecayedType(T: FromType2); |
4346 | |
4347 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); |
4348 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); |
4349 | |
4350 | if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1)) |
4351 | return ImplicitConversionSequence::Better; |
4352 | else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2)) |
4353 | return ImplicitConversionSequence::Worse; |
4354 | |
4355 | // Objective-C++: If one interface is more specific than the |
4356 | // other, it is the better one. |
4357 | const ObjCObjectPointerType* FromObjCPtr1 |
4358 | = FromType1->getAs<ObjCObjectPointerType>(); |
4359 | const ObjCObjectPointerType* FromObjCPtr2 |
4360 | = FromType2->getAs<ObjCObjectPointerType>(); |
4361 | if (FromObjCPtr1 && FromObjCPtr2) { |
4362 | bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1, |
4363 | RHSOPT: FromObjCPtr2); |
4364 | bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2, |
4365 | RHSOPT: FromObjCPtr1); |
4366 | if (AssignLeft != AssignRight) { |
4367 | return AssignLeft? ImplicitConversionSequence::Better |
4368 | : ImplicitConversionSequence::Worse; |
4369 | } |
4370 | } |
4371 | } |
4372 | |
4373 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4374 | // Check for a better reference binding based on the kind of bindings. |
4375 | if (isBetterReferenceBindingKind(SCS1, SCS2)) |
4376 | return ImplicitConversionSequence::Better; |
4377 | else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1)) |
4378 | return ImplicitConversionSequence::Worse; |
4379 | } |
4380 | |
4381 | // Compare based on qualification conversions (C++ 13.3.3.2p3, |
4382 | // bullet 3). |
4383 | if (ImplicitConversionSequence::CompareKind QualCK |
4384 | = CompareQualificationConversions(S, SCS1, SCS2)) |
4385 | return QualCK; |
4386 | |
4387 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4388 | // C++ [over.ics.rank]p3b4: |
4389 | // -- S1 and S2 are reference bindings (8.5.3), and the types to |
4390 | // which the references refer are the same type except for |
4391 | // top-level cv-qualifiers, and the type to which the reference |
4392 | // initialized by S2 refers is more cv-qualified than the type |
4393 | // to which the reference initialized by S1 refers. |
4394 | QualType T1 = SCS1.getToType(Idx: 2); |
4395 | QualType T2 = SCS2.getToType(Idx: 2); |
4396 | T1 = S.Context.getCanonicalType(T: T1); |
4397 | T2 = S.Context.getCanonicalType(T: T2); |
4398 | Qualifiers T1Quals, T2Quals; |
4399 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals); |
4400 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals); |
4401 | if (UnqualT1 == UnqualT2) { |
4402 | // Objective-C++ ARC: If the references refer to objects with different |
4403 | // lifetimes, prefer bindings that don't change lifetime. |
4404 | if (SCS1.ObjCLifetimeConversionBinding != |
4405 | SCS2.ObjCLifetimeConversionBinding) { |
4406 | return SCS1.ObjCLifetimeConversionBinding |
4407 | ? ImplicitConversionSequence::Worse |
4408 | : ImplicitConversionSequence::Better; |
4409 | } |
4410 | |
4411 | // If the type is an array type, promote the element qualifiers to the |
4412 | // type for comparison. |
4413 | if (isa<ArrayType>(Val: T1) && T1Quals) |
4414 | T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals); |
4415 | if (isa<ArrayType>(Val: T2) && T2Quals) |
4416 | T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals); |
4417 | if (T2.isMoreQualifiedThan(other: T1)) |
4418 | return ImplicitConversionSequence::Better; |
4419 | if (T1.isMoreQualifiedThan(other: T2)) |
4420 | return ImplicitConversionSequence::Worse; |
4421 | } |
4422 | } |
4423 | |
4424 | // In Microsoft mode (below 19.28), prefer an integral conversion to a |
4425 | // floating-to-integral conversion if the integral conversion |
4426 | // is between types of the same size. |
4427 | // For example: |
4428 | // void f(float); |
4429 | // void f(int); |
4430 | // int main { |
4431 | // long a; |
4432 | // f(a); |
4433 | // } |
4434 | // Here, MSVC will call f(int) instead of generating a compile error |
4435 | // as clang will do in standard mode. |
4436 | if (S.getLangOpts().MSVCCompat && |
4437 | !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) && |
4438 | SCS1.Second == ICK_Integral_Conversion && |
4439 | SCS2.Second == ICK_Floating_Integral && |
4440 | S.Context.getTypeSize(T: SCS1.getFromType()) == |
4441 | S.Context.getTypeSize(T: SCS1.getToType(Idx: 2))) |
4442 | return ImplicitConversionSequence::Better; |
4443 | |
4444 | // Prefer a compatible vector conversion over a lax vector conversion |
4445 | // For example: |
4446 | // |
4447 | // typedef float __v4sf __attribute__((__vector_size__(16))); |
4448 | // void f(vector float); |
4449 | // void f(vector signed int); |
4450 | // int main() { |
4451 | // __v4sf a; |
4452 | // f(a); |
4453 | // } |
4454 | // Here, we'd like to choose f(vector float) and not |
4455 | // report an ambiguous call error |
4456 | if (SCS1.Second == ICK_Vector_Conversion && |
4457 | SCS2.Second == ICK_Vector_Conversion) { |
4458 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4459 | FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2)); |
4460 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4461 | FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2)); |
4462 | |
4463 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) |
4464 | return SCS1IsCompatibleVectorConversion |
4465 | ? ImplicitConversionSequence::Better |
4466 | : ImplicitConversionSequence::Worse; |
4467 | } |
4468 | |
4469 | if (SCS1.Second == ICK_SVE_Vector_Conversion && |
4470 | SCS2.Second == ICK_SVE_Vector_Conversion) { |
4471 | bool SCS1IsCompatibleSVEVectorConversion = |
4472 | S.Context.areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2)); |
4473 | bool SCS2IsCompatibleSVEVectorConversion = |
4474 | S.Context.areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2)); |
4475 | |
4476 | if (SCS1IsCompatibleSVEVectorConversion != |
4477 | SCS2IsCompatibleSVEVectorConversion) |
4478 | return SCS1IsCompatibleSVEVectorConversion |
4479 | ? ImplicitConversionSequence::Better |
4480 | : ImplicitConversionSequence::Worse; |
4481 | } |
4482 | |
4483 | if (SCS1.Second == ICK_RVV_Vector_Conversion && |
4484 | SCS2.Second == ICK_RVV_Vector_Conversion) { |
4485 | bool SCS1IsCompatibleRVVVectorConversion = |
4486 | S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2)); |
4487 | bool SCS2IsCompatibleRVVVectorConversion = |
4488 | S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2)); |
4489 | |
4490 | if (SCS1IsCompatibleRVVVectorConversion != |
4491 | SCS2IsCompatibleRVVVectorConversion) |
4492 | return SCS1IsCompatibleRVVVectorConversion |
4493 | ? ImplicitConversionSequence::Better |
4494 | : ImplicitConversionSequence::Worse; |
4495 | } |
4496 | |
4497 | return ImplicitConversionSequence::Indistinguishable; |
4498 | } |
4499 | |
4500 | /// CompareQualificationConversions - Compares two standard conversion |
4501 | /// sequences to determine whether they can be ranked based on their |
4502 | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). |
4503 | static ImplicitConversionSequence::CompareKind |
4504 | CompareQualificationConversions(Sema &S, |
4505 | const StandardConversionSequence& SCS1, |
4506 | const StandardConversionSequence& SCS2) { |
4507 | // C++ [over.ics.rank]p3: |
4508 | // -- S1 and S2 differ only in their qualification conversion and |
4509 | // yield similar types T1 and T2 (C++ 4.4), respectively, [...] |
4510 | // [C++98] |
4511 | // [...] and the cv-qualification signature of type T1 is a proper subset |
4512 | // of the cv-qualification signature of type T2, and S1 is not the |
4513 | // deprecated string literal array-to-pointer conversion (4.2). |
4514 | // [C++2a] |
4515 | // [...] where T1 can be converted to T2 by a qualification conversion. |
4516 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || |
4517 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) |
4518 | return ImplicitConversionSequence::Indistinguishable; |
4519 | |
4520 | // FIXME: the example in the standard doesn't use a qualification |
4521 | // conversion (!) |
4522 | QualType T1 = SCS1.getToType(Idx: 2); |
4523 | QualType T2 = SCS2.getToType(Idx: 2); |
4524 | T1 = S.Context.getCanonicalType(T: T1); |
4525 | T2 = S.Context.getCanonicalType(T: T2); |
4526 | assert(!T1->isReferenceType() && !T2->isReferenceType()); |
4527 | Qualifiers T1Quals, T2Quals; |
4528 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals); |
4529 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals); |
4530 | |
4531 | // If the types are the same, we won't learn anything by unwrapping |
4532 | // them. |
4533 | if (UnqualT1 == UnqualT2) |
4534 | return ImplicitConversionSequence::Indistinguishable; |
4535 | |
4536 | // Don't ever prefer a standard conversion sequence that uses the deprecated |
4537 | // string literal array to pointer conversion. |
4538 | bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; |
4539 | bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; |
4540 | |
4541 | // Objective-C++ ARC: |
4542 | // Prefer qualification conversions not involving a change in lifetime |
4543 | // to qualification conversions that do change lifetime. |
4544 | if (SCS1.QualificationIncludesObjCLifetime && |
4545 | !SCS2.QualificationIncludesObjCLifetime) |
4546 | CanPick1 = false; |
4547 | if (SCS2.QualificationIncludesObjCLifetime && |
4548 | !SCS1.QualificationIncludesObjCLifetime) |
4549 | CanPick2 = false; |
4550 | |
4551 | bool ObjCLifetimeConversion; |
4552 | if (CanPick1 && |
4553 | !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion)) |
4554 | CanPick1 = false; |
4555 | // FIXME: In Objective-C ARC, we can have qualification conversions in both |
4556 | // directions, so we can't short-cut this second check in general. |
4557 | if (CanPick2 && |
4558 | !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion)) |
4559 | CanPick2 = false; |
4560 | |
4561 | if (CanPick1 != CanPick2) |
4562 | return CanPick1 ? ImplicitConversionSequence::Better |
4563 | : ImplicitConversionSequence::Worse; |
4564 | return ImplicitConversionSequence::Indistinguishable; |
4565 | } |
4566 | |
4567 | /// CompareDerivedToBaseConversions - Compares two standard conversion |
4568 | /// sequences to determine whether they can be ranked based on their |
4569 | /// various kinds of derived-to-base conversions (C++ |
4570 | /// [over.ics.rank]p4b3). As part of these checks, we also look at |
4571 | /// conversions between Objective-C interface types. |
4572 | static ImplicitConversionSequence::CompareKind |
4573 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
4574 | const StandardConversionSequence& SCS1, |
4575 | const StandardConversionSequence& SCS2) { |
4576 | QualType FromType1 = SCS1.getFromType(); |
4577 | QualType ToType1 = SCS1.getToType(Idx: 1); |
4578 | QualType FromType2 = SCS2.getFromType(); |
4579 | QualType ToType2 = SCS2.getToType(Idx: 1); |
4580 | |
4581 | // Adjust the types we're converting from via the array-to-pointer |
4582 | // conversion, if we need to. |
4583 | if (SCS1.First == ICK_Array_To_Pointer) |
4584 | FromType1 = S.Context.getArrayDecayedType(T: FromType1); |
4585 | if (SCS2.First == ICK_Array_To_Pointer) |
4586 | FromType2 = S.Context.getArrayDecayedType(T: FromType2); |
4587 | |
4588 | // Canonicalize all of the types. |
4589 | FromType1 = S.Context.getCanonicalType(T: FromType1); |
4590 | ToType1 = S.Context.getCanonicalType(T: ToType1); |
4591 | FromType2 = S.Context.getCanonicalType(T: FromType2); |
4592 | ToType2 = S.Context.getCanonicalType(T: ToType2); |
4593 | |
4594 | // C++ [over.ics.rank]p4b3: |
4595 | // |
4596 | // If class B is derived directly or indirectly from class A and |
4597 | // class C is derived directly or indirectly from B, |
4598 | // |
4599 | // Compare based on pointer conversions. |
4600 | if (SCS1.Second == ICK_Pointer_Conversion && |
4601 | SCS2.Second == ICK_Pointer_Conversion && |
4602 | /*FIXME: Remove if Objective-C id conversions get their own rank*/ |
4603 | FromType1->isPointerType() && FromType2->isPointerType() && |
4604 | ToType1->isPointerType() && ToType2->isPointerType()) { |
4605 | QualType FromPointee1 = |
4606 | FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4607 | QualType ToPointee1 = |
4608 | ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4609 | QualType FromPointee2 = |
4610 | FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4611 | QualType ToPointee2 = |
4612 | ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4613 | |
4614 | // -- conversion of C* to B* is better than conversion of C* to A*, |
4615 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4616 | if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2)) |
4617 | return ImplicitConversionSequence::Better; |
4618 | else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1)) |
4619 | return ImplicitConversionSequence::Worse; |
4620 | } |
4621 | |
4622 | // -- conversion of B* to A* is better than conversion of C* to A*, |
4623 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { |
4624 | if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1)) |
4625 | return ImplicitConversionSequence::Better; |
4626 | else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2)) |
4627 | return ImplicitConversionSequence::Worse; |
4628 | } |
4629 | } else if (SCS1.Second == ICK_Pointer_Conversion && |
4630 | SCS2.Second == ICK_Pointer_Conversion) { |
4631 | const ObjCObjectPointerType *FromPtr1 |
4632 | = FromType1->getAs<ObjCObjectPointerType>(); |
4633 | const ObjCObjectPointerType *FromPtr2 |
4634 | = FromType2->getAs<ObjCObjectPointerType>(); |
4635 | const ObjCObjectPointerType *ToPtr1 |
4636 | = ToType1->getAs<ObjCObjectPointerType>(); |
4637 | const ObjCObjectPointerType *ToPtr2 |
4638 | = ToType2->getAs<ObjCObjectPointerType>(); |
4639 | |
4640 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { |
4641 | // Apply the same conversion ranking rules for Objective-C pointer types |
4642 | // that we do for C++ pointers to class types. However, we employ the |
4643 | // Objective-C pseudo-subtyping relationship used for assignment of |
4644 | // Objective-C pointer types. |
4645 | bool FromAssignLeft |
4646 | = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2); |
4647 | bool FromAssignRight |
4648 | = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1); |
4649 | bool ToAssignLeft |
4650 | = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2); |
4651 | bool ToAssignRight |
4652 | = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1); |
4653 | |
4654 | // A conversion to an a non-id object pointer type or qualified 'id' |
4655 | // type is better than a conversion to 'id'. |
4656 | if (ToPtr1->isObjCIdType() && |
4657 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) |
4658 | return ImplicitConversionSequence::Worse; |
4659 | if (ToPtr2->isObjCIdType() && |
4660 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) |
4661 | return ImplicitConversionSequence::Better; |
4662 | |
4663 | // A conversion to a non-id object pointer type is better than a |
4664 | // conversion to a qualified 'id' type |
4665 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) |
4666 | return ImplicitConversionSequence::Worse; |
4667 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) |
4668 | return ImplicitConversionSequence::Better; |
4669 | |
4670 | // A conversion to an a non-Class object pointer type or qualified 'Class' |
4671 | // type is better than a conversion to 'Class'. |
4672 | if (ToPtr1->isObjCClassType() && |
4673 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) |
4674 | return ImplicitConversionSequence::Worse; |
4675 | if (ToPtr2->isObjCClassType() && |
4676 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) |
4677 | return ImplicitConversionSequence::Better; |
4678 | |
4679 | // A conversion to a non-Class object pointer type is better than a |
4680 | // conversion to a qualified 'Class' type. |
4681 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) |
4682 | return ImplicitConversionSequence::Worse; |
4683 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) |
4684 | return ImplicitConversionSequence::Better; |
4685 | |
4686 | // -- "conversion of C* to B* is better than conversion of C* to A*," |
4687 | if (S.Context.hasSameType(T1: FromType1, T2: FromType2) && |
4688 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && |
4689 | (ToAssignLeft != ToAssignRight)) { |
4690 | if (FromPtr1->isSpecialized()) { |
4691 | // "conversion of B<A> * to B * is better than conversion of B * to |
4692 | // C *. |
4693 | bool IsFirstSame = |
4694 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); |
4695 | bool IsSecondSame = |
4696 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); |
4697 | if (IsFirstSame) { |
4698 | if (!IsSecondSame) |
4699 | return ImplicitConversionSequence::Better; |
4700 | } else if (IsSecondSame) |
4701 | return ImplicitConversionSequence::Worse; |
4702 | } |
4703 | return ToAssignLeft? ImplicitConversionSequence::Worse |
4704 | : ImplicitConversionSequence::Better; |
4705 | } |
4706 | |
4707 | // -- "conversion of B* to A* is better than conversion of C* to A*," |
4708 | if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) && |
4709 | (FromAssignLeft != FromAssignRight)) |
4710 | return FromAssignLeft? ImplicitConversionSequence::Better |
4711 | : ImplicitConversionSequence::Worse; |
4712 | } |
4713 | } |
4714 | |
4715 | // Ranking of member-pointer types. |
4716 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && |
4717 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && |
4718 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { |
4719 | const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); |
4720 | const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); |
4721 | const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); |
4722 | const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); |
4723 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); |
4724 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); |
4725 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); |
4726 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); |
4727 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); |
4728 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); |
4729 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); |
4730 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); |
4731 | // conversion of A::* to B::* is better than conversion of A::* to C::*, |
4732 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4733 | if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2)) |
4734 | return ImplicitConversionSequence::Worse; |
4735 | else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1)) |
4736 | return ImplicitConversionSequence::Better; |
4737 | } |
4738 | // conversion of B::* to C::* is better than conversion of A::* to C::* |
4739 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { |
4740 | if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2)) |
4741 | return ImplicitConversionSequence::Better; |
4742 | else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1)) |
4743 | return ImplicitConversionSequence::Worse; |
4744 | } |
4745 | } |
4746 | |
4747 | if (SCS1.Second == ICK_Derived_To_Base) { |
4748 | // -- conversion of C to B is better than conversion of C to A, |
4749 | // -- binding of an expression of type C to a reference of type |
4750 | // B& is better than binding an expression of type C to a |
4751 | // reference of type A&, |
4752 | if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) && |
4753 | !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) { |
4754 | if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2)) |
4755 | return ImplicitConversionSequence::Better; |
4756 | else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1)) |
4757 | return ImplicitConversionSequence::Worse; |
4758 | } |
4759 | |
4760 | // -- conversion of B to A is better than conversion of C to A. |
4761 | // -- binding of an expression of type B to a reference of type |
4762 | // A& is better than binding an expression of type C to a |
4763 | // reference of type A&, |
4764 | if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) && |
4765 | S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) { |
4766 | if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1)) |
4767 | return ImplicitConversionSequence::Better; |
4768 | else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2)) |
4769 | return ImplicitConversionSequence::Worse; |
4770 | } |
4771 | } |
4772 | |
4773 | return ImplicitConversionSequence::Indistinguishable; |
4774 | } |
4775 | |
4776 | static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { |
4777 | if (!T.getQualifiers().hasUnaligned()) |
4778 | return T; |
4779 | |
4780 | Qualifiers Q; |
4781 | T = Ctx.getUnqualifiedArrayType(T, Quals&: Q); |
4782 | Q.removeUnaligned(); |
4783 | return Ctx.getQualifiedType(T, Qs: Q); |
4784 | } |
4785 | |
4786 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to |
4787 | /// determine whether they are reference-compatible, |
4788 | /// reference-related, or incompatible, for use in C++ initialization by |
4789 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference |
4790 | /// type, and the first type (T1) is the pointee type of the reference |
4791 | /// type being initialized. |
4792 | Sema::ReferenceCompareResult |
4793 | Sema::CompareReferenceRelationship(SourceLocation Loc, |
4794 | QualType OrigT1, QualType OrigT2, |
4795 | ReferenceConversions *ConvOut) { |
4796 | assert(!OrigT1->isReferenceType() && |
4797 | "T1 must be the pointee type of the reference type" ); |
4798 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type" ); |
4799 | |
4800 | QualType T1 = Context.getCanonicalType(T: OrigT1); |
4801 | QualType T2 = Context.getCanonicalType(T: OrigT2); |
4802 | Qualifiers T1Quals, T2Quals; |
4803 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals); |
4804 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals); |
4805 | |
4806 | ReferenceConversions ConvTmp; |
4807 | ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; |
4808 | Conv = ReferenceConversions(); |
4809 | |
4810 | // C++2a [dcl.init.ref]p4: |
4811 | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is |
4812 | // reference-related to "cv2 T2" if T1 is similar to T2, or |
4813 | // T1 is a base class of T2. |
4814 | // "cv1 T1" is reference-compatible with "cv2 T2" if |
4815 | // a prvalue of type "pointer to cv2 T2" can be converted to the type |
4816 | // "pointer to cv1 T1" via a standard conversion sequence. |
4817 | |
4818 | // Check for standard conversions we can apply to pointers: derived-to-base |
4819 | // conversions, ObjC pointer conversions, and function pointer conversions. |
4820 | // (Qualification conversions are checked last.) |
4821 | QualType ConvertedT2; |
4822 | if (UnqualT1 == UnqualT2) { |
4823 | // Nothing to do. |
4824 | } else if (isCompleteType(Loc, T: OrigT2) && |
4825 | IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1)) |
4826 | Conv |= ReferenceConversions::DerivedToBase; |
4827 | else if (UnqualT1->isObjCObjectOrInterfaceType() && |
4828 | UnqualT2->isObjCObjectOrInterfaceType() && |
4829 | Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2)) |
4830 | Conv |= ReferenceConversions::ObjC; |
4831 | else if (UnqualT2->isFunctionType() && |
4832 | IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1, ResultTy&: ConvertedT2)) { |
4833 | Conv |= ReferenceConversions::Function; |
4834 | // No need to check qualifiers; function types don't have them. |
4835 | return Ref_Compatible; |
4836 | } |
4837 | bool ConvertedReferent = Conv != 0; |
4838 | |
4839 | // We can have a qualification conversion. Compute whether the types are |
4840 | // similar at the same time. |
4841 | bool PreviousToQualsIncludeConst = true; |
4842 | bool TopLevel = true; |
4843 | do { |
4844 | if (T1 == T2) |
4845 | break; |
4846 | |
4847 | // We will need a qualification conversion. |
4848 | Conv |= ReferenceConversions::Qualification; |
4849 | |
4850 | // Track whether we performed a qualification conversion anywhere other |
4851 | // than the top level. This matters for ranking reference bindings in |
4852 | // overload resolution. |
4853 | if (!TopLevel) |
4854 | Conv |= ReferenceConversions::NestedQualification; |
4855 | |
4856 | // MS compiler ignores __unaligned qualifier for references; do the same. |
4857 | T1 = withoutUnaligned(Ctx&: Context, T: T1); |
4858 | T2 = withoutUnaligned(Ctx&: Context, T: T2); |
4859 | |
4860 | // If we find a qualifier mismatch, the types are not reference-compatible, |
4861 | // but are still be reference-related if they're similar. |
4862 | bool ObjCLifetimeConversion = false; |
4863 | if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel, |
4864 | PreviousToQualsIncludeConst, |
4865 | ObjCLifetimeConversion)) |
4866 | return (ConvertedReferent || Context.hasSimilarType(T1, T2)) |
4867 | ? Ref_Related |
4868 | : Ref_Incompatible; |
4869 | |
4870 | // FIXME: Should we track this for any level other than the first? |
4871 | if (ObjCLifetimeConversion) |
4872 | Conv |= ReferenceConversions::ObjCLifetime; |
4873 | |
4874 | TopLevel = false; |
4875 | } while (Context.UnwrapSimilarTypes(T1, T2)); |
4876 | |
4877 | // At this point, if the types are reference-related, we must either have the |
4878 | // same inner type (ignoring qualifiers), or must have already worked out how |
4879 | // to convert the referent. |
4880 | return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) |
4881 | ? Ref_Compatible |
4882 | : Ref_Incompatible; |
4883 | } |
4884 | |
4885 | /// Look for a user-defined conversion to a value reference-compatible |
4886 | /// with DeclType. Return true if something definite is found. |
4887 | static bool |
4888 | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, |
4889 | QualType DeclType, SourceLocation DeclLoc, |
4890 | Expr *Init, QualType T2, bool AllowRvalues, |
4891 | bool AllowExplicit) { |
4892 | assert(T2->isRecordType() && "Can only find conversions of record types." ); |
4893 | auto *T2RecordDecl = cast<CXXRecordDecl>(Val: T2->castAs<RecordType>()->getDecl()); |
4894 | |
4895 | OverloadCandidateSet CandidateSet( |
4896 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
4897 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
4898 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4899 | NamedDecl *D = *I; |
4900 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4901 | if (isa<UsingShadowDecl>(Val: D)) |
4902 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
4903 | |
4904 | FunctionTemplateDecl *ConvTemplate |
4905 | = dyn_cast<FunctionTemplateDecl>(Val: D); |
4906 | CXXConversionDecl *Conv; |
4907 | if (ConvTemplate) |
4908 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
4909 | else |
4910 | Conv = cast<CXXConversionDecl>(Val: D); |
4911 | |
4912 | if (AllowRvalues) { |
4913 | // If we are initializing an rvalue reference, don't permit conversion |
4914 | // functions that return lvalues. |
4915 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { |
4916 | const ReferenceType *RefType |
4917 | = Conv->getConversionType()->getAs<LValueReferenceType>(); |
4918 | if (RefType && !RefType->getPointeeType()->isFunctionType()) |
4919 | continue; |
4920 | } |
4921 | |
4922 | if (!ConvTemplate && |
4923 | S.CompareReferenceRelationship( |
4924 | Loc: DeclLoc, |
4925 | OrigT1: Conv->getConversionType() |
4926 | .getNonReferenceType() |
4927 | .getUnqualifiedType(), |
4928 | OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) == |
4929 | Sema::Ref_Incompatible) |
4930 | continue; |
4931 | } else { |
4932 | // If the conversion function doesn't return a reference type, |
4933 | // it can't be considered for this conversion. An rvalue reference |
4934 | // is only acceptable if its referencee is a function type. |
4935 | |
4936 | const ReferenceType *RefType = |
4937 | Conv->getConversionType()->getAs<ReferenceType>(); |
4938 | if (!RefType || |
4939 | (!RefType->isLValueReferenceType() && |
4940 | !RefType->getPointeeType()->isFunctionType())) |
4941 | continue; |
4942 | } |
4943 | |
4944 | if (ConvTemplate) |
4945 | S.AddTemplateConversionCandidate( |
4946 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet, |
4947 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4948 | else |
4949 | S.AddConversionCandidate( |
4950 | Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet, |
4951 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4952 | } |
4953 | |
4954 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4955 | |
4956 | OverloadCandidateSet::iterator Best; |
4957 | switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) { |
4958 | case OR_Success: |
4959 | // C++ [over.ics.ref]p1: |
4960 | // |
4961 | // [...] If the parameter binds directly to the result of |
4962 | // applying a conversion function to the argument |
4963 | // expression, the implicit conversion sequence is a |
4964 | // user-defined conversion sequence (13.3.3.1.2), with the |
4965 | // second standard conversion sequence either an identity |
4966 | // conversion or, if the conversion function returns an |
4967 | // entity of a type that is a derived class of the parameter |
4968 | // type, a derived-to-base Conversion. |
4969 | if (!Best->FinalConversion.DirectBinding) |
4970 | return false; |
4971 | |
4972 | ICS.setUserDefined(); |
4973 | ICS.UserDefined.Before = Best->Conversions[0].Standard; |
4974 | ICS.UserDefined.After = Best->FinalConversion; |
4975 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; |
4976 | ICS.UserDefined.ConversionFunction = Best->Function; |
4977 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; |
4978 | ICS.UserDefined.EllipsisConversion = false; |
4979 | assert(ICS.UserDefined.After.ReferenceBinding && |
4980 | ICS.UserDefined.After.DirectBinding && |
4981 | "Expected a direct reference binding!" ); |
4982 | return true; |
4983 | |
4984 | case OR_Ambiguous: |
4985 | ICS.setAmbiguous(); |
4986 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); |
4987 | Cand != CandidateSet.end(); ++Cand) |
4988 | if (Cand->Best) |
4989 | ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function); |
4990 | return true; |
4991 | |
4992 | case OR_No_Viable_Function: |
4993 | case OR_Deleted: |
4994 | // There was no suitable conversion, or we found a deleted |
4995 | // conversion; continue with other checks. |
4996 | return false; |
4997 | } |
4998 | |
4999 | llvm_unreachable("Invalid OverloadResult!" ); |
5000 | } |
5001 | |
5002 | /// Compute an implicit conversion sequence for reference |
5003 | /// initialization. |
5004 | static ImplicitConversionSequence |
5005 | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, |
5006 | SourceLocation DeclLoc, |
5007 | bool SuppressUserConversions, |
5008 | bool AllowExplicit) { |
5009 | assert(DeclType->isReferenceType() && "Reference init needs a reference" ); |
5010 | |
5011 | // Most paths end in a failed conversion. |
5012 | ImplicitConversionSequence ICS; |
5013 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType); |
5014 | |
5015 | QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); |
5016 | QualType T2 = Init->getType(); |
5017 | |
5018 | // If the initializer is the address of an overloaded function, try |
5019 | // to resolve the overloaded function. If all goes well, T2 is the |
5020 | // type of the resulting function. |
5021 | if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) { |
5022 | DeclAccessPair Found; |
5023 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType, |
5024 | Complain: false, Found)) |
5025 | T2 = Fn->getType(); |
5026 | } |
5027 | |
5028 | // Compute some basic properties of the types and the initializer. |
5029 | bool isRValRef = DeclType->isRValueReferenceType(); |
5030 | Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context); |
5031 | |
5032 | Sema::ReferenceConversions RefConv; |
5033 | Sema::ReferenceCompareResult RefRelationship = |
5034 | S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv); |
5035 | |
5036 | auto SetAsReferenceBinding = [&](bool BindsDirectly) { |
5037 | ICS.setStandard(); |
5038 | ICS.Standard.First = ICK_Identity; |
5039 | // FIXME: A reference binding can be a function conversion too. We should |
5040 | // consider that when ordering reference-to-function bindings. |
5041 | ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5042 | ? ICK_Derived_To_Base |
5043 | : (RefConv & Sema::ReferenceConversions::ObjC) |
5044 | ? ICK_Compatible_Conversion |
5045 | : ICK_Identity; |
5046 | // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank |
5047 | // a reference binding that performs a non-top-level qualification |
5048 | // conversion as a qualification conversion, not as an identity conversion. |
5049 | ICS.Standard.Third = (RefConv & |
5050 | Sema::ReferenceConversions::NestedQualification) |
5051 | ? ICK_Qualification |
5052 | : ICK_Identity; |
5053 | ICS.Standard.setFromType(T2); |
5054 | ICS.Standard.setToType(Idx: 0, T: T2); |
5055 | ICS.Standard.setToType(Idx: 1, T: T1); |
5056 | ICS.Standard.setToType(Idx: 2, T: T1); |
5057 | ICS.Standard.ReferenceBinding = true; |
5058 | ICS.Standard.DirectBinding = BindsDirectly; |
5059 | ICS.Standard.IsLvalueReference = !isRValRef; |
5060 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); |
5061 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); |
5062 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5063 | ICS.Standard.ObjCLifetimeConversionBinding = |
5064 | (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; |
5065 | ICS.Standard.CopyConstructor = nullptr; |
5066 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; |
5067 | }; |
5068 | |
5069 | // C++0x [dcl.init.ref]p5: |
5070 | // A reference to type "cv1 T1" is initialized by an expression |
5071 | // of type "cv2 T2" as follows: |
5072 | |
5073 | // -- If reference is an lvalue reference and the initializer expression |
5074 | if (!isRValRef) { |
5075 | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is |
5076 | // reference-compatible with "cv2 T2," or |
5077 | // |
5078 | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. |
5079 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { |
5080 | // C++ [over.ics.ref]p1: |
5081 | // When a parameter of reference type binds directly (8.5.3) |
5082 | // to an argument expression, the implicit conversion sequence |
5083 | // is the identity conversion, unless the argument expression |
5084 | // has a type that is a derived class of the parameter type, |
5085 | // in which case the implicit conversion sequence is a |
5086 | // derived-to-base Conversion (13.3.3.1). |
5087 | SetAsReferenceBinding(/*BindsDirectly=*/true); |
5088 | |
5089 | // Nothing more to do: the inaccessibility/ambiguity check for |
5090 | // derived-to-base conversions is suppressed when we're |
5091 | // computing the implicit conversion sequence (C++ |
5092 | // [over.best.ics]p2). |
5093 | return ICS; |
5094 | } |
5095 | |
5096 | // -- has a class type (i.e., T2 is a class type), where T1 is |
5097 | // not reference-related to T2, and can be implicitly |
5098 | // converted to an lvalue of type "cv3 T3," where "cv1 T1" |
5099 | // is reference-compatible with "cv3 T3" 92) (this |
5100 | // conversion is selected by enumerating the applicable |
5101 | // conversion functions (13.3.1.6) and choosing the best |
5102 | // one through overload resolution (13.3)), |
5103 | if (!SuppressUserConversions && T2->isRecordType() && |
5104 | S.isCompleteType(Loc: DeclLoc, T: T2) && |
5105 | RefRelationship == Sema::Ref_Incompatible) { |
5106 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
5107 | Init, T2, /*AllowRvalues=*/false, |
5108 | AllowExplicit)) |
5109 | return ICS; |
5110 | } |
5111 | } |
5112 | |
5113 | // -- Otherwise, the reference shall be an lvalue reference to a |
5114 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
5115 | // shall be an rvalue reference. |
5116 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { |
5117 | if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) |
5118 | ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType); |
5119 | return ICS; |
5120 | } |
5121 | |
5122 | // -- If the initializer expression |
5123 | // |
5124 | // -- is an xvalue, class prvalue, array prvalue or function |
5125 | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or |
5126 | if (RefRelationship == Sema::Ref_Compatible && |
5127 | (InitCategory.isXValue() || |
5128 | (InitCategory.isPRValue() && |
5129 | (T2->isRecordType() || T2->isArrayType())) || |
5130 | (InitCategory.isLValue() && T2->isFunctionType()))) { |
5131 | // In C++11, this is always a direct binding. In C++98/03, it's a direct |
5132 | // binding unless we're binding to a class prvalue. |
5133 | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we |
5134 | // allow the use of rvalue references in C++98/03 for the benefit of |
5135 | // standard library implementors; therefore, we need the xvalue check here. |
5136 | SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || |
5137 | !(InitCategory.isPRValue() || T2->isRecordType())); |
5138 | return ICS; |
5139 | } |
5140 | |
5141 | // -- has a class type (i.e., T2 is a class type), where T1 is not |
5142 | // reference-related to T2, and can be implicitly converted to |
5143 | // an xvalue, class prvalue, or function lvalue of type |
5144 | // "cv3 T3", where "cv1 T1" is reference-compatible with |
5145 | // "cv3 T3", |
5146 | // |
5147 | // then the reference is bound to the value of the initializer |
5148 | // expression in the first case and to the result of the conversion |
5149 | // in the second case (or, in either case, to an appropriate base |
5150 | // class subobject). |
5151 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5152 | T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) && |
5153 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
5154 | Init, T2, /*AllowRvalues=*/true, |
5155 | AllowExplicit)) { |
5156 | // In the second case, if the reference is an rvalue reference |
5157 | // and the second standard conversion sequence of the |
5158 | // user-defined conversion sequence includes an lvalue-to-rvalue |
5159 | // conversion, the program is ill-formed. |
5160 | if (ICS.isUserDefined() && isRValRef && |
5161 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) |
5162 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType); |
5163 | |
5164 | return ICS; |
5165 | } |
5166 | |
5167 | // A temporary of function type cannot be created; don't even try. |
5168 | if (T1->isFunctionType()) |
5169 | return ICS; |
5170 | |
5171 | // -- Otherwise, a temporary of type "cv1 T1" is created and |
5172 | // initialized from the initializer expression using the |
5173 | // rules for a non-reference copy initialization (8.5). The |
5174 | // reference is then bound to the temporary. If T1 is |
5175 | // reference-related to T2, cv1 must be the same |
5176 | // cv-qualification as, or greater cv-qualification than, |
5177 | // cv2; otherwise, the program is ill-formed. |
5178 | if (RefRelationship == Sema::Ref_Related) { |
5179 | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then |
5180 | // we would be reference-compatible or reference-compatible with |
5181 | // added qualification. But that wasn't the case, so the reference |
5182 | // initialization fails. |
5183 | // |
5184 | // Note that we only want to check address spaces and cvr-qualifiers here. |
5185 | // ObjC GC, lifetime and unaligned qualifiers aren't important. |
5186 | Qualifiers T1Quals = T1.getQualifiers(); |
5187 | Qualifiers T2Quals = T2.getQualifiers(); |
5188 | T1Quals.removeObjCGCAttr(); |
5189 | T1Quals.removeObjCLifetime(); |
5190 | T2Quals.removeObjCGCAttr(); |
5191 | T2Quals.removeObjCLifetime(); |
5192 | // MS compiler ignores __unaligned qualifier for references; do the same. |
5193 | T1Quals.removeUnaligned(); |
5194 | T2Quals.removeUnaligned(); |
5195 | if (!T1Quals.compatiblyIncludes(other: T2Quals)) |
5196 | return ICS; |
5197 | } |
5198 | |
5199 | // If at least one of the types is a class type, the types are not |
5200 | // related, and we aren't allowed any user conversions, the |
5201 | // reference binding fails. This case is important for breaking |
5202 | // recursion, since TryImplicitConversion below will attempt to |
5203 | // create a temporary through the use of a copy constructor. |
5204 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5205 | (T1->isRecordType() || T2->isRecordType())) |
5206 | return ICS; |
5207 | |
5208 | // If T1 is reference-related to T2 and the reference is an rvalue |
5209 | // reference, the initializer expression shall not be an lvalue. |
5210 | if (RefRelationship >= Sema::Ref_Related && isRValRef && |
5211 | Init->Classify(Ctx&: S.Context).isLValue()) { |
5212 | ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType); |
5213 | return ICS; |
5214 | } |
5215 | |
5216 | // C++ [over.ics.ref]p2: |
5217 | // When a parameter of reference type is not bound directly to |
5218 | // an argument expression, the conversion sequence is the one |
5219 | // required to convert the argument expression to the |
5220 | // underlying type of the reference according to |
5221 | // 13.3.3.1. Conceptually, this conversion sequence corresponds |
5222 | // to copy-initializing a temporary of the underlying type with |
5223 | // the argument expression. Any difference in top-level |
5224 | // cv-qualification is subsumed by the initialization itself |
5225 | // and does not constitute a conversion. |
5226 | ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions, |
5227 | AllowExplicit: AllowedExplicit::None, |
5228 | /*InOverloadResolution=*/false, |
5229 | /*CStyle=*/false, |
5230 | /*AllowObjCWritebackConversion=*/false, |
5231 | /*AllowObjCConversionOnExplicit=*/false); |
5232 | |
5233 | // Of course, that's still a reference binding. |
5234 | if (ICS.isStandard()) { |
5235 | ICS.Standard.ReferenceBinding = true; |
5236 | ICS.Standard.IsLvalueReference = !isRValRef; |
5237 | ICS.Standard.BindsToFunctionLvalue = false; |
5238 | ICS.Standard.BindsToRvalue = true; |
5239 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5240 | ICS.Standard.ObjCLifetimeConversionBinding = false; |
5241 | } else if (ICS.isUserDefined()) { |
5242 | const ReferenceType *LValRefType = |
5243 | ICS.UserDefined.ConversionFunction->getReturnType() |
5244 | ->getAs<LValueReferenceType>(); |
5245 | |
5246 | // C++ [over.ics.ref]p3: |
5247 | // Except for an implicit object parameter, for which see 13.3.1, a |
5248 | // standard conversion sequence cannot be formed if it requires [...] |
5249 | // binding an rvalue reference to an lvalue other than a function |
5250 | // lvalue. |
5251 | // Note that the function case is not possible here. |
5252 | if (isRValRef && LValRefType) { |
5253 | ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType); |
5254 | return ICS; |
5255 | } |
5256 | |
5257 | ICS.UserDefined.After.ReferenceBinding = true; |
5258 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; |
5259 | ICS.UserDefined.After.BindsToFunctionLvalue = false; |
5260 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; |
5261 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5262 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; |
5263 | } |
5264 | |
5265 | return ICS; |
5266 | } |
5267 | |
5268 | static ImplicitConversionSequence |
5269 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5270 | bool SuppressUserConversions, |
5271 | bool InOverloadResolution, |
5272 | bool AllowObjCWritebackConversion, |
5273 | bool AllowExplicit = false); |
5274 | |
5275 | /// TryListConversion - Try to copy-initialize a value of type ToType from the |
5276 | /// initializer list From. |
5277 | static ImplicitConversionSequence |
5278 | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, |
5279 | bool SuppressUserConversions, |
5280 | bool InOverloadResolution, |
5281 | bool AllowObjCWritebackConversion) { |
5282 | // C++11 [over.ics.list]p1: |
5283 | // When an argument is an initializer list, it is not an expression and |
5284 | // special rules apply for converting it to a parameter type. |
5285 | |
5286 | ImplicitConversionSequence Result; |
5287 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); |
5288 | |
5289 | // We need a complete type for what follows. With one C++20 exception, |
5290 | // incomplete types can never be initialized from init lists. |
5291 | QualType InitTy = ToType; |
5292 | const ArrayType *AT = S.Context.getAsArrayType(T: ToType); |
5293 | if (AT && S.getLangOpts().CPlusPlus20) |
5294 | if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) |
5295 | // C++20 allows list initialization of an incomplete array type. |
5296 | InitTy = IAT->getElementType(); |
5297 | if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy)) |
5298 | return Result; |
5299 | |
5300 | // C++20 [over.ics.list]/2: |
5301 | // If the initializer list is a designated-initializer-list, a conversion |
5302 | // is only possible if the parameter has an aggregate type |
5303 | // |
5304 | // FIXME: The exception for reference initialization here is not part of the |
5305 | // language rules, but follow other compilers in adding it as a tentative DR |
5306 | // resolution. |
5307 | bool IsDesignatedInit = From->hasDesignatedInit(); |
5308 | if (!ToType->isAggregateType() && !ToType->isReferenceType() && |
5309 | IsDesignatedInit) |
5310 | return Result; |
5311 | |
5312 | // Per DR1467: |
5313 | // If the parameter type is a class X and the initializer list has a single |
5314 | // element of type cv U, where U is X or a class derived from X, the |
5315 | // implicit conversion sequence is the one required to convert the element |
5316 | // to the parameter type. |
5317 | // |
5318 | // Otherwise, if the parameter type is a character array [... ] |
5319 | // and the initializer list has a single element that is an |
5320 | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the |
5321 | // implicit conversion sequence is the identity conversion. |
5322 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5323 | if (ToType->isRecordType()) { |
5324 | QualType InitType = From->getInit(Init: 0)->getType(); |
5325 | if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) || |
5326 | S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType)) |
5327 | return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType, |
5328 | SuppressUserConversions, |
5329 | InOverloadResolution, |
5330 | AllowObjCWritebackConversion); |
5331 | } |
5332 | |
5333 | if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) { |
5334 | InitializedEntity Entity = |
5335 | InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType, |
5336 | /*Consumed=*/false); |
5337 | if (S.CanPerformCopyInitialization(Entity, From)) { |
5338 | Result.setStandard(); |
5339 | Result.Standard.setAsIdentityConversion(); |
5340 | Result.Standard.setFromType(ToType); |
5341 | Result.Standard.setAllToTypes(ToType); |
5342 | return Result; |
5343 | } |
5344 | } |
5345 | } |
5346 | |
5347 | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). |
5348 | // C++11 [over.ics.list]p2: |
5349 | // If the parameter type is std::initializer_list<X> or "array of X" and |
5350 | // all the elements can be implicitly converted to X, the implicit |
5351 | // conversion sequence is the worst conversion necessary to convert an |
5352 | // element of the list to X. |
5353 | // |
5354 | // C++14 [over.ics.list]p3: |
5355 | // Otherwise, if the parameter type is "array of N X", if the initializer |
5356 | // list has exactly N elements or if it has fewer than N elements and X is |
5357 | // default-constructible, and if all the elements of the initializer list |
5358 | // can be implicitly converted to X, the implicit conversion sequence is |
5359 | // the worst conversion necessary to convert an element of the list to X. |
5360 | if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) { |
5361 | unsigned e = From->getNumInits(); |
5362 | ImplicitConversionSequence DfltElt; |
5363 | DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(), |
5364 | ToType: QualType()); |
5365 | QualType ContTy = ToType; |
5366 | bool IsUnbounded = false; |
5367 | if (AT) { |
5368 | InitTy = AT->getElementType(); |
5369 | if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) { |
5370 | if (CT->getSize().ult(RHS: e)) { |
5371 | // Too many inits, fatally bad |
5372 | Result.setBad(BadConversionSequence::too_many_initializers, From, |
5373 | ToType); |
5374 | Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded); |
5375 | return Result; |
5376 | } |
5377 | if (CT->getSize().ugt(RHS: e)) { |
5378 | // Need an init from empty {}, is there one? |
5379 | InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt, |
5380 | From->getEndLoc()); |
5381 | EmptyList.setType(S.Context.VoidTy); |
5382 | DfltElt = TryListConversion( |
5383 | S, From: &EmptyList, ToType: InitTy, SuppressUserConversions, |
5384 | InOverloadResolution, AllowObjCWritebackConversion); |
5385 | if (DfltElt.isBad()) { |
5386 | // No {} init, fatally bad |
5387 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5388 | ToType); |
5389 | Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded); |
5390 | return Result; |
5391 | } |
5392 | } |
5393 | } else { |
5394 | assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array" ); |
5395 | IsUnbounded = true; |
5396 | if (!e) { |
5397 | // Cannot convert to zero-sized. |
5398 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5399 | ToType); |
5400 | Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded); |
5401 | return Result; |
5402 | } |
5403 | llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e); |
5404 | ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr, |
5405 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
5406 | } |
5407 | } |
5408 | |
5409 | Result.setStandard(); |
5410 | Result.Standard.setAsIdentityConversion(); |
5411 | Result.Standard.setFromType(InitTy); |
5412 | Result.Standard.setAllToTypes(InitTy); |
5413 | for (unsigned i = 0; i < e; ++i) { |
5414 | Expr *Init = From->getInit(Init: i); |
5415 | ImplicitConversionSequence ICS = TryCopyInitialization( |
5416 | S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution, |
5417 | AllowObjCWritebackConversion); |
5418 | |
5419 | // Keep the worse conversion seen so far. |
5420 | // FIXME: Sequences are not totally ordered, so 'worse' can be |
5421 | // ambiguous. CWG has been informed. |
5422 | if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS, |
5423 | ICS2: Result) == |
5424 | ImplicitConversionSequence::Worse) { |
5425 | Result = ICS; |
5426 | // Bail as soon as we find something unconvertible. |
5427 | if (Result.isBad()) { |
5428 | Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded); |
5429 | return Result; |
5430 | } |
5431 | } |
5432 | } |
5433 | |
5434 | // If we needed any implicit {} initialization, compare that now. |
5435 | // over.ics.list/6 indicates we should compare that conversion. Again CWG |
5436 | // has been informed that this might not be the best thing. |
5437 | if (!DfltElt.isBad() && CompareImplicitConversionSequences( |
5438 | S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) == |
5439 | ImplicitConversionSequence::Worse) |
5440 | Result = DfltElt; |
5441 | // Record the type being initialized so that we may compare sequences |
5442 | Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded); |
5443 | return Result; |
5444 | } |
5445 | |
5446 | // C++14 [over.ics.list]p4: |
5447 | // C++11 [over.ics.list]p3: |
5448 | // Otherwise, if the parameter is a non-aggregate class X and overload |
5449 | // resolution chooses a single best constructor [...] the implicit |
5450 | // conversion sequence is a user-defined conversion sequence. If multiple |
5451 | // constructors are viable but none is better than the others, the |
5452 | // implicit conversion sequence is a user-defined conversion sequence. |
5453 | if (ToType->isRecordType() && !ToType->isAggregateType()) { |
5454 | // This function can deal with initializer lists. |
5455 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
5456 | AllowedExplicit::None, |
5457 | InOverloadResolution, /*CStyle=*/false, |
5458 | AllowObjCWritebackConversion, |
5459 | /*AllowObjCConversionOnExplicit=*/false); |
5460 | } |
5461 | |
5462 | // C++14 [over.ics.list]p5: |
5463 | // C++11 [over.ics.list]p4: |
5464 | // Otherwise, if the parameter has an aggregate type which can be |
5465 | // initialized from the initializer list [...] the implicit conversion |
5466 | // sequence is a user-defined conversion sequence. |
5467 | if (ToType->isAggregateType()) { |
5468 | // Type is an aggregate, argument is an init list. At this point it comes |
5469 | // down to checking whether the initialization works. |
5470 | // FIXME: Find out whether this parameter is consumed or not. |
5471 | InitializedEntity Entity = |
5472 | InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType, |
5473 | /*Consumed=*/false); |
5474 | if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, |
5475 | From)) { |
5476 | Result.setUserDefined(); |
5477 | Result.UserDefined.Before.setAsIdentityConversion(); |
5478 | // Initializer lists don't have a type. |
5479 | Result.UserDefined.Before.setFromType(QualType()); |
5480 | Result.UserDefined.Before.setAllToTypes(QualType()); |
5481 | |
5482 | Result.UserDefined.After.setAsIdentityConversion(); |
5483 | Result.UserDefined.After.setFromType(ToType); |
5484 | Result.UserDefined.After.setAllToTypes(ToType); |
5485 | Result.UserDefined.ConversionFunction = nullptr; |
5486 | } |
5487 | return Result; |
5488 | } |
5489 | |
5490 | // C++14 [over.ics.list]p6: |
5491 | // C++11 [over.ics.list]p5: |
5492 | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. |
5493 | if (ToType->isReferenceType()) { |
5494 | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't |
5495 | // mention initializer lists in any way. So we go by what list- |
5496 | // initialization would do and try to extrapolate from that. |
5497 | |
5498 | QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); |
5499 | |
5500 | // If the initializer list has a single element that is reference-related |
5501 | // to the parameter type, we initialize the reference from that. |
5502 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5503 | Expr *Init = From->getInit(Init: 0); |
5504 | |
5505 | QualType T2 = Init->getType(); |
5506 | |
5507 | // If the initializer is the address of an overloaded function, try |
5508 | // to resolve the overloaded function. If all goes well, T2 is the |
5509 | // type of the resulting function. |
5510 | if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) { |
5511 | DeclAccessPair Found; |
5512 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( |
5513 | AddressOfExpr: Init, TargetType: ToType, Complain: false, Found)) |
5514 | T2 = Fn->getType(); |
5515 | } |
5516 | |
5517 | // Compute some basic properties of the types and the initializer. |
5518 | Sema::ReferenceCompareResult RefRelationship = |
5519 | S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2); |
5520 | |
5521 | if (RefRelationship >= Sema::Ref_Related) { |
5522 | return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(), |
5523 | SuppressUserConversions, |
5524 | /*AllowExplicit=*/false); |
5525 | } |
5526 | } |
5527 | |
5528 | // Otherwise, we bind the reference to a temporary created from the |
5529 | // initializer list. |
5530 | Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions, |
5531 | InOverloadResolution, |
5532 | AllowObjCWritebackConversion); |
5533 | if (Result.isFailure()) |
5534 | return Result; |
5535 | assert(!Result.isEllipsis() && |
5536 | "Sub-initialization cannot result in ellipsis conversion." ); |
5537 | |
5538 | // Can we even bind to a temporary? |
5539 | if (ToType->isRValueReferenceType() || |
5540 | (T1.isConstQualified() && !T1.isVolatileQualified())) { |
5541 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : |
5542 | Result.UserDefined.After; |
5543 | SCS.ReferenceBinding = true; |
5544 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); |
5545 | SCS.BindsToRvalue = true; |
5546 | SCS.BindsToFunctionLvalue = false; |
5547 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5548 | SCS.ObjCLifetimeConversionBinding = false; |
5549 | } else |
5550 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, |
5551 | From, ToType); |
5552 | return Result; |
5553 | } |
5554 | |
5555 | // C++14 [over.ics.list]p7: |
5556 | // C++11 [over.ics.list]p6: |
5557 | // Otherwise, if the parameter type is not a class: |
5558 | if (!ToType->isRecordType()) { |
5559 | // - if the initializer list has one element that is not itself an |
5560 | // initializer list, the implicit conversion sequence is the one |
5561 | // required to convert the element to the parameter type. |
5562 | unsigned NumInits = From->getNumInits(); |
5563 | if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0))) |
5564 | Result = TryCopyInitialization(S, From: From->getInit(Init: 0), ToType, |
5565 | SuppressUserConversions, |
5566 | InOverloadResolution, |
5567 | AllowObjCWritebackConversion); |
5568 | // - if the initializer list has no elements, the implicit conversion |
5569 | // sequence is the identity conversion. |
5570 | else if (NumInits == 0) { |
5571 | Result.setStandard(); |
5572 | Result.Standard.setAsIdentityConversion(); |
5573 | Result.Standard.setFromType(ToType); |
5574 | Result.Standard.setAllToTypes(ToType); |
5575 | } |
5576 | return Result; |
5577 | } |
5578 | |
5579 | // C++14 [over.ics.list]p8: |
5580 | // C++11 [over.ics.list]p7: |
5581 | // In all cases other than those enumerated above, no conversion is possible |
5582 | return Result; |
5583 | } |
5584 | |
5585 | /// TryCopyInitialization - Try to copy-initialize a value of type |
5586 | /// ToType from the expression From. Return the implicit conversion |
5587 | /// sequence required to pass this argument, which may be a bad |
5588 | /// conversion sequence (meaning that the argument cannot be passed to |
5589 | /// a parameter of this type). If @p SuppressUserConversions, then we |
5590 | /// do not permit any user-defined conversion sequences. |
5591 | static ImplicitConversionSequence |
5592 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5593 | bool SuppressUserConversions, |
5594 | bool InOverloadResolution, |
5595 | bool AllowObjCWritebackConversion, |
5596 | bool AllowExplicit) { |
5597 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From)) |
5598 | return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions, |
5599 | InOverloadResolution,AllowObjCWritebackConversion); |
5600 | |
5601 | if (ToType->isReferenceType()) |
5602 | return TryReferenceInit(S, From, ToType, |
5603 | /*FIXME:*/ From->getBeginLoc(), |
5604 | SuppressUserConversions, AllowExplicit); |
5605 | |
5606 | return TryImplicitConversion(S, From, ToType, |
5607 | SuppressUserConversions, |
5608 | AllowExplicit: AllowedExplicit::None, |
5609 | InOverloadResolution, |
5610 | /*CStyle=*/false, |
5611 | AllowObjCWritebackConversion, |
5612 | /*AllowObjCConversionOnExplicit=*/false); |
5613 | } |
5614 | |
5615 | static bool TryCopyInitialization(const CanQualType FromQTy, |
5616 | const CanQualType ToQTy, |
5617 | Sema &S, |
5618 | SourceLocation Loc, |
5619 | ExprValueKind FromVK) { |
5620 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); |
5621 | ImplicitConversionSequence ICS = |
5622 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); |
5623 | |
5624 | return !ICS.isBad(); |
5625 | } |
5626 | |
5627 | /// TryObjectArgumentInitialization - Try to initialize the object |
5628 | /// parameter of the given member function (@c Method) from the |
5629 | /// expression @p From. |
5630 | static ImplicitConversionSequence TryObjectArgumentInitialization( |
5631 | Sema &S, SourceLocation Loc, QualType FromType, |
5632 | Expr::Classification FromClassification, CXXMethodDecl *Method, |
5633 | const CXXRecordDecl *ActingContext, bool InOverloadResolution = false, |
5634 | QualType ExplicitParameterType = QualType(), |
5635 | bool SuppressUserConversion = false) { |
5636 | |
5637 | // We need to have an object of class type. |
5638 | if (const auto *PT = FromType->getAs<PointerType>()) { |
5639 | FromType = PT->getPointeeType(); |
5640 | |
5641 | // When we had a pointer, it's implicitly dereferenced, so we |
5642 | // better have an lvalue. |
5643 | assert(FromClassification.isLValue()); |
5644 | } |
5645 | |
5646 | auto ValueKindFromClassification = [](Expr::Classification C) { |
5647 | if (C.isPRValue()) |
5648 | return clang::VK_PRValue; |
5649 | if (C.isXValue()) |
5650 | return VK_XValue; |
5651 | return clang::VK_LValue; |
5652 | }; |
5653 | |
5654 | if (Method->isExplicitObjectMemberFunction()) { |
5655 | if (ExplicitParameterType.isNull()) |
5656 | ExplicitParameterType = Method->getFunctionObjectParameterReferenceType(); |
5657 | OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(), |
5658 | ValueKindFromClassification(FromClassification)); |
5659 | ImplicitConversionSequence ICS = TryCopyInitialization( |
5660 | S, &TmpExpr, ExplicitParameterType, SuppressUserConversion, |
5661 | /*InOverloadResolution=*/true, false); |
5662 | if (ICS.isBad()) |
5663 | ICS.Bad.FromExpr = nullptr; |
5664 | return ICS; |
5665 | } |
5666 | |
5667 | assert(FromType->isRecordType()); |
5668 | |
5669 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); |
5670 | // C++98 [class.dtor]p2: |
5671 | // A destructor can be invoked for a const, volatile or const volatile |
5672 | // object. |
5673 | // C++98 [over.match.funcs]p4: |
5674 | // For static member functions, the implicit object parameter is considered |
5675 | // to match any object (since if the function is selected, the object is |
5676 | // discarded). |
5677 | Qualifiers Quals = Method->getMethodQualifiers(); |
5678 | if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) { |
5679 | Quals.addConst(); |
5680 | Quals.addVolatile(); |
5681 | } |
5682 | |
5683 | QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals); |
5684 | |
5685 | // Set up the conversion sequence as a "bad" conversion, to allow us |
5686 | // to exit early. |
5687 | ImplicitConversionSequence ICS; |
5688 | |
5689 | // C++0x [over.match.funcs]p4: |
5690 | // For non-static member functions, the type of the implicit object |
5691 | // parameter is |
5692 | // |
5693 | // - "lvalue reference to cv X" for functions declared without a |
5694 | // ref-qualifier or with the & ref-qualifier |
5695 | // - "rvalue reference to cv X" for functions declared with the && |
5696 | // ref-qualifier |
5697 | // |
5698 | // where X is the class of which the function is a member and cv is the |
5699 | // cv-qualification on the member function declaration. |
5700 | // |
5701 | // However, when finding an implicit conversion sequence for the argument, we |
5702 | // are not allowed to perform user-defined conversions |
5703 | // (C++ [over.match.funcs]p5). We perform a simplified version of |
5704 | // reference binding here, that allows class rvalues to bind to |
5705 | // non-constant references. |
5706 | |
5707 | // First check the qualifiers. |
5708 | QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType); |
5709 | // MSVC ignores __unaligned qualifier for overload candidates; do the same. |
5710 | if (ImplicitParamType.getCVRQualifiers() != |
5711 | FromTypeCanon.getLocalCVRQualifiers() && |
5712 | !ImplicitParamType.isAtLeastAsQualifiedAs( |
5713 | other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon))) { |
5714 | ICS.setBad(Failure: BadConversionSequence::bad_qualifiers, |
5715 | FromType, ToType: ImplicitParamType); |
5716 | return ICS; |
5717 | } |
5718 | |
5719 | if (FromTypeCanon.hasAddressSpace()) { |
5720 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); |
5721 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); |
5722 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType)) { |
5723 | ICS.setBad(Failure: BadConversionSequence::bad_qualifiers, |
5724 | FromType, ToType: ImplicitParamType); |
5725 | return ICS; |
5726 | } |
5727 | } |
5728 | |
5729 | // Check that we have either the same type or a derived type. It |
5730 | // affects the conversion rank. |
5731 | QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType); |
5732 | ImplicitConversionKind SecondKind; |
5733 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { |
5734 | SecondKind = ICK_Identity; |
5735 | } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) { |
5736 | SecondKind = ICK_Derived_To_Base; |
5737 | } else if (!Method->isExplicitObjectMemberFunction()) { |
5738 | ICS.setBad(Failure: BadConversionSequence::unrelated_class, |
5739 | FromType, ToType: ImplicitParamType); |
5740 | return ICS; |
5741 | } |
5742 | |
5743 | // Check the ref-qualifier. |
5744 | switch (Method->getRefQualifier()) { |
5745 | case RQ_None: |
5746 | // Do nothing; we don't care about lvalueness or rvalueness. |
5747 | break; |
5748 | |
5749 | case RQ_LValue: |
5750 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { |
5751 | // non-const lvalue reference cannot bind to an rvalue |
5752 | ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType, |
5753 | ToType: ImplicitParamType); |
5754 | return ICS; |
5755 | } |
5756 | break; |
5757 | |
5758 | case RQ_RValue: |
5759 | if (!FromClassification.isRValue()) { |
5760 | // rvalue reference cannot bind to an lvalue |
5761 | ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType, |
5762 | ToType: ImplicitParamType); |
5763 | return ICS; |
5764 | } |
5765 | break; |
5766 | } |
5767 | |
5768 | // Success. Mark this as a reference binding. |
5769 | ICS.setStandard(); |
5770 | ICS.Standard.setAsIdentityConversion(); |
5771 | ICS.Standard.Second = SecondKind; |
5772 | ICS.Standard.setFromType(FromType); |
5773 | ICS.Standard.setAllToTypes(ImplicitParamType); |
5774 | ICS.Standard.ReferenceBinding = true; |
5775 | ICS.Standard.DirectBinding = true; |
5776 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; |
5777 | ICS.Standard.BindsToFunctionLvalue = false; |
5778 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); |
5779 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier |
5780 | = (Method->getRefQualifier() == RQ_None); |
5781 | return ICS; |
5782 | } |
5783 | |
5784 | /// PerformObjectArgumentInitialization - Perform initialization of |
5785 | /// the implicit object parameter for the given Method with the given |
5786 | /// expression. |
5787 | ExprResult Sema::PerformImplicitObjectArgumentInitialization( |
5788 | Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, |
5789 | CXXMethodDecl *Method) { |
5790 | QualType FromRecordType, DestType; |
5791 | QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType(); |
5792 | |
5793 | Expr::Classification FromClassification; |
5794 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { |
5795 | FromRecordType = PT->getPointeeType(); |
5796 | DestType = Method->getThisType(); |
5797 | FromClassification = Expr::Classification::makeSimpleLValue(); |
5798 | } else { |
5799 | FromRecordType = From->getType(); |
5800 | DestType = ImplicitParamRecordType; |
5801 | FromClassification = From->Classify(Ctx&: Context); |
5802 | |
5803 | // When performing member access on a prvalue, materialize a temporary. |
5804 | if (From->isPRValue()) { |
5805 | From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From, |
5806 | BoundToLvalueReference: Method->getRefQualifier() != |
5807 | RefQualifierKind::RQ_RValue); |
5808 | } |
5809 | } |
5810 | |
5811 | // Note that we always use the true parent context when performing |
5812 | // the actual argument initialization. |
5813 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( |
5814 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, |
5815 | Method->getParent()); |
5816 | if (ICS.isBad()) { |
5817 | switch (ICS.Bad.Kind) { |
5818 | case BadConversionSequence::bad_qualifiers: { |
5819 | Qualifiers FromQs = FromRecordType.getQualifiers(); |
5820 | Qualifiers ToQs = DestType.getQualifiers(); |
5821 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
5822 | if (CVR) { |
5823 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) |
5824 | << Method->getDeclName() << FromRecordType << (CVR - 1) |
5825 | << From->getSourceRange(); |
5826 | Diag(Method->getLocation(), diag::note_previous_decl) |
5827 | << Method->getDeclName(); |
5828 | return ExprError(); |
5829 | } |
5830 | break; |
5831 | } |
5832 | |
5833 | case BadConversionSequence::lvalue_ref_to_rvalue: |
5834 | case BadConversionSequence::rvalue_ref_to_lvalue: { |
5835 | bool IsRValueQualified = |
5836 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; |
5837 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) |
5838 | << Method->getDeclName() << FromClassification.isRValue() |
5839 | << IsRValueQualified; |
5840 | Diag(Method->getLocation(), diag::note_previous_decl) |
5841 | << Method->getDeclName(); |
5842 | return ExprError(); |
5843 | } |
5844 | |
5845 | case BadConversionSequence::no_conversion: |
5846 | case BadConversionSequence::unrelated_class: |
5847 | break; |
5848 | |
5849 | case BadConversionSequence::too_few_initializers: |
5850 | case BadConversionSequence::too_many_initializers: |
5851 | llvm_unreachable("Lists are not objects" ); |
5852 | } |
5853 | |
5854 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) |
5855 | << ImplicitParamRecordType << FromRecordType |
5856 | << From->getSourceRange(); |
5857 | } |
5858 | |
5859 | if (ICS.Standard.Second == ICK_Derived_To_Base) { |
5860 | ExprResult FromRes = |
5861 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); |
5862 | if (FromRes.isInvalid()) |
5863 | return ExprError(); |
5864 | From = FromRes.get(); |
5865 | } |
5866 | |
5867 | if (!Context.hasSameType(T1: From->getType(), T2: DestType)) { |
5868 | CastKind CK; |
5869 | QualType PteeTy = DestType->getPointeeType(); |
5870 | LangAS DestAS = |
5871 | PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); |
5872 | if (FromRecordType.getAddressSpace() != DestAS) |
5873 | CK = CK_AddressSpaceConversion; |
5874 | else |
5875 | CK = CK_NoOp; |
5876 | From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get(); |
5877 | } |
5878 | return From; |
5879 | } |
5880 | |
5881 | /// TryContextuallyConvertToBool - Attempt to contextually convert the |
5882 | /// expression From to bool (C++0x [conv]p3). |
5883 | static ImplicitConversionSequence |
5884 | TryContextuallyConvertToBool(Sema &S, Expr *From) { |
5885 | // C++ [dcl.init]/17.8: |
5886 | // - Otherwise, if the initialization is direct-initialization, the source |
5887 | // type is std::nullptr_t, and the destination type is bool, the initial |
5888 | // value of the object being initialized is false. |
5889 | if (From->getType()->isNullPtrType()) |
5890 | return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(), |
5891 | DestType: S.Context.BoolTy, |
5892 | NeedLValToRVal: From->isGLValue()); |
5893 | |
5894 | // All other direct-initialization of bool is equivalent to an implicit |
5895 | // conversion to bool in which explicit conversions are permitted. |
5896 | return TryImplicitConversion(S, From, S.Context.BoolTy, |
5897 | /*SuppressUserConversions=*/false, |
5898 | AllowedExplicit::Conversions, |
5899 | /*InOverloadResolution=*/false, |
5900 | /*CStyle=*/false, |
5901 | /*AllowObjCWritebackConversion=*/false, |
5902 | /*AllowObjCConversionOnExplicit=*/false); |
5903 | } |
5904 | |
5905 | /// PerformContextuallyConvertToBool - Perform a contextual conversion |
5906 | /// of the expression From to bool (C++0x [conv]p3). |
5907 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { |
5908 | if (checkPlaceholderForOverload(S&: *this, E&: From)) |
5909 | return ExprError(); |
5910 | |
5911 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From); |
5912 | if (!ICS.isBad()) |
5913 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); |
5914 | |
5915 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) |
5916 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) |
5917 | << From->getType() << From->getSourceRange(); |
5918 | return ExprError(); |
5919 | } |
5920 | |
5921 | /// Check that the specified conversion is permitted in a converted constant |
5922 | /// expression, according to C++11 [expr.const]p3. Return true if the conversion |
5923 | /// is acceptable. |
5924 | static bool CheckConvertedConstantConversions(Sema &S, |
5925 | StandardConversionSequence &SCS) { |
5926 | // Since we know that the target type is an integral or unscoped enumeration |
5927 | // type, most conversion kinds are impossible. All possible First and Third |
5928 | // conversions are fine. |
5929 | switch (SCS.Second) { |
5930 | case ICK_Identity: |
5931 | case ICK_Integral_Promotion: |
5932 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. |
5933 | case ICK_Zero_Queue_Conversion: |
5934 | return true; |
5935 | |
5936 | case ICK_Boolean_Conversion: |
5937 | // Conversion from an integral or unscoped enumeration type to bool is |
5938 | // classified as ICK_Boolean_Conversion, but it's also arguably an integral |
5939 | // conversion, so we allow it in a converted constant expression. |
5940 | // |
5941 | // FIXME: Per core issue 1407, we should not allow this, but that breaks |
5942 | // a lot of popular code. We should at least add a warning for this |
5943 | // (non-conforming) extension. |
5944 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && |
5945 | SCS.getToType(Idx: 2)->isBooleanType(); |
5946 | |
5947 | case ICK_Pointer_Conversion: |
5948 | case ICK_Pointer_Member: |
5949 | // C++1z: null pointer conversions and null member pointer conversions are |
5950 | // only permitted if the source type is std::nullptr_t. |
5951 | return SCS.getFromType()->isNullPtrType(); |
5952 | |
5953 | case ICK_Floating_Promotion: |
5954 | case ICK_Complex_Promotion: |
5955 | case ICK_Floating_Conversion: |
5956 | case ICK_Complex_Conversion: |
5957 | case ICK_Floating_Integral: |
5958 | case ICK_Compatible_Conversion: |
5959 | case ICK_Derived_To_Base: |
5960 | case ICK_Vector_Conversion: |
5961 | case ICK_SVE_Vector_Conversion: |
5962 | case ICK_RVV_Vector_Conversion: |
5963 | case ICK_Vector_Splat: |
5964 | case ICK_Complex_Real: |
5965 | case ICK_Block_Pointer_Conversion: |
5966 | case ICK_TransparentUnionConversion: |
5967 | case ICK_Writeback_Conversion: |
5968 | case ICK_Zero_Event_Conversion: |
5969 | case ICK_C_Only_Conversion: |
5970 | case ICK_Incompatible_Pointer_Conversion: |
5971 | case ICK_Fixed_Point_Conversion: |
5972 | return false; |
5973 | |
5974 | case ICK_Lvalue_To_Rvalue: |
5975 | case ICK_Array_To_Pointer: |
5976 | case ICK_Function_To_Pointer: |
5977 | llvm_unreachable("found a first conversion kind in Second" ); |
5978 | |
5979 | case ICK_Function_Conversion: |
5980 | case ICK_Qualification: |
5981 | llvm_unreachable("found a third conversion kind in Second" ); |
5982 | |
5983 | case ICK_Num_Conversion_Kinds: |
5984 | break; |
5985 | } |
5986 | |
5987 | llvm_unreachable("unknown conversion kind" ); |
5988 | } |
5989 | |
5990 | /// BuildConvertedConstantExpression - Check that the expression From is a |
5991 | /// converted constant expression of type T, perform the conversion but |
5992 | /// does not evaluate the expression |
5993 | static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, |
5994 | QualType T, |
5995 | Sema::CCEKind CCE, |
5996 | NamedDecl *Dest, |
5997 | APValue &PreNarrowingValue) { |
5998 | assert(S.getLangOpts().CPlusPlus11 && |
5999 | "converted constant expression outside C++11" ); |
6000 | |
6001 | if (checkPlaceholderForOverload(S, E&: From)) |
6002 | return ExprError(); |
6003 | |
6004 | // C++1z [expr.const]p3: |
6005 | // A converted constant expression of type T is an expression, |
6006 | // implicitly converted to type T, where the converted |
6007 | // expression is a constant expression and the implicit conversion |
6008 | // sequence contains only [... list of conversions ...]. |
6009 | ImplicitConversionSequence ICS = |
6010 | (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) |
6011 | ? TryContextuallyConvertToBool(S, From) |
6012 | : TryCopyInitialization(S, From, ToType: T, |
6013 | /*SuppressUserConversions=*/false, |
6014 | /*InOverloadResolution=*/false, |
6015 | /*AllowObjCWritebackConversion=*/false, |
6016 | /*AllowExplicit=*/false); |
6017 | StandardConversionSequence *SCS = nullptr; |
6018 | switch (ICS.getKind()) { |
6019 | case ImplicitConversionSequence::StandardConversion: |
6020 | SCS = &ICS.Standard; |
6021 | break; |
6022 | case ImplicitConversionSequence::UserDefinedConversion: |
6023 | if (T->isRecordType()) |
6024 | SCS = &ICS.UserDefined.Before; |
6025 | else |
6026 | SCS = &ICS.UserDefined.After; |
6027 | break; |
6028 | case ImplicitConversionSequence::AmbiguousConversion: |
6029 | case ImplicitConversionSequence::BadConversion: |
6030 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) |
6031 | return S.Diag(From->getBeginLoc(), |
6032 | diag::err_typecheck_converted_constant_expression) |
6033 | << From->getType() << From->getSourceRange() << T; |
6034 | return ExprError(); |
6035 | |
6036 | case ImplicitConversionSequence::EllipsisConversion: |
6037 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
6038 | llvm_unreachable("bad conversion in converted constant expression" ); |
6039 | } |
6040 | |
6041 | // Check that we would only use permitted conversions. |
6042 | if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) { |
6043 | return S.Diag(From->getBeginLoc(), |
6044 | diag::err_typecheck_converted_constant_expression_disallowed) |
6045 | << From->getType() << From->getSourceRange() << T; |
6046 | } |
6047 | // [...] and where the reference binding (if any) binds directly. |
6048 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { |
6049 | return S.Diag(From->getBeginLoc(), |
6050 | diag::err_typecheck_converted_constant_expression_indirect) |
6051 | << From->getType() << From->getSourceRange() << T; |
6052 | } |
6053 | // 'TryCopyInitialization' returns incorrect info for attempts to bind |
6054 | // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely, |
6055 | // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not |
6056 | // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this |
6057 | // case explicitly. |
6058 | if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) { |
6059 | return S.Diag(From->getBeginLoc(), |
6060 | diag::err_reference_bind_to_bitfield_in_cce) |
6061 | << From->getSourceRange(); |
6062 | } |
6063 | |
6064 | // Usually we can simply apply the ImplicitConversionSequence we formed |
6065 | // earlier, but that's not guaranteed to work when initializing an object of |
6066 | // class type. |
6067 | ExprResult Result; |
6068 | if (T->isRecordType()) { |
6069 | assert(CCE == Sema::CCEK_TemplateArg && |
6070 | "unexpected class type converted constant expr" ); |
6071 | Result = S.PerformCopyInitialization( |
6072 | Entity: InitializedEntity::InitializeTemplateParameter( |
6073 | T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)), |
6074 | EqualLoc: SourceLocation(), Init: From); |
6075 | } else { |
6076 | Result = S.PerformImplicitConversion(From, ToType: T, ICS, Action: Sema::AA_Converting); |
6077 | } |
6078 | if (Result.isInvalid()) |
6079 | return Result; |
6080 | |
6081 | // C++2a [intro.execution]p5: |
6082 | // A full-expression is [...] a constant-expression [...] |
6083 | Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(), |
6084 | /*DiscardedValue=*/false, /*IsConstexpr=*/true, |
6085 | IsTemplateArgument: CCE == Sema::CCEKind::CCEK_TemplateArg); |
6086 | if (Result.isInvalid()) |
6087 | return Result; |
6088 | |
6089 | // Check for a narrowing implicit conversion. |
6090 | bool ReturnPreNarrowingValue = false; |
6091 | QualType PreNarrowingType; |
6092 | switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue, |
6093 | ConstantType&: PreNarrowingType)) { |
6094 | case NK_Dependent_Narrowing: |
6095 | // Implicit conversion to a narrower type, but the expression is |
6096 | // value-dependent so we can't tell whether it's actually narrowing. |
6097 | case NK_Variable_Narrowing: |
6098 | // Implicit conversion to a narrower type, and the value is not a constant |
6099 | // expression. We'll diagnose this in a moment. |
6100 | case NK_Not_Narrowing: |
6101 | break; |
6102 | |
6103 | case NK_Constant_Narrowing: |
6104 | if (CCE == Sema::CCEK_ArrayBound && |
6105 | PreNarrowingType->isIntegralOrEnumerationType() && |
6106 | PreNarrowingValue.isInt()) { |
6107 | // Don't diagnose array bound narrowing here; we produce more precise |
6108 | // errors by allowing the un-narrowed value through. |
6109 | ReturnPreNarrowingValue = true; |
6110 | break; |
6111 | } |
6112 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
6113 | << CCE << /*Constant*/ 1 |
6114 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; |
6115 | break; |
6116 | |
6117 | case NK_Type_Narrowing: |
6118 | // FIXME: It would be better to diagnose that the expression is not a |
6119 | // constant expression. |
6120 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
6121 | << CCE << /*Constant*/ 0 << From->getType() << T; |
6122 | break; |
6123 | } |
6124 | if (!ReturnPreNarrowingValue) |
6125 | PreNarrowingValue = {}; |
6126 | |
6127 | return Result; |
6128 | } |
6129 | |
6130 | /// CheckConvertedConstantExpression - Check that the expression From is a |
6131 | /// converted constant expression of type T, perform the conversion and produce |
6132 | /// the converted expression, per C++11 [expr.const]p3. |
6133 | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, |
6134 | QualType T, APValue &Value, |
6135 | Sema::CCEKind CCE, |
6136 | bool RequireInt, |
6137 | NamedDecl *Dest) { |
6138 | |
6139 | APValue PreNarrowingValue; |
6140 | ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest, |
6141 | PreNarrowingValue); |
6142 | if (Result.isInvalid() || Result.get()->isValueDependent()) { |
6143 | Value = APValue(); |
6144 | return Result; |
6145 | } |
6146 | return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE, |
6147 | RequireInt, PreNarrowingValue); |
6148 | } |
6149 | |
6150 | ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T, |
6151 | CCEKind CCE, |
6152 | NamedDecl *Dest) { |
6153 | APValue PreNarrowingValue; |
6154 | return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest, |
6155 | PreNarrowingValue); |
6156 | } |
6157 | |
6158 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6159 | APValue &Value, CCEKind CCE, |
6160 | NamedDecl *Dest) { |
6161 | return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false, |
6162 | Dest); |
6163 | } |
6164 | |
6165 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6166 | llvm::APSInt &Value, |
6167 | CCEKind CCE) { |
6168 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type" ); |
6169 | |
6170 | APValue V; |
6171 | auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true, |
6172 | /*Dest=*/nullptr); |
6173 | if (!R.isInvalid() && !R.get()->isValueDependent()) |
6174 | Value = V.getInt(); |
6175 | return R; |
6176 | } |
6177 | |
6178 | /// EvaluateConvertedConstantExpression - Evaluate an Expression |
6179 | /// That is a converted constant expression |
6180 | /// (which was built with BuildConvertedConstantExpression) |
6181 | ExprResult |
6182 | Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, |
6183 | Sema::CCEKind CCE, bool RequireInt, |
6184 | const APValue &PreNarrowingValue) { |
6185 | |
6186 | ExprResult Result = E; |
6187 | // Check the expression is a constant expression. |
6188 | SmallVector<PartialDiagnosticAt, 8> Notes; |
6189 | Expr::EvalResult Eval; |
6190 | Eval.Diag = &Notes; |
6191 | |
6192 | ConstantExprKind Kind; |
6193 | if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) |
6194 | Kind = ConstantExprKind::ClassTemplateArgument; |
6195 | else if (CCE == Sema::CCEK_TemplateArg) |
6196 | Kind = ConstantExprKind::NonClassTemplateArgument; |
6197 | else |
6198 | Kind = ConstantExprKind::Normal; |
6199 | |
6200 | if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) || |
6201 | (RequireInt && !Eval.Val.isInt())) { |
6202 | // The expression can't be folded, so we can't keep it at this position in |
6203 | // the AST. |
6204 | Result = ExprError(); |
6205 | } else { |
6206 | Value = Eval.Val; |
6207 | |
6208 | if (Notes.empty()) { |
6209 | // It's a constant expression. |
6210 | Expr *E = Result.get(); |
6211 | if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) { |
6212 | // We expect a ConstantExpr to have a value associated with it |
6213 | // by this point. |
6214 | assert(CE->getResultStorageKind() != ConstantResultStorageKind::None && |
6215 | "ConstantExpr has no value associated with it" ); |
6216 | } else { |
6217 | E = ConstantExpr::Create(Context, E: Result.get(), Result: Value); |
6218 | } |
6219 | if (!PreNarrowingValue.isAbsent()) |
6220 | Value = std::move(PreNarrowingValue); |
6221 | return E; |
6222 | } |
6223 | } |
6224 | |
6225 | // It's not a constant expression. Produce an appropriate diagnostic. |
6226 | if (Notes.size() == 1 && |
6227 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { |
6228 | Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; |
6229 | } else if (!Notes.empty() && Notes[0].second.getDiagID() == |
6230 | diag::note_constexpr_invalid_template_arg) { |
6231 | Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); |
6232 | for (unsigned I = 0; I < Notes.size(); ++I) |
6233 | Diag(Loc: Notes[I].first, PD: Notes[I].second); |
6234 | } else { |
6235 | Diag(E->getBeginLoc(), diag::err_expr_not_cce) |
6236 | << CCE << E->getSourceRange(); |
6237 | for (unsigned I = 0; I < Notes.size(); ++I) |
6238 | Diag(Loc: Notes[I].first, PD: Notes[I].second); |
6239 | } |
6240 | return ExprError(); |
6241 | } |
6242 | |
6243 | /// dropPointerConversions - If the given standard conversion sequence |
6244 | /// involves any pointer conversions, remove them. This may change |
6245 | /// the result type of the conversion sequence. |
6246 | static void dropPointerConversion(StandardConversionSequence &SCS) { |
6247 | if (SCS.Second == ICK_Pointer_Conversion) { |
6248 | SCS.Second = ICK_Identity; |
6249 | SCS.Third = ICK_Identity; |
6250 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; |
6251 | } |
6252 | } |
6253 | |
6254 | /// TryContextuallyConvertToObjCPointer - Attempt to contextually |
6255 | /// convert the expression From to an Objective-C pointer type. |
6256 | static ImplicitConversionSequence |
6257 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { |
6258 | // Do an implicit conversion to 'id'. |
6259 | QualType Ty = S.Context.getObjCIdType(); |
6260 | ImplicitConversionSequence ICS |
6261 | = TryImplicitConversion(S, From, ToType: Ty, |
6262 | // FIXME: Are these flags correct? |
6263 | /*SuppressUserConversions=*/false, |
6264 | AllowExplicit: AllowedExplicit::Conversions, |
6265 | /*InOverloadResolution=*/false, |
6266 | /*CStyle=*/false, |
6267 | /*AllowObjCWritebackConversion=*/false, |
6268 | /*AllowObjCConversionOnExplicit=*/true); |
6269 | |
6270 | // Strip off any final conversions to 'id'. |
6271 | switch (ICS.getKind()) { |
6272 | case ImplicitConversionSequence::BadConversion: |
6273 | case ImplicitConversionSequence::AmbiguousConversion: |
6274 | case ImplicitConversionSequence::EllipsisConversion: |
6275 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
6276 | break; |
6277 | |
6278 | case ImplicitConversionSequence::UserDefinedConversion: |
6279 | dropPointerConversion(SCS&: ICS.UserDefined.After); |
6280 | break; |
6281 | |
6282 | case ImplicitConversionSequence::StandardConversion: |
6283 | dropPointerConversion(SCS&: ICS.Standard); |
6284 | break; |
6285 | } |
6286 | |
6287 | return ICS; |
6288 | } |
6289 | |
6290 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual |
6291 | /// conversion of the expression From to an Objective-C pointer type. |
6292 | /// Returns a valid but null ExprResult if no conversion sequence exists. |
6293 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { |
6294 | if (checkPlaceholderForOverload(S&: *this, E&: From)) |
6295 | return ExprError(); |
6296 | |
6297 | QualType Ty = Context.getObjCIdType(); |
6298 | ImplicitConversionSequence ICS = |
6299 | TryContextuallyConvertToObjCPointer(S&: *this, From); |
6300 | if (!ICS.isBad()) |
6301 | return PerformImplicitConversion(From, ToType: Ty, ICS, Action: AA_Converting); |
6302 | return ExprResult(); |
6303 | } |
6304 | |
6305 | static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) { |
6306 | const Expr *Base = nullptr; |
6307 | assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) && |
6308 | "expected a member expression" ); |
6309 | |
6310 | if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE); |
6311 | M && !M->isImplicitAccess()) |
6312 | Base = M->getBase(); |
6313 | else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE); |
6314 | M && !M->isImplicitAccess()) |
6315 | Base = M->getBase(); |
6316 | |
6317 | QualType T = Base ? Base->getType() : S.getCurrentThisType(); |
6318 | |
6319 | if (T->isPointerType()) |
6320 | T = T->getPointeeType(); |
6321 | |
6322 | return T; |
6323 | } |
6324 | |
6325 | static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj, |
6326 | const FunctionDecl *Fun) { |
6327 | QualType ObjType = Obj->getType(); |
6328 | if (ObjType->isPointerType()) { |
6329 | ObjType = ObjType->getPointeeType(); |
6330 | Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType, |
6331 | VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(), |
6332 | /*CanOverflow=*/false, FPFeatures: FPOptionsOverride()); |
6333 | } |
6334 | if (Obj->Classify(Ctx&: S.getASTContext()).isPRValue()) { |
6335 | Obj = S.CreateMaterializeTemporaryExpr( |
6336 | T: ObjType, Temporary: Obj, |
6337 | BoundToLvalueReference: !Fun->getParamDecl(i: 0)->getType()->isRValueReferenceType()); |
6338 | } |
6339 | return Obj; |
6340 | } |
6341 | |
6342 | ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj, |
6343 | FunctionDecl *Fun) { |
6344 | Obj = GetExplicitObjectExpr(S, Obj, Fun); |
6345 | return S.PerformCopyInitialization( |
6346 | Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)), |
6347 | EqualLoc: Obj->getExprLoc(), Init: Obj); |
6348 | } |
6349 | |
6350 | static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, |
6351 | Expr *Object, MultiExprArg &Args, |
6352 | SmallVectorImpl<Expr *> &NewArgs) { |
6353 | assert(Method->isExplicitObjectMemberFunction() && |
6354 | "Method is not an explicit member function" ); |
6355 | assert(NewArgs.empty() && "NewArgs should be empty" ); |
6356 | NewArgs.reserve(N: Args.size() + 1); |
6357 | Expr *This = GetExplicitObjectExpr(S, Object, Method); |
6358 | NewArgs.push_back(Elt: This); |
6359 | NewArgs.append(in_start: Args.begin(), in_end: Args.end()); |
6360 | Args = NewArgs; |
6361 | } |
6362 | |
6363 | /// Determine whether the provided type is an integral type, or an enumeration |
6364 | /// type of a permitted flavor. |
6365 | bool Sema::ICEConvertDiagnoser::match(QualType T) { |
6366 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() |
6367 | : T->isIntegralOrUnscopedEnumerationType(); |
6368 | } |
6369 | |
6370 | static ExprResult |
6371 | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, |
6372 | Sema::ContextualImplicitConverter &Converter, |
6373 | QualType T, UnresolvedSetImpl &ViableConversions) { |
6374 | |
6375 | if (Converter.Suppress) |
6376 | return ExprError(); |
6377 | |
6378 | Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange(); |
6379 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6380 | CXXConversionDecl *Conv = |
6381 | cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl()); |
6382 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); |
6383 | Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy); |
6384 | } |
6385 | return From; |
6386 | } |
6387 | |
6388 | static bool |
6389 | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6390 | Sema::ContextualImplicitConverter &Converter, |
6391 | QualType T, bool HadMultipleCandidates, |
6392 | UnresolvedSetImpl &ExplicitConversions) { |
6393 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { |
6394 | DeclAccessPair Found = ExplicitConversions[0]; |
6395 | CXXConversionDecl *Conversion = |
6396 | cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl()); |
6397 | |
6398 | // The user probably meant to invoke the given explicit |
6399 | // conversion; use it. |
6400 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); |
6401 | std::string TypeStr; |
6402 | ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy()); |
6403 | |
6404 | Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy) |
6405 | << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(), |
6406 | Code: "static_cast<" + TypeStr + ">(" ) |
6407 | << FixItHint::CreateInsertion( |
6408 | InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")" ); |
6409 | Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy); |
6410 | |
6411 | // If we aren't in a SFINAE context, build a call to the |
6412 | // explicit conversion function. |
6413 | if (SemaRef.isSFINAEContext()) |
6414 | return true; |
6415 | |
6416 | SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found); |
6417 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion, |
6418 | HadMultipleCandidates); |
6419 | if (Result.isInvalid()) |
6420 | return true; |
6421 | // Record usage of conversion in an implicit cast. |
6422 | From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(), |
6423 | Kind: CK_UserDefinedConversion, Operand: Result.get(), |
6424 | BasePath: nullptr, Cat: Result.get()->getValueKind(), |
6425 | FPO: SemaRef.CurFPFeatureOverrides()); |
6426 | } |
6427 | return false; |
6428 | } |
6429 | |
6430 | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6431 | Sema::ContextualImplicitConverter &Converter, |
6432 | QualType T, bool HadMultipleCandidates, |
6433 | DeclAccessPair &Found) { |
6434 | CXXConversionDecl *Conversion = |
6435 | cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl()); |
6436 | SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found); |
6437 | |
6438 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); |
6439 | if (!Converter.SuppressConversion) { |
6440 | if (SemaRef.isSFINAEContext()) |
6441 | return true; |
6442 | |
6443 | Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType) |
6444 | << From->getSourceRange(); |
6445 | } |
6446 | |
6447 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion, |
6448 | HadMultipleCandidates); |
6449 | if (Result.isInvalid()) |
6450 | return true; |
6451 | // Record usage of conversion in an implicit cast. |
6452 | From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(), |
6453 | Kind: CK_UserDefinedConversion, Operand: Result.get(), |
6454 | BasePath: nullptr, Cat: Result.get()->getValueKind(), |
6455 | FPO: SemaRef.CurFPFeatureOverrides()); |
6456 | return false; |
6457 | } |
6458 | |
6459 | static ExprResult finishContextualImplicitConversion( |
6460 | Sema &SemaRef, SourceLocation Loc, Expr *From, |
6461 | Sema::ContextualImplicitConverter &Converter) { |
6462 | if (!Converter.match(T: From->getType()) && !Converter.Suppress) |
6463 | Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType()) |
6464 | << From->getSourceRange(); |
6465 | |
6466 | return SemaRef.DefaultLvalueConversion(E: From); |
6467 | } |
6468 | |
6469 | static void |
6470 | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, |
6471 | UnresolvedSetImpl &ViableConversions, |
6472 | OverloadCandidateSet &CandidateSet) { |
6473 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6474 | DeclAccessPair FoundDecl = ViableConversions[I]; |
6475 | NamedDecl *D = FoundDecl.getDecl(); |
6476 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
6477 | if (isa<UsingShadowDecl>(Val: D)) |
6478 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
6479 | |
6480 | CXXConversionDecl *Conv; |
6481 | FunctionTemplateDecl *ConvTemplate; |
6482 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D))) |
6483 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
6484 | else |
6485 | Conv = cast<CXXConversionDecl>(Val: D); |
6486 | |
6487 | if (ConvTemplate) |
6488 | SemaRef.AddTemplateConversionCandidate( |
6489 | FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, |
6490 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); |
6491 | else |
6492 | SemaRef.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, |
6493 | ToType, CandidateSet, |
6494 | /*AllowObjCConversionOnExplicit=*/false, |
6495 | /*AllowExplicit*/ true); |
6496 | } |
6497 | } |
6498 | |
6499 | /// Attempt to convert the given expression to a type which is accepted |
6500 | /// by the given converter. |
6501 | /// |
6502 | /// This routine will attempt to convert an expression of class type to a |
6503 | /// type accepted by the specified converter. In C++11 and before, the class |
6504 | /// must have a single non-explicit conversion function converting to a matching |
6505 | /// type. In C++1y, there can be multiple such conversion functions, but only |
6506 | /// one target type. |
6507 | /// |
6508 | /// \param Loc The source location of the construct that requires the |
6509 | /// conversion. |
6510 | /// |
6511 | /// \param From The expression we're converting from. |
6512 | /// |
6513 | /// \param Converter Used to control and diagnose the conversion process. |
6514 | /// |
6515 | /// \returns The expression, converted to an integral or enumeration type if |
6516 | /// successful. |
6517 | ExprResult Sema::PerformContextualImplicitConversion( |
6518 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { |
6519 | // We can't perform any more checking for type-dependent expressions. |
6520 | if (From->isTypeDependent()) |
6521 | return From; |
6522 | |
6523 | // Process placeholders immediately. |
6524 | if (From->hasPlaceholderType()) { |
6525 | ExprResult result = CheckPlaceholderExpr(E: From); |
6526 | if (result.isInvalid()) |
6527 | return result; |
6528 | From = result.get(); |
6529 | } |
6530 | |
6531 | // Try converting the expression to an Lvalue first, to get rid of qualifiers. |
6532 | ExprResult Converted = DefaultLvalueConversion(E: From); |
6533 | QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType(); |
6534 | // If the expression already has a matching type, we're golden. |
6535 | if (Converter.match(T)) |
6536 | return Converted; |
6537 | |
6538 | // FIXME: Check for missing '()' if T is a function type? |
6539 | |
6540 | // We can only perform contextual implicit conversions on objects of class |
6541 | // type. |
6542 | const RecordType *RecordTy = T->getAs<RecordType>(); |
6543 | if (!RecordTy || !getLangOpts().CPlusPlus) { |
6544 | if (!Converter.Suppress) |
6545 | Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange(); |
6546 | return From; |
6547 | } |
6548 | |
6549 | // We must have a complete class type. |
6550 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { |
6551 | ContextualImplicitConverter &Converter; |
6552 | Expr *From; |
6553 | |
6554 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) |
6555 | : Converter(Converter), From(From) {} |
6556 | |
6557 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
6558 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); |
6559 | } |
6560 | } IncompleteDiagnoser(Converter, From); |
6561 | |
6562 | if (Converter.Suppress ? !isCompleteType(Loc, T) |
6563 | : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser)) |
6564 | return From; |
6565 | |
6566 | // Look for a conversion to an integral or enumeration type. |
6567 | UnresolvedSet<4> |
6568 | ViableConversions; // These are *potentially* viable in C++1y. |
6569 | UnresolvedSet<4> ExplicitConversions; |
6570 | const auto &Conversions = |
6571 | cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getVisibleConversionFunctions(); |
6572 | |
6573 | bool HadMultipleCandidates = |
6574 | (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1); |
6575 | |
6576 | // To check that there is only one target type, in C++1y: |
6577 | QualType ToType; |
6578 | bool HasUniqueTargetType = true; |
6579 | |
6580 | // Collect explicit or viable (potentially in C++1y) conversions. |
6581 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
6582 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
6583 | CXXConversionDecl *Conversion; |
6584 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
6585 | if (ConvTemplate) { |
6586 | if (getLangOpts().CPlusPlus14) |
6587 | Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
6588 | else |
6589 | continue; // C++11 does not consider conversion operator templates(?). |
6590 | } else |
6591 | Conversion = cast<CXXConversionDecl>(Val: D); |
6592 | |
6593 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) && |
6594 | "Conversion operator templates are considered potentially " |
6595 | "viable in C++1y" ); |
6596 | |
6597 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); |
6598 | if (Converter.match(T: CurToType) || ConvTemplate) { |
6599 | |
6600 | if (Conversion->isExplicit()) { |
6601 | // FIXME: For C++1y, do we need this restriction? |
6602 | // cf. diagnoseNoViableConversion() |
6603 | if (!ConvTemplate) |
6604 | ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess()); |
6605 | } else { |
6606 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { |
6607 | if (ToType.isNull()) |
6608 | ToType = CurToType.getUnqualifiedType(); |
6609 | else if (HasUniqueTargetType && |
6610 | (CurToType.getUnqualifiedType() != ToType)) |
6611 | HasUniqueTargetType = false; |
6612 | } |
6613 | ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess()); |
6614 | } |
6615 | } |
6616 | } |
6617 | |
6618 | if (getLangOpts().CPlusPlus14) { |
6619 | // C++1y [conv]p6: |
6620 | // ... An expression e of class type E appearing in such a context |
6621 | // is said to be contextually implicitly converted to a specified |
6622 | // type T and is well-formed if and only if e can be implicitly |
6623 | // converted to a type T that is determined as follows: E is searched |
6624 | // for conversion functions whose return type is cv T or reference to |
6625 | // cv T such that T is allowed by the context. There shall be |
6626 | // exactly one such T. |
6627 | |
6628 | // If no unique T is found: |
6629 | if (ToType.isNull()) { |
6630 | if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T, |
6631 | HadMultipleCandidates, |
6632 | ExplicitConversions)) |
6633 | return ExprError(); |
6634 | return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter); |
6635 | } |
6636 | |
6637 | // If more than one unique Ts are found: |
6638 | if (!HasUniqueTargetType) |
6639 | return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T, |
6640 | ViableConversions); |
6641 | |
6642 | // If one unique T is found: |
6643 | // First, build a candidate set from the previously recorded |
6644 | // potentially viable conversions. |
6645 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6646 | collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions, |
6647 | CandidateSet); |
6648 | |
6649 | // Then, perform overload resolution over the candidate set. |
6650 | OverloadCandidateSet::iterator Best; |
6651 | switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) { |
6652 | case OR_Success: { |
6653 | // Apply this conversion. |
6654 | DeclAccessPair Found = |
6655 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); |
6656 | if (recordConversion(SemaRef&: *this, Loc, From, Converter, T, |
6657 | HadMultipleCandidates, Found)) |
6658 | return ExprError(); |
6659 | break; |
6660 | } |
6661 | case OR_Ambiguous: |
6662 | return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T, |
6663 | ViableConversions); |
6664 | case OR_No_Viable_Function: |
6665 | if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T, |
6666 | HadMultipleCandidates, |
6667 | ExplicitConversions)) |
6668 | return ExprError(); |
6669 | [[fallthrough]]; |
6670 | case OR_Deleted: |
6671 | // We'll complain below about a non-integral condition type. |
6672 | break; |
6673 | } |
6674 | } else { |
6675 | switch (ViableConversions.size()) { |
6676 | case 0: { |
6677 | if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T, |
6678 | HadMultipleCandidates, |
6679 | ExplicitConversions)) |
6680 | return ExprError(); |
6681 | |
6682 | // We'll complain below about a non-integral condition type. |
6683 | break; |
6684 | } |
6685 | case 1: { |
6686 | // Apply this conversion. |
6687 | DeclAccessPair Found = ViableConversions[0]; |
6688 | if (recordConversion(SemaRef&: *this, Loc, From, Converter, T, |
6689 | HadMultipleCandidates, Found)) |
6690 | return ExprError(); |
6691 | break; |
6692 | } |
6693 | default: |
6694 | return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T, |
6695 | ViableConversions); |
6696 | } |
6697 | } |
6698 | |
6699 | return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter); |
6700 | } |
6701 | |
6702 | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is |
6703 | /// an acceptable non-member overloaded operator for a call whose |
6704 | /// arguments have types T1 (and, if non-empty, T2). This routine |
6705 | /// implements the check in C++ [over.match.oper]p3b2 concerning |
6706 | /// enumeration types. |
6707 | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, |
6708 | FunctionDecl *Fn, |
6709 | ArrayRef<Expr *> Args) { |
6710 | QualType T1 = Args[0]->getType(); |
6711 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); |
6712 | |
6713 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) |
6714 | return true; |
6715 | |
6716 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) |
6717 | return true; |
6718 | |
6719 | const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); |
6720 | if (Proto->getNumParams() < 1) |
6721 | return false; |
6722 | |
6723 | if (T1->isEnumeralType()) { |
6724 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); |
6725 | if (Context.hasSameUnqualifiedType(T1, T2: ArgType)) |
6726 | return true; |
6727 | } |
6728 | |
6729 | if (Proto->getNumParams() < 2) |
6730 | return false; |
6731 | |
6732 | if (!T2.isNull() && T2->isEnumeralType()) { |
6733 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); |
6734 | if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType)) |
6735 | return true; |
6736 | } |
6737 | |
6738 | return false; |
6739 | } |
6740 | |
6741 | /// AddOverloadCandidate - Adds the given function to the set of |
6742 | /// candidate functions, using the given function call arguments. If |
6743 | /// @p SuppressUserConversions, then don't allow user-defined |
6744 | /// conversions via constructors or conversion operators. |
6745 | /// |
6746 | /// \param PartialOverloading true if we are performing "partial" overloading |
6747 | /// based on an incomplete set of function arguments. This feature is used by |
6748 | /// code completion. |
6749 | void Sema::AddOverloadCandidate( |
6750 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, |
6751 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6752 | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, |
6753 | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, |
6754 | OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { |
6755 | const FunctionProtoType *Proto |
6756 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); |
6757 | assert(Proto && "Functions without a prototype cannot be overloaded" ); |
6758 | assert(!Function->getDescribedFunctionTemplate() && |
6759 | "Use AddTemplateOverloadCandidate for function templates" ); |
6760 | |
6761 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) { |
6762 | if (!isa<CXXConstructorDecl>(Val: Method)) { |
6763 | // If we get here, it's because we're calling a member function |
6764 | // that is named without a member access expression (e.g., |
6765 | // "this->f") that was either written explicitly or created |
6766 | // implicitly. This can happen with a qualified call to a member |
6767 | // function, e.g., X::f(). We use an empty type for the implied |
6768 | // object argument (C++ [over.call.func]p3), and the acting context |
6769 | // is irrelevant. |
6770 | AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(), |
6771 | ObjectClassification: Expr::Classification::makeSimpleLValue(), Args, |
6772 | CandidateSet, SuppressUserConversions, |
6773 | PartialOverloading, EarlyConversions, PO); |
6774 | return; |
6775 | } |
6776 | // We treat a constructor like a non-member function, since its object |
6777 | // argument doesn't participate in overload resolution. |
6778 | } |
6779 | |
6780 | if (!CandidateSet.isNewCandidate(Function, PO)) |
6781 | return; |
6782 | |
6783 | // C++11 [class.copy]p11: [DR1402] |
6784 | // A defaulted move constructor that is defined as deleted is ignored by |
6785 | // overload resolution. |
6786 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function); |
6787 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && |
6788 | Constructor->isMoveConstructor()) |
6789 | return; |
6790 | |
6791 | // Overload resolution is always an unevaluated context. |
6792 | EnterExpressionEvaluationContext Unevaluated( |
6793 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6794 | |
6795 | // C++ [over.match.oper]p3: |
6796 | // if no operand has a class type, only those non-member functions in the |
6797 | // lookup set that have a first parameter of type T1 or "reference to |
6798 | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there |
6799 | // is a right operand) a second parameter of type T2 or "reference to |
6800 | // (possibly cv-qualified) T2", when T2 is an enumeration type, are |
6801 | // candidate functions. |
6802 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && |
6803 | !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args)) |
6804 | return; |
6805 | |
6806 | // Add this candidate |
6807 | OverloadCandidate &Candidate = |
6808 | CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions); |
6809 | Candidate.FoundDecl = FoundDecl; |
6810 | Candidate.Function = Function; |
6811 | Candidate.Viable = true; |
6812 | Candidate.RewriteKind = |
6813 | CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO); |
6814 | Candidate.IsSurrogate = false; |
6815 | Candidate.IsADLCandidate = IsADLCandidate; |
6816 | Candidate.IgnoreObjectArgument = false; |
6817 | Candidate.ExplicitCallArguments = Args.size(); |
6818 | |
6819 | // Explicit functions are not actually candidates at all if we're not |
6820 | // allowing them in this context, but keep them around so we can point |
6821 | // to them in diagnostics. |
6822 | if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { |
6823 | Candidate.Viable = false; |
6824 | Candidate.FailureKind = ovl_fail_explicit; |
6825 | return; |
6826 | } |
6827 | |
6828 | // Functions with internal linkage are only viable in the same module unit. |
6829 | if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { |
6830 | /// FIXME: Currently, the semantics of linkage in clang is slightly |
6831 | /// different from the semantics in C++ spec. In C++ spec, only names |
6832 | /// have linkage. So that all entities of the same should share one |
6833 | /// linkage. But in clang, different entities of the same could have |
6834 | /// different linkage. |
6835 | NamedDecl *ND = Function; |
6836 | if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) |
6837 | ND = SpecInfo->getTemplate(); |
6838 | |
6839 | if (ND->getFormalLinkage() == Linkage::Internal) { |
6840 | Candidate.Viable = false; |
6841 | Candidate.FailureKind = ovl_fail_module_mismatched; |
6842 | return; |
6843 | } |
6844 | } |
6845 | |
6846 | if (Function->isMultiVersion() && |
6847 | ((Function->hasAttr<TargetAttr>() && |
6848 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) || |
6849 | (Function->hasAttr<TargetVersionAttr>() && |
6850 | !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
6851 | Candidate.Viable = false; |
6852 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
6853 | return; |
6854 | } |
6855 | |
6856 | if (Constructor) { |
6857 | // C++ [class.copy]p3: |
6858 | // A member function template is never instantiated to perform the copy |
6859 | // of a class object to an object of its class type. |
6860 | QualType ClassType = Context.getTypeDeclType(Decl: Constructor->getParent()); |
6861 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && |
6862 | (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) || |
6863 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), |
6864 | ClassType))) { |
6865 | Candidate.Viable = false; |
6866 | Candidate.FailureKind = ovl_fail_illegal_constructor; |
6867 | return; |
6868 | } |
6869 | |
6870 | // C++ [over.match.funcs]p8: (proposed DR resolution) |
6871 | // A constructor inherited from class type C that has a first parameter |
6872 | // of type "reference to P" (including such a constructor instantiated |
6873 | // from a template) is excluded from the set of candidate functions when |
6874 | // constructing an object of type cv D if the argument list has exactly |
6875 | // one argument and D is reference-related to P and P is reference-related |
6876 | // to C. |
6877 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl()); |
6878 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && |
6879 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { |
6880 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); |
6881 | QualType C = Context.getRecordType(Decl: Constructor->getParent()); |
6882 | QualType D = Context.getRecordType(Shadow->getParent()); |
6883 | SourceLocation Loc = Args.front()->getExprLoc(); |
6884 | if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) && |
6885 | (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) { |
6886 | Candidate.Viable = false; |
6887 | Candidate.FailureKind = ovl_fail_inhctor_slice; |
6888 | return; |
6889 | } |
6890 | } |
6891 | |
6892 | // Check that the constructor is capable of constructing an object in the |
6893 | // destination address space. |
6894 | if (!Qualifiers::isAddressSpaceSupersetOf( |
6895 | Constructor->getMethodQualifiers().getAddressSpace(), |
6896 | CandidateSet.getDestAS())) { |
6897 | Candidate.Viable = false; |
6898 | Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; |
6899 | } |
6900 | } |
6901 | |
6902 | unsigned NumParams = Proto->getNumParams(); |
6903 | |
6904 | // (C++ 13.3.2p2): A candidate function having fewer than m |
6905 | // parameters is viable only if it has an ellipsis in its parameter |
6906 | // list (8.3.5). |
6907 | if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) && |
6908 | !Proto->isVariadic() && |
6909 | shouldEnforceArgLimit(PartialOverloading, Function)) { |
6910 | Candidate.Viable = false; |
6911 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
6912 | return; |
6913 | } |
6914 | |
6915 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
6916 | // is viable only if the (m+1)st parameter has a default argument |
6917 | // (8.3.6). For the purposes of overload resolution, the |
6918 | // parameter list is truncated on the right, so that there are |
6919 | // exactly m parameters. |
6920 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); |
6921 | if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs && |
6922 | !PartialOverloading) { |
6923 | // Not enough arguments. |
6924 | Candidate.Viable = false; |
6925 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
6926 | return; |
6927 | } |
6928 | |
6929 | // (CUDA B.1): Check for invalid calls between targets. |
6930 | if (getLangOpts().CUDA) { |
6931 | const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
6932 | // Skip the check for callers that are implicit members, because in this |
6933 | // case we may not yet know what the member's target is; the target is |
6934 | // inferred for the member automatically, based on the bases and fields of |
6935 | // the class. |
6936 | if (!(Caller && Caller->isImplicit()) && |
6937 | !IsAllowedCUDACall(Caller, Callee: Function)) { |
6938 | Candidate.Viable = false; |
6939 | Candidate.FailureKind = ovl_fail_bad_target; |
6940 | return; |
6941 | } |
6942 | } |
6943 | |
6944 | if (Function->getTrailingRequiresClause()) { |
6945 | ConstraintSatisfaction Satisfaction; |
6946 | if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {}, |
6947 | /*ForOverloadResolution*/ true) || |
6948 | !Satisfaction.IsSatisfied) { |
6949 | Candidate.Viable = false; |
6950 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
6951 | return; |
6952 | } |
6953 | } |
6954 | |
6955 | // Determine the implicit conversion sequences for each of the |
6956 | // arguments. |
6957 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
6958 | unsigned ConvIdx = |
6959 | PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; |
6960 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
6961 | // We already formed a conversion sequence for this parameter during |
6962 | // template argument deduction. |
6963 | } else if (ArgIdx < NumParams) { |
6964 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
6965 | // exist for each argument an implicit conversion sequence |
6966 | // (13.3.3.1) that converts that argument to the corresponding |
6967 | // parameter of F. |
6968 | QualType ParamType = Proto->getParamType(i: ArgIdx); |
6969 | Candidate.Conversions[ConvIdx] = TryCopyInitialization( |
6970 | S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions, |
6971 | /*InOverloadResolution=*/true, |
6972 | /*AllowObjCWritebackConversion=*/ |
6973 | getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions); |
6974 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6975 | Candidate.Viable = false; |
6976 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6977 | return; |
6978 | } |
6979 | } else { |
6980 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
6981 | // argument for which there is no corresponding parameter is |
6982 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
6983 | Candidate.Conversions[ConvIdx].setEllipsis(); |
6984 | } |
6985 | } |
6986 | |
6987 | if (EnableIfAttr *FailedAttr = |
6988 | CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) { |
6989 | Candidate.Viable = false; |
6990 | Candidate.FailureKind = ovl_fail_enable_if; |
6991 | Candidate.DeductionFailure.Data = FailedAttr; |
6992 | return; |
6993 | } |
6994 | } |
6995 | |
6996 | ObjCMethodDecl * |
6997 | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, |
6998 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { |
6999 | if (Methods.size() <= 1) |
7000 | return nullptr; |
7001 | |
7002 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
7003 | bool Match = true; |
7004 | ObjCMethodDecl *Method = Methods[b]; |
7005 | unsigned NumNamedArgs = Sel.getNumArgs(); |
7006 | // Method might have more arguments than selector indicates. This is due |
7007 | // to addition of c-style arguments in method. |
7008 | if (Method->param_size() > NumNamedArgs) |
7009 | NumNamedArgs = Method->param_size(); |
7010 | if (Args.size() < NumNamedArgs) |
7011 | continue; |
7012 | |
7013 | for (unsigned i = 0; i < NumNamedArgs; i++) { |
7014 | // We can't do any type-checking on a type-dependent argument. |
7015 | if (Args[i]->isTypeDependent()) { |
7016 | Match = false; |
7017 | break; |
7018 | } |
7019 | |
7020 | ParmVarDecl *param = Method->parameters()[i]; |
7021 | Expr *argExpr = Args[i]; |
7022 | assert(argExpr && "SelectBestMethod(): missing expression" ); |
7023 | |
7024 | // Strip the unbridged-cast placeholder expression off unless it's |
7025 | // a consumed argument. |
7026 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && |
7027 | !param->hasAttr<CFConsumedAttr>()) |
7028 | argExpr = stripARCUnbridgedCast(e: argExpr); |
7029 | |
7030 | // If the parameter is __unknown_anytype, move on to the next method. |
7031 | if (param->getType() == Context.UnknownAnyTy) { |
7032 | Match = false; |
7033 | break; |
7034 | } |
7035 | |
7036 | ImplicitConversionSequence ConversionState |
7037 | = TryCopyInitialization(*this, argExpr, param->getType(), |
7038 | /*SuppressUserConversions*/false, |
7039 | /*InOverloadResolution=*/true, |
7040 | /*AllowObjCWritebackConversion=*/ |
7041 | getLangOpts().ObjCAutoRefCount, |
7042 | /*AllowExplicit*/false); |
7043 | // This function looks for a reasonably-exact match, so we consider |
7044 | // incompatible pointer conversions to be a failure here. |
7045 | if (ConversionState.isBad() || |
7046 | (ConversionState.isStandard() && |
7047 | ConversionState.Standard.Second == |
7048 | ICK_Incompatible_Pointer_Conversion)) { |
7049 | Match = false; |
7050 | break; |
7051 | } |
7052 | } |
7053 | // Promote additional arguments to variadic methods. |
7054 | if (Match && Method->isVariadic()) { |
7055 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { |
7056 | if (Args[i]->isTypeDependent()) { |
7057 | Match = false; |
7058 | break; |
7059 | } |
7060 | ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod, |
7061 | FDecl: nullptr); |
7062 | if (Arg.isInvalid()) { |
7063 | Match = false; |
7064 | break; |
7065 | } |
7066 | } |
7067 | } else { |
7068 | // Check for extra arguments to non-variadic methods. |
7069 | if (Args.size() != NumNamedArgs) |
7070 | Match = false; |
7071 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { |
7072 | // Special case when selectors have no argument. In this case, select |
7073 | // one with the most general result type of 'id'. |
7074 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
7075 | QualType ReturnT = Methods[b]->getReturnType(); |
7076 | if (ReturnT->isObjCIdType()) |
7077 | return Methods[b]; |
7078 | } |
7079 | } |
7080 | } |
7081 | |
7082 | if (Match) |
7083 | return Method; |
7084 | } |
7085 | return nullptr; |
7086 | } |
7087 | |
7088 | static bool convertArgsForAvailabilityChecks( |
7089 | Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, |
7090 | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, |
7091 | Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { |
7092 | if (ThisArg) { |
7093 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function); |
7094 | assert(!isa<CXXConstructorDecl>(Method) && |
7095 | "Shouldn't have `this` for ctors!" ); |
7096 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!" ); |
7097 | ExprResult R = S.PerformImplicitObjectArgumentInitialization( |
7098 | ThisArg, /*Qualifier=*/nullptr, Method, Method); |
7099 | if (R.isInvalid()) |
7100 | return false; |
7101 | ConvertedThis = R.get(); |
7102 | } else { |
7103 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) { |
7104 | (void)MD; |
7105 | assert((MissingImplicitThis || MD->isStatic() || |
7106 | isa<CXXConstructorDecl>(MD)) && |
7107 | "Expected `this` for non-ctor instance methods" ); |
7108 | } |
7109 | ConvertedThis = nullptr; |
7110 | } |
7111 | |
7112 | // Ignore any variadic arguments. Converting them is pointless, since the |
7113 | // user can't refer to them in the function condition. |
7114 | unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size()); |
7115 | |
7116 | // Convert the arguments. |
7117 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { |
7118 | ExprResult R; |
7119 | R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter( |
7120 | Context&: S.Context, Parm: Function->getParamDecl(i: I)), |
7121 | EqualLoc: SourceLocation(), Init: Args[I]); |
7122 | |
7123 | if (R.isInvalid()) |
7124 | return false; |
7125 | |
7126 | ConvertedArgs.push_back(Elt: R.get()); |
7127 | } |
7128 | |
7129 | if (Trap.hasErrorOccurred()) |
7130 | return false; |
7131 | |
7132 | // Push default arguments if needed. |
7133 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { |
7134 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { |
7135 | ParmVarDecl *P = Function->getParamDecl(i); |
7136 | if (!P->hasDefaultArg()) |
7137 | return false; |
7138 | ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P); |
7139 | if (R.isInvalid()) |
7140 | return false; |
7141 | ConvertedArgs.push_back(Elt: R.get()); |
7142 | } |
7143 | |
7144 | if (Trap.hasErrorOccurred()) |
7145 | return false; |
7146 | } |
7147 | return true; |
7148 | } |
7149 | |
7150 | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, |
7151 | SourceLocation CallLoc, |
7152 | ArrayRef<Expr *> Args, |
7153 | bool MissingImplicitThis) { |
7154 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); |
7155 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) |
7156 | return nullptr; |
7157 | |
7158 | SFINAETrap Trap(*this); |
7159 | SmallVector<Expr *, 16> ConvertedArgs; |
7160 | // FIXME: We should look into making enable_if late-parsed. |
7161 | Expr *DiscardedThis; |
7162 | if (!convertArgsForAvailabilityChecks( |
7163 | S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, |
7164 | /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs)) |
7165 | return *EnableIfAttrs.begin(); |
7166 | |
7167 | for (auto *EIA : EnableIfAttrs) { |
7168 | APValue Result; |
7169 | // FIXME: This doesn't consider value-dependent cases, because doing so is |
7170 | // very difficult. Ideally, we should handle them more gracefully. |
7171 | if (EIA->getCond()->isValueDependent() || |
7172 | !EIA->getCond()->EvaluateWithSubstitution( |
7173 | Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) |
7174 | return EIA; |
7175 | |
7176 | if (!Result.isInt() || !Result.getInt().getBoolValue()) |
7177 | return EIA; |
7178 | } |
7179 | return nullptr; |
7180 | } |
7181 | |
7182 | template <typename CheckFn> |
7183 | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, |
7184 | bool ArgDependent, SourceLocation Loc, |
7185 | CheckFn &&IsSuccessful) { |
7186 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; |
7187 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { |
7188 | if (ArgDependent == DIA->getArgDependent()) |
7189 | Attrs.push_back(DIA); |
7190 | } |
7191 | |
7192 | // Common case: No diagnose_if attributes, so we can quit early. |
7193 | if (Attrs.empty()) |
7194 | return false; |
7195 | |
7196 | auto WarningBegin = std::stable_partition( |
7197 | Attrs.begin(), Attrs.end(), |
7198 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); |
7199 | |
7200 | // Note that diagnose_if attributes are late-parsed, so they appear in the |
7201 | // correct order (unlike enable_if attributes). |
7202 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), |
7203 | IsSuccessful); |
7204 | if (ErrAttr != WarningBegin) { |
7205 | const DiagnoseIfAttr *DIA = *ErrAttr; |
7206 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); |
7207 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
7208 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
7209 | return true; |
7210 | } |
7211 | |
7212 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) |
7213 | if (IsSuccessful(DIA)) { |
7214 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); |
7215 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
7216 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
7217 | } |
7218 | |
7219 | return false; |
7220 | } |
7221 | |
7222 | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
7223 | const Expr *ThisArg, |
7224 | ArrayRef<const Expr *> Args, |
7225 | SourceLocation Loc) { |
7226 | return diagnoseDiagnoseIfAttrsWith( |
7227 | *this, Function, /*ArgDependent=*/true, Loc, |
7228 | [&](const DiagnoseIfAttr *DIA) { |
7229 | APValue Result; |
7230 | // It's sane to use the same Args for any redecl of this function, since |
7231 | // EvaluateWithSubstitution only cares about the position of each |
7232 | // argument in the arg list, not the ParmVarDecl* it maps to. |
7233 | if (!DIA->getCond()->EvaluateWithSubstitution( |
7234 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) |
7235 | return false; |
7236 | return Result.isInt() && Result.getInt().getBoolValue(); |
7237 | }); |
7238 | } |
7239 | |
7240 | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
7241 | SourceLocation Loc) { |
7242 | return diagnoseDiagnoseIfAttrsWith( |
7243 | S&: *this, ND, /*ArgDependent=*/false, Loc, |
7244 | IsSuccessful: [&](const DiagnoseIfAttr *DIA) { |
7245 | bool Result; |
7246 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && |
7247 | Result; |
7248 | }); |
7249 | } |
7250 | |
7251 | /// Add all of the function declarations in the given function set to |
7252 | /// the overload candidate set. |
7253 | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, |
7254 | ArrayRef<Expr *> Args, |
7255 | OverloadCandidateSet &CandidateSet, |
7256 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
7257 | bool SuppressUserConversions, |
7258 | bool PartialOverloading, |
7259 | bool FirstArgumentIsBase) { |
7260 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
7261 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
7262 | ArrayRef<Expr *> FunctionArgs = Args; |
7263 | |
7264 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D); |
7265 | FunctionDecl *FD = |
7266 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D); |
7267 | |
7268 | if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) { |
7269 | QualType ObjectType; |
7270 | Expr::Classification ObjectClassification; |
7271 | if (Args.size() > 0) { |
7272 | if (Expr *E = Args[0]) { |
7273 | // Use the explicit base to restrict the lookup: |
7274 | ObjectType = E->getType(); |
7275 | // Pointers in the object arguments are implicitly dereferenced, so we |
7276 | // always classify them as l-values. |
7277 | if (!ObjectType.isNull() && ObjectType->isPointerType()) |
7278 | ObjectClassification = Expr::Classification::makeSimpleLValue(); |
7279 | else |
7280 | ObjectClassification = E->Classify(Ctx&: Context); |
7281 | } // .. else there is an implicit base. |
7282 | FunctionArgs = Args.slice(N: 1); |
7283 | } |
7284 | if (FunTmpl) { |
7285 | AddMethodTemplateCandidate( |
7286 | MethodTmpl: FunTmpl, FoundDecl: F.getPair(), |
7287 | ActingContext: cast<CXXRecordDecl>(FunTmpl->getDeclContext()), |
7288 | ExplicitTemplateArgs, ObjectType, ObjectClassification, |
7289 | Args: FunctionArgs, CandidateSet, SuppressUserConversions, |
7290 | PartialOverloading); |
7291 | } else { |
7292 | AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(), |
7293 | ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType, |
7294 | ObjectClassification, Args: FunctionArgs, CandidateSet, |
7295 | SuppressUserConversions, PartialOverloading); |
7296 | } |
7297 | } else { |
7298 | // This branch handles both standalone functions and static methods. |
7299 | |
7300 | // Slice the first argument (which is the base) when we access |
7301 | // static method as non-static. |
7302 | if (Args.size() > 0 && |
7303 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) && |
7304 | !isa<CXXConstructorDecl>(Val: FD)))) { |
7305 | assert(cast<CXXMethodDecl>(FD)->isStatic()); |
7306 | FunctionArgs = Args.slice(N: 1); |
7307 | } |
7308 | if (FunTmpl) { |
7309 | AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), |
7310 | ExplicitTemplateArgs, Args: FunctionArgs, |
7311 | CandidateSet, SuppressUserConversions, |
7312 | PartialOverloading); |
7313 | } else { |
7314 | AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet, |
7315 | SuppressUserConversions, PartialOverloading); |
7316 | } |
7317 | } |
7318 | } |
7319 | } |
7320 | |
7321 | /// AddMethodCandidate - Adds a named decl (which is some kind of |
7322 | /// method) as a method candidate to the given overload set. |
7323 | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, |
7324 | Expr::Classification ObjectClassification, |
7325 | ArrayRef<Expr *> Args, |
7326 | OverloadCandidateSet &CandidateSet, |
7327 | bool SuppressUserConversions, |
7328 | OverloadCandidateParamOrder PO) { |
7329 | NamedDecl *Decl = FoundDecl.getDecl(); |
7330 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); |
7331 | |
7332 | if (isa<UsingShadowDecl>(Val: Decl)) |
7333 | Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl(); |
7334 | |
7335 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) { |
7336 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && |
7337 | "Expected a member function template" ); |
7338 | AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext, |
7339 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType, |
7340 | ObjectClassification, Args, CandidateSet, |
7341 | SuppressUserConversions, PartialOverloading: false, PO); |
7342 | } else { |
7343 | AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext, |
7344 | ObjectType, ObjectClassification, Args, CandidateSet, |
7345 | SuppressUserConversions, PartialOverloading: false, EarlyConversions: std::nullopt, PO); |
7346 | } |
7347 | } |
7348 | |
7349 | /// AddMethodCandidate - Adds the given C++ member function to the set |
7350 | /// of candidate functions, using the given function call arguments |
7351 | /// and the object argument (@c Object). For example, in a call |
7352 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain |
7353 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't |
7354 | /// allow user-defined conversions via constructors or conversion |
7355 | /// operators. |
7356 | void |
7357 | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, |
7358 | CXXRecordDecl *ActingContext, QualType ObjectType, |
7359 | Expr::Classification ObjectClassification, |
7360 | ArrayRef<Expr *> Args, |
7361 | OverloadCandidateSet &CandidateSet, |
7362 | bool SuppressUserConversions, |
7363 | bool PartialOverloading, |
7364 | ConversionSequenceList EarlyConversions, |
7365 | OverloadCandidateParamOrder PO) { |
7366 | const FunctionProtoType *Proto |
7367 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); |
7368 | assert(Proto && "Methods without a prototype cannot be overloaded" ); |
7369 | assert(!isa<CXXConstructorDecl>(Method) && |
7370 | "Use AddOverloadCandidate for constructors" ); |
7371 | |
7372 | if (!CandidateSet.isNewCandidate(Method, PO)) |
7373 | return; |
7374 | |
7375 | // C++11 [class.copy]p23: [DR1402] |
7376 | // A defaulted move assignment operator that is defined as deleted is |
7377 | // ignored by overload resolution. |
7378 | if (Method->isDefaulted() && Method->isDeleted() && |
7379 | Method->isMoveAssignmentOperator()) |
7380 | return; |
7381 | |
7382 | // Overload resolution is always an unevaluated context. |
7383 | EnterExpressionEvaluationContext Unevaluated( |
7384 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7385 | |
7386 | // Add this candidate |
7387 | OverloadCandidate &Candidate = |
7388 | CandidateSet.addCandidate(NumConversions: Args.size() + 1, Conversions: EarlyConversions); |
7389 | Candidate.FoundDecl = FoundDecl; |
7390 | Candidate.Function = Method; |
7391 | Candidate.RewriteKind = |
7392 | CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); |
7393 | Candidate.IsSurrogate = false; |
7394 | Candidate.IgnoreObjectArgument = false; |
7395 | Candidate.ExplicitCallArguments = Args.size(); |
7396 | |
7397 | unsigned NumParams = Method->getNumExplicitParams(); |
7398 | unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0; |
7399 | |
7400 | // (C++ 13.3.2p2): A candidate function having fewer than m |
7401 | // parameters is viable only if it has an ellipsis in its parameter |
7402 | // list (8.3.5). |
7403 | if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) && |
7404 | !Proto->isVariadic() && |
7405 | shouldEnforceArgLimit(PartialOverloading, Method)) { |
7406 | Candidate.Viable = false; |
7407 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
7408 | return; |
7409 | } |
7410 | |
7411 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
7412 | // is viable only if the (m+1)st parameter has a default argument |
7413 | // (8.3.6). For the purposes of overload resolution, the |
7414 | // parameter list is truncated on the right, so that there are |
7415 | // exactly m parameters. |
7416 | unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments(); |
7417 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
7418 | // Not enough arguments. |
7419 | Candidate.Viable = false; |
7420 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
7421 | return; |
7422 | } |
7423 | |
7424 | Candidate.Viable = true; |
7425 | |
7426 | unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7427 | if (ObjectType.isNull()) |
7428 | Candidate.IgnoreObjectArgument = true; |
7429 | else if (Method->isStatic()) { |
7430 | // [over.best.ics.general]p8 |
7431 | // When the parameter is the implicit object parameter of a static member |
7432 | // function, the implicit conversion sequence is a standard conversion |
7433 | // sequence that is neither better nor worse than any other standard |
7434 | // conversion sequence. |
7435 | // |
7436 | // This is a rule that was introduced in C++23 to support static lambdas. We |
7437 | // apply it retroactively because we want to support static lambdas as an |
7438 | // extension and it doesn't hurt previous code. |
7439 | Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); |
7440 | } else { |
7441 | // Determine the implicit conversion sequence for the object |
7442 | // parameter. |
7443 | Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( |
7444 | S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification, |
7445 | Method, ActingContext, /*InOverloadResolution=*/true); |
7446 | if (Candidate.Conversions[FirstConvIdx].isBad()) { |
7447 | Candidate.Viable = false; |
7448 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7449 | return; |
7450 | } |
7451 | } |
7452 | |
7453 | // (CUDA B.1): Check for invalid calls between targets. |
7454 | if (getLangOpts().CUDA) |
7455 | if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) { |
7456 | Candidate.Viable = false; |
7457 | Candidate.FailureKind = ovl_fail_bad_target; |
7458 | return; |
7459 | } |
7460 | |
7461 | if (Method->getTrailingRequiresClause()) { |
7462 | ConstraintSatisfaction Satisfaction; |
7463 | if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, |
7464 | /*ForOverloadResolution*/ true) || |
7465 | !Satisfaction.IsSatisfied) { |
7466 | Candidate.Viable = false; |
7467 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7468 | return; |
7469 | } |
7470 | } |
7471 | |
7472 | // Determine the implicit conversion sequences for each of the |
7473 | // arguments. |
7474 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
7475 | unsigned ConvIdx = |
7476 | PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); |
7477 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
7478 | // We already formed a conversion sequence for this parameter during |
7479 | // template argument deduction. |
7480 | } else if (ArgIdx < NumParams) { |
7481 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
7482 | // exist for each argument an implicit conversion sequence |
7483 | // (13.3.3.1) that converts that argument to the corresponding |
7484 | // parameter of F. |
7485 | QualType ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset); |
7486 | Candidate.Conversions[ConvIdx] |
7487 | = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType, |
7488 | SuppressUserConversions, |
7489 | /*InOverloadResolution=*/true, |
7490 | /*AllowObjCWritebackConversion=*/ |
7491 | getLangOpts().ObjCAutoRefCount); |
7492 | if (Candidate.Conversions[ConvIdx].isBad()) { |
7493 | Candidate.Viable = false; |
7494 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7495 | return; |
7496 | } |
7497 | } else { |
7498 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
7499 | // argument for which there is no corresponding parameter is |
7500 | // considered to "match the ellipsis" (C+ 13.3.3.1.3). |
7501 | Candidate.Conversions[ConvIdx].setEllipsis(); |
7502 | } |
7503 | } |
7504 | |
7505 | if (EnableIfAttr *FailedAttr = |
7506 | CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { |
7507 | Candidate.Viable = false; |
7508 | Candidate.FailureKind = ovl_fail_enable_if; |
7509 | Candidate.DeductionFailure.Data = FailedAttr; |
7510 | return; |
7511 | } |
7512 | |
7513 | if (Method->isMultiVersion() && |
7514 | ((Method->hasAttr<TargetAttr>() && |
7515 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) || |
7516 | (Method->hasAttr<TargetVersionAttr>() && |
7517 | !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
7518 | Candidate.Viable = false; |
7519 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7520 | } |
7521 | } |
7522 | |
7523 | /// Add a C++ member function template as a candidate to the candidate |
7524 | /// set, using template argument deduction to produce an appropriate member |
7525 | /// function template specialization. |
7526 | void Sema::AddMethodTemplateCandidate( |
7527 | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, |
7528 | CXXRecordDecl *ActingContext, |
7529 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, |
7530 | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, |
7531 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7532 | bool PartialOverloading, OverloadCandidateParamOrder PO) { |
7533 | if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) |
7534 | return; |
7535 | |
7536 | // C++ [over.match.funcs]p7: |
7537 | // In each case where a candidate is a function template, candidate |
7538 | // function template specializations are generated using template argument |
7539 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7540 | // candidate functions in the usual way.113) A given name can refer to one |
7541 | // or more function templates and also to a set of overloaded non-template |
7542 | // functions. In such a case, the candidate functions generated from each |
7543 | // function template are combined with the set of non-template candidate |
7544 | // functions. |
7545 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7546 | FunctionDecl *Specialization = nullptr; |
7547 | ConversionSequenceList Conversions; |
7548 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7549 | FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, |
7550 | PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType, |
7551 | ObjectClassification, |
7552 | CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) { |
7553 | return CheckNonDependentConversions( |
7554 | FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, |
7555 | SuppressUserConversions, ActingContext, ObjectType, |
7556 | ObjectClassification, PO); |
7557 | }); |
7558 | Result != TemplateDeductionResult::Success) { |
7559 | OverloadCandidate &Candidate = |
7560 | CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions); |
7561 | Candidate.FoundDecl = FoundDecl; |
7562 | Candidate.Function = MethodTmpl->getTemplatedDecl(); |
7563 | Candidate.Viable = false; |
7564 | Candidate.RewriteKind = |
7565 | CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO); |
7566 | Candidate.IsSurrogate = false; |
7567 | Candidate.IgnoreObjectArgument = |
7568 | cast<CXXMethodDecl>(Val: Candidate.Function)->isStatic() || |
7569 | ObjectType.isNull(); |
7570 | Candidate.ExplicitCallArguments = Args.size(); |
7571 | if (Result == TemplateDeductionResult::NonDependentConversionFailure) |
7572 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7573 | else { |
7574 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7575 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result, |
7576 | Info); |
7577 | } |
7578 | return; |
7579 | } |
7580 | |
7581 | // Add the function template specialization produced by template argument |
7582 | // deduction as a candidate. |
7583 | assert(Specialization && "Missing member function template specialization?" ); |
7584 | assert(isa<CXXMethodDecl>(Specialization) && |
7585 | "Specialization is not a member function?" ); |
7586 | AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, |
7587 | ActingContext, ObjectType, ObjectClassification, Args, |
7588 | CandidateSet, SuppressUserConversions, PartialOverloading, |
7589 | EarlyConversions: Conversions, PO); |
7590 | } |
7591 | |
7592 | /// Determine whether a given function template has a simple explicit specifier |
7593 | /// or a non-value-dependent explicit-specification that evaluates to true. |
7594 | static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { |
7595 | return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit(); |
7596 | } |
7597 | |
7598 | /// Add a C++ function template specialization as a candidate |
7599 | /// in the candidate set, using template argument deduction to produce |
7600 | /// an appropriate function template specialization. |
7601 | void Sema::AddTemplateOverloadCandidate( |
7602 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
7603 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
7604 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7605 | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, |
7606 | OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { |
7607 | if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) |
7608 | return; |
7609 | |
7610 | // If the function template has a non-dependent explicit specification, |
7611 | // exclude it now if appropriate; we are not permitted to perform deduction |
7612 | // and substitution in this case. |
7613 | if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) { |
7614 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7615 | Candidate.FoundDecl = FoundDecl; |
7616 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7617 | Candidate.Viable = false; |
7618 | Candidate.FailureKind = ovl_fail_explicit; |
7619 | return; |
7620 | } |
7621 | |
7622 | // C++ [over.match.funcs]p7: |
7623 | // In each case where a candidate is a function template, candidate |
7624 | // function template specializations are generated using template argument |
7625 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7626 | // candidate functions in the usual way.113) A given name can refer to one |
7627 | // or more function templates and also to a set of overloaded non-template |
7628 | // functions. In such a case, the candidate functions generated from each |
7629 | // function template are combined with the set of non-template candidate |
7630 | // functions. |
7631 | TemplateDeductionInfo Info(CandidateSet.getLocation(), |
7632 | FunctionTemplate->getTemplateDepth()); |
7633 | FunctionDecl *Specialization = nullptr; |
7634 | ConversionSequenceList Conversions; |
7635 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7636 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, |
7637 | PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction, |
7638 | /*ObjectType=*/QualType(), |
7639 | /*ObjectClassification=*/Expr::Classification(), |
7640 | CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) { |
7641 | return CheckNonDependentConversions( |
7642 | FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, |
7643 | SuppressUserConversions, ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO); |
7644 | }); |
7645 | Result != TemplateDeductionResult::Success) { |
7646 | OverloadCandidate &Candidate = |
7647 | CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions); |
7648 | Candidate.FoundDecl = FoundDecl; |
7649 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7650 | Candidate.Viable = false; |
7651 | Candidate.RewriteKind = |
7652 | CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO); |
7653 | Candidate.IsSurrogate = false; |
7654 | Candidate.IsADLCandidate = IsADLCandidate; |
7655 | // Ignore the object argument if there is one, since we don't have an object |
7656 | // type. |
7657 | Candidate.IgnoreObjectArgument = |
7658 | isa<CXXMethodDecl>(Val: Candidate.Function) && |
7659 | !isa<CXXConstructorDecl>(Val: Candidate.Function); |
7660 | Candidate.ExplicitCallArguments = Args.size(); |
7661 | if (Result == TemplateDeductionResult::NonDependentConversionFailure) |
7662 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7663 | else { |
7664 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7665 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result, |
7666 | Info); |
7667 | } |
7668 | return; |
7669 | } |
7670 | |
7671 | // Add the function template specialization produced by template argument |
7672 | // deduction as a candidate. |
7673 | assert(Specialization && "Missing function template specialization?" ); |
7674 | AddOverloadCandidate( |
7675 | Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, |
7676 | PartialOverloading, AllowExplicit, |
7677 | /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO, |
7678 | AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity); |
7679 | } |
7680 | |
7681 | /// Check that implicit conversion sequences can be formed for each argument |
7682 | /// whose corresponding parameter has a non-dependent type, per DR1391's |
7683 | /// [temp.deduct.call]p10. |
7684 | bool Sema::CheckNonDependentConversions( |
7685 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, |
7686 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, |
7687 | ConversionSequenceList &Conversions, bool SuppressUserConversions, |
7688 | CXXRecordDecl *ActingContext, QualType ObjectType, |
7689 | Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { |
7690 | // FIXME: The cases in which we allow explicit conversions for constructor |
7691 | // arguments never consider calling a constructor template. It's not clear |
7692 | // that is correct. |
7693 | const bool AllowExplicit = false; |
7694 | |
7695 | auto *FD = FunctionTemplate->getTemplatedDecl(); |
7696 | auto *Method = dyn_cast<CXXMethodDecl>(Val: FD); |
7697 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Val: Method); |
7698 | unsigned ThisConversions = HasThisConversion ? 1 : 0; |
7699 | |
7700 | Conversions = |
7701 | CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size()); |
7702 | |
7703 | // Overload resolution is always an unevaluated context. |
7704 | EnterExpressionEvaluationContext Unevaluated( |
7705 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7706 | |
7707 | // For a method call, check the 'this' conversion here too. DR1391 doesn't |
7708 | // require that, but this check should never result in a hard error, and |
7709 | // overload resolution is permitted to sidestep instantiations. |
7710 | if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() && |
7711 | !ObjectType.isNull()) { |
7712 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7713 | if (!FD->hasCXXExplicitFunctionObjectParameter() || |
7714 | !ParamTypes[0]->isDependentType()) { |
7715 | Conversions[ConvIdx] = TryObjectArgumentInitialization( |
7716 | S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification, |
7717 | Method, ActingContext, /*InOverloadResolution=*/true, |
7718 | ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0] |
7719 | : QualType()); |
7720 | if (Conversions[ConvIdx].isBad()) |
7721 | return true; |
7722 | } |
7723 | } |
7724 | |
7725 | unsigned Offset = |
7726 | Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; |
7727 | |
7728 | for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size()); |
7729 | I != N; ++I) { |
7730 | QualType ParamType = ParamTypes[I + Offset]; |
7731 | if (!ParamType->isDependentType()) { |
7732 | unsigned ConvIdx; |
7733 | if (PO == OverloadCandidateParamOrder::Reversed) { |
7734 | ConvIdx = Args.size() - 1 - I; |
7735 | assert(Args.size() + ThisConversions == 2 && |
7736 | "number of args (including 'this') must be exactly 2 for " |
7737 | "reversed order" ); |
7738 | // For members, there would be only one arg 'Args[0]' whose ConvIdx |
7739 | // would also be 0. 'this' got ConvIdx = 1 previously. |
7740 | assert(!HasThisConversion || (ConvIdx == 0 && I == 0)); |
7741 | } else { |
7742 | // For members, 'this' got ConvIdx = 0 previously. |
7743 | ConvIdx = ThisConversions + I; |
7744 | } |
7745 | Conversions[ConvIdx] |
7746 | = TryCopyInitialization(S&: *this, From: Args[I], ToType: ParamType, |
7747 | SuppressUserConversions, |
7748 | /*InOverloadResolution=*/true, |
7749 | /*AllowObjCWritebackConversion=*/ |
7750 | getLangOpts().ObjCAutoRefCount, |
7751 | AllowExplicit); |
7752 | if (Conversions[ConvIdx].isBad()) |
7753 | return true; |
7754 | } |
7755 | } |
7756 | |
7757 | return false; |
7758 | } |
7759 | |
7760 | /// Determine whether this is an allowable conversion from the result |
7761 | /// of an explicit conversion operator to the expected type, per C++ |
7762 | /// [over.match.conv]p1 and [over.match.ref]p1. |
7763 | /// |
7764 | /// \param ConvType The return type of the conversion function. |
7765 | /// |
7766 | /// \param ToType The type we are converting to. |
7767 | /// |
7768 | /// \param AllowObjCPointerConversion Allow a conversion from one |
7769 | /// Objective-C pointer to another. |
7770 | /// |
7771 | /// \returns true if the conversion is allowable, false otherwise. |
7772 | static bool isAllowableExplicitConversion(Sema &S, |
7773 | QualType ConvType, QualType ToType, |
7774 | bool AllowObjCPointerConversion) { |
7775 | QualType ToNonRefType = ToType.getNonReferenceType(); |
7776 | |
7777 | // Easy case: the types are the same. |
7778 | if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType)) |
7779 | return true; |
7780 | |
7781 | // Allow qualification conversions. |
7782 | bool ObjCLifetimeConversion; |
7783 | if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false, |
7784 | ObjCLifetimeConversion)) |
7785 | return true; |
7786 | |
7787 | // If we're not allowed to consider Objective-C pointer conversions, |
7788 | // we're done. |
7789 | if (!AllowObjCPointerConversion) |
7790 | return false; |
7791 | |
7792 | // Is this an Objective-C pointer conversion? |
7793 | bool IncompatibleObjC = false; |
7794 | QualType ConvertedType; |
7795 | return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType, |
7796 | IncompatibleObjC); |
7797 | } |
7798 | |
7799 | /// AddConversionCandidate - Add a C++ conversion function as a |
7800 | /// candidate in the candidate set (C++ [over.match.conv], |
7801 | /// C++ [over.match.copy]). From is the expression we're converting from, |
7802 | /// and ToType is the type that we're eventually trying to convert to |
7803 | /// (which may or may not be the same type as the type that the |
7804 | /// conversion function produces). |
7805 | void Sema::AddConversionCandidate( |
7806 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
7807 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
7808 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7809 | bool AllowExplicit, bool AllowResultConversion) { |
7810 | assert(!Conversion->getDescribedFunctionTemplate() && |
7811 | "Conversion function templates use AddTemplateConversionCandidate" ); |
7812 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); |
7813 | if (!CandidateSet.isNewCandidate(Conversion)) |
7814 | return; |
7815 | |
7816 | // If the conversion function has an undeduced return type, trigger its |
7817 | // deduction now. |
7818 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { |
7819 | if (DeduceReturnType(Conversion, From->getExprLoc())) |
7820 | return; |
7821 | ConvType = Conversion->getConversionType().getNonReferenceType(); |
7822 | } |
7823 | |
7824 | // If we don't allow any conversion of the result type, ignore conversion |
7825 | // functions that don't convert to exactly (possibly cv-qualified) T. |
7826 | if (!AllowResultConversion && |
7827 | !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType)) |
7828 | return; |
7829 | |
7830 | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion |
7831 | // operator is only a candidate if its return type is the target type or |
7832 | // can be converted to the target type with a qualification conversion. |
7833 | // |
7834 | // FIXME: Include such functions in the candidate list and explain why we |
7835 | // can't select them. |
7836 | if (Conversion->isExplicit() && |
7837 | !isAllowableExplicitConversion(S&: *this, ConvType, ToType, |
7838 | AllowObjCPointerConversion: AllowObjCConversionOnExplicit)) |
7839 | return; |
7840 | |
7841 | // Overload resolution is always an unevaluated context. |
7842 | EnterExpressionEvaluationContext Unevaluated( |
7843 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7844 | |
7845 | // Add this candidate |
7846 | OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1); |
7847 | Candidate.FoundDecl = FoundDecl; |
7848 | Candidate.Function = Conversion; |
7849 | Candidate.IsSurrogate = false; |
7850 | Candidate.IgnoreObjectArgument = false; |
7851 | Candidate.FinalConversion.setAsIdentityConversion(); |
7852 | Candidate.FinalConversion.setFromType(ConvType); |
7853 | Candidate.FinalConversion.setAllToTypes(ToType); |
7854 | Candidate.Viable = true; |
7855 | Candidate.ExplicitCallArguments = 1; |
7856 | |
7857 | // Explicit functions are not actually candidates at all if we're not |
7858 | // allowing them in this context, but keep them around so we can point |
7859 | // to them in diagnostics. |
7860 | if (!AllowExplicit && Conversion->isExplicit()) { |
7861 | Candidate.Viable = false; |
7862 | Candidate.FailureKind = ovl_fail_explicit; |
7863 | return; |
7864 | } |
7865 | |
7866 | // C++ [over.match.funcs]p4: |
7867 | // For conversion functions, the function is considered to be a member of |
7868 | // the class of the implicit implied object argument for the purpose of |
7869 | // defining the type of the implicit object parameter. |
7870 | // |
7871 | // Determine the implicit conversion sequence for the implicit |
7872 | // object parameter. |
7873 | QualType ObjectType = From->getType(); |
7874 | if (const auto *FromPtrType = ObjectType->getAs<PointerType>()) |
7875 | ObjectType = FromPtrType->getPointeeType(); |
7876 | const auto *ConversionContext = |
7877 | cast<CXXRecordDecl>(Val: ObjectType->castAs<RecordType>()->getDecl()); |
7878 | |
7879 | // C++23 [over.best.ics.general] |
7880 | // However, if the target is [...] |
7881 | // - the object parameter of a user-defined conversion function |
7882 | // [...] user-defined conversion sequences are not considered. |
7883 | Candidate.Conversions[0] = TryObjectArgumentInitialization( |
7884 | *this, CandidateSet.getLocation(), From->getType(), |
7885 | From->Classify(Ctx&: Context), Conversion, ConversionContext, |
7886 | /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(), |
7887 | /*SuppressUserConversion*/ true); |
7888 | |
7889 | if (Candidate.Conversions[0].isBad()) { |
7890 | Candidate.Viable = false; |
7891 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7892 | return; |
7893 | } |
7894 | |
7895 | if (Conversion->getTrailingRequiresClause()) { |
7896 | ConstraintSatisfaction Satisfaction; |
7897 | if (CheckFunctionConstraints(Conversion, Satisfaction) || |
7898 | !Satisfaction.IsSatisfied) { |
7899 | Candidate.Viable = false; |
7900 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7901 | return; |
7902 | } |
7903 | } |
7904 | |
7905 | // We won't go through a user-defined type conversion function to convert a |
7906 | // derived to base as such conversions are given Conversion Rank. They only |
7907 | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] |
7908 | QualType FromCanon |
7909 | = Context.getCanonicalType(T: From->getType().getUnqualifiedType()); |
7910 | QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType(); |
7911 | if (FromCanon == ToCanon || |
7912 | IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) { |
7913 | Candidate.Viable = false; |
7914 | Candidate.FailureKind = ovl_fail_trivial_conversion; |
7915 | return; |
7916 | } |
7917 | |
7918 | // To determine what the conversion from the result of calling the |
7919 | // conversion function to the type we're eventually trying to |
7920 | // convert to (ToType), we need to synthesize a call to the |
7921 | // conversion function and attempt copy initialization from it. This |
7922 | // makes sure that we get the right semantics with respect to |
7923 | // lvalues/rvalues and the type. Fortunately, we can allocate this |
7924 | // call on the stack and we don't need its arguments to be |
7925 | // well-formed. |
7926 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), |
7927 | VK_LValue, From->getBeginLoc()); |
7928 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, |
7929 | Context.getPointerType(Conversion->getType()), |
7930 | CK_FunctionToPointerDecay, &ConversionRef, |
7931 | VK_PRValue, FPOptionsOverride()); |
7932 | |
7933 | QualType ConversionType = Conversion->getConversionType(); |
7934 | if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) { |
7935 | Candidate.Viable = false; |
7936 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7937 | return; |
7938 | } |
7939 | |
7940 | ExprValueKind VK = Expr::getValueKindForType(T: ConversionType); |
7941 | |
7942 | // Note that it is safe to allocate CallExpr on the stack here because |
7943 | // there are 0 arguments (i.e., nothing is allocated using ASTContext's |
7944 | // allocator). |
7945 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); |
7946 | |
7947 | alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
7948 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( |
7949 | Mem: Buffer, Fn: &ConversionFn, Ty: CallResultType, VK, RParenLoc: From->getBeginLoc()); |
7950 | |
7951 | ImplicitConversionSequence ICS = |
7952 | TryCopyInitialization(*this, TheTemporaryCall, ToType, |
7953 | /*SuppressUserConversions=*/true, |
7954 | /*InOverloadResolution=*/false, |
7955 | /*AllowObjCWritebackConversion=*/false); |
7956 | |
7957 | switch (ICS.getKind()) { |
7958 | case ImplicitConversionSequence::StandardConversion: |
7959 | Candidate.FinalConversion = ICS.Standard; |
7960 | |
7961 | // C++ [over.ics.user]p3: |
7962 | // If the user-defined conversion is specified by a specialization of a |
7963 | // conversion function template, the second standard conversion sequence |
7964 | // shall have exact match rank. |
7965 | if (Conversion->getPrimaryTemplate() && |
7966 | GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) { |
7967 | Candidate.Viable = false; |
7968 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; |
7969 | return; |
7970 | } |
7971 | |
7972 | // C++0x [dcl.init.ref]p5: |
7973 | // In the second case, if the reference is an rvalue reference and |
7974 | // the second standard conversion sequence of the user-defined |
7975 | // conversion sequence includes an lvalue-to-rvalue conversion, the |
7976 | // program is ill-formed. |
7977 | if (ToType->isRValueReferenceType() && |
7978 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
7979 | Candidate.Viable = false; |
7980 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7981 | return; |
7982 | } |
7983 | break; |
7984 | |
7985 | case ImplicitConversionSequence::BadConversion: |
7986 | Candidate.Viable = false; |
7987 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7988 | return; |
7989 | |
7990 | default: |
7991 | llvm_unreachable( |
7992 | "Can only end up with a standard conversion sequence or failure" ); |
7993 | } |
7994 | |
7995 | if (EnableIfAttr *FailedAttr = |
7996 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
7997 | Candidate.Viable = false; |
7998 | Candidate.FailureKind = ovl_fail_enable_if; |
7999 | Candidate.DeductionFailure.Data = FailedAttr; |
8000 | return; |
8001 | } |
8002 | |
8003 | if (Conversion->isMultiVersion() && |
8004 | ((Conversion->hasAttr<TargetAttr>() && |
8005 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) || |
8006 | (Conversion->hasAttr<TargetVersionAttr>() && |
8007 | !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
8008 | Candidate.Viable = false; |
8009 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
8010 | } |
8011 | } |
8012 | |
8013 | /// Adds a conversion function template specialization |
8014 | /// candidate to the overload set, using template argument deduction |
8015 | /// to deduce the template arguments of the conversion function |
8016 | /// template from the type that we are converting to (C++ |
8017 | /// [temp.deduct.conv]). |
8018 | void Sema::AddTemplateConversionCandidate( |
8019 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
8020 | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, |
8021 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
8022 | bool AllowExplicit, bool AllowResultConversion) { |
8023 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && |
8024 | "Only conversion function templates permitted here" ); |
8025 | |
8026 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) |
8027 | return; |
8028 | |
8029 | // If the function template has a non-dependent explicit specification, |
8030 | // exclude it now if appropriate; we are not permitted to perform deduction |
8031 | // and substitution in this case. |
8032 | if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) { |
8033 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
8034 | Candidate.FoundDecl = FoundDecl; |
8035 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
8036 | Candidate.Viable = false; |
8037 | Candidate.FailureKind = ovl_fail_explicit; |
8038 | return; |
8039 | } |
8040 | |
8041 | QualType ObjectType = From->getType(); |
8042 | Expr::Classification ObjectClassification = From->Classify(Ctx&: getASTContext()); |
8043 | |
8044 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
8045 | CXXConversionDecl *Specialization = nullptr; |
8046 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
8047 | FunctionTemplate, ObjectType, ObjectClassification, ToType, |
8048 | Specialization, Info); |
8049 | Result != TemplateDeductionResult::Success) { |
8050 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
8051 | Candidate.FoundDecl = FoundDecl; |
8052 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
8053 | Candidate.Viable = false; |
8054 | Candidate.FailureKind = ovl_fail_bad_deduction; |
8055 | Candidate.IsSurrogate = false; |
8056 | Candidate.IgnoreObjectArgument = false; |
8057 | Candidate.ExplicitCallArguments = 1; |
8058 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result, |
8059 | Info); |
8060 | return; |
8061 | } |
8062 | |
8063 | // Add the conversion function template specialization produced by |
8064 | // template argument deduction as a candidate. |
8065 | assert(Specialization && "Missing function template specialization?" ); |
8066 | AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext: ActingDC, From, ToType, |
8067 | CandidateSet, AllowObjCConversionOnExplicit, |
8068 | AllowExplicit, AllowResultConversion); |
8069 | } |
8070 | |
8071 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that |
8072 | /// converts the given @c Object to a function pointer via the |
8073 | /// conversion function @c Conversion, and then attempts to call it |
8074 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is |
8075 | /// the type of function that we'll eventually be calling. |
8076 | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, |
8077 | DeclAccessPair FoundDecl, |
8078 | CXXRecordDecl *ActingContext, |
8079 | const FunctionProtoType *Proto, |
8080 | Expr *Object, |
8081 | ArrayRef<Expr *> Args, |
8082 | OverloadCandidateSet& CandidateSet) { |
8083 | if (!CandidateSet.isNewCandidate(Conversion)) |
8084 | return; |
8085 | |
8086 | // Overload resolution is always an unevaluated context. |
8087 | EnterExpressionEvaluationContext Unevaluated( |
8088 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
8089 | |
8090 | OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1); |
8091 | Candidate.FoundDecl = FoundDecl; |
8092 | Candidate.Function = nullptr; |
8093 | Candidate.Surrogate = Conversion; |
8094 | Candidate.Viable = true; |
8095 | Candidate.IsSurrogate = true; |
8096 | Candidate.IgnoreObjectArgument = false; |
8097 | Candidate.ExplicitCallArguments = Args.size(); |
8098 | |
8099 | // Determine the implicit conversion sequence for the implicit |
8100 | // object parameter. |
8101 | ImplicitConversionSequence ObjectInit; |
8102 | if (Conversion->hasCXXExplicitFunctionObjectParameter()) { |
8103 | ObjectInit = TryCopyInitialization(*this, Object, |
8104 | Conversion->getParamDecl(0)->getType(), |
8105 | /*SuppressUserConversions=*/false, |
8106 | /*InOverloadResolution=*/true, false); |
8107 | } else { |
8108 | ObjectInit = TryObjectArgumentInitialization( |
8109 | *this, CandidateSet.getLocation(), Object->getType(), |
8110 | Object->Classify(Ctx&: Context), Conversion, ActingContext); |
8111 | } |
8112 | |
8113 | if (ObjectInit.isBad()) { |
8114 | Candidate.Viable = false; |
8115 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8116 | Candidate.Conversions[0] = ObjectInit; |
8117 | return; |
8118 | } |
8119 | |
8120 | // The first conversion is actually a user-defined conversion whose |
8121 | // first conversion is ObjectInit's standard conversion (which is |
8122 | // effectively a reference binding). Record it as such. |
8123 | Candidate.Conversions[0].setUserDefined(); |
8124 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; |
8125 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; |
8126 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; |
8127 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; |
8128 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; |
8129 | Candidate.Conversions[0].UserDefined.After |
8130 | = Candidate.Conversions[0].UserDefined.Before; |
8131 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); |
8132 | |
8133 | // Find the |
8134 | unsigned NumParams = Proto->getNumParams(); |
8135 | |
8136 | // (C++ 13.3.2p2): A candidate function having fewer than m |
8137 | // parameters is viable only if it has an ellipsis in its parameter |
8138 | // list (8.3.5). |
8139 | if (Args.size() > NumParams && !Proto->isVariadic()) { |
8140 | Candidate.Viable = false; |
8141 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
8142 | return; |
8143 | } |
8144 | |
8145 | // Function types don't have any default arguments, so just check if |
8146 | // we have enough arguments. |
8147 | if (Args.size() < NumParams) { |
8148 | // Not enough arguments. |
8149 | Candidate.Viable = false; |
8150 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
8151 | return; |
8152 | } |
8153 | |
8154 | // Determine the implicit conversion sequences for each of the |
8155 | // arguments. |
8156 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8157 | if (ArgIdx < NumParams) { |
8158 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
8159 | // exist for each argument an implicit conversion sequence |
8160 | // (13.3.3.1) that converts that argument to the corresponding |
8161 | // parameter of F. |
8162 | QualType ParamType = Proto->getParamType(i: ArgIdx); |
8163 | Candidate.Conversions[ArgIdx + 1] |
8164 | = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType, |
8165 | /*SuppressUserConversions=*/false, |
8166 | /*InOverloadResolution=*/false, |
8167 | /*AllowObjCWritebackConversion=*/ |
8168 | getLangOpts().ObjCAutoRefCount); |
8169 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { |
8170 | Candidate.Viable = false; |
8171 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8172 | return; |
8173 | } |
8174 | } else { |
8175 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
8176 | // argument for which there is no corresponding parameter is |
8177 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
8178 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); |
8179 | } |
8180 | } |
8181 | |
8182 | if (Conversion->getTrailingRequiresClause()) { |
8183 | ConstraintSatisfaction Satisfaction; |
8184 | if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {}, |
8185 | /*ForOverloadResolution*/ true) || |
8186 | !Satisfaction.IsSatisfied) { |
8187 | Candidate.Viable = false; |
8188 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
8189 | return; |
8190 | } |
8191 | } |
8192 | |
8193 | if (EnableIfAttr *FailedAttr = |
8194 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
8195 | Candidate.Viable = false; |
8196 | Candidate.FailureKind = ovl_fail_enable_if; |
8197 | Candidate.DeductionFailure.Data = FailedAttr; |
8198 | return; |
8199 | } |
8200 | } |
8201 | |
8202 | /// Add all of the non-member operator function declarations in the given |
8203 | /// function set to the overload candidate set. |
8204 | void Sema::AddNonMemberOperatorCandidates( |
8205 | const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, |
8206 | OverloadCandidateSet &CandidateSet, |
8207 | TemplateArgumentListInfo *ExplicitTemplateArgs) { |
8208 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
8209 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
8210 | ArrayRef<Expr *> FunctionArgs = Args; |
8211 | |
8212 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D); |
8213 | FunctionDecl *FD = |
8214 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D); |
8215 | |
8216 | // Don't consider rewritten functions if we're not rewriting. |
8217 | if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) |
8218 | continue; |
8219 | |
8220 | assert(!isa<CXXMethodDecl>(FD) && |
8221 | "unqualified operator lookup found a member function" ); |
8222 | |
8223 | if (FunTmpl) { |
8224 | AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs, |
8225 | Args: FunctionArgs, CandidateSet); |
8226 | if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) |
8227 | AddTemplateOverloadCandidate( |
8228 | FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs, |
8229 | Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, |
8230 | AllowExplicit: true, IsADLCandidate: ADLCallKind::NotADL, PO: OverloadCandidateParamOrder::Reversed); |
8231 | } else { |
8232 | if (ExplicitTemplateArgs) |
8233 | continue; |
8234 | AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet); |
8235 | if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) |
8236 | AddOverloadCandidate( |
8237 | Function: FD, FoundDecl: F.getPair(), Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, |
8238 | SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: std::nullopt, |
8239 | PO: OverloadCandidateParamOrder::Reversed); |
8240 | } |
8241 | } |
8242 | } |
8243 | |
8244 | /// Add overload candidates for overloaded operators that are |
8245 | /// member functions. |
8246 | /// |
8247 | /// Add the overloaded operator candidates that are member functions |
8248 | /// for the operator Op that was used in an operator expression such |
8249 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and |
8250 | /// CandidateSet will store the added overload candidates. (C++ |
8251 | /// [over.match.oper]). |
8252 | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
8253 | SourceLocation OpLoc, |
8254 | ArrayRef<Expr *> Args, |
8255 | OverloadCandidateSet &CandidateSet, |
8256 | OverloadCandidateParamOrder PO) { |
8257 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
8258 | |
8259 | // C++ [over.match.oper]p3: |
8260 | // For a unary operator @ with an operand of a type whose |
8261 | // cv-unqualified version is T1, and for a binary operator @ with |
8262 | // a left operand of a type whose cv-unqualified version is T1 and |
8263 | // a right operand of a type whose cv-unqualified version is T2, |
8264 | // three sets of candidate functions, designated member |
8265 | // candidates, non-member candidates and built-in candidates, are |
8266 | // constructed as follows: |
8267 | QualType T1 = Args[0]->getType(); |
8268 | |
8269 | // -- If T1 is a complete class type or a class currently being |
8270 | // defined, the set of member candidates is the result of the |
8271 | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, |
8272 | // the set of member candidates is empty. |
8273 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { |
8274 | // Complete the type if it can be completed. |
8275 | if (!isCompleteType(Loc: OpLoc, T: T1) && !T1Rec->isBeingDefined()) |
8276 | return; |
8277 | // If the type is neither complete nor being defined, bail out now. |
8278 | if (!T1Rec->getDecl()->getDefinition()) |
8279 | return; |
8280 | |
8281 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); |
8282 | LookupQualifiedName(Operators, T1Rec->getDecl()); |
8283 | Operators.suppressAccessDiagnostics(); |
8284 | |
8285 | for (LookupResult::iterator Oper = Operators.begin(), |
8286 | OperEnd = Operators.end(); |
8287 | Oper != OperEnd; ++Oper) { |
8288 | if (Oper->getAsFunction() && |
8289 | PO == OverloadCandidateParamOrder::Reversed && |
8290 | !CandidateSet.getRewriteInfo().shouldAddReversed( |
8291 | S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction())) |
8292 | continue; |
8293 | AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(), |
8294 | ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1), |
8295 | CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO); |
8296 | } |
8297 | } |
8298 | } |
8299 | |
8300 | /// AddBuiltinCandidate - Add a candidate for a built-in |
8301 | /// operator. ResultTy and ParamTys are the result and parameter types |
8302 | /// of the built-in candidate, respectively. Args and NumArgs are the |
8303 | /// arguments being passed to the candidate. IsAssignmentOperator |
8304 | /// should be true when this built-in candidate is an assignment |
8305 | /// operator. NumContextualBoolArguments is the number of arguments |
8306 | /// (at the beginning of the argument list) that will be contextually |
8307 | /// converted to bool. |
8308 | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
8309 | OverloadCandidateSet& CandidateSet, |
8310 | bool IsAssignmentOperator, |
8311 | unsigned NumContextualBoolArguments) { |
8312 | // Overload resolution is always an unevaluated context. |
8313 | EnterExpressionEvaluationContext Unevaluated( |
8314 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
8315 | |
8316 | // Add this candidate |
8317 | OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size()); |
8318 | Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none); |
8319 | Candidate.Function = nullptr; |
8320 | Candidate.IsSurrogate = false; |
8321 | Candidate.IgnoreObjectArgument = false; |
8322 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); |
8323 | |
8324 | // Determine the implicit conversion sequences for each of the |
8325 | // arguments. |
8326 | Candidate.Viable = true; |
8327 | Candidate.ExplicitCallArguments = Args.size(); |
8328 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8329 | // C++ [over.match.oper]p4: |
8330 | // For the built-in assignment operators, conversions of the |
8331 | // left operand are restricted as follows: |
8332 | // -- no temporaries are introduced to hold the left operand, and |
8333 | // -- no user-defined conversions are applied to the left |
8334 | // operand to achieve a type match with the left-most |
8335 | // parameter of a built-in candidate. |
8336 | // |
8337 | // We block these conversions by turning off user-defined |
8338 | // conversions, since that is the only way that initialization of |
8339 | // a reference to a non-class type can occur from something that |
8340 | // is not of the same type. |
8341 | if (ArgIdx < NumContextualBoolArguments) { |
8342 | assert(ParamTys[ArgIdx] == Context.BoolTy && |
8343 | "Contextual conversion to bool requires bool type" ); |
8344 | Candidate.Conversions[ArgIdx] |
8345 | = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]); |
8346 | } else { |
8347 | Candidate.Conversions[ArgIdx] |
8348 | = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx], |
8349 | SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator, |
8350 | /*InOverloadResolution=*/false, |
8351 | /*AllowObjCWritebackConversion=*/ |
8352 | getLangOpts().ObjCAutoRefCount); |
8353 | } |
8354 | if (Candidate.Conversions[ArgIdx].isBad()) { |
8355 | Candidate.Viable = false; |
8356 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8357 | break; |
8358 | } |
8359 | } |
8360 | } |
8361 | |
8362 | namespace { |
8363 | |
8364 | /// BuiltinCandidateTypeSet - A set of types that will be used for the |
8365 | /// candidate operator functions for built-in operators (C++ |
8366 | /// [over.built]). The types are separated into pointer types and |
8367 | /// enumeration types. |
8368 | class BuiltinCandidateTypeSet { |
8369 | /// TypeSet - A set of types. |
8370 | typedef llvm::SmallSetVector<QualType, 8> TypeSet; |
8371 | |
8372 | /// PointerTypes - The set of pointer types that will be used in the |
8373 | /// built-in candidates. |
8374 | TypeSet PointerTypes; |
8375 | |
8376 | /// MemberPointerTypes - The set of member pointer types that will be |
8377 | /// used in the built-in candidates. |
8378 | TypeSet MemberPointerTypes; |
8379 | |
8380 | /// EnumerationTypes - The set of enumeration types that will be |
8381 | /// used in the built-in candidates. |
8382 | TypeSet EnumerationTypes; |
8383 | |
8384 | /// The set of vector types that will be used in the built-in |
8385 | /// candidates. |
8386 | TypeSet VectorTypes; |
8387 | |
8388 | /// The set of matrix types that will be used in the built-in |
8389 | /// candidates. |
8390 | TypeSet MatrixTypes; |
8391 | |
8392 | /// A flag indicating non-record types are viable candidates |
8393 | bool HasNonRecordTypes; |
8394 | |
8395 | /// A flag indicating whether either arithmetic or enumeration types |
8396 | /// were present in the candidate set. |
8397 | bool HasArithmeticOrEnumeralTypes; |
8398 | |
8399 | /// A flag indicating whether the nullptr type was present in the |
8400 | /// candidate set. |
8401 | bool HasNullPtrType; |
8402 | |
8403 | /// Sema - The semantic analysis instance where we are building the |
8404 | /// candidate type set. |
8405 | Sema &SemaRef; |
8406 | |
8407 | /// Context - The AST context in which we will build the type sets. |
8408 | ASTContext &Context; |
8409 | |
8410 | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8411 | const Qualifiers &VisibleQuals); |
8412 | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); |
8413 | |
8414 | public: |
8415 | /// iterator - Iterates through the types that are part of the set. |
8416 | typedef TypeSet::iterator iterator; |
8417 | |
8418 | BuiltinCandidateTypeSet(Sema &SemaRef) |
8419 | : HasNonRecordTypes(false), |
8420 | HasArithmeticOrEnumeralTypes(false), |
8421 | HasNullPtrType(false), |
8422 | SemaRef(SemaRef), |
8423 | Context(SemaRef.Context) { } |
8424 | |
8425 | void AddTypesConvertedFrom(QualType Ty, |
8426 | SourceLocation Loc, |
8427 | bool AllowUserConversions, |
8428 | bool AllowExplicitConversions, |
8429 | const Qualifiers &VisibleTypeConversionsQuals); |
8430 | |
8431 | llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } |
8432 | llvm::iterator_range<iterator> member_pointer_types() { |
8433 | return MemberPointerTypes; |
8434 | } |
8435 | llvm::iterator_range<iterator> enumeration_types() { |
8436 | return EnumerationTypes; |
8437 | } |
8438 | llvm::iterator_range<iterator> vector_types() { return VectorTypes; } |
8439 | llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } |
8440 | |
8441 | bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); } |
8442 | bool hasNonRecordTypes() { return HasNonRecordTypes; } |
8443 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } |
8444 | bool hasNullPtrType() const { return HasNullPtrType; } |
8445 | }; |
8446 | |
8447 | } // end anonymous namespace |
8448 | |
8449 | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to |
8450 | /// the set of pointer types along with any more-qualified variants of |
8451 | /// that type. For example, if @p Ty is "int const *", this routine |
8452 | /// will add "int const *", "int const volatile *", "int const |
8453 | /// restrict *", and "int const volatile restrict *" to the set of |
8454 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8455 | /// false otherwise. |
8456 | /// |
8457 | /// FIXME: what to do about extended qualifiers? |
8458 | bool |
8459 | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8460 | const Qualifiers &VisibleQuals) { |
8461 | |
8462 | // Insert this type. |
8463 | if (!PointerTypes.insert(X: Ty)) |
8464 | return false; |
8465 | |
8466 | QualType PointeeTy; |
8467 | const PointerType *PointerTy = Ty->getAs<PointerType>(); |
8468 | bool buildObjCPtr = false; |
8469 | if (!PointerTy) { |
8470 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); |
8471 | PointeeTy = PTy->getPointeeType(); |
8472 | buildObjCPtr = true; |
8473 | } else { |
8474 | PointeeTy = PointerTy->getPointeeType(); |
8475 | } |
8476 | |
8477 | // Don't add qualified variants of arrays. For one, they're not allowed |
8478 | // (the qualifier would sink to the element type), and for another, the |
8479 | // only overload situation where it matters is subscript or pointer +- int, |
8480 | // and those shouldn't have qualifier variants anyway. |
8481 | if (PointeeTy->isArrayType()) |
8482 | return true; |
8483 | |
8484 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8485 | bool hasVolatile = VisibleQuals.hasVolatile(); |
8486 | bool hasRestrict = VisibleQuals.hasRestrict(); |
8487 | |
8488 | // Iterate through all strict supersets of BaseCVR. |
8489 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8490 | if ((CVR | BaseCVR) != CVR) continue; |
8491 | // Skip over volatile if no volatile found anywhere in the types. |
8492 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; |
8493 | |
8494 | // Skip over restrict if no restrict found anywhere in the types, or if |
8495 | // the type cannot be restrict-qualified. |
8496 | if ((CVR & Qualifiers::Restrict) && |
8497 | (!hasRestrict || |
8498 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) |
8499 | continue; |
8500 | |
8501 | // Build qualified pointee type. |
8502 | QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR); |
8503 | |
8504 | // Build qualified pointer type. |
8505 | QualType QPointerTy; |
8506 | if (!buildObjCPtr) |
8507 | QPointerTy = Context.getPointerType(T: QPointeeTy); |
8508 | else |
8509 | QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy); |
8510 | |
8511 | // Insert qualified pointer type. |
8512 | PointerTypes.insert(X: QPointerTy); |
8513 | } |
8514 | |
8515 | return true; |
8516 | } |
8517 | |
8518 | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty |
8519 | /// to the set of pointer types along with any more-qualified variants of |
8520 | /// that type. For example, if @p Ty is "int const *", this routine |
8521 | /// will add "int const *", "int const volatile *", "int const |
8522 | /// restrict *", and "int const volatile restrict *" to the set of |
8523 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8524 | /// false otherwise. |
8525 | /// |
8526 | /// FIXME: what to do about extended qualifiers? |
8527 | bool |
8528 | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( |
8529 | QualType Ty) { |
8530 | // Insert this type. |
8531 | if (!MemberPointerTypes.insert(X: Ty)) |
8532 | return false; |
8533 | |
8534 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); |
8535 | assert(PointerTy && "type was not a member pointer type!" ); |
8536 | |
8537 | QualType PointeeTy = PointerTy->getPointeeType(); |
8538 | // Don't add qualified variants of arrays. For one, they're not allowed |
8539 | // (the qualifier would sink to the element type), and for another, the |
8540 | // only overload situation where it matters is subscript or pointer +- int, |
8541 | // and those shouldn't have qualifier variants anyway. |
8542 | if (PointeeTy->isArrayType()) |
8543 | return true; |
8544 | const Type *ClassTy = PointerTy->getClass(); |
8545 | |
8546 | // Iterate through all strict supersets of the pointee type's CVR |
8547 | // qualifiers. |
8548 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8549 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8550 | if ((CVR | BaseCVR) != CVR) continue; |
8551 | |
8552 | QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR); |
8553 | MemberPointerTypes.insert( |
8554 | X: Context.getMemberPointerType(T: QPointeeTy, Cls: ClassTy)); |
8555 | } |
8556 | |
8557 | return true; |
8558 | } |
8559 | |
8560 | /// AddTypesConvertedFrom - Add each of the types to which the type @p |
8561 | /// Ty can be implicit converted to the given set of @p Types. We're |
8562 | /// primarily interested in pointer types and enumeration types. We also |
8563 | /// take member pointer types, for the conditional operator. |
8564 | /// AllowUserConversions is true if we should look at the conversion |
8565 | /// functions of a class type, and AllowExplicitConversions if we |
8566 | /// should also include the explicit conversion functions of a class |
8567 | /// type. |
8568 | void |
8569 | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, |
8570 | SourceLocation Loc, |
8571 | bool AllowUserConversions, |
8572 | bool AllowExplicitConversions, |
8573 | const Qualifiers &VisibleQuals) { |
8574 | // Only deal with canonical types. |
8575 | Ty = Context.getCanonicalType(T: Ty); |
8576 | |
8577 | // Look through reference types; they aren't part of the type of an |
8578 | // expression for the purposes of conversions. |
8579 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) |
8580 | Ty = RefTy->getPointeeType(); |
8581 | |
8582 | // If we're dealing with an array type, decay to the pointer. |
8583 | if (Ty->isArrayType()) |
8584 | Ty = SemaRef.Context.getArrayDecayedType(T: Ty); |
8585 | |
8586 | // Otherwise, we don't care about qualifiers on the type. |
8587 | Ty = Ty.getLocalUnqualifiedType(); |
8588 | |
8589 | // Flag if we ever add a non-record type. |
8590 | const RecordType *TyRec = Ty->getAs<RecordType>(); |
8591 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; |
8592 | |
8593 | // Flag if we encounter an arithmetic type. |
8594 | HasArithmeticOrEnumeralTypes = |
8595 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); |
8596 | |
8597 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) |
8598 | PointerTypes.insert(X: Ty); |
8599 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { |
8600 | // Insert our type, and its more-qualified variants, into the set |
8601 | // of types. |
8602 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) |
8603 | return; |
8604 | } else if (Ty->isMemberPointerType()) { |
8605 | // Member pointers are far easier, since the pointee can't be converted. |
8606 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) |
8607 | return; |
8608 | } else if (Ty->isEnumeralType()) { |
8609 | HasArithmeticOrEnumeralTypes = true; |
8610 | EnumerationTypes.insert(X: Ty); |
8611 | } else if (Ty->isVectorType()) { |
8612 | // We treat vector types as arithmetic types in many contexts as an |
8613 | // extension. |
8614 | HasArithmeticOrEnumeralTypes = true; |
8615 | VectorTypes.insert(X: Ty); |
8616 | } else if (Ty->isMatrixType()) { |
8617 | // Similar to vector types, we treat vector types as arithmetic types in |
8618 | // many contexts as an extension. |
8619 | HasArithmeticOrEnumeralTypes = true; |
8620 | MatrixTypes.insert(X: Ty); |
8621 | } else if (Ty->isNullPtrType()) { |
8622 | HasNullPtrType = true; |
8623 | } else if (AllowUserConversions && TyRec) { |
8624 | // No conversion functions in incomplete types. |
8625 | if (!SemaRef.isCompleteType(Loc, T: Ty)) |
8626 | return; |
8627 | |
8628 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl()); |
8629 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8630 | if (isa<UsingShadowDecl>(Val: D)) |
8631 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
8632 | |
8633 | // Skip conversion function templates; they don't tell us anything |
8634 | // about which builtin types we can convert to. |
8635 | if (isa<FunctionTemplateDecl>(Val: D)) |
8636 | continue; |
8637 | |
8638 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D); |
8639 | if (AllowExplicitConversions || !Conv->isExplicit()) { |
8640 | AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false, |
8641 | VisibleQuals); |
8642 | } |
8643 | } |
8644 | } |
8645 | } |
8646 | /// Helper function for adjusting address spaces for the pointer or reference |
8647 | /// operands of builtin operators depending on the argument. |
8648 | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, |
8649 | Expr *Arg) { |
8650 | return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace()); |
8651 | } |
8652 | |
8653 | /// Helper function for AddBuiltinOperatorCandidates() that adds |
8654 | /// the volatile- and non-volatile-qualified assignment operators for the |
8655 | /// given type to the candidate set. |
8656 | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, |
8657 | QualType T, |
8658 | ArrayRef<Expr *> Args, |
8659 | OverloadCandidateSet &CandidateSet) { |
8660 | QualType ParamTypes[2]; |
8661 | |
8662 | // T& operator=(T&, T) |
8663 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8664 | T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0])); |
8665 | ParamTypes[1] = T; |
8666 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
8667 | /*IsAssignmentOperator=*/true); |
8668 | |
8669 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { |
8670 | // volatile T& operator=(volatile T&, T) |
8671 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8672 | T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T), |
8673 | Arg: Args[0])); |
8674 | ParamTypes[1] = T; |
8675 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
8676 | /*IsAssignmentOperator=*/true); |
8677 | } |
8678 | } |
8679 | |
8680 | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, |
8681 | /// if any, found in visible type conversion functions found in ArgExpr's type. |
8682 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { |
8683 | Qualifiers VRQuals; |
8684 | const RecordType *TyRec; |
8685 | if (const MemberPointerType *RHSMPType = |
8686 | ArgExpr->getType()->getAs<MemberPointerType>()) |
8687 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); |
8688 | else |
8689 | TyRec = ArgExpr->getType()->getAs<RecordType>(); |
8690 | if (!TyRec) { |
8691 | // Just to be safe, assume the worst case. |
8692 | VRQuals.addVolatile(); |
8693 | VRQuals.addRestrict(); |
8694 | return VRQuals; |
8695 | } |
8696 | |
8697 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl()); |
8698 | if (!ClassDecl->hasDefinition()) |
8699 | return VRQuals; |
8700 | |
8701 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8702 | if (isa<UsingShadowDecl>(Val: D)) |
8703 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
8704 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) { |
8705 | QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType()); |
8706 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) |
8707 | CanTy = ResTypeRef->getPointeeType(); |
8708 | // Need to go down the pointer/mempointer chain and add qualifiers |
8709 | // as see them. |
8710 | bool done = false; |
8711 | while (!done) { |
8712 | if (CanTy.isRestrictQualified()) |
8713 | VRQuals.addRestrict(); |
8714 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) |
8715 | CanTy = ResTypePtr->getPointeeType(); |
8716 | else if (const MemberPointerType *ResTypeMPtr = |
8717 | CanTy->getAs<MemberPointerType>()) |
8718 | CanTy = ResTypeMPtr->getPointeeType(); |
8719 | else |
8720 | done = true; |
8721 | if (CanTy.isVolatileQualified()) |
8722 | VRQuals.addVolatile(); |
8723 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) |
8724 | return VRQuals; |
8725 | } |
8726 | } |
8727 | } |
8728 | return VRQuals; |
8729 | } |
8730 | |
8731 | // Note: We're currently only handling qualifiers that are meaningful for the |
8732 | // LHS of compound assignment overloading. |
8733 | static void forAllQualifierCombinationsImpl( |
8734 | QualifiersAndAtomic Available, QualifiersAndAtomic Applied, |
8735 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8736 | // _Atomic |
8737 | if (Available.hasAtomic()) { |
8738 | Available.removeAtomic(); |
8739 | forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback); |
8740 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8741 | return; |
8742 | } |
8743 | |
8744 | // volatile |
8745 | if (Available.hasVolatile()) { |
8746 | Available.removeVolatile(); |
8747 | assert(!Applied.hasVolatile()); |
8748 | forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(), |
8749 | Callback); |
8750 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8751 | return; |
8752 | } |
8753 | |
8754 | Callback(Applied); |
8755 | } |
8756 | |
8757 | static void forAllQualifierCombinations( |
8758 | QualifiersAndAtomic Quals, |
8759 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8760 | return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(), |
8761 | Callback); |
8762 | } |
8763 | |
8764 | static QualType makeQualifiedLValueReferenceType(QualType Base, |
8765 | QualifiersAndAtomic Quals, |
8766 | Sema &S) { |
8767 | if (Quals.hasAtomic()) |
8768 | Base = S.Context.getAtomicType(T: Base); |
8769 | if (Quals.hasVolatile()) |
8770 | Base = S.Context.getVolatileType(T: Base); |
8771 | return S.Context.getLValueReferenceType(T: Base); |
8772 | } |
8773 | |
8774 | namespace { |
8775 | |
8776 | /// Helper class to manage the addition of builtin operator overload |
8777 | /// candidates. It provides shared state and utility methods used throughout |
8778 | /// the process, as well as a helper method to add each group of builtin |
8779 | /// operator overloads from the standard to a candidate set. |
8780 | class BuiltinOperatorOverloadBuilder { |
8781 | // Common instance state available to all overload candidate addition methods. |
8782 | Sema &S; |
8783 | ArrayRef<Expr *> Args; |
8784 | QualifiersAndAtomic VisibleTypeConversionsQuals; |
8785 | bool HasArithmeticOrEnumeralCandidateType; |
8786 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; |
8787 | OverloadCandidateSet &CandidateSet; |
8788 | |
8789 | static constexpr int ArithmeticTypesCap = 24; |
8790 | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; |
8791 | |
8792 | // Define some indices used to iterate over the arithmetic types in |
8793 | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic |
8794 | // types are that preserved by promotion (C++ [over.built]p2). |
8795 | unsigned FirstIntegralType, |
8796 | LastIntegralType; |
8797 | unsigned FirstPromotedIntegralType, |
8798 | LastPromotedIntegralType; |
8799 | unsigned FirstPromotedArithmeticType, |
8800 | LastPromotedArithmeticType; |
8801 | unsigned NumArithmeticTypes; |
8802 | |
8803 | void InitArithmeticTypes() { |
8804 | // Start of promoted types. |
8805 | FirstPromotedArithmeticType = 0; |
8806 | ArithmeticTypes.push_back(Elt: S.Context.FloatTy); |
8807 | ArithmeticTypes.push_back(Elt: S.Context.DoubleTy); |
8808 | ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy); |
8809 | if (S.Context.getTargetInfo().hasFloat128Type()) |
8810 | ArithmeticTypes.push_back(Elt: S.Context.Float128Ty); |
8811 | if (S.Context.getTargetInfo().hasIbm128Type()) |
8812 | ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty); |
8813 | |
8814 | // Start of integral types. |
8815 | FirstIntegralType = ArithmeticTypes.size(); |
8816 | FirstPromotedIntegralType = ArithmeticTypes.size(); |
8817 | ArithmeticTypes.push_back(Elt: S.Context.IntTy); |
8818 | ArithmeticTypes.push_back(Elt: S.Context.LongTy); |
8819 | ArithmeticTypes.push_back(Elt: S.Context.LongLongTy); |
8820 | if (S.Context.getTargetInfo().hasInt128Type() || |
8821 | (S.Context.getAuxTargetInfo() && |
8822 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8823 | ArithmeticTypes.push_back(Elt: S.Context.Int128Ty); |
8824 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy); |
8825 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy); |
8826 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy); |
8827 | if (S.Context.getTargetInfo().hasInt128Type() || |
8828 | (S.Context.getAuxTargetInfo() && |
8829 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8830 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty); |
8831 | LastPromotedIntegralType = ArithmeticTypes.size(); |
8832 | LastPromotedArithmeticType = ArithmeticTypes.size(); |
8833 | // End of promoted types. |
8834 | |
8835 | ArithmeticTypes.push_back(Elt: S.Context.BoolTy); |
8836 | ArithmeticTypes.push_back(Elt: S.Context.CharTy); |
8837 | ArithmeticTypes.push_back(Elt: S.Context.WCharTy); |
8838 | if (S.Context.getLangOpts().Char8) |
8839 | ArithmeticTypes.push_back(Elt: S.Context.Char8Ty); |
8840 | ArithmeticTypes.push_back(Elt: S.Context.Char16Ty); |
8841 | ArithmeticTypes.push_back(Elt: S.Context.Char32Ty); |
8842 | ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy); |
8843 | ArithmeticTypes.push_back(Elt: S.Context.ShortTy); |
8844 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy); |
8845 | ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy); |
8846 | LastIntegralType = ArithmeticTypes.size(); |
8847 | NumArithmeticTypes = ArithmeticTypes.size(); |
8848 | // End of integral types. |
8849 | // FIXME: What about complex? What about half? |
8850 | |
8851 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap && |
8852 | "Enough inline storage for all arithmetic types." ); |
8853 | } |
8854 | |
8855 | /// Helper method to factor out the common pattern of adding overloads |
8856 | /// for '++' and '--' builtin operators. |
8857 | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, |
8858 | bool HasVolatile, |
8859 | bool HasRestrict) { |
8860 | QualType ParamTypes[2] = { |
8861 | S.Context.getLValueReferenceType(T: CandidateTy), |
8862 | S.Context.IntTy |
8863 | }; |
8864 | |
8865 | // Non-volatile version. |
8866 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
8867 | |
8868 | // Use a heuristic to reduce number of builtin candidates in the set: |
8869 | // add volatile version only if there are conversions to a volatile type. |
8870 | if (HasVolatile) { |
8871 | ParamTypes[0] = |
8872 | S.Context.getLValueReferenceType( |
8873 | T: S.Context.getVolatileType(T: CandidateTy)); |
8874 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
8875 | } |
8876 | |
8877 | // Add restrict version only if there are conversions to a restrict type |
8878 | // and our candidate type is a non-restrict-qualified pointer. |
8879 | if (HasRestrict && CandidateTy->isAnyPointerType() && |
8880 | !CandidateTy.isRestrictQualified()) { |
8881 | ParamTypes[0] |
8882 | = S.Context.getLValueReferenceType( |
8883 | T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict)); |
8884 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
8885 | |
8886 | if (HasVolatile) { |
8887 | ParamTypes[0] |
8888 | = S.Context.getLValueReferenceType( |
8889 | T: S.Context.getCVRQualifiedType(T: CandidateTy, |
8890 | CVR: (Qualifiers::Volatile | |
8891 | Qualifiers::Restrict))); |
8892 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
8893 | } |
8894 | } |
8895 | |
8896 | } |
8897 | |
8898 | /// Helper to add an overload candidate for a binary builtin with types \p L |
8899 | /// and \p R. |
8900 | void AddCandidate(QualType L, QualType R) { |
8901 | QualType LandR[2] = {L, R}; |
8902 | S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet); |
8903 | } |
8904 | |
8905 | public: |
8906 | BuiltinOperatorOverloadBuilder( |
8907 | Sema &S, ArrayRef<Expr *> Args, |
8908 | QualifiersAndAtomic VisibleTypeConversionsQuals, |
8909 | bool HasArithmeticOrEnumeralCandidateType, |
8910 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, |
8911 | OverloadCandidateSet &CandidateSet) |
8912 | : S(S), Args(Args), |
8913 | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), |
8914 | HasArithmeticOrEnumeralCandidateType( |
8915 | HasArithmeticOrEnumeralCandidateType), |
8916 | CandidateTypes(CandidateTypes), |
8917 | CandidateSet(CandidateSet) { |
8918 | |
8919 | InitArithmeticTypes(); |
8920 | } |
8921 | |
8922 | // Increment is deprecated for bool since C++17. |
8923 | // |
8924 | // C++ [over.built]p3: |
8925 | // |
8926 | // For every pair (T, VQ), where T is an arithmetic type other |
8927 | // than bool, and VQ is either volatile or empty, there exist |
8928 | // candidate operator functions of the form |
8929 | // |
8930 | // VQ T& operator++(VQ T&); |
8931 | // T operator++(VQ T&, int); |
8932 | // |
8933 | // C++ [over.built]p4: |
8934 | // |
8935 | // For every pair (T, VQ), where T is an arithmetic type other |
8936 | // than bool, and VQ is either volatile or empty, there exist |
8937 | // candidate operator functions of the form |
8938 | // |
8939 | // VQ T& operator--(VQ T&); |
8940 | // T operator--(VQ T&, int); |
8941 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { |
8942 | if (!HasArithmeticOrEnumeralCandidateType) |
8943 | return; |
8944 | |
8945 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { |
8946 | const auto TypeOfT = ArithmeticTypes[Arith]; |
8947 | if (TypeOfT == S.Context.BoolTy) { |
8948 | if (Op == OO_MinusMinus) |
8949 | continue; |
8950 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) |
8951 | continue; |
8952 | } |
8953 | addPlusPlusMinusMinusStyleOverloads( |
8954 | CandidateTy: TypeOfT, |
8955 | HasVolatile: VisibleTypeConversionsQuals.hasVolatile(), |
8956 | HasRestrict: VisibleTypeConversionsQuals.hasRestrict()); |
8957 | } |
8958 | } |
8959 | |
8960 | // C++ [over.built]p5: |
8961 | // |
8962 | // For every pair (T, VQ), where T is a cv-qualified or |
8963 | // cv-unqualified object type, and VQ is either volatile or |
8964 | // empty, there exist candidate operator functions of the form |
8965 | // |
8966 | // T*VQ& operator++(T*VQ&); |
8967 | // T*VQ& operator--(T*VQ&); |
8968 | // T* operator++(T*VQ&, int); |
8969 | // T* operator--(T*VQ&, int); |
8970 | void addPlusPlusMinusMinusPointerOverloads() { |
8971 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
8972 | // Skip pointer types that aren't pointers to object types. |
8973 | if (!PtrTy->getPointeeType()->isObjectType()) |
8974 | continue; |
8975 | |
8976 | addPlusPlusMinusMinusStyleOverloads( |
8977 | CandidateTy: PtrTy, |
8978 | HasVolatile: (!PtrTy.isVolatileQualified() && |
8979 | VisibleTypeConversionsQuals.hasVolatile()), |
8980 | HasRestrict: (!PtrTy.isRestrictQualified() && |
8981 | VisibleTypeConversionsQuals.hasRestrict())); |
8982 | } |
8983 | } |
8984 | |
8985 | // C++ [over.built]p6: |
8986 | // For every cv-qualified or cv-unqualified object type T, there |
8987 | // exist candidate operator functions of the form |
8988 | // |
8989 | // T& operator*(T*); |
8990 | // |
8991 | // C++ [over.built]p7: |
8992 | // For every function type T that does not have cv-qualifiers or a |
8993 | // ref-qualifier, there exist candidate operator functions of the form |
8994 | // T& operator*(T*); |
8995 | void addUnaryStarPointerOverloads() { |
8996 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) { |
8997 | QualType PointeeTy = ParamTy->getPointeeType(); |
8998 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) |
8999 | continue; |
9000 | |
9001 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) |
9002 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) |
9003 | continue; |
9004 | |
9005 | S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet); |
9006 | } |
9007 | } |
9008 | |
9009 | // C++ [over.built]p9: |
9010 | // For every promoted arithmetic type T, there exist candidate |
9011 | // operator functions of the form |
9012 | // |
9013 | // T operator+(T); |
9014 | // T operator-(T); |
9015 | void addUnaryPlusOrMinusArithmeticOverloads() { |
9016 | if (!HasArithmeticOrEnumeralCandidateType) |
9017 | return; |
9018 | |
9019 | for (unsigned Arith = FirstPromotedArithmeticType; |
9020 | Arith < LastPromotedArithmeticType; ++Arith) { |
9021 | QualType ArithTy = ArithmeticTypes[Arith]; |
9022 | S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet); |
9023 | } |
9024 | |
9025 | // Extension: We also add these operators for vector types. |
9026 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
9027 | S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet); |
9028 | } |
9029 | |
9030 | // C++ [over.built]p8: |
9031 | // For every type T, there exist candidate operator functions of |
9032 | // the form |
9033 | // |
9034 | // T* operator+(T*); |
9035 | void addUnaryPlusPointerOverloads() { |
9036 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) |
9037 | S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet); |
9038 | } |
9039 | |
9040 | // C++ [over.built]p10: |
9041 | // For every promoted integral type T, there exist candidate |
9042 | // operator functions of the form |
9043 | // |
9044 | // T operator~(T); |
9045 | void addUnaryTildePromotedIntegralOverloads() { |
9046 | if (!HasArithmeticOrEnumeralCandidateType) |
9047 | return; |
9048 | |
9049 | for (unsigned Int = FirstPromotedIntegralType; |
9050 | Int < LastPromotedIntegralType; ++Int) { |
9051 | QualType IntTy = ArithmeticTypes[Int]; |
9052 | S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet); |
9053 | } |
9054 | |
9055 | // Extension: We also add this operator for vector types. |
9056 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
9057 | S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet); |
9058 | } |
9059 | |
9060 | // C++ [over.match.oper]p16: |
9061 | // For every pointer to member type T or type std::nullptr_t, there |
9062 | // exist candidate operator functions of the form |
9063 | // |
9064 | // bool operator==(T,T); |
9065 | // bool operator!=(T,T); |
9066 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { |
9067 | /// Set of (canonical) types that we've already handled. |
9068 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9069 | |
9070 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9071 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9072 | // Don't add the same builtin candidate twice. |
9073 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second) |
9074 | continue; |
9075 | |
9076 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
9077 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9078 | } |
9079 | |
9080 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { |
9081 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); |
9082 | if (AddedTypes.insert(Ptr: NullPtrTy).second) { |
9083 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; |
9084 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9085 | } |
9086 | } |
9087 | } |
9088 | } |
9089 | |
9090 | // C++ [over.built]p15: |
9091 | // |
9092 | // For every T, where T is an enumeration type or a pointer type, |
9093 | // there exist candidate operator functions of the form |
9094 | // |
9095 | // bool operator<(T, T); |
9096 | // bool operator>(T, T); |
9097 | // bool operator<=(T, T); |
9098 | // bool operator>=(T, T); |
9099 | // bool operator==(T, T); |
9100 | // bool operator!=(T, T); |
9101 | // R operator<=>(T, T) |
9102 | void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { |
9103 | // C++ [over.match.oper]p3: |
9104 | // [...]the built-in candidates include all of the candidate operator |
9105 | // functions defined in 13.6 that, compared to the given operator, [...] |
9106 | // do not have the same parameter-type-list as any non-template non-member |
9107 | // candidate. |
9108 | // |
9109 | // Note that in practice, this only affects enumeration types because there |
9110 | // aren't any built-in candidates of record type, and a user-defined operator |
9111 | // must have an operand of record or enumeration type. Also, the only other |
9112 | // overloaded operator with enumeration arguments, operator=, |
9113 | // cannot be overloaded for enumeration types, so this is the only place |
9114 | // where we must suppress candidates like this. |
9115 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > |
9116 | UserDefinedBinaryOperators; |
9117 | |
9118 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9119 | if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { |
9120 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), |
9121 | CEnd = CandidateSet.end(); |
9122 | C != CEnd; ++C) { |
9123 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) |
9124 | continue; |
9125 | |
9126 | if (C->Function->isFunctionTemplateSpecialization()) |
9127 | continue; |
9128 | |
9129 | // We interpret "same parameter-type-list" as applying to the |
9130 | // "synthesized candidate, with the order of the two parameters |
9131 | // reversed", not to the original function. |
9132 | bool Reversed = C->isReversed(); |
9133 | QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0) |
9134 | ->getType() |
9135 | .getUnqualifiedType(); |
9136 | QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1) |
9137 | ->getType() |
9138 | .getUnqualifiedType(); |
9139 | |
9140 | // Skip if either parameter isn't of enumeral type. |
9141 | if (!FirstParamType->isEnumeralType() || |
9142 | !SecondParamType->isEnumeralType()) |
9143 | continue; |
9144 | |
9145 | // Add this operator to the set of known user-defined operators. |
9146 | UserDefinedBinaryOperators.insert( |
9147 | V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType), |
9148 | y: S.Context.getCanonicalType(T: SecondParamType))); |
9149 | } |
9150 | } |
9151 | } |
9152 | |
9153 | /// Set of (canonical) types that we've already handled. |
9154 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9155 | |
9156 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9157 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
9158 | // Don't add the same builtin candidate twice. |
9159 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second) |
9160 | continue; |
9161 | if (IsSpaceship && PtrTy->isFunctionPointerType()) |
9162 | continue; |
9163 | |
9164 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9165 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9166 | } |
9167 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9168 | CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy); |
9169 | |
9170 | // Don't add the same builtin candidate twice, or if a user defined |
9171 | // candidate exists. |
9172 | if (!AddedTypes.insert(Ptr: CanonType).second || |
9173 | UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType, |
9174 | y&: CanonType))) |
9175 | continue; |
9176 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
9177 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9178 | } |
9179 | } |
9180 | } |
9181 | |
9182 | // C++ [over.built]p13: |
9183 | // |
9184 | // For every cv-qualified or cv-unqualified object type T |
9185 | // there exist candidate operator functions of the form |
9186 | // |
9187 | // T* operator+(T*, ptrdiff_t); |
9188 | // T& operator[](T*, ptrdiff_t); [BELOW] |
9189 | // T* operator-(T*, ptrdiff_t); |
9190 | // T* operator+(ptrdiff_t, T*); |
9191 | // T& operator[](ptrdiff_t, T*); [BELOW] |
9192 | // |
9193 | // C++ [over.built]p14: |
9194 | // |
9195 | // For every T, where T is a pointer to object type, there |
9196 | // exist candidate operator functions of the form |
9197 | // |
9198 | // ptrdiff_t operator-(T, T); |
9199 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { |
9200 | /// Set of (canonical) types that we've already handled. |
9201 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9202 | |
9203 | for (int Arg = 0; Arg < 2; ++Arg) { |
9204 | QualType AsymmetricParamTypes[2] = { |
9205 | S.Context.getPointerDiffType(), |
9206 | S.Context.getPointerDiffType(), |
9207 | }; |
9208 | for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { |
9209 | QualType PointeeTy = PtrTy->getPointeeType(); |
9210 | if (!PointeeTy->isObjectType()) |
9211 | continue; |
9212 | |
9213 | AsymmetricParamTypes[Arg] = PtrTy; |
9214 | if (Arg == 0 || Op == OO_Plus) { |
9215 | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) |
9216 | // T* operator+(ptrdiff_t, T*); |
9217 | S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet); |
9218 | } |
9219 | if (Op == OO_Minus) { |
9220 | // ptrdiff_t operator-(T, T); |
9221 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second) |
9222 | continue; |
9223 | |
9224 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9225 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9226 | } |
9227 | } |
9228 | } |
9229 | } |
9230 | |
9231 | // C++ [over.built]p12: |
9232 | // |
9233 | // For every pair of promoted arithmetic types L and R, there |
9234 | // exist candidate operator functions of the form |
9235 | // |
9236 | // LR operator*(L, R); |
9237 | // LR operator/(L, R); |
9238 | // LR operator+(L, R); |
9239 | // LR operator-(L, R); |
9240 | // bool operator<(L, R); |
9241 | // bool operator>(L, R); |
9242 | // bool operator<=(L, R); |
9243 | // bool operator>=(L, R); |
9244 | // bool operator==(L, R); |
9245 | // bool operator!=(L, R); |
9246 | // |
9247 | // where LR is the result of the usual arithmetic conversions |
9248 | // between types L and R. |
9249 | // |
9250 | // C++ [over.built]p24: |
9251 | // |
9252 | // For every pair of promoted arithmetic types L and R, there exist |
9253 | // candidate operator functions of the form |
9254 | // |
9255 | // LR operator?(bool, L, R); |
9256 | // |
9257 | // where LR is the result of the usual arithmetic conversions |
9258 | // between types L and R. |
9259 | // Our candidates ignore the first parameter. |
9260 | void addGenericBinaryArithmeticOverloads() { |
9261 | if (!HasArithmeticOrEnumeralCandidateType) |
9262 | return; |
9263 | |
9264 | for (unsigned Left = FirstPromotedArithmeticType; |
9265 | Left < LastPromotedArithmeticType; ++Left) { |
9266 | for (unsigned Right = FirstPromotedArithmeticType; |
9267 | Right < LastPromotedArithmeticType; ++Right) { |
9268 | QualType LandR[2] = { ArithmeticTypes[Left], |
9269 | ArithmeticTypes[Right] }; |
9270 | S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet); |
9271 | } |
9272 | } |
9273 | |
9274 | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the |
9275 | // conditional operator for vector types. |
9276 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
9277 | for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { |
9278 | QualType LandR[2] = {Vec1Ty, Vec2Ty}; |
9279 | S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet); |
9280 | } |
9281 | } |
9282 | |
9283 | /// Add binary operator overloads for each candidate matrix type M1, M2: |
9284 | /// * (M1, M1) -> M1 |
9285 | /// * (M1, M1.getElementType()) -> M1 |
9286 | /// * (M2.getElementType(), M2) -> M2 |
9287 | /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. |
9288 | void addMatrixBinaryArithmeticOverloads() { |
9289 | if (!HasArithmeticOrEnumeralCandidateType) |
9290 | return; |
9291 | |
9292 | for (QualType M1 : CandidateTypes[0].matrix_types()) { |
9293 | AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType()); |
9294 | AddCandidate(L: M1, R: M1); |
9295 | } |
9296 | |
9297 | for (QualType M2 : CandidateTypes[1].matrix_types()) { |
9298 | AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2); |
9299 | if (!CandidateTypes[0].containsMatrixType(Ty: M2)) |
9300 | AddCandidate(L: M2, R: M2); |
9301 | } |
9302 | } |
9303 | |
9304 | // C++2a [over.built]p14: |
9305 | // |
9306 | // For every integral type T there exists a candidate operator function |
9307 | // of the form |
9308 | // |
9309 | // std::strong_ordering operator<=>(T, T) |
9310 | // |
9311 | // C++2a [over.built]p15: |
9312 | // |
9313 | // For every pair of floating-point types L and R, there exists a candidate |
9314 | // operator function of the form |
9315 | // |
9316 | // std::partial_ordering operator<=>(L, R); |
9317 | // |
9318 | // FIXME: The current specification for integral types doesn't play nice with |
9319 | // the direction of p0946r0, which allows mixed integral and unscoped-enum |
9320 | // comparisons. Under the current spec this can lead to ambiguity during |
9321 | // overload resolution. For example: |
9322 | // |
9323 | // enum A : int {a}; |
9324 | // auto x = (a <=> (long)42); |
9325 | // |
9326 | // error: call is ambiguous for arguments 'A' and 'long'. |
9327 | // note: candidate operator<=>(int, int) |
9328 | // note: candidate operator<=>(long, long) |
9329 | // |
9330 | // To avoid this error, this function deviates from the specification and adds |
9331 | // the mixed overloads `operator<=>(L, R)` where L and R are promoted |
9332 | // arithmetic types (the same as the generic relational overloads). |
9333 | // |
9334 | // For now this function acts as a placeholder. |
9335 | void addThreeWayArithmeticOverloads() { |
9336 | addGenericBinaryArithmeticOverloads(); |
9337 | } |
9338 | |
9339 | // C++ [over.built]p17: |
9340 | // |
9341 | // For every pair of promoted integral types L and R, there |
9342 | // exist candidate operator functions of the form |
9343 | // |
9344 | // LR operator%(L, R); |
9345 | // LR operator&(L, R); |
9346 | // LR operator^(L, R); |
9347 | // LR operator|(L, R); |
9348 | // L operator<<(L, R); |
9349 | // L operator>>(L, R); |
9350 | // |
9351 | // where LR is the result of the usual arithmetic conversions |
9352 | // between types L and R. |
9353 | void addBinaryBitwiseArithmeticOverloads() { |
9354 | if (!HasArithmeticOrEnumeralCandidateType) |
9355 | return; |
9356 | |
9357 | for (unsigned Left = FirstPromotedIntegralType; |
9358 | Left < LastPromotedIntegralType; ++Left) { |
9359 | for (unsigned Right = FirstPromotedIntegralType; |
9360 | Right < LastPromotedIntegralType; ++Right) { |
9361 | QualType LandR[2] = { ArithmeticTypes[Left], |
9362 | ArithmeticTypes[Right] }; |
9363 | S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet); |
9364 | } |
9365 | } |
9366 | } |
9367 | |
9368 | // C++ [over.built]p20: |
9369 | // |
9370 | // For every pair (T, VQ), where T is an enumeration or |
9371 | // pointer to member type and VQ is either volatile or |
9372 | // empty, there exist candidate operator functions of the form |
9373 | // |
9374 | // VQ T& operator=(VQ T&, T); |
9375 | void addAssignmentMemberPointerOrEnumeralOverloads() { |
9376 | /// Set of (canonical) types that we've already handled. |
9377 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9378 | |
9379 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9380 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9381 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second) |
9382 | continue; |
9383 | |
9384 | AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet); |
9385 | } |
9386 | |
9387 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9388 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second) |
9389 | continue; |
9390 | |
9391 | AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet); |
9392 | } |
9393 | } |
9394 | } |
9395 | |
9396 | // C++ [over.built]p19: |
9397 | // |
9398 | // For every pair (T, VQ), where T is any type and VQ is either |
9399 | // volatile or empty, there exist candidate operator functions |
9400 | // of the form |
9401 | // |
9402 | // T*VQ& operator=(T*VQ&, T*); |
9403 | // |
9404 | // C++ [over.built]p21: |
9405 | // |
9406 | // For every pair (T, VQ), where T is a cv-qualified or |
9407 | // cv-unqualified object type and VQ is either volatile or |
9408 | // empty, there exist candidate operator functions of the form |
9409 | // |
9410 | // T*VQ& operator+=(T*VQ&, ptrdiff_t); |
9411 | // T*VQ& operator-=(T*VQ&, ptrdiff_t); |
9412 | void addAssignmentPointerOverloads(bool isEqualOp) { |
9413 | /// Set of (canonical) types that we've already handled. |
9414 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9415 | |
9416 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9417 | // If this is operator=, keep track of the builtin candidates we added. |
9418 | if (isEqualOp) |
9419 | AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)); |
9420 | else if (!PtrTy->getPointeeType()->isObjectType()) |
9421 | continue; |
9422 | |
9423 | // non-volatile version |
9424 | QualType ParamTypes[2] = { |
9425 | S.Context.getLValueReferenceType(T: PtrTy), |
9426 | isEqualOp ? PtrTy : S.Context.getPointerDiffType(), |
9427 | }; |
9428 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9429 | /*IsAssignmentOperator=*/ isEqualOp); |
9430 | |
9431 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9432 | VisibleTypeConversionsQuals.hasVolatile(); |
9433 | if (NeedVolatile) { |
9434 | // volatile version |
9435 | ParamTypes[0] = |
9436 | S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy)); |
9437 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9438 | /*IsAssignmentOperator=*/isEqualOp); |
9439 | } |
9440 | |
9441 | if (!PtrTy.isRestrictQualified() && |
9442 | VisibleTypeConversionsQuals.hasRestrict()) { |
9443 | // restrict version |
9444 | ParamTypes[0] = |
9445 | S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy)); |
9446 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9447 | /*IsAssignmentOperator=*/isEqualOp); |
9448 | |
9449 | if (NeedVolatile) { |
9450 | // volatile restrict version |
9451 | ParamTypes[0] = |
9452 | S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType( |
9453 | T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict))); |
9454 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9455 | /*IsAssignmentOperator=*/isEqualOp); |
9456 | } |
9457 | } |
9458 | } |
9459 | |
9460 | if (isEqualOp) { |
9461 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9462 | // Make sure we don't add the same candidate twice. |
9463 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second) |
9464 | continue; |
9465 | |
9466 | QualType ParamTypes[2] = { |
9467 | S.Context.getLValueReferenceType(T: PtrTy), |
9468 | PtrTy, |
9469 | }; |
9470 | |
9471 | // non-volatile version |
9472 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9473 | /*IsAssignmentOperator=*/true); |
9474 | |
9475 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9476 | VisibleTypeConversionsQuals.hasVolatile(); |
9477 | if (NeedVolatile) { |
9478 | // volatile version |
9479 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9480 | T: S.Context.getVolatileType(T: PtrTy)); |
9481 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9482 | /*IsAssignmentOperator=*/true); |
9483 | } |
9484 | |
9485 | if (!PtrTy.isRestrictQualified() && |
9486 | VisibleTypeConversionsQuals.hasRestrict()) { |
9487 | // restrict version |
9488 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9489 | T: S.Context.getRestrictType(T: PtrTy)); |
9490 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9491 | /*IsAssignmentOperator=*/true); |
9492 | |
9493 | if (NeedVolatile) { |
9494 | // volatile restrict version |
9495 | ParamTypes[0] = |
9496 | S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType( |
9497 | T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict))); |
9498 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9499 | /*IsAssignmentOperator=*/true); |
9500 | } |
9501 | } |
9502 | } |
9503 | } |
9504 | } |
9505 | |
9506 | // C++ [over.built]p18: |
9507 | // |
9508 | // For every triple (L, VQ, R), where L is an arithmetic type, |
9509 | // VQ is either volatile or empty, and R is a promoted |
9510 | // arithmetic type, there exist candidate operator functions of |
9511 | // the form |
9512 | // |
9513 | // VQ L& operator=(VQ L&, R); |
9514 | // VQ L& operator*=(VQ L&, R); |
9515 | // VQ L& operator/=(VQ L&, R); |
9516 | // VQ L& operator+=(VQ L&, R); |
9517 | // VQ L& operator-=(VQ L&, R); |
9518 | void addAssignmentArithmeticOverloads(bool isEqualOp) { |
9519 | if (!HasArithmeticOrEnumeralCandidateType) |
9520 | return; |
9521 | |
9522 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { |
9523 | for (unsigned Right = FirstPromotedArithmeticType; |
9524 | Right < LastPromotedArithmeticType; ++Right) { |
9525 | QualType ParamTypes[2]; |
9526 | ParamTypes[1] = ArithmeticTypes[Right]; |
9527 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9528 | S, T: ArithmeticTypes[Left], Arg: Args[0]); |
9529 | |
9530 | forAllQualifierCombinations( |
9531 | Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) { |
9532 | ParamTypes[0] = |
9533 | makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S); |
9534 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9535 | /*IsAssignmentOperator=*/isEqualOp); |
9536 | }); |
9537 | } |
9538 | } |
9539 | |
9540 | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. |
9541 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
9542 | for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { |
9543 | QualType ParamTypes[2]; |
9544 | ParamTypes[1] = Vec2Ty; |
9545 | // Add this built-in operator as a candidate (VQ is empty). |
9546 | ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty); |
9547 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9548 | /*IsAssignmentOperator=*/isEqualOp); |
9549 | |
9550 | // Add this built-in operator as a candidate (VQ is 'volatile'). |
9551 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
9552 | ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty); |
9553 | ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]); |
9554 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9555 | /*IsAssignmentOperator=*/isEqualOp); |
9556 | } |
9557 | } |
9558 | } |
9559 | |
9560 | // C++ [over.built]p22: |
9561 | // |
9562 | // For every triple (L, VQ, R), where L is an integral type, VQ |
9563 | // is either volatile or empty, and R is a promoted integral |
9564 | // type, there exist candidate operator functions of the form |
9565 | // |
9566 | // VQ L& operator%=(VQ L&, R); |
9567 | // VQ L& operator<<=(VQ L&, R); |
9568 | // VQ L& operator>>=(VQ L&, R); |
9569 | // VQ L& operator&=(VQ L&, R); |
9570 | // VQ L& operator^=(VQ L&, R); |
9571 | // VQ L& operator|=(VQ L&, R); |
9572 | void addAssignmentIntegralOverloads() { |
9573 | if (!HasArithmeticOrEnumeralCandidateType) |
9574 | return; |
9575 | |
9576 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { |
9577 | for (unsigned Right = FirstPromotedIntegralType; |
9578 | Right < LastPromotedIntegralType; ++Right) { |
9579 | QualType ParamTypes[2]; |
9580 | ParamTypes[1] = ArithmeticTypes[Right]; |
9581 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9582 | S, T: ArithmeticTypes[Left], Arg: Args[0]); |
9583 | |
9584 | forAllQualifierCombinations( |
9585 | Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) { |
9586 | ParamTypes[0] = |
9587 | makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S); |
9588 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9589 | }); |
9590 | } |
9591 | } |
9592 | } |
9593 | |
9594 | // C++ [over.operator]p23: |
9595 | // |
9596 | // There also exist candidate operator functions of the form |
9597 | // |
9598 | // bool operator!(bool); |
9599 | // bool operator&&(bool, bool); |
9600 | // bool operator||(bool, bool); |
9601 | void addExclaimOverload() { |
9602 | QualType ParamTy = S.Context.BoolTy; |
9603 | S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet, |
9604 | /*IsAssignmentOperator=*/false, |
9605 | /*NumContextualBoolArguments=*/1); |
9606 | } |
9607 | void addAmpAmpOrPipePipeOverload() { |
9608 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; |
9609 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet, |
9610 | /*IsAssignmentOperator=*/false, |
9611 | /*NumContextualBoolArguments=*/2); |
9612 | } |
9613 | |
9614 | // C++ [over.built]p13: |
9615 | // |
9616 | // For every cv-qualified or cv-unqualified object type T there |
9617 | // exist candidate operator functions of the form |
9618 | // |
9619 | // T* operator+(T*, ptrdiff_t); [ABOVE] |
9620 | // T& operator[](T*, ptrdiff_t); |
9621 | // T* operator-(T*, ptrdiff_t); [ABOVE] |
9622 | // T* operator+(ptrdiff_t, T*); [ABOVE] |
9623 | // T& operator[](ptrdiff_t, T*); |
9624 | void addSubscriptOverloads() { |
9625 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9626 | QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; |
9627 | QualType PointeeType = PtrTy->getPointeeType(); |
9628 | if (!PointeeType->isObjectType()) |
9629 | continue; |
9630 | |
9631 | // T& operator[](T*, ptrdiff_t) |
9632 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9633 | } |
9634 | |
9635 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9636 | QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; |
9637 | QualType PointeeType = PtrTy->getPointeeType(); |
9638 | if (!PointeeType->isObjectType()) |
9639 | continue; |
9640 | |
9641 | // T& operator[](ptrdiff_t, T*) |
9642 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9643 | } |
9644 | } |
9645 | |
9646 | // C++ [over.built]p11: |
9647 | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, |
9648 | // C1 is the same type as C2 or is a derived class of C2, T is an object |
9649 | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, |
9650 | // there exist candidate operator functions of the form |
9651 | // |
9652 | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); |
9653 | // |
9654 | // where CV12 is the union of CV1 and CV2. |
9655 | void addArrowStarOverloads() { |
9656 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9657 | QualType C1Ty = PtrTy; |
9658 | QualType C1; |
9659 | QualifierCollector Q1; |
9660 | C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0); |
9661 | if (!isa<RecordType>(Val: C1)) |
9662 | continue; |
9663 | // heuristic to reduce number of builtin candidates in the set. |
9664 | // Add volatile/restrict version only if there are conversions to a |
9665 | // volatile/restrict type. |
9666 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) |
9667 | continue; |
9668 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) |
9669 | continue; |
9670 | for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { |
9671 | const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy); |
9672 | QualType C2 = QualType(mptr->getClass(), 0); |
9673 | C2 = C2.getUnqualifiedType(); |
9674 | if (C1 != C2 && !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: C1, Base: C2)) |
9675 | break; |
9676 | QualType ParamTypes[2] = {PtrTy, MemPtrTy}; |
9677 | // build CV12 T& |
9678 | QualType T = mptr->getPointeeType(); |
9679 | if (!VisibleTypeConversionsQuals.hasVolatile() && |
9680 | T.isVolatileQualified()) |
9681 | continue; |
9682 | if (!VisibleTypeConversionsQuals.hasRestrict() && |
9683 | T.isRestrictQualified()) |
9684 | continue; |
9685 | T = Q1.apply(Context: S.Context, QT: T); |
9686 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9687 | } |
9688 | } |
9689 | } |
9690 | |
9691 | // Note that we don't consider the first argument, since it has been |
9692 | // contextually converted to bool long ago. The candidates below are |
9693 | // therefore added as binary. |
9694 | // |
9695 | // C++ [over.built]p25: |
9696 | // For every type T, where T is a pointer, pointer-to-member, or scoped |
9697 | // enumeration type, there exist candidate operator functions of the form |
9698 | // |
9699 | // T operator?(bool, T, T); |
9700 | // |
9701 | void addConditionalOperatorOverloads() { |
9702 | /// Set of (canonical) types that we've already handled. |
9703 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9704 | |
9705 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9706 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
9707 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second) |
9708 | continue; |
9709 | |
9710 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9711 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9712 | } |
9713 | |
9714 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9715 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second) |
9716 | continue; |
9717 | |
9718 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
9719 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9720 | } |
9721 | |
9722 | if (S.getLangOpts().CPlusPlus11) { |
9723 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9724 | if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) |
9725 | continue; |
9726 | |
9727 | if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second) |
9728 | continue; |
9729 | |
9730 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
9731 | S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet); |
9732 | } |
9733 | } |
9734 | } |
9735 | } |
9736 | }; |
9737 | |
9738 | } // end anonymous namespace |
9739 | |
9740 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in |
9741 | /// operator overloads to the candidate set (C++ [over.built]), based |
9742 | /// on the operator @p Op and the arguments given. For example, if the |
9743 | /// operator is a binary '+', this routine might add "int |
9744 | /// operator+(int, int)" to cover integer addition. |
9745 | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
9746 | SourceLocation OpLoc, |
9747 | ArrayRef<Expr *> Args, |
9748 | OverloadCandidateSet &CandidateSet) { |
9749 | // Find all of the types that the arguments can convert to, but only |
9750 | // if the operator we're looking at has built-in operator candidates |
9751 | // that make use of these types. Also record whether we encounter non-record |
9752 | // candidate types or either arithmetic or enumeral candidate types. |
9753 | QualifiersAndAtomic VisibleTypeConversionsQuals; |
9754 | VisibleTypeConversionsQuals.addConst(); |
9755 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9756 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]); |
9757 | if (Args[ArgIdx]->getType()->isAtomicType()) |
9758 | VisibleTypeConversionsQuals.addAtomic(); |
9759 | } |
9760 | |
9761 | bool HasNonRecordCandidateType = false; |
9762 | bool HasArithmeticOrEnumeralCandidateType = false; |
9763 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; |
9764 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9765 | CandidateTypes.emplace_back(Args&: *this); |
9766 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(), |
9767 | Loc: OpLoc, |
9768 | AllowUserConversions: true, |
9769 | AllowExplicitConversions: (Op == OO_Exclaim || |
9770 | Op == OO_AmpAmp || |
9771 | Op == OO_PipePipe), |
9772 | VisibleQuals: VisibleTypeConversionsQuals); |
9773 | HasNonRecordCandidateType = HasNonRecordCandidateType || |
9774 | CandidateTypes[ArgIdx].hasNonRecordTypes(); |
9775 | HasArithmeticOrEnumeralCandidateType = |
9776 | HasArithmeticOrEnumeralCandidateType || |
9777 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); |
9778 | } |
9779 | |
9780 | // Exit early when no non-record types have been added to the candidate set |
9781 | // for any of the arguments to the operator. |
9782 | // |
9783 | // We can't exit early for !, ||, or &&, since there we have always have |
9784 | // 'bool' overloads. |
9785 | if (!HasNonRecordCandidateType && |
9786 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) |
9787 | return; |
9788 | |
9789 | // Setup an object to manage the common state for building overloads. |
9790 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, |
9791 | VisibleTypeConversionsQuals, |
9792 | HasArithmeticOrEnumeralCandidateType, |
9793 | CandidateTypes, CandidateSet); |
9794 | |
9795 | // Dispatch over the operation to add in only those overloads which apply. |
9796 | switch (Op) { |
9797 | case OO_None: |
9798 | case NUM_OVERLOADED_OPERATORS: |
9799 | llvm_unreachable("Expected an overloaded operator" ); |
9800 | |
9801 | case OO_New: |
9802 | case OO_Delete: |
9803 | case OO_Array_New: |
9804 | case OO_Array_Delete: |
9805 | case OO_Call: |
9806 | llvm_unreachable( |
9807 | "Special operators don't use AddBuiltinOperatorCandidates" ); |
9808 | |
9809 | case OO_Comma: |
9810 | case OO_Arrow: |
9811 | case OO_Coawait: |
9812 | // C++ [over.match.oper]p3: |
9813 | // -- For the operator ',', the unary operator '&', the |
9814 | // operator '->', or the operator 'co_await', the |
9815 | // built-in candidates set is empty. |
9816 | break; |
9817 | |
9818 | case OO_Plus: // '+' is either unary or binary |
9819 | if (Args.size() == 1) |
9820 | OpBuilder.addUnaryPlusPointerOverloads(); |
9821 | [[fallthrough]]; |
9822 | |
9823 | case OO_Minus: // '-' is either unary or binary |
9824 | if (Args.size() == 1) { |
9825 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); |
9826 | } else { |
9827 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); |
9828 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9829 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9830 | } |
9831 | break; |
9832 | |
9833 | case OO_Star: // '*' is either unary or binary |
9834 | if (Args.size() == 1) |
9835 | OpBuilder.addUnaryStarPointerOverloads(); |
9836 | else { |
9837 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9838 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9839 | } |
9840 | break; |
9841 | |
9842 | case OO_Slash: |
9843 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9844 | break; |
9845 | |
9846 | case OO_PlusPlus: |
9847 | case OO_MinusMinus: |
9848 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); |
9849 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); |
9850 | break; |
9851 | |
9852 | case OO_EqualEqual: |
9853 | case OO_ExclaimEqual: |
9854 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); |
9855 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9856 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9857 | break; |
9858 | |
9859 | case OO_Less: |
9860 | case OO_Greater: |
9861 | case OO_LessEqual: |
9862 | case OO_GreaterEqual: |
9863 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9864 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9865 | break; |
9866 | |
9867 | case OO_Spaceship: |
9868 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); |
9869 | OpBuilder.addThreeWayArithmeticOverloads(); |
9870 | break; |
9871 | |
9872 | case OO_Percent: |
9873 | case OO_Caret: |
9874 | case OO_Pipe: |
9875 | case OO_LessLess: |
9876 | case OO_GreaterGreater: |
9877 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9878 | break; |
9879 | |
9880 | case OO_Amp: // '&' is either unary or binary |
9881 | if (Args.size() == 1) |
9882 | // C++ [over.match.oper]p3: |
9883 | // -- For the operator ',', the unary operator '&', or the |
9884 | // operator '->', the built-in candidates set is empty. |
9885 | break; |
9886 | |
9887 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9888 | break; |
9889 | |
9890 | case OO_Tilde: |
9891 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); |
9892 | break; |
9893 | |
9894 | case OO_Equal: |
9895 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); |
9896 | [[fallthrough]]; |
9897 | |
9898 | case OO_PlusEqual: |
9899 | case OO_MinusEqual: |
9900 | OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal); |
9901 | [[fallthrough]]; |
9902 | |
9903 | case OO_StarEqual: |
9904 | case OO_SlashEqual: |
9905 | OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal); |
9906 | break; |
9907 | |
9908 | case OO_PercentEqual: |
9909 | case OO_LessLessEqual: |
9910 | case OO_GreaterGreaterEqual: |
9911 | case OO_AmpEqual: |
9912 | case OO_CaretEqual: |
9913 | case OO_PipeEqual: |
9914 | OpBuilder.addAssignmentIntegralOverloads(); |
9915 | break; |
9916 | |
9917 | case OO_Exclaim: |
9918 | OpBuilder.addExclaimOverload(); |
9919 | break; |
9920 | |
9921 | case OO_AmpAmp: |
9922 | case OO_PipePipe: |
9923 | OpBuilder.addAmpAmpOrPipePipeOverload(); |
9924 | break; |
9925 | |
9926 | case OO_Subscript: |
9927 | if (Args.size() == 2) |
9928 | OpBuilder.addSubscriptOverloads(); |
9929 | break; |
9930 | |
9931 | case OO_ArrowStar: |
9932 | OpBuilder.addArrowStarOverloads(); |
9933 | break; |
9934 | |
9935 | case OO_Conditional: |
9936 | OpBuilder.addConditionalOperatorOverloads(); |
9937 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9938 | break; |
9939 | } |
9940 | } |
9941 | |
9942 | /// Add function candidates found via argument-dependent lookup |
9943 | /// to the set of overloading candidates. |
9944 | /// |
9945 | /// This routine performs argument-dependent name lookup based on the |
9946 | /// given function name (which may also be an operator name) and adds |
9947 | /// all of the overload candidates found by ADL to the overload |
9948 | /// candidate set (C++ [basic.lookup.argdep]). |
9949 | void |
9950 | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, |
9951 | SourceLocation Loc, |
9952 | ArrayRef<Expr *> Args, |
9953 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
9954 | OverloadCandidateSet& CandidateSet, |
9955 | bool PartialOverloading) { |
9956 | ADLResult Fns; |
9957 | |
9958 | // FIXME: This approach for uniquing ADL results (and removing |
9959 | // redundant candidates from the set) relies on pointer-equality, |
9960 | // which means we need to key off the canonical decl. However, |
9961 | // always going back to the canonical decl might not get us the |
9962 | // right set of default arguments. What default arguments are |
9963 | // we supposed to consider on ADL candidates, anyway? |
9964 | |
9965 | // FIXME: Pass in the explicit template arguments? |
9966 | ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns); |
9967 | |
9968 | // Erase all of the candidates we already knew about. |
9969 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), |
9970 | CandEnd = CandidateSet.end(); |
9971 | Cand != CandEnd; ++Cand) |
9972 | if (Cand->Function) { |
9973 | Fns.erase(Cand->Function); |
9974 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) |
9975 | Fns.erase(FunTmpl); |
9976 | } |
9977 | |
9978 | // For each of the ADL candidates we found, add it to the overload |
9979 | // set. |
9980 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { |
9981 | DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none); |
9982 | |
9983 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) { |
9984 | if (ExplicitTemplateArgs) |
9985 | continue; |
9986 | |
9987 | AddOverloadCandidate( |
9988 | Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, |
9989 | PartialOverloading, /*AllowExplicit=*/true, |
9990 | /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL); |
9991 | if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) { |
9992 | AddOverloadCandidate( |
9993 | Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet, |
9994 | /*SuppressUserConversions=*/false, PartialOverloading, |
9995 | /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false, |
9996 | IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: std::nullopt, |
9997 | PO: OverloadCandidateParamOrder::Reversed); |
9998 | } |
9999 | } else { |
10000 | auto *FTD = cast<FunctionTemplateDecl>(Val: *I); |
10001 | AddTemplateOverloadCandidate( |
10002 | FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, |
10003 | /*SuppressUserConversions=*/false, PartialOverloading, |
10004 | /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL); |
10005 | if (CandidateSet.getRewriteInfo().shouldAddReversed( |
10006 | S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) { |
10007 | AddTemplateOverloadCandidate( |
10008 | FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: {Args[1], Args[0]}, |
10009 | CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, |
10010 | /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL, |
10011 | PO: OverloadCandidateParamOrder::Reversed); |
10012 | } |
10013 | } |
10014 | } |
10015 | } |
10016 | |
10017 | namespace { |
10018 | enum class Comparison { Equal, Better, Worse }; |
10019 | } |
10020 | |
10021 | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of |
10022 | /// overload resolution. |
10023 | /// |
10024 | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff |
10025 | /// Cand1's first N enable_if attributes have precisely the same conditions as |
10026 | /// Cand2's first N enable_if attributes (where N = the number of enable_if |
10027 | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. |
10028 | /// |
10029 | /// Note that you can have a pair of candidates such that Cand1's enable_if |
10030 | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are |
10031 | /// worse than Cand1's. |
10032 | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, |
10033 | const FunctionDecl *Cand2) { |
10034 | // Common case: One (or both) decls don't have enable_if attrs. |
10035 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); |
10036 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); |
10037 | if (!Cand1Attr || !Cand2Attr) { |
10038 | if (Cand1Attr == Cand2Attr) |
10039 | return Comparison::Equal; |
10040 | return Cand1Attr ? Comparison::Better : Comparison::Worse; |
10041 | } |
10042 | |
10043 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); |
10044 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); |
10045 | |
10046 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; |
10047 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { |
10048 | std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); |
10049 | std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); |
10050 | |
10051 | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 |
10052 | // has fewer enable_if attributes than Cand2, and vice versa. |
10053 | if (!Cand1A) |
10054 | return Comparison::Worse; |
10055 | if (!Cand2A) |
10056 | return Comparison::Better; |
10057 | |
10058 | Cand1ID.clear(); |
10059 | Cand2ID.clear(); |
10060 | |
10061 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); |
10062 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); |
10063 | if (Cand1ID != Cand2ID) |
10064 | return Comparison::Worse; |
10065 | } |
10066 | |
10067 | return Comparison::Equal; |
10068 | } |
10069 | |
10070 | static Comparison |
10071 | isBetterMultiversionCandidate(const OverloadCandidate &Cand1, |
10072 | const OverloadCandidate &Cand2) { |
10073 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || |
10074 | !Cand2.Function->isMultiVersion()) |
10075 | return Comparison::Equal; |
10076 | |
10077 | // If both are invalid, they are equal. If one of them is invalid, the other |
10078 | // is better. |
10079 | if (Cand1.Function->isInvalidDecl()) { |
10080 | if (Cand2.Function->isInvalidDecl()) |
10081 | return Comparison::Equal; |
10082 | return Comparison::Worse; |
10083 | } |
10084 | if (Cand2.Function->isInvalidDecl()) |
10085 | return Comparison::Better; |
10086 | |
10087 | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer |
10088 | // cpu_dispatch, else arbitrarily based on the identifiers. |
10089 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); |
10090 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); |
10091 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); |
10092 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); |
10093 | |
10094 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) |
10095 | return Comparison::Equal; |
10096 | |
10097 | if (Cand1CPUDisp && !Cand2CPUDisp) |
10098 | return Comparison::Better; |
10099 | if (Cand2CPUDisp && !Cand1CPUDisp) |
10100 | return Comparison::Worse; |
10101 | |
10102 | if (Cand1CPUSpec && Cand2CPUSpec) { |
10103 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) |
10104 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() |
10105 | ? Comparison::Better |
10106 | : Comparison::Worse; |
10107 | |
10108 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> |
10109 | FirstDiff = std::mismatch( |
10110 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), |
10111 | Cand2CPUSpec->cpus_begin(), |
10112 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { |
10113 | return LHS->getName() == RHS->getName(); |
10114 | }); |
10115 | |
10116 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && |
10117 | "Two different cpu-specific versions should not have the same " |
10118 | "identifier list, otherwise they'd be the same decl!" ); |
10119 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() |
10120 | ? Comparison::Better |
10121 | : Comparison::Worse; |
10122 | } |
10123 | llvm_unreachable("No way to get here unless both had cpu_dispatch" ); |
10124 | } |
10125 | |
10126 | /// Compute the type of the implicit object parameter for the given function, |
10127 | /// if any. Returns std::nullopt if there is no implicit object parameter, and a |
10128 | /// null QualType if there is a 'matches anything' implicit object parameter. |
10129 | static std::optional<QualType> |
10130 | getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { |
10131 | if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F)) |
10132 | return std::nullopt; |
10133 | |
10134 | auto *M = cast<CXXMethodDecl>(Val: F); |
10135 | // Static member functions' object parameters match all types. |
10136 | if (M->isStatic()) |
10137 | return QualType(); |
10138 | return M->getFunctionObjectParameterReferenceType(); |
10139 | } |
10140 | |
10141 | // As a Clang extension, allow ambiguity among F1 and F2 if they represent |
10142 | // represent the same entity. |
10143 | static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, |
10144 | const FunctionDecl *F2) { |
10145 | if (declaresSameEntity(F1, F2)) |
10146 | return true; |
10147 | auto PT1 = F1->getPrimaryTemplate(); |
10148 | auto PT2 = F2->getPrimaryTemplate(); |
10149 | if (PT1 && PT2) { |
10150 | if (declaresSameEntity(PT1, PT2) || |
10151 | declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(), |
10152 | PT2->getInstantiatedFromMemberTemplate())) |
10153 | return true; |
10154 | } |
10155 | // TODO: It is not clear whether comparing parameters is necessary (i.e. |
10156 | // different functions with same params). Consider removing this (as no test |
10157 | // fail w/o it). |
10158 | auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { |
10159 | if (First) { |
10160 | if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) |
10161 | return *T; |
10162 | } |
10163 | assert(I < F->getNumParams()); |
10164 | return F->getParamDecl(I++)->getType(); |
10165 | }; |
10166 | |
10167 | unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1); |
10168 | unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2); |
10169 | |
10170 | if (F1NumParams != F2NumParams) |
10171 | return false; |
10172 | |
10173 | unsigned I1 = 0, I2 = 0; |
10174 | for (unsigned I = 0; I != F1NumParams; ++I) { |
10175 | QualType T1 = NextParam(F1, I1, I == 0); |
10176 | QualType T2 = NextParam(F2, I2, I == 0); |
10177 | assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types" ); |
10178 | if (!Context.hasSameUnqualifiedType(T1, T2)) |
10179 | return false; |
10180 | } |
10181 | return true; |
10182 | } |
10183 | |
10184 | /// We're allowed to use constraints partial ordering only if the candidates |
10185 | /// have the same parameter types: |
10186 | /// [over.match.best.general]p2.6 |
10187 | /// F1 and F2 are non-template functions with the same |
10188 | /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...] |
10189 | static bool sameFunctionParameterTypeLists(Sema &S, |
10190 | const OverloadCandidate &Cand1, |
10191 | const OverloadCandidate &Cand2) { |
10192 | if (!Cand1.Function || !Cand2.Function) |
10193 | return false; |
10194 | |
10195 | FunctionDecl *Fn1 = Cand1.Function; |
10196 | FunctionDecl *Fn2 = Cand2.Function; |
10197 | |
10198 | if (Fn1->isVariadic() != Fn1->isVariadic()) |
10199 | return false; |
10200 | |
10201 | if (!S.FunctionNonObjectParamTypesAreEqual( |
10202 | OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr, Reversed: Cand1.isReversed() ^ Cand2.isReversed())) |
10203 | return false; |
10204 | |
10205 | auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1); |
10206 | auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2); |
10207 | if (Mem1 && Mem2) { |
10208 | // if they are member functions, both are direct members of the same class, |
10209 | // and |
10210 | if (Mem1->getParent() != Mem2->getParent()) |
10211 | return false; |
10212 | // if both are non-static member functions, they have the same types for |
10213 | // their object parameters |
10214 | if (Mem1->isInstance() && Mem2->isInstance() && |
10215 | !S.getASTContext().hasSameType( |
10216 | T1: Mem1->getFunctionObjectParameterReferenceType(), |
10217 | T2: Mem1->getFunctionObjectParameterReferenceType())) |
10218 | return false; |
10219 | } |
10220 | return true; |
10221 | } |
10222 | |
10223 | /// isBetterOverloadCandidate - Determines whether the first overload |
10224 | /// candidate is a better candidate than the second (C++ 13.3.3p1). |
10225 | bool clang::isBetterOverloadCandidate( |
10226 | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, |
10227 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { |
10228 | // Define viable functions to be better candidates than non-viable |
10229 | // functions. |
10230 | if (!Cand2.Viable) |
10231 | return Cand1.Viable; |
10232 | else if (!Cand1.Viable) |
10233 | return false; |
10234 | |
10235 | // [CUDA] A function with 'never' preference is marked not viable, therefore |
10236 | // is never shown up here. The worst preference shown up here is 'wrong side', |
10237 | // e.g. an H function called by a HD function in device compilation. This is |
10238 | // valid AST as long as the HD function is not emitted, e.g. it is an inline |
10239 | // function which is called only by an H function. A deferred diagnostic will |
10240 | // be triggered if it is emitted. However a wrong-sided function is still |
10241 | // a viable candidate here. |
10242 | // |
10243 | // If Cand1 can be emitted and Cand2 cannot be emitted in the current |
10244 | // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 |
10245 | // can be emitted, Cand1 is not better than Cand2. This rule should have |
10246 | // precedence over other rules. |
10247 | // |
10248 | // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then |
10249 | // other rules should be used to determine which is better. This is because |
10250 | // host/device based overloading resolution is mostly for determining |
10251 | // viability of a function. If two functions are both viable, other factors |
10252 | // should take precedence in preference, e.g. the standard-defined preferences |
10253 | // like argument conversion ranks or enable_if partial-ordering. The |
10254 | // preference for pass-object-size parameters is probably most similar to a |
10255 | // type-based-overloading decision and so should take priority. |
10256 | // |
10257 | // If other rules cannot determine which is better, CUDA preference will be |
10258 | // used again to determine which is better. |
10259 | // |
10260 | // TODO: Currently IdentifyCUDAPreference does not return correct values |
10261 | // for functions called in global variable initializers due to missing |
10262 | // correct context about device/host. Therefore we can only enforce this |
10263 | // rule when there is a caller. We should enforce this rule for functions |
10264 | // in global variable initializers once proper context is added. |
10265 | // |
10266 | // TODO: We can only enable the hostness based overloading resolution when |
10267 | // -fgpu-exclude-wrong-side-overloads is on since this requires deferring |
10268 | // overloading resolution diagnostics. |
10269 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && |
10270 | S.getLangOpts().GPUExcludeWrongSideOverloads) { |
10271 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { |
10272 | bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(D: Caller); |
10273 | bool IsCand1ImplicitHD = |
10274 | Sema::isCUDAImplicitHostDeviceFunction(D: Cand1.Function); |
10275 | bool IsCand2ImplicitHD = |
10276 | Sema::isCUDAImplicitHostDeviceFunction(D: Cand2.Function); |
10277 | auto P1 = S.IdentifyCUDAPreference(Caller, Callee: Cand1.Function); |
10278 | auto P2 = S.IdentifyCUDAPreference(Caller, Callee: Cand2.Function); |
10279 | assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); |
10280 | // The implicit HD function may be a function in a system header which |
10281 | // is forced by pragma. In device compilation, if we prefer HD candidates |
10282 | // over wrong-sided candidates, overloading resolution may change, which |
10283 | // may result in non-deferrable diagnostics. As a workaround, we let |
10284 | // implicit HD candidates take equal preference as wrong-sided candidates. |
10285 | // This will preserve the overloading resolution. |
10286 | // TODO: We still need special handling of implicit HD functions since |
10287 | // they may incur other diagnostics to be deferred. We should make all |
10288 | // host/device related diagnostics deferrable and remove special handling |
10289 | // of implicit HD functions. |
10290 | auto EmitThreshold = |
10291 | (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && |
10292 | (IsCand1ImplicitHD || IsCand2ImplicitHD)) |
10293 | ? Sema::CFP_Never |
10294 | : Sema::CFP_WrongSide; |
10295 | auto Cand1Emittable = P1 > EmitThreshold; |
10296 | auto Cand2Emittable = P2 > EmitThreshold; |
10297 | if (Cand1Emittable && !Cand2Emittable) |
10298 | return true; |
10299 | if (!Cand1Emittable && Cand2Emittable) |
10300 | return false; |
10301 | } |
10302 | } |
10303 | |
10304 | // C++ [over.match.best]p1: (Changed in C++23) |
10305 | // |
10306 | // -- if F is a static member function, ICS1(F) is defined such |
10307 | // that ICS1(F) is neither better nor worse than ICS1(G) for |
10308 | // any function G, and, symmetrically, ICS1(G) is neither |
10309 | // better nor worse than ICS1(F). |
10310 | unsigned StartArg = 0; |
10311 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) |
10312 | StartArg = 1; |
10313 | |
10314 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { |
10315 | // We don't allow incompatible pointer conversions in C++. |
10316 | if (!S.getLangOpts().CPlusPlus) |
10317 | return ICS.isStandard() && |
10318 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; |
10319 | |
10320 | // The only ill-formed conversion we allow in C++ is the string literal to |
10321 | // char* conversion, which is only considered ill-formed after C++11. |
10322 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
10323 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); |
10324 | }; |
10325 | |
10326 | // Define functions that don't require ill-formed conversions for a given |
10327 | // argument to be better candidates than functions that do. |
10328 | unsigned NumArgs = Cand1.Conversions.size(); |
10329 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch" ); |
10330 | bool HasBetterConversion = false; |
10331 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
10332 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); |
10333 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); |
10334 | if (Cand1Bad != Cand2Bad) { |
10335 | if (Cand1Bad) |
10336 | return false; |
10337 | HasBetterConversion = true; |
10338 | } |
10339 | } |
10340 | |
10341 | if (HasBetterConversion) |
10342 | return true; |
10343 | |
10344 | // C++ [over.match.best]p1: |
10345 | // A viable function F1 is defined to be a better function than another |
10346 | // viable function F2 if for all arguments i, ICSi(F1) is not a worse |
10347 | // conversion sequence than ICSi(F2), and then... |
10348 | bool HasWorseConversion = false; |
10349 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
10350 | switch (CompareImplicitConversionSequences(S, Loc, |
10351 | ICS1: Cand1.Conversions[ArgIdx], |
10352 | ICS2: Cand2.Conversions[ArgIdx])) { |
10353 | case ImplicitConversionSequence::Better: |
10354 | // Cand1 has a better conversion sequence. |
10355 | HasBetterConversion = true; |
10356 | break; |
10357 | |
10358 | case ImplicitConversionSequence::Worse: |
10359 | if (Cand1.Function && Cand2.Function && |
10360 | Cand1.isReversed() != Cand2.isReversed() && |
10361 | allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) { |
10362 | // Work around large-scale breakage caused by considering reversed |
10363 | // forms of operator== in C++20: |
10364 | // |
10365 | // When comparing a function against a reversed function, if we have a |
10366 | // better conversion for one argument and a worse conversion for the |
10367 | // other, the implicit conversion sequences are treated as being equally |
10368 | // good. |
10369 | // |
10370 | // This prevents a comparison function from being considered ambiguous |
10371 | // with a reversed form that is written in the same way. |
10372 | // |
10373 | // We diagnose this as an extension from CreateOverloadedBinOp. |
10374 | HasWorseConversion = true; |
10375 | break; |
10376 | } |
10377 | |
10378 | // Cand1 can't be better than Cand2. |
10379 | return false; |
10380 | |
10381 | case ImplicitConversionSequence::Indistinguishable: |
10382 | // Do nothing. |
10383 | break; |
10384 | } |
10385 | } |
10386 | |
10387 | // -- for some argument j, ICSj(F1) is a better conversion sequence than |
10388 | // ICSj(F2), or, if not that, |
10389 | if (HasBetterConversion && !HasWorseConversion) |
10390 | return true; |
10391 | |
10392 | // -- the context is an initialization by user-defined conversion |
10393 | // (see 8.5, 13.3.1.5) and the standard conversion sequence |
10394 | // from the return type of F1 to the destination type (i.e., |
10395 | // the type of the entity being initialized) is a better |
10396 | // conversion sequence than the standard conversion sequence |
10397 | // from the return type of F2 to the destination type. |
10398 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && |
10399 | Cand1.Function && Cand2.Function && |
10400 | isa<CXXConversionDecl>(Val: Cand1.Function) && |
10401 | isa<CXXConversionDecl>(Val: Cand2.Function)) { |
10402 | // First check whether we prefer one of the conversion functions over the |
10403 | // other. This only distinguishes the results in non-standard, extension |
10404 | // cases such as the conversion from a lambda closure type to a function |
10405 | // pointer or block. |
10406 | ImplicitConversionSequence::CompareKind Result = |
10407 | compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function); |
10408 | if (Result == ImplicitConversionSequence::Indistinguishable) |
10409 | Result = CompareStandardConversionSequences(S, Loc, |
10410 | SCS1: Cand1.FinalConversion, |
10411 | SCS2: Cand2.FinalConversion); |
10412 | |
10413 | if (Result != ImplicitConversionSequence::Indistinguishable) |
10414 | return Result == ImplicitConversionSequence::Better; |
10415 | |
10416 | // FIXME: Compare kind of reference binding if conversion functions |
10417 | // convert to a reference type used in direct reference binding, per |
10418 | // C++14 [over.match.best]p1 section 2 bullet 3. |
10419 | } |
10420 | |
10421 | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, |
10422 | // as combined with the resolution to CWG issue 243. |
10423 | // |
10424 | // When the context is initialization by constructor ([over.match.ctor] or |
10425 | // either phase of [over.match.list]), a constructor is preferred over |
10426 | // a conversion function. |
10427 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && |
10428 | Cand1.Function && Cand2.Function && |
10429 | isa<CXXConstructorDecl>(Val: Cand1.Function) != |
10430 | isa<CXXConstructorDecl>(Val: Cand2.Function)) |
10431 | return isa<CXXConstructorDecl>(Val: Cand1.Function); |
10432 | |
10433 | // -- F1 is a non-template function and F2 is a function template |
10434 | // specialization, or, if not that, |
10435 | bool Cand1IsSpecialization = Cand1.Function && |
10436 | Cand1.Function->getPrimaryTemplate(); |
10437 | bool Cand2IsSpecialization = Cand2.Function && |
10438 | Cand2.Function->getPrimaryTemplate(); |
10439 | if (Cand1IsSpecialization != Cand2IsSpecialization) |
10440 | return Cand2IsSpecialization; |
10441 | |
10442 | // -- F1 and F2 are function template specializations, and the function |
10443 | // template for F1 is more specialized than the template for F2 |
10444 | // according to the partial ordering rules described in 14.5.5.2, or, |
10445 | // if not that, |
10446 | if (Cand1IsSpecialization && Cand2IsSpecialization) { |
10447 | if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( |
10448 | FT1: Cand1.Function->getPrimaryTemplate(), |
10449 | FT2: Cand2.Function->getPrimaryTemplate(), Loc, |
10450 | TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion |
10451 | : TPOC_Call, |
10452 | NumCallArguments1: Cand1.ExplicitCallArguments, NumCallArguments2: Cand2.ExplicitCallArguments, |
10453 | Reversed: Cand1.isReversed() ^ Cand2.isReversed())) |
10454 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); |
10455 | } |
10456 | |
10457 | // -— F1 and F2 are non-template functions with the same |
10458 | // parameter-type-lists, and F1 is more constrained than F2 [...], |
10459 | if (!Cand1IsSpecialization && !Cand2IsSpecialization && |
10460 | sameFunctionParameterTypeLists(S, Cand1, Cand2)) { |
10461 | FunctionDecl *Function1 = Cand1.Function; |
10462 | FunctionDecl *Function2 = Cand2.Function; |
10463 | if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction()) |
10464 | Function1 = MF; |
10465 | if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction()) |
10466 | Function2 = MF; |
10467 | |
10468 | const Expr *RC1 = Function1->getTrailingRequiresClause(); |
10469 | const Expr *RC2 = Function2->getTrailingRequiresClause(); |
10470 | if (RC1 && RC2) { |
10471 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
10472 | if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2, |
10473 | AtLeastAsConstrained1) || |
10474 | S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1, |
10475 | AtLeastAsConstrained2)) |
10476 | return false; |
10477 | if (AtLeastAsConstrained1 != AtLeastAsConstrained2) |
10478 | return AtLeastAsConstrained1; |
10479 | } else if (RC1 || RC2) { |
10480 | return RC1 != nullptr; |
10481 | } |
10482 | } |
10483 | |
10484 | // -- F1 is a constructor for a class D, F2 is a constructor for a base |
10485 | // class B of D, and for all arguments the corresponding parameters of |
10486 | // F1 and F2 have the same type. |
10487 | // FIXME: Implement the "all parameters have the same type" check. |
10488 | bool Cand1IsInherited = |
10489 | isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl()); |
10490 | bool Cand2IsInherited = |
10491 | isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl()); |
10492 | if (Cand1IsInherited != Cand2IsInherited) |
10493 | return Cand2IsInherited; |
10494 | else if (Cand1IsInherited) { |
10495 | assert(Cand2IsInherited); |
10496 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); |
10497 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); |
10498 | if (Cand1Class->isDerivedFrom(Cand2Class)) |
10499 | return true; |
10500 | if (Cand2Class->isDerivedFrom(Cand1Class)) |
10501 | return false; |
10502 | // Inherited from sibling base classes: still ambiguous. |
10503 | } |
10504 | |
10505 | // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not |
10506 | // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate |
10507 | // with reversed order of parameters and F1 is not |
10508 | // |
10509 | // We rank reversed + different operator as worse than just reversed, but |
10510 | // that comparison can never happen, because we only consider reversing for |
10511 | // the maximally-rewritten operator (== or <=>). |
10512 | if (Cand1.RewriteKind != Cand2.RewriteKind) |
10513 | return Cand1.RewriteKind < Cand2.RewriteKind; |
10514 | |
10515 | // Check C++17 tie-breakers for deduction guides. |
10516 | { |
10517 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function); |
10518 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function); |
10519 | if (Guide1 && Guide2) { |
10520 | // -- F1 is generated from a deduction-guide and F2 is not |
10521 | if (Guide1->isImplicit() != Guide2->isImplicit()) |
10522 | return Guide2->isImplicit(); |
10523 | |
10524 | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not |
10525 | if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy) |
10526 | return true; |
10527 | if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy) |
10528 | return false; |
10529 | |
10530 | // --F1 is generated from a non-template constructor and F2 is generated |
10531 | // from a constructor template |
10532 | const auto *Constructor1 = Guide1->getCorrespondingConstructor(); |
10533 | const auto *Constructor2 = Guide2->getCorrespondingConstructor(); |
10534 | if (Constructor1 && Constructor2) { |
10535 | bool isC1Templated = Constructor1->getTemplatedKind() != |
10536 | FunctionDecl::TemplatedKind::TK_NonTemplate; |
10537 | bool isC2Templated = Constructor2->getTemplatedKind() != |
10538 | FunctionDecl::TemplatedKind::TK_NonTemplate; |
10539 | if (isC1Templated != isC2Templated) |
10540 | return isC2Templated; |
10541 | } |
10542 | } |
10543 | } |
10544 | |
10545 | // Check for enable_if value-based overload resolution. |
10546 | if (Cand1.Function && Cand2.Function) { |
10547 | Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function); |
10548 | if (Cmp != Comparison::Equal) |
10549 | return Cmp == Comparison::Better; |
10550 | } |
10551 | |
10552 | bool HasPS1 = Cand1.Function != nullptr && |
10553 | functionHasPassObjectSizeParams(FD: Cand1.Function); |
10554 | bool HasPS2 = Cand2.Function != nullptr && |
10555 | functionHasPassObjectSizeParams(FD: Cand2.Function); |
10556 | if (HasPS1 != HasPS2 && HasPS1) |
10557 | return true; |
10558 | |
10559 | auto MV = isBetterMultiversionCandidate(Cand1, Cand2); |
10560 | if (MV == Comparison::Better) |
10561 | return true; |
10562 | if (MV == Comparison::Worse) |
10563 | return false; |
10564 | |
10565 | // If other rules cannot determine which is better, CUDA preference is used |
10566 | // to determine which is better. |
10567 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { |
10568 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10569 | return S.IdentifyCUDAPreference(Caller, Callee: Cand1.Function) > |
10570 | S.IdentifyCUDAPreference(Caller, Callee: Cand2.Function); |
10571 | } |
10572 | |
10573 | // General member function overloading is handled above, so this only handles |
10574 | // constructors with address spaces. |
10575 | // This only handles address spaces since C++ has no other |
10576 | // qualifier that can be used with constructors. |
10577 | const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function); |
10578 | const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function); |
10579 | if (CD1 && CD2) { |
10580 | LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); |
10581 | LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); |
10582 | if (AS1 != AS2) { |
10583 | if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1)) |
10584 | return true; |
10585 | if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2)) |
10586 | return false; |
10587 | } |
10588 | } |
10589 | |
10590 | return false; |
10591 | } |
10592 | |
10593 | /// Determine whether two declarations are "equivalent" for the purposes of |
10594 | /// name lookup and overload resolution. This applies when the same internal/no |
10595 | /// linkage entity is defined by two modules (probably by textually including |
10596 | /// the same header). In such a case, we don't consider the declarations to |
10597 | /// declare the same entity, but we also don't want lookups with both |
10598 | /// declarations visible to be ambiguous in some cases (this happens when using |
10599 | /// a modularized libstdc++). |
10600 | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
10601 | const NamedDecl *B) { |
10602 | auto *VA = dyn_cast_or_null<ValueDecl>(Val: A); |
10603 | auto *VB = dyn_cast_or_null<ValueDecl>(Val: B); |
10604 | if (!VA || !VB) |
10605 | return false; |
10606 | |
10607 | // The declarations must be declaring the same name as an internal linkage |
10608 | // entity in different modules. |
10609 | if (!VA->getDeclContext()->getRedeclContext()->Equals( |
10610 | VB->getDeclContext()->getRedeclContext()) || |
10611 | getOwningModule(VA) == getOwningModule(VB) || |
10612 | VA->isExternallyVisible() || VB->isExternallyVisible()) |
10613 | return false; |
10614 | |
10615 | // Check that the declarations appear to be equivalent. |
10616 | // |
10617 | // FIXME: Checking the type isn't really enough to resolve the ambiguity. |
10618 | // For constants and functions, we should check the initializer or body is |
10619 | // the same. For non-constant variables, we shouldn't allow it at all. |
10620 | if (Context.hasSameType(T1: VA->getType(), T2: VB->getType())) |
10621 | return true; |
10622 | |
10623 | // Enum constants within unnamed enumerations will have different types, but |
10624 | // may still be similar enough to be interchangeable for our purposes. |
10625 | if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) { |
10626 | if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) { |
10627 | // Only handle anonymous enums. If the enumerations were named and |
10628 | // equivalent, they would have been merged to the same type. |
10629 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); |
10630 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); |
10631 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || |
10632 | !Context.hasSameType(EnumA->getIntegerType(), |
10633 | EnumB->getIntegerType())) |
10634 | return false; |
10635 | // Allow this only if the value is the same for both enumerators. |
10636 | return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal()); |
10637 | } |
10638 | } |
10639 | |
10640 | // Nothing else is sufficiently similar. |
10641 | return false; |
10642 | } |
10643 | |
10644 | void Sema::diagnoseEquivalentInternalLinkageDeclarations( |
10645 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { |
10646 | assert(D && "Unknown declaration" ); |
10647 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; |
10648 | |
10649 | Module *M = getOwningModule(D); |
10650 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10651 | << !M << (M ? M->getFullModuleName() : "" ); |
10652 | |
10653 | for (auto *E : Equiv) { |
10654 | Module *M = getOwningModule(E); |
10655 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10656 | << !M << (M ? M->getFullModuleName() : "" ); |
10657 | } |
10658 | } |
10659 | |
10660 | bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { |
10661 | return FailureKind == ovl_fail_bad_deduction && |
10662 | static_cast<TemplateDeductionResult>(DeductionFailure.Result) == |
10663 | TemplateDeductionResult::ConstraintsNotSatisfied && |
10664 | static_cast<CNSInfo *>(DeductionFailure.Data) |
10665 | ->Satisfaction.ContainsErrors; |
10666 | } |
10667 | |
10668 | /// Computes the best viable function (C++ 13.3.3) |
10669 | /// within an overload candidate set. |
10670 | /// |
10671 | /// \param Loc The location of the function name (or operator symbol) for |
10672 | /// which overload resolution occurs. |
10673 | /// |
10674 | /// \param Best If overload resolution was successful or found a deleted |
10675 | /// function, \p Best points to the candidate function found. |
10676 | /// |
10677 | /// \returns The result of overload resolution. |
10678 | OverloadingResult |
10679 | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, |
10680 | iterator &Best) { |
10681 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; |
10682 | std::transform(first: begin(), last: end(), result: std::back_inserter(x&: Candidates), |
10683 | unary_op: [](OverloadCandidate &Cand) { return &Cand; }); |
10684 | |
10685 | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but |
10686 | // are accepted by both clang and NVCC. However, during a particular |
10687 | // compilation mode only one call variant is viable. We need to |
10688 | // exclude non-viable overload candidates from consideration based |
10689 | // only on their host/device attributes. Specifically, if one |
10690 | // candidate call is WrongSide and the other is SameSide, we ignore |
10691 | // the WrongSide candidate. |
10692 | // We only need to remove wrong-sided candidates here if |
10693 | // -fgpu-exclude-wrong-side-overloads is off. When |
10694 | // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared |
10695 | // uniformly in isBetterOverloadCandidate. |
10696 | if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { |
10697 | const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10698 | bool ContainsSameSideCandidate = |
10699 | llvm::any_of(Range&: Candidates, P: [&](OverloadCandidate *Cand) { |
10700 | // Check viable function only. |
10701 | return Cand->Viable && Cand->Function && |
10702 | S.IdentifyCUDAPreference(Caller, Callee: Cand->Function) == |
10703 | Sema::CFP_SameSide; |
10704 | }); |
10705 | if (ContainsSameSideCandidate) { |
10706 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { |
10707 | // Check viable function only to avoid unnecessary data copying/moving. |
10708 | return Cand->Viable && Cand->Function && |
10709 | S.IdentifyCUDAPreference(Caller, Callee: Cand->Function) == |
10710 | Sema::CFP_WrongSide; |
10711 | }; |
10712 | llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate); |
10713 | } |
10714 | } |
10715 | |
10716 | // Find the best viable function. |
10717 | Best = end(); |
10718 | for (auto *Cand : Candidates) { |
10719 | Cand->Best = false; |
10720 | if (Cand->Viable) { |
10721 | if (Best == end() || |
10722 | isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind)) |
10723 | Best = Cand; |
10724 | } else if (Cand->NotValidBecauseConstraintExprHasError()) { |
10725 | // This candidate has constraint that we were unable to evaluate because |
10726 | // it referenced an expression that contained an error. Rather than fall |
10727 | // back onto a potentially unintended candidate (made worse by |
10728 | // subsuming constraints), treat this as 'no viable candidate'. |
10729 | Best = end(); |
10730 | return OR_No_Viable_Function; |
10731 | } |
10732 | } |
10733 | |
10734 | // If we didn't find any viable functions, abort. |
10735 | if (Best == end()) |
10736 | return OR_No_Viable_Function; |
10737 | |
10738 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; |
10739 | |
10740 | llvm::SmallVector<OverloadCandidate*, 4> PendingBest; |
10741 | PendingBest.push_back(Elt: &*Best); |
10742 | Best->Best = true; |
10743 | |
10744 | // Make sure that this function is better than every other viable |
10745 | // function. If not, we have an ambiguity. |
10746 | while (!PendingBest.empty()) { |
10747 | auto *Curr = PendingBest.pop_back_val(); |
10748 | for (auto *Cand : Candidates) { |
10749 | if (Cand->Viable && !Cand->Best && |
10750 | !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) { |
10751 | PendingBest.push_back(Elt: Cand); |
10752 | Cand->Best = true; |
10753 | |
10754 | if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, |
10755 | Curr->Function)) |
10756 | EquivalentCands.push_back(Cand->Function); |
10757 | else |
10758 | Best = end(); |
10759 | } |
10760 | } |
10761 | } |
10762 | |
10763 | // If we found more than one best candidate, this is ambiguous. |
10764 | if (Best == end()) |
10765 | return OR_Ambiguous; |
10766 | |
10767 | // Best is the best viable function. |
10768 | if (Best->Function && Best->Function->isDeleted()) |
10769 | return OR_Deleted; |
10770 | |
10771 | if (!EquivalentCands.empty()) |
10772 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, |
10773 | EquivalentCands); |
10774 | |
10775 | return OR_Success; |
10776 | } |
10777 | |
10778 | namespace { |
10779 | |
10780 | enum OverloadCandidateKind { |
10781 | oc_function, |
10782 | oc_method, |
10783 | oc_reversed_binary_operator, |
10784 | oc_constructor, |
10785 | oc_implicit_default_constructor, |
10786 | oc_implicit_copy_constructor, |
10787 | oc_implicit_move_constructor, |
10788 | oc_implicit_copy_assignment, |
10789 | oc_implicit_move_assignment, |
10790 | oc_implicit_equality_comparison, |
10791 | oc_inherited_constructor |
10792 | }; |
10793 | |
10794 | enum OverloadCandidateSelect { |
10795 | ocs_non_template, |
10796 | ocs_template, |
10797 | ocs_described_template, |
10798 | }; |
10799 | |
10800 | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> |
10801 | ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, |
10802 | const FunctionDecl *Fn, |
10803 | OverloadCandidateRewriteKind CRK, |
10804 | std::string &Description) { |
10805 | |
10806 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); |
10807 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { |
10808 | isTemplate = true; |
10809 | Description = S.getTemplateArgumentBindingsText( |
10810 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); |
10811 | } |
10812 | |
10813 | OverloadCandidateSelect Select = [&]() { |
10814 | if (!Description.empty()) |
10815 | return ocs_described_template; |
10816 | return isTemplate ? ocs_template : ocs_non_template; |
10817 | }(); |
10818 | |
10819 | OverloadCandidateKind Kind = [&]() { |
10820 | if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) |
10821 | return oc_implicit_equality_comparison; |
10822 | |
10823 | if (CRK & CRK_Reversed) |
10824 | return oc_reversed_binary_operator; |
10825 | |
10826 | if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) { |
10827 | if (!Ctor->isImplicit()) { |
10828 | if (isa<ConstructorUsingShadowDecl>(Val: Found)) |
10829 | return oc_inherited_constructor; |
10830 | else |
10831 | return oc_constructor; |
10832 | } |
10833 | |
10834 | if (Ctor->isDefaultConstructor()) |
10835 | return oc_implicit_default_constructor; |
10836 | |
10837 | if (Ctor->isMoveConstructor()) |
10838 | return oc_implicit_move_constructor; |
10839 | |
10840 | assert(Ctor->isCopyConstructor() && |
10841 | "unexpected sort of implicit constructor" ); |
10842 | return oc_implicit_copy_constructor; |
10843 | } |
10844 | |
10845 | if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) { |
10846 | // This actually gets spelled 'candidate function' for now, but |
10847 | // it doesn't hurt to split it out. |
10848 | if (!Meth->isImplicit()) |
10849 | return oc_method; |
10850 | |
10851 | if (Meth->isMoveAssignmentOperator()) |
10852 | return oc_implicit_move_assignment; |
10853 | |
10854 | if (Meth->isCopyAssignmentOperator()) |
10855 | return oc_implicit_copy_assignment; |
10856 | |
10857 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion" ); |
10858 | return oc_method; |
10859 | } |
10860 | |
10861 | return oc_function; |
10862 | }(); |
10863 | |
10864 | return std::make_pair(x&: Kind, y&: Select); |
10865 | } |
10866 | |
10867 | void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { |
10868 | // FIXME: It'd be nice to only emit a note once per using-decl per overload |
10869 | // set. |
10870 | if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) |
10871 | S.Diag(FoundDecl->getLocation(), |
10872 | diag::note_ovl_candidate_inherited_constructor) |
10873 | << Shadow->getNominatedBaseClass(); |
10874 | } |
10875 | |
10876 | } // end anonymous namespace |
10877 | |
10878 | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, |
10879 | const FunctionDecl *FD) { |
10880 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { |
10881 | bool AlwaysTrue; |
10882 | if (EnableIf->getCond()->isValueDependent() || |
10883 | !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) |
10884 | return false; |
10885 | if (!AlwaysTrue) |
10886 | return false; |
10887 | } |
10888 | return true; |
10889 | } |
10890 | |
10891 | /// Returns true if we can take the address of the function. |
10892 | /// |
10893 | /// \param Complain - If true, we'll emit a diagnostic |
10894 | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are |
10895 | /// we in overload resolution? |
10896 | /// \param Loc - The location of the statement we're complaining about. Ignored |
10897 | /// if we're not complaining, or if we're in overload resolution. |
10898 | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, |
10899 | bool Complain, |
10900 | bool InOverloadResolution, |
10901 | SourceLocation Loc) { |
10902 | if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) { |
10903 | if (Complain) { |
10904 | if (InOverloadResolution) |
10905 | S.Diag(FD->getBeginLoc(), |
10906 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); |
10907 | else |
10908 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; |
10909 | } |
10910 | return false; |
10911 | } |
10912 | |
10913 | if (FD->getTrailingRequiresClause()) { |
10914 | ConstraintSatisfaction Satisfaction; |
10915 | if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc)) |
10916 | return false; |
10917 | if (!Satisfaction.IsSatisfied) { |
10918 | if (Complain) { |
10919 | if (InOverloadResolution) { |
10920 | SmallString<128> TemplateArgString; |
10921 | if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { |
10922 | TemplateArgString += " " ; |
10923 | TemplateArgString += S.getTemplateArgumentBindingsText( |
10924 | FunTmpl->getTemplateParameters(), |
10925 | *FD->getTemplateSpecializationArgs()); |
10926 | } |
10927 | |
10928 | S.Diag(FD->getBeginLoc(), |
10929 | diag::note_ovl_candidate_unsatisfied_constraints) |
10930 | << TemplateArgString; |
10931 | } else |
10932 | S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) |
10933 | << FD; |
10934 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
10935 | } |
10936 | return false; |
10937 | } |
10938 | } |
10939 | |
10940 | auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) { |
10941 | return P->hasAttr<PassObjectSizeAttr>(); |
10942 | }); |
10943 | if (I == FD->param_end()) |
10944 | return true; |
10945 | |
10946 | if (Complain) { |
10947 | // Add one to ParamNo because it's user-facing |
10948 | unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1; |
10949 | if (InOverloadResolution) |
10950 | S.Diag(FD->getLocation(), |
10951 | diag::note_ovl_candidate_has_pass_object_size_params) |
10952 | << ParamNo; |
10953 | else |
10954 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) |
10955 | << FD << ParamNo; |
10956 | } |
10957 | return false; |
10958 | } |
10959 | |
10960 | static bool checkAddressOfCandidateIsAvailable(Sema &S, |
10961 | const FunctionDecl *FD) { |
10962 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, |
10963 | /*InOverloadResolution=*/true, |
10964 | /*Loc=*/SourceLocation()); |
10965 | } |
10966 | |
10967 | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
10968 | bool Complain, |
10969 | SourceLocation Loc) { |
10970 | return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain, |
10971 | /*InOverloadResolution=*/false, |
10972 | Loc); |
10973 | } |
10974 | |
10975 | // Don't print candidates other than the one that matches the calling |
10976 | // convention of the call operator, since that is guaranteed to exist. |
10977 | static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { |
10978 | const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn); |
10979 | |
10980 | if (!ConvD) |
10981 | return false; |
10982 | const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); |
10983 | if (!RD->isLambda()) |
10984 | return false; |
10985 | |
10986 | CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); |
10987 | CallingConv CallOpCC = |
10988 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
10989 | QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); |
10990 | CallingConv ConvToCC = |
10991 | ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); |
10992 | |
10993 | return ConvToCC != CallOpCC; |
10994 | } |
10995 | |
10996 | // Notes the location of an overload candidate. |
10997 | void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, |
10998 | OverloadCandidateRewriteKind RewriteKind, |
10999 | QualType DestType, bool TakingAddress) { |
11000 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn)) |
11001 | return; |
11002 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && |
11003 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) |
11004 | return; |
11005 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && |
11006 | !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) |
11007 | return; |
11008 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
11009 | return; |
11010 | |
11011 | std::string FnDesc; |
11012 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = |
11013 | ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc); |
11014 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) |
11015 | << (unsigned)KSPair.first << (unsigned)KSPair.second |
11016 | << Fn << FnDesc; |
11017 | |
11018 | HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType); |
11019 | Diag(Fn->getLocation(), PD); |
11020 | MaybeEmitInheritedConstructorNote(*this, Found); |
11021 | } |
11022 | |
11023 | static void |
11024 | MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { |
11025 | // Perhaps the ambiguity was caused by two atomic constraints that are |
11026 | // 'identical' but not equivalent: |
11027 | // |
11028 | // void foo() requires (sizeof(T) > 4) { } // #1 |
11029 | // void foo() requires (sizeof(T) > 4) && T::value { } // #2 |
11030 | // |
11031 | // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause |
11032 | // #2 to subsume #1, but these constraint are not considered equivalent |
11033 | // according to the subsumption rules because they are not the same |
11034 | // source-level construct. This behavior is quite confusing and we should try |
11035 | // to help the user figure out what happened. |
11036 | |
11037 | SmallVector<const Expr *, 3> FirstAC, SecondAC; |
11038 | FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; |
11039 | for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
11040 | if (!I->Function) |
11041 | continue; |
11042 | SmallVector<const Expr *, 3> AC; |
11043 | if (auto *Template = I->Function->getPrimaryTemplate()) |
11044 | Template->getAssociatedConstraints(AC); |
11045 | else |
11046 | I->Function->getAssociatedConstraints(AC); |
11047 | if (AC.empty()) |
11048 | continue; |
11049 | if (FirstCand == nullptr) { |
11050 | FirstCand = I->Function; |
11051 | FirstAC = AC; |
11052 | } else if (SecondCand == nullptr) { |
11053 | SecondCand = I->Function; |
11054 | SecondAC = AC; |
11055 | } else { |
11056 | // We have more than one pair of constrained functions - this check is |
11057 | // expensive and we'd rather not try to diagnose it. |
11058 | return; |
11059 | } |
11060 | } |
11061 | if (!SecondCand) |
11062 | return; |
11063 | // The diagnostic can only happen if there are associated constraints on |
11064 | // both sides (there needs to be some identical atomic constraint). |
11065 | if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, |
11066 | SecondCand, SecondAC)) |
11067 | // Just show the user one diagnostic, they'll probably figure it out |
11068 | // from here. |
11069 | return; |
11070 | } |
11071 | |
11072 | // Notes the location of all overload candidates designated through |
11073 | // OverloadedExpr |
11074 | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, |
11075 | bool TakingAddress) { |
11076 | assert(OverloadedExpr->getType() == Context.OverloadTy); |
11077 | |
11078 | OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr); |
11079 | OverloadExpr *OvlExpr = Ovl.Expression; |
11080 | |
11081 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
11082 | IEnd = OvlExpr->decls_end(); |
11083 | I != IEnd; ++I) { |
11084 | if (FunctionTemplateDecl *FunTmpl = |
11085 | dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) { |
11086 | NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType, |
11087 | TakingAddress); |
11088 | } else if (FunctionDecl *Fun |
11089 | = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) { |
11090 | NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress); |
11091 | } |
11092 | } |
11093 | } |
11094 | |
11095 | /// Diagnoses an ambiguous conversion. The partial diagnostic is the |
11096 | /// "lead" diagnostic; it will be given two arguments, the source and |
11097 | /// target types of the conversion. |
11098 | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( |
11099 | Sema &S, |
11100 | SourceLocation CaretLoc, |
11101 | const PartialDiagnostic &PDiag) const { |
11102 | S.Diag(Loc: CaretLoc, PD: PDiag) |
11103 | << Ambiguous.getFromType() << Ambiguous.getToType(); |
11104 | unsigned CandsShown = 0; |
11105 | AmbiguousConversionSequence::const_iterator I, E; |
11106 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { |
11107 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) |
11108 | break; |
11109 | ++CandsShown; |
11110 | S.NoteOverloadCandidate(Found: I->first, Fn: I->second); |
11111 | } |
11112 | S.Diags.overloadCandidatesShown(N: CandsShown); |
11113 | if (I != E) |
11114 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); |
11115 | } |
11116 | |
11117 | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, |
11118 | unsigned I, bool TakingCandidateAddress) { |
11119 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; |
11120 | assert(Conv.isBad()); |
11121 | assert(Cand->Function && "for now, candidate must be a function" ); |
11122 | FunctionDecl *Fn = Cand->Function; |
11123 | |
11124 | // There's a conversion slot for the object argument if this is a |
11125 | // non-constructor method. Note that 'I' corresponds the |
11126 | // conversion-slot index. |
11127 | bool isObjectArgument = false; |
11128 | if (isa<CXXMethodDecl>(Val: Fn) && !isa<CXXConstructorDecl>(Val: Fn)) { |
11129 | if (I == 0) |
11130 | isObjectArgument = true; |
11131 | else |
11132 | I--; |
11133 | } |
11134 | |
11135 | std::string FnDesc; |
11136 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11137 | ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(), |
11138 | Description&: FnDesc); |
11139 | |
11140 | Expr *FromExpr = Conv.Bad.FromExpr; |
11141 | QualType FromTy = Conv.Bad.getFromType(); |
11142 | QualType ToTy = Conv.Bad.getToType(); |
11143 | SourceRange ToParamRange = |
11144 | !isObjectArgument ? Fn->getParamDecl(i: I)->getSourceRange() : SourceRange(); |
11145 | |
11146 | if (FromTy == S.Context.OverloadTy) { |
11147 | assert(FromExpr && "overload set argument came from implicit argument?" ); |
11148 | Expr *E = FromExpr->IgnoreParens(); |
11149 | if (isa<UnaryOperator>(Val: E)) |
11150 | E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens(); |
11151 | DeclarationName Name = cast<OverloadExpr>(Val: E)->getName(); |
11152 | |
11153 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) |
11154 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11155 | << ToParamRange << ToTy << Name << I + 1; |
11156 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11157 | return; |
11158 | } |
11159 | |
11160 | // Do some hand-waving analysis to see if the non-viability is due |
11161 | // to a qualifier mismatch. |
11162 | CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy); |
11163 | CanQualType CToTy = S.Context.getCanonicalType(T: ToTy); |
11164 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) |
11165 | CToTy = RT->getPointeeType(); |
11166 | else { |
11167 | // TODO: detect and diagnose the full richness of const mismatches. |
11168 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) |
11169 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { |
11170 | CFromTy = FromPT->getPointeeType(); |
11171 | CToTy = ToPT->getPointeeType(); |
11172 | } |
11173 | } |
11174 | |
11175 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && |
11176 | !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy)) { |
11177 | Qualifiers FromQs = CFromTy.getQualifiers(); |
11178 | Qualifiers ToQs = CToTy.getQualifiers(); |
11179 | |
11180 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { |
11181 | if (isObjectArgument) |
11182 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) |
11183 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11184 | << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace(); |
11185 | else |
11186 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) |
11187 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11188 | << FnDesc << ToParamRange << FromQs.getAddressSpace() |
11189 | << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1; |
11190 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11191 | return; |
11192 | } |
11193 | |
11194 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
11195 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) |
11196 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11197 | << ToParamRange << FromTy << FromQs.getObjCLifetime() |
11198 | << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1; |
11199 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11200 | return; |
11201 | } |
11202 | |
11203 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { |
11204 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) |
11205 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11206 | << ToParamRange << FromTy << FromQs.getObjCGCAttr() |
11207 | << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1; |
11208 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11209 | return; |
11210 | } |
11211 | |
11212 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
11213 | assert(CVR && "expected qualifiers mismatch" ); |
11214 | |
11215 | if (isObjectArgument) { |
11216 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) |
11217 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11218 | << FromTy << (CVR - 1); |
11219 | } else { |
11220 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) |
11221 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11222 | << ToParamRange << FromTy << (CVR - 1) << I + 1; |
11223 | } |
11224 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11225 | return; |
11226 | } |
11227 | |
11228 | if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || |
11229 | Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { |
11230 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) |
11231 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11232 | << (unsigned)isObjectArgument << I + 1 |
11233 | << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) |
11234 | << ToParamRange; |
11235 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11236 | return; |
11237 | } |
11238 | |
11239 | // Special diagnostic for failure to convert an initializer list, since |
11240 | // telling the user that it has type void is not useful. |
11241 | if (FromExpr && isa<InitListExpr>(Val: FromExpr)) { |
11242 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) |
11243 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11244 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11245 | << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 |
11246 | : Conv.Bad.Kind == BadConversionSequence::too_many_initializers |
11247 | ? 2 |
11248 | : 0); |
11249 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11250 | return; |
11251 | } |
11252 | |
11253 | // Diagnose references or pointers to incomplete types differently, |
11254 | // since it's far from impossible that the incompleteness triggered |
11255 | // the failure. |
11256 | QualType TempFromTy = FromTy.getNonReferenceType(); |
11257 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) |
11258 | TempFromTy = PTy->getPointeeType(); |
11259 | if (TempFromTy->isIncompleteType()) { |
11260 | // Emit the generic diagnostic and, optionally, add the hints to it. |
11261 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) |
11262 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11263 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11264 | << (unsigned)(Cand->Fix.Kind); |
11265 | |
11266 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11267 | return; |
11268 | } |
11269 | |
11270 | // Diagnose base -> derived pointer conversions. |
11271 | unsigned BaseToDerivedConversion = 0; |
11272 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { |
11273 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { |
11274 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
11275 | other: FromPtrTy->getPointeeType()) && |
11276 | !FromPtrTy->getPointeeType()->isIncompleteType() && |
11277 | !ToPtrTy->getPointeeType()->isIncompleteType() && |
11278 | S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(), |
11279 | Base: FromPtrTy->getPointeeType())) |
11280 | BaseToDerivedConversion = 1; |
11281 | } |
11282 | } else if (const ObjCObjectPointerType *FromPtrTy |
11283 | = FromTy->getAs<ObjCObjectPointerType>()) { |
11284 | if (const ObjCObjectPointerType *ToPtrTy |
11285 | = ToTy->getAs<ObjCObjectPointerType>()) |
11286 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) |
11287 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) |
11288 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
11289 | other: FromPtrTy->getPointeeType()) && |
11290 | FromIface->isSuperClassOf(I: ToIface)) |
11291 | BaseToDerivedConversion = 2; |
11292 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { |
11293 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy) && |
11294 | !FromTy->isIncompleteType() && |
11295 | !ToRefTy->getPointeeType()->isIncompleteType() && |
11296 | S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) { |
11297 | BaseToDerivedConversion = 3; |
11298 | } |
11299 | } |
11300 | |
11301 | if (BaseToDerivedConversion) { |
11302 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) |
11303 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11304 | << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy |
11305 | << I + 1; |
11306 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11307 | return; |
11308 | } |
11309 | |
11310 | if (isa<ObjCObjectPointerType>(Val: CFromTy) && |
11311 | isa<PointerType>(Val: CToTy)) { |
11312 | Qualifiers FromQs = CFromTy.getQualifiers(); |
11313 | Qualifiers ToQs = CToTy.getQualifiers(); |
11314 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
11315 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) |
11316 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11317 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument |
11318 | << I + 1; |
11319 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11320 | return; |
11321 | } |
11322 | } |
11323 | |
11324 | if (TakingCandidateAddress && |
11325 | !checkAddressOfCandidateIsAvailable(S, FD: Cand->Function)) |
11326 | return; |
11327 | |
11328 | // Emit the generic diagnostic and, optionally, add the hints to it. |
11329 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); |
11330 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11331 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11332 | << (unsigned)(Cand->Fix.Kind); |
11333 | |
11334 | // Check that location of Fn is not in system header. |
11335 | if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) { |
11336 | // If we can fix the conversion, suggest the FixIts. |
11337 | for (const FixItHint &HI : Cand->Fix.Hints) |
11338 | FDiag << HI; |
11339 | } |
11340 | |
11341 | S.Diag(Fn->getLocation(), FDiag); |
11342 | |
11343 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11344 | } |
11345 | |
11346 | /// Additional arity mismatch diagnosis specific to a function overload |
11347 | /// candidates. This is not covered by the more general DiagnoseArityMismatch() |
11348 | /// over a candidate in any candidate set. |
11349 | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, |
11350 | unsigned NumArgs) { |
11351 | FunctionDecl *Fn = Cand->Function; |
11352 | unsigned MinParams = Fn->getMinRequiredArguments(); |
11353 | |
11354 | // With invalid overloaded operators, it's possible that we think we |
11355 | // have an arity mismatch when in fact it looks like we have the |
11356 | // right number of arguments, because only overloaded operators have |
11357 | // the weird behavior of overloading member and non-member functions. |
11358 | // Just don't report anything. |
11359 | if (Fn->isInvalidDecl() && |
11360 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) |
11361 | return true; |
11362 | |
11363 | if (NumArgs < MinParams) { |
11364 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) || |
11365 | (Cand->FailureKind == ovl_fail_bad_deduction && |
11366 | Cand->DeductionFailure.getResult() == |
11367 | TemplateDeductionResult::TooFewArguments)); |
11368 | } else { |
11369 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) || |
11370 | (Cand->FailureKind == ovl_fail_bad_deduction && |
11371 | Cand->DeductionFailure.getResult() == |
11372 | TemplateDeductionResult::TooManyArguments)); |
11373 | } |
11374 | |
11375 | return false; |
11376 | } |
11377 | |
11378 | /// General arity mismatch diagnosis over a candidate in a candidate set. |
11379 | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, |
11380 | unsigned NumFormalArgs) { |
11381 | assert(isa<FunctionDecl>(D) && |
11382 | "The templated declaration should at least be a function" |
11383 | " when diagnosing bad template argument deduction due to too many" |
11384 | " or too few arguments" ); |
11385 | |
11386 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
11387 | |
11388 | // TODO: treat calls to a missing default constructor as a special case |
11389 | const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); |
11390 | unsigned MinParams = Fn->getMinRequiredExplicitArguments(); |
11391 | |
11392 | // at least / at most / exactly |
11393 | bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter(); |
11394 | unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0); |
11395 | unsigned mode, modeCount; |
11396 | if (NumFormalArgs < MinParams) { |
11397 | if (MinParams != ParamCount || FnTy->isVariadic() || |
11398 | FnTy->isTemplateVariadic()) |
11399 | mode = 0; // "at least" |
11400 | else |
11401 | mode = 2; // "exactly" |
11402 | modeCount = MinParams; |
11403 | } else { |
11404 | if (MinParams != ParamCount) |
11405 | mode = 1; // "at most" |
11406 | else |
11407 | mode = 2; // "exactly" |
11408 | modeCount = ParamCount; |
11409 | } |
11410 | |
11411 | std::string Description; |
11412 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11413 | ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description); |
11414 | |
11415 | if (modeCount == 1 && |
11416 | Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName()) |
11417 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) |
11418 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11419 | << Description << mode |
11420 | << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs |
11421 | << HasExplicitObjectParam << Fn->getParametersSourceRange(); |
11422 | else |
11423 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) |
11424 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11425 | << Description << mode << modeCount << NumFormalArgs |
11426 | << HasExplicitObjectParam << Fn->getParametersSourceRange(); |
11427 | |
11428 | MaybeEmitInheritedConstructorNote(S, Found); |
11429 | } |
11430 | |
11431 | /// Arity mismatch diagnosis specific to a function overload candidate. |
11432 | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, |
11433 | unsigned NumFormalArgs) { |
11434 | if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs)) |
11435 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); |
11436 | } |
11437 | |
11438 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { |
11439 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) |
11440 | return TD; |
11441 | llvm_unreachable("Unsupported: Getting the described template declaration" |
11442 | " for bad deduction diagnosis" ); |
11443 | } |
11444 | |
11445 | /// Diagnose a failed template-argument deduction. |
11446 | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, |
11447 | DeductionFailureInfo &DeductionFailure, |
11448 | unsigned NumArgs, |
11449 | bool TakingCandidateAddress) { |
11450 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); |
11451 | NamedDecl *ParamD; |
11452 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || |
11453 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || |
11454 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); |
11455 | switch (DeductionFailure.getResult()) { |
11456 | case TemplateDeductionResult::Success: |
11457 | llvm_unreachable( |
11458 | "TemplateDeductionResult::Success while diagnosing bad deduction" ); |
11459 | case TemplateDeductionResult::NonDependentConversionFailure: |
11460 | llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure " |
11461 | "while diagnosing bad deduction" ); |
11462 | case TemplateDeductionResult::Invalid: |
11463 | case TemplateDeductionResult::AlreadyDiagnosed: |
11464 | return; |
11465 | |
11466 | case TemplateDeductionResult::Incomplete: { |
11467 | assert(ParamD && "no parameter found for incomplete deduction result" ); |
11468 | S.Diag(Templated->getLocation(), |
11469 | diag::note_ovl_candidate_incomplete_deduction) |
11470 | << ParamD->getDeclName(); |
11471 | MaybeEmitInheritedConstructorNote(S, Found); |
11472 | return; |
11473 | } |
11474 | |
11475 | case TemplateDeductionResult::IncompletePack: { |
11476 | assert(ParamD && "no parameter found for incomplete deduction result" ); |
11477 | S.Diag(Templated->getLocation(), |
11478 | diag::note_ovl_candidate_incomplete_deduction_pack) |
11479 | << ParamD->getDeclName() |
11480 | << (DeductionFailure.getFirstArg()->pack_size() + 1) |
11481 | << *DeductionFailure.getFirstArg(); |
11482 | MaybeEmitInheritedConstructorNote(S, Found); |
11483 | return; |
11484 | } |
11485 | |
11486 | case TemplateDeductionResult::Underqualified: { |
11487 | assert(ParamD && "no parameter found for bad qualifiers deduction result" ); |
11488 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD); |
11489 | |
11490 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); |
11491 | |
11492 | // Param will have been canonicalized, but it should just be a |
11493 | // qualified version of ParamD, so move the qualifiers to that. |
11494 | QualifierCollector Qs; |
11495 | Qs.strip(type: Param); |
11496 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); |
11497 | assert(S.Context.hasSameType(Param, NonCanonParam)); |
11498 | |
11499 | // Arg has also been canonicalized, but there's nothing we can do |
11500 | // about that. It also doesn't matter as much, because it won't |
11501 | // have any template parameters in it (because deduction isn't |
11502 | // done on dependent types). |
11503 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); |
11504 | |
11505 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) |
11506 | << ParamD->getDeclName() << Arg << NonCanonParam; |
11507 | MaybeEmitInheritedConstructorNote(S, Found); |
11508 | return; |
11509 | } |
11510 | |
11511 | case TemplateDeductionResult::Inconsistent: { |
11512 | assert(ParamD && "no parameter found for inconsistent deduction result" ); |
11513 | int which = 0; |
11514 | if (isa<TemplateTypeParmDecl>(Val: ParamD)) |
11515 | which = 0; |
11516 | else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) { |
11517 | // Deduction might have failed because we deduced arguments of two |
11518 | // different types for a non-type template parameter. |
11519 | // FIXME: Use a different TDK value for this. |
11520 | QualType T1 = |
11521 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); |
11522 | QualType T2 = |
11523 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); |
11524 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { |
11525 | S.Diag(Templated->getLocation(), |
11526 | diag::note_ovl_candidate_inconsistent_deduction_types) |
11527 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 |
11528 | << *DeductionFailure.getSecondArg() << T2; |
11529 | MaybeEmitInheritedConstructorNote(S, Found); |
11530 | return; |
11531 | } |
11532 | |
11533 | which = 1; |
11534 | } else { |
11535 | which = 2; |
11536 | } |
11537 | |
11538 | // Tweak the diagnostic if the problem is that we deduced packs of |
11539 | // different arities. We'll print the actual packs anyway in case that |
11540 | // includes additional useful information. |
11541 | if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && |
11542 | DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && |
11543 | DeductionFailure.getFirstArg()->pack_size() != |
11544 | DeductionFailure.getSecondArg()->pack_size()) { |
11545 | which = 3; |
11546 | } |
11547 | |
11548 | S.Diag(Templated->getLocation(), |
11549 | diag::note_ovl_candidate_inconsistent_deduction) |
11550 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() |
11551 | << *DeductionFailure.getSecondArg(); |
11552 | MaybeEmitInheritedConstructorNote(S, Found); |
11553 | return; |
11554 | } |
11555 | |
11556 | case TemplateDeductionResult::InvalidExplicitArguments: |
11557 | assert(ParamD && "no parameter found for invalid explicit arguments" ); |
11558 | if (ParamD->getDeclName()) |
11559 | S.Diag(Templated->getLocation(), |
11560 | diag::note_ovl_candidate_explicit_arg_mismatch_named) |
11561 | << ParamD->getDeclName(); |
11562 | else { |
11563 | int index = 0; |
11564 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD)) |
11565 | index = TTP->getIndex(); |
11566 | else if (NonTypeTemplateParmDecl *NTTP |
11567 | = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD)) |
11568 | index = NTTP->getIndex(); |
11569 | else |
11570 | index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex(); |
11571 | S.Diag(Templated->getLocation(), |
11572 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) |
11573 | << (index + 1); |
11574 | } |
11575 | MaybeEmitInheritedConstructorNote(S, Found); |
11576 | return; |
11577 | |
11578 | case TemplateDeductionResult::ConstraintsNotSatisfied: { |
11579 | // Format the template argument list into the argument string. |
11580 | SmallString<128> TemplateArgString; |
11581 | TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); |
11582 | TemplateArgString = " " ; |
11583 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11584 | Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args); |
11585 | if (TemplateArgString.size() == 1) |
11586 | TemplateArgString.clear(); |
11587 | S.Diag(Templated->getLocation(), |
11588 | diag::note_ovl_candidate_unsatisfied_constraints) |
11589 | << TemplateArgString; |
11590 | |
11591 | S.DiagnoseUnsatisfiedConstraint( |
11592 | Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); |
11593 | return; |
11594 | } |
11595 | case TemplateDeductionResult::TooManyArguments: |
11596 | case TemplateDeductionResult::TooFewArguments: |
11597 | DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs); |
11598 | return; |
11599 | |
11600 | case TemplateDeductionResult::InstantiationDepth: |
11601 | S.Diag(Templated->getLocation(), |
11602 | diag::note_ovl_candidate_instantiation_depth); |
11603 | MaybeEmitInheritedConstructorNote(S, Found); |
11604 | return; |
11605 | |
11606 | case TemplateDeductionResult::SubstitutionFailure: { |
11607 | // Format the template argument list into the argument string. |
11608 | SmallString<128> TemplateArgString; |
11609 | if (TemplateArgumentList *Args = |
11610 | DeductionFailure.getTemplateArgumentList()) { |
11611 | TemplateArgString = " " ; |
11612 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11613 | Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args); |
11614 | if (TemplateArgString.size() == 1) |
11615 | TemplateArgString.clear(); |
11616 | } |
11617 | |
11618 | // If this candidate was disabled by enable_if, say so. |
11619 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); |
11620 | if (PDiag && PDiag->second.getDiagID() == |
11621 | diag::err_typename_nested_not_found_enable_if) { |
11622 | // FIXME: Use the source range of the condition, and the fully-qualified |
11623 | // name of the enable_if template. These are both present in PDiag. |
11624 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) |
11625 | << "'enable_if'" << TemplateArgString; |
11626 | return; |
11627 | } |
11628 | |
11629 | // We found a specific requirement that disabled the enable_if. |
11630 | if (PDiag && PDiag->second.getDiagID() == |
11631 | diag::err_typename_nested_not_found_requirement) { |
11632 | S.Diag(Templated->getLocation(), |
11633 | diag::note_ovl_candidate_disabled_by_requirement) |
11634 | << PDiag->second.getStringArg(0) << TemplateArgString; |
11635 | return; |
11636 | } |
11637 | |
11638 | // Format the SFINAE diagnostic into the argument string. |
11639 | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s |
11640 | // formatted message in another diagnostic. |
11641 | SmallString<128> SFINAEArgString; |
11642 | SourceRange R; |
11643 | if (PDiag) { |
11644 | SFINAEArgString = ": " ; |
11645 | R = SourceRange(PDiag->first, PDiag->first); |
11646 | PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString); |
11647 | } |
11648 | |
11649 | S.Diag(Templated->getLocation(), |
11650 | diag::note_ovl_candidate_substitution_failure) |
11651 | << TemplateArgString << SFINAEArgString << R; |
11652 | MaybeEmitInheritedConstructorNote(S, Found); |
11653 | return; |
11654 | } |
11655 | |
11656 | case TemplateDeductionResult::DeducedMismatch: |
11657 | case TemplateDeductionResult::DeducedMismatchNested: { |
11658 | // Format the template argument list into the argument string. |
11659 | SmallString<128> TemplateArgString; |
11660 | if (TemplateArgumentList *Args = |
11661 | DeductionFailure.getTemplateArgumentList()) { |
11662 | TemplateArgString = " " ; |
11663 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11664 | Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args); |
11665 | if (TemplateArgString.size() == 1) |
11666 | TemplateArgString.clear(); |
11667 | } |
11668 | |
11669 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) |
11670 | << (*DeductionFailure.getCallArgIndex() + 1) |
11671 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() |
11672 | << TemplateArgString |
11673 | << (DeductionFailure.getResult() == |
11674 | TemplateDeductionResult::DeducedMismatchNested); |
11675 | break; |
11676 | } |
11677 | |
11678 | case TemplateDeductionResult::NonDeducedMismatch: { |
11679 | // FIXME: Provide a source location to indicate what we couldn't match. |
11680 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); |
11681 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); |
11682 | if (FirstTA.getKind() == TemplateArgument::Template && |
11683 | SecondTA.getKind() == TemplateArgument::Template) { |
11684 | TemplateName FirstTN = FirstTA.getAsTemplate(); |
11685 | TemplateName SecondTN = SecondTA.getAsTemplate(); |
11686 | if (FirstTN.getKind() == TemplateName::Template && |
11687 | SecondTN.getKind() == TemplateName::Template) { |
11688 | if (FirstTN.getAsTemplateDecl()->getName() == |
11689 | SecondTN.getAsTemplateDecl()->getName()) { |
11690 | // FIXME: This fixes a bad diagnostic where both templates are named |
11691 | // the same. This particular case is a bit difficult since: |
11692 | // 1) It is passed as a string to the diagnostic printer. |
11693 | // 2) The diagnostic printer only attempts to find a better |
11694 | // name for types, not decls. |
11695 | // Ideally, this should folded into the diagnostic printer. |
11696 | S.Diag(Templated->getLocation(), |
11697 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) |
11698 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); |
11699 | return; |
11700 | } |
11701 | } |
11702 | } |
11703 | |
11704 | if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) && |
11705 | !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated))) |
11706 | return; |
11707 | |
11708 | // FIXME: For generic lambda parameters, check if the function is a lambda |
11709 | // call operator, and if so, emit a prettier and more informative |
11710 | // diagnostic that mentions 'auto' and lambda in addition to |
11711 | // (or instead of?) the canonical template type parameters. |
11712 | S.Diag(Templated->getLocation(), |
11713 | diag::note_ovl_candidate_non_deduced_mismatch) |
11714 | << FirstTA << SecondTA; |
11715 | return; |
11716 | } |
11717 | // TODO: diagnose these individually, then kill off |
11718 | // note_ovl_candidate_bad_deduction, which is uselessly vague. |
11719 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
11720 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); |
11721 | MaybeEmitInheritedConstructorNote(S, Found); |
11722 | return; |
11723 | case TemplateDeductionResult::CUDATargetMismatch: |
11724 | S.Diag(Templated->getLocation(), |
11725 | diag::note_cuda_ovl_candidate_target_mismatch); |
11726 | return; |
11727 | } |
11728 | } |
11729 | |
11730 | /// Diagnose a failed template-argument deduction, for function calls. |
11731 | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, |
11732 | unsigned NumArgs, |
11733 | bool TakingCandidateAddress) { |
11734 | TemplateDeductionResult TDK = Cand->DeductionFailure.getResult(); |
11735 | if (TDK == TemplateDeductionResult::TooFewArguments || |
11736 | TDK == TemplateDeductionResult::TooManyArguments) { |
11737 | if (CheckArityMismatch(S, Cand, NumArgs)) |
11738 | return; |
11739 | } |
11740 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern |
11741 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); |
11742 | } |
11743 | |
11744 | /// CUDA: diagnose an invalid call across targets. |
11745 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { |
11746 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
11747 | FunctionDecl *Callee = Cand->Function; |
11748 | |
11749 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(D: Caller), |
11750 | CalleeTarget = S.IdentifyCUDATarget(D: Callee); |
11751 | |
11752 | std::string FnDesc; |
11753 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11754 | ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee, |
11755 | CRK: Cand->getRewriteKind(), Description&: FnDesc); |
11756 | |
11757 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) |
11758 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11759 | << FnDesc /* Ignored */ |
11760 | << CalleeTarget << CallerTarget; |
11761 | |
11762 | // This could be an implicit constructor for which we could not infer the |
11763 | // target due to a collsion. Diagnose that case. |
11764 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee); |
11765 | if (Meth != nullptr && Meth->isImplicit()) { |
11766 | CXXRecordDecl *ParentClass = Meth->getParent(); |
11767 | Sema::CXXSpecialMember CSM; |
11768 | |
11769 | switch (FnKindPair.first) { |
11770 | default: |
11771 | return; |
11772 | case oc_implicit_default_constructor: |
11773 | CSM = Sema::CXXDefaultConstructor; |
11774 | break; |
11775 | case oc_implicit_copy_constructor: |
11776 | CSM = Sema::CXXCopyConstructor; |
11777 | break; |
11778 | case oc_implicit_move_constructor: |
11779 | CSM = Sema::CXXMoveConstructor; |
11780 | break; |
11781 | case oc_implicit_copy_assignment: |
11782 | CSM = Sema::CXXCopyAssignment; |
11783 | break; |
11784 | case oc_implicit_move_assignment: |
11785 | CSM = Sema::CXXMoveAssignment; |
11786 | break; |
11787 | }; |
11788 | |
11789 | bool ConstRHS = false; |
11790 | if (Meth->getNumParams()) { |
11791 | if (const ReferenceType *RT = |
11792 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { |
11793 | ConstRHS = RT->getPointeeType().isConstQualified(); |
11794 | } |
11795 | } |
11796 | |
11797 | S.inferCUDATargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth, |
11798 | /* ConstRHS */ ConstRHS, |
11799 | /* Diagnose */ true); |
11800 | } |
11801 | } |
11802 | |
11803 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { |
11804 | FunctionDecl *Callee = Cand->Function; |
11805 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); |
11806 | |
11807 | S.Diag(Callee->getLocation(), |
11808 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
11809 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
11810 | } |
11811 | |
11812 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { |
11813 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Cand->Function); |
11814 | assert(ES.isExplicit() && "not an explicit candidate" ); |
11815 | |
11816 | unsigned Kind; |
11817 | switch (Cand->Function->getDeclKind()) { |
11818 | case Decl::Kind::CXXConstructor: |
11819 | Kind = 0; |
11820 | break; |
11821 | case Decl::Kind::CXXConversion: |
11822 | Kind = 1; |
11823 | break; |
11824 | case Decl::Kind::CXXDeductionGuide: |
11825 | Kind = Cand->Function->isImplicit() ? 0 : 2; |
11826 | break; |
11827 | default: |
11828 | llvm_unreachable("invalid Decl" ); |
11829 | } |
11830 | |
11831 | // Note the location of the first (in-class) declaration; a redeclaration |
11832 | // (particularly an out-of-class definition) will typically lack the |
11833 | // 'explicit' specifier. |
11834 | // FIXME: This is probably a good thing to do for all 'candidate' notes. |
11835 | FunctionDecl *First = Cand->Function->getFirstDecl(); |
11836 | if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) |
11837 | First = Pattern->getFirstDecl(); |
11838 | |
11839 | S.Diag(First->getLocation(), |
11840 | diag::note_ovl_candidate_explicit) |
11841 | << Kind << (ES.getExpr() ? 1 : 0) |
11842 | << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); |
11843 | } |
11844 | |
11845 | /// Generates a 'note' diagnostic for an overload candidate. We've |
11846 | /// already generated a primary error at the call site. |
11847 | /// |
11848 | /// It really does need to be a single diagnostic with its caret |
11849 | /// pointed at the candidate declaration. Yes, this creates some |
11850 | /// major challenges of technical writing. Yes, this makes pointing |
11851 | /// out problems with specific arguments quite awkward. It's still |
11852 | /// better than generating twenty screens of text for every failed |
11853 | /// overload. |
11854 | /// |
11855 | /// It would be great to be able to express per-candidate problems |
11856 | /// more richly for those diagnostic clients that cared, but we'd |
11857 | /// still have to be just as careful with the default diagnostics. |
11858 | /// \param CtorDestAS Addr space of object being constructed (for ctor |
11859 | /// candidates only). |
11860 | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, |
11861 | unsigned NumArgs, |
11862 | bool TakingCandidateAddress, |
11863 | LangAS CtorDestAS = LangAS::Default) { |
11864 | FunctionDecl *Fn = Cand->Function; |
11865 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
11866 | return; |
11867 | |
11868 | // There is no physical candidate declaration to point to for OpenCL builtins. |
11869 | // Except for failed conversions, the notes are identical for each candidate, |
11870 | // so do not generate such notes. |
11871 | if (S.getLangOpts().OpenCL && Fn->isImplicit() && |
11872 | Cand->FailureKind != ovl_fail_bad_conversion) |
11873 | return; |
11874 | |
11875 | // Note deleted candidates, but only if they're viable. |
11876 | if (Cand->Viable) { |
11877 | if (Fn->isDeleted()) { |
11878 | std::string FnDesc; |
11879 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11880 | ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, |
11881 | CRK: Cand->getRewriteKind(), Description&: FnDesc); |
11882 | |
11883 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) |
11884 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11885 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); |
11886 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11887 | return; |
11888 | } |
11889 | |
11890 | // We don't really have anything else to say about viable candidates. |
11891 | S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind()); |
11892 | return; |
11893 | } |
11894 | |
11895 | switch (Cand->FailureKind) { |
11896 | case ovl_fail_too_many_arguments: |
11897 | case ovl_fail_too_few_arguments: |
11898 | return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs); |
11899 | |
11900 | case ovl_fail_bad_deduction: |
11901 | return DiagnoseBadDeduction(S, Cand, NumArgs, |
11902 | TakingCandidateAddress); |
11903 | |
11904 | case ovl_fail_illegal_constructor: { |
11905 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) |
11906 | << (Fn->getPrimaryTemplate() ? 1 : 0); |
11907 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11908 | return; |
11909 | } |
11910 | |
11911 | case ovl_fail_object_addrspace_mismatch: { |
11912 | Qualifiers QualsForPrinting; |
11913 | QualsForPrinting.setAddressSpace(CtorDestAS); |
11914 | S.Diag(Fn->getLocation(), |
11915 | diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) |
11916 | << QualsForPrinting; |
11917 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11918 | return; |
11919 | } |
11920 | |
11921 | case ovl_fail_trivial_conversion: |
11922 | case ovl_fail_bad_final_conversion: |
11923 | case ovl_fail_final_conversion_not_exact: |
11924 | return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind()); |
11925 | |
11926 | case ovl_fail_bad_conversion: { |
11927 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); |
11928 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) |
11929 | if (Cand->Conversions[I].isBad()) |
11930 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); |
11931 | |
11932 | // FIXME: this currently happens when we're called from SemaInit |
11933 | // when user-conversion overload fails. Figure out how to handle |
11934 | // those conditions and diagnose them well. |
11935 | return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind()); |
11936 | } |
11937 | |
11938 | case ovl_fail_bad_target: |
11939 | return DiagnoseBadTarget(S, Cand); |
11940 | |
11941 | case ovl_fail_enable_if: |
11942 | return DiagnoseFailedEnableIfAttr(S, Cand); |
11943 | |
11944 | case ovl_fail_explicit: |
11945 | return DiagnoseFailedExplicitSpec(S, Cand); |
11946 | |
11947 | case ovl_fail_inhctor_slice: |
11948 | // It's generally not interesting to note copy/move constructors here. |
11949 | if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor()) |
11950 | return; |
11951 | S.Diag(Fn->getLocation(), |
11952 | diag::note_ovl_candidate_inherited_constructor_slice) |
11953 | << (Fn->getPrimaryTemplate() ? 1 : 0) |
11954 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); |
11955 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11956 | return; |
11957 | |
11958 | case ovl_fail_addr_not_available: { |
11959 | bool Available = checkAddressOfCandidateIsAvailable(S, FD: Cand->Function); |
11960 | (void)Available; |
11961 | assert(!Available); |
11962 | break; |
11963 | } |
11964 | case ovl_non_default_multiversion_function: |
11965 | // Do nothing, these should simply be ignored. |
11966 | break; |
11967 | |
11968 | case ovl_fail_constraints_not_satisfied: { |
11969 | std::string FnDesc; |
11970 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11971 | ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, |
11972 | CRK: Cand->getRewriteKind(), Description&: FnDesc); |
11973 | |
11974 | S.Diag(Fn->getLocation(), |
11975 | diag::note_ovl_candidate_constraints_not_satisfied) |
11976 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11977 | << FnDesc /* Ignored */; |
11978 | ConstraintSatisfaction Satisfaction; |
11979 | if (S.CheckFunctionConstraints(FD: Fn, Satisfaction)) |
11980 | break; |
11981 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
11982 | } |
11983 | } |
11984 | } |
11985 | |
11986 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { |
11987 | if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) |
11988 | return; |
11989 | |
11990 | // Desugar the type of the surrogate down to a function type, |
11991 | // retaining as many typedefs as possible while still showing |
11992 | // the function type (and, therefore, its parameter types). |
11993 | QualType FnType = Cand->Surrogate->getConversionType(); |
11994 | bool isLValueReference = false; |
11995 | bool isRValueReference = false; |
11996 | bool isPointer = false; |
11997 | if (const LValueReferenceType *FnTypeRef = |
11998 | FnType->getAs<LValueReferenceType>()) { |
11999 | FnType = FnTypeRef->getPointeeType(); |
12000 | isLValueReference = true; |
12001 | } else if (const RValueReferenceType *FnTypeRef = |
12002 | FnType->getAs<RValueReferenceType>()) { |
12003 | FnType = FnTypeRef->getPointeeType(); |
12004 | isRValueReference = true; |
12005 | } |
12006 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { |
12007 | FnType = FnTypePtr->getPointeeType(); |
12008 | isPointer = true; |
12009 | } |
12010 | // Desugar down to a function type. |
12011 | FnType = QualType(FnType->getAs<FunctionType>(), 0); |
12012 | // Reconstruct the pointer/reference as appropriate. |
12013 | if (isPointer) FnType = S.Context.getPointerType(T: FnType); |
12014 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType); |
12015 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType); |
12016 | |
12017 | if (!Cand->Viable && |
12018 | Cand->FailureKind == ovl_fail_constraints_not_satisfied) { |
12019 | S.Diag(Cand->Surrogate->getLocation(), |
12020 | diag::note_ovl_surrogate_constraints_not_satisfied) |
12021 | << Cand->Surrogate; |
12022 | ConstraintSatisfaction Satisfaction; |
12023 | if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction)) |
12024 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
12025 | } else { |
12026 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) |
12027 | << FnType; |
12028 | } |
12029 | } |
12030 | |
12031 | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, |
12032 | SourceLocation OpLoc, |
12033 | OverloadCandidate *Cand) { |
12034 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary" ); |
12035 | std::string TypeStr("operator" ); |
12036 | TypeStr += Opc; |
12037 | TypeStr += "(" ; |
12038 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); |
12039 | if (Cand->Conversions.size() == 1) { |
12040 | TypeStr += ")" ; |
12041 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
12042 | } else { |
12043 | TypeStr += ", " ; |
12044 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); |
12045 | TypeStr += ")" ; |
12046 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
12047 | } |
12048 | } |
12049 | |
12050 | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, |
12051 | OverloadCandidate *Cand) { |
12052 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { |
12053 | if (ICS.isBad()) break; // all meaningless after first invalid |
12054 | if (!ICS.isAmbiguous()) continue; |
12055 | |
12056 | ICS.DiagnoseAmbiguousConversion( |
12057 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); |
12058 | } |
12059 | } |
12060 | |
12061 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { |
12062 | if (Cand->Function) |
12063 | return Cand->Function->getLocation(); |
12064 | if (Cand->IsSurrogate) |
12065 | return Cand->Surrogate->getLocation(); |
12066 | return SourceLocation(); |
12067 | } |
12068 | |
12069 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { |
12070 | switch (static_cast<TemplateDeductionResult>(DFI.Result)) { |
12071 | case TemplateDeductionResult::Success: |
12072 | case TemplateDeductionResult::NonDependentConversionFailure: |
12073 | case TemplateDeductionResult::AlreadyDiagnosed: |
12074 | llvm_unreachable("non-deduction failure while diagnosing bad deduction" ); |
12075 | |
12076 | case TemplateDeductionResult::Invalid: |
12077 | case TemplateDeductionResult::Incomplete: |
12078 | case TemplateDeductionResult::IncompletePack: |
12079 | return 1; |
12080 | |
12081 | case TemplateDeductionResult::Underqualified: |
12082 | case TemplateDeductionResult::Inconsistent: |
12083 | return 2; |
12084 | |
12085 | case TemplateDeductionResult::SubstitutionFailure: |
12086 | case TemplateDeductionResult::DeducedMismatch: |
12087 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
12088 | case TemplateDeductionResult::DeducedMismatchNested: |
12089 | case TemplateDeductionResult::NonDeducedMismatch: |
12090 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
12091 | case TemplateDeductionResult::CUDATargetMismatch: |
12092 | return 3; |
12093 | |
12094 | case TemplateDeductionResult::InstantiationDepth: |
12095 | return 4; |
12096 | |
12097 | case TemplateDeductionResult::InvalidExplicitArguments: |
12098 | return 5; |
12099 | |
12100 | case TemplateDeductionResult::TooManyArguments: |
12101 | case TemplateDeductionResult::TooFewArguments: |
12102 | return 6; |
12103 | } |
12104 | llvm_unreachable("Unhandled deduction result" ); |
12105 | } |
12106 | |
12107 | namespace { |
12108 | |
12109 | struct CompareOverloadCandidatesForDisplay { |
12110 | Sema &S; |
12111 | SourceLocation Loc; |
12112 | size_t NumArgs; |
12113 | OverloadCandidateSet::CandidateSetKind CSK; |
12114 | |
12115 | CompareOverloadCandidatesForDisplay( |
12116 | Sema &S, SourceLocation Loc, size_t NArgs, |
12117 | OverloadCandidateSet::CandidateSetKind CSK) |
12118 | : S(S), NumArgs(NArgs), CSK(CSK) {} |
12119 | |
12120 | OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { |
12121 | // If there are too many or too few arguments, that's the high-order bit we |
12122 | // want to sort by, even if the immediate failure kind was something else. |
12123 | if (C->FailureKind == ovl_fail_too_many_arguments || |
12124 | C->FailureKind == ovl_fail_too_few_arguments) |
12125 | return static_cast<OverloadFailureKind>(C->FailureKind); |
12126 | |
12127 | if (C->Function) { |
12128 | if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) |
12129 | return ovl_fail_too_many_arguments; |
12130 | if (NumArgs < C->Function->getMinRequiredArguments()) |
12131 | return ovl_fail_too_few_arguments; |
12132 | } |
12133 | |
12134 | return static_cast<OverloadFailureKind>(C->FailureKind); |
12135 | } |
12136 | |
12137 | bool operator()(const OverloadCandidate *L, |
12138 | const OverloadCandidate *R) { |
12139 | // Fast-path this check. |
12140 | if (L == R) return false; |
12141 | |
12142 | // Order first by viability. |
12143 | if (L->Viable) { |
12144 | if (!R->Viable) return true; |
12145 | |
12146 | if (int Ord = CompareConversions(L: *L, R: *R)) |
12147 | return Ord < 0; |
12148 | // Use other tie breakers. |
12149 | } else if (R->Viable) |
12150 | return false; |
12151 | |
12152 | assert(L->Viable == R->Viable); |
12153 | |
12154 | // Criteria by which we can sort non-viable candidates: |
12155 | if (!L->Viable) { |
12156 | OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L); |
12157 | OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R); |
12158 | |
12159 | // 1. Arity mismatches come after other candidates. |
12160 | if (LFailureKind == ovl_fail_too_many_arguments || |
12161 | LFailureKind == ovl_fail_too_few_arguments) { |
12162 | if (RFailureKind == ovl_fail_too_many_arguments || |
12163 | RFailureKind == ovl_fail_too_few_arguments) { |
12164 | int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs); |
12165 | int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs); |
12166 | if (LDist == RDist) { |
12167 | if (LFailureKind == RFailureKind) |
12168 | // Sort non-surrogates before surrogates. |
12169 | return !L->IsSurrogate && R->IsSurrogate; |
12170 | // Sort candidates requiring fewer parameters than there were |
12171 | // arguments given after candidates requiring more parameters |
12172 | // than there were arguments given. |
12173 | return LFailureKind == ovl_fail_too_many_arguments; |
12174 | } |
12175 | return LDist < RDist; |
12176 | } |
12177 | return false; |
12178 | } |
12179 | if (RFailureKind == ovl_fail_too_many_arguments || |
12180 | RFailureKind == ovl_fail_too_few_arguments) |
12181 | return true; |
12182 | |
12183 | // 2. Bad conversions come first and are ordered by the number |
12184 | // of bad conversions and quality of good conversions. |
12185 | if (LFailureKind == ovl_fail_bad_conversion) { |
12186 | if (RFailureKind != ovl_fail_bad_conversion) |
12187 | return true; |
12188 | |
12189 | // The conversion that can be fixed with a smaller number of changes, |
12190 | // comes first. |
12191 | unsigned numLFixes = L->Fix.NumConversionsFixed; |
12192 | unsigned numRFixes = R->Fix.NumConversionsFixed; |
12193 | numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; |
12194 | numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; |
12195 | if (numLFixes != numRFixes) { |
12196 | return numLFixes < numRFixes; |
12197 | } |
12198 | |
12199 | // If there's any ordering between the defined conversions... |
12200 | if (int Ord = CompareConversions(L: *L, R: *R)) |
12201 | return Ord < 0; |
12202 | } else if (RFailureKind == ovl_fail_bad_conversion) |
12203 | return false; |
12204 | |
12205 | if (LFailureKind == ovl_fail_bad_deduction) { |
12206 | if (RFailureKind != ovl_fail_bad_deduction) |
12207 | return true; |
12208 | |
12209 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) { |
12210 | unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure); |
12211 | unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure); |
12212 | if (LRank != RRank) |
12213 | return LRank < RRank; |
12214 | } |
12215 | } else if (RFailureKind == ovl_fail_bad_deduction) |
12216 | return false; |
12217 | |
12218 | // TODO: others? |
12219 | } |
12220 | |
12221 | // Sort everything else by location. |
12222 | SourceLocation LLoc = GetLocationForCandidate(Cand: L); |
12223 | SourceLocation RLoc = GetLocationForCandidate(Cand: R); |
12224 | |
12225 | // Put candidates without locations (e.g. builtins) at the end. |
12226 | if (LLoc.isValid() && RLoc.isValid()) |
12227 | return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc); |
12228 | if (LLoc.isValid() && !RLoc.isValid()) |
12229 | return true; |
12230 | if (RLoc.isValid() && !LLoc.isValid()) |
12231 | return false; |
12232 | assert(!LLoc.isValid() && !RLoc.isValid()); |
12233 | // For builtins and other functions without locations, fallback to the order |
12234 | // in which they were added into the candidate set. |
12235 | return L < R; |
12236 | } |
12237 | |
12238 | private: |
12239 | struct ConversionSignals { |
12240 | unsigned KindRank = 0; |
12241 | ImplicitConversionRank Rank = ICR_Exact_Match; |
12242 | |
12243 | static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) { |
12244 | ConversionSignals Sig; |
12245 | Sig.KindRank = Seq.getKindRank(); |
12246 | if (Seq.isStandard()) |
12247 | Sig.Rank = Seq.Standard.getRank(); |
12248 | else if (Seq.isUserDefined()) |
12249 | Sig.Rank = Seq.UserDefined.After.getRank(); |
12250 | // We intend StaticObjectArgumentConversion to compare the same as |
12251 | // StandardConversion with ICR_ExactMatch rank. |
12252 | return Sig; |
12253 | } |
12254 | |
12255 | static ConversionSignals ForObjectArgument() { |
12256 | // We intend StaticObjectArgumentConversion to compare the same as |
12257 | // StandardConversion with ICR_ExactMatch rank. Default give us that. |
12258 | return {}; |
12259 | } |
12260 | }; |
12261 | |
12262 | // Returns -1 if conversions in L are considered better. |
12263 | // 0 if they are considered indistinguishable. |
12264 | // 1 if conversions in R are better. |
12265 | int CompareConversions(const OverloadCandidate &L, |
12266 | const OverloadCandidate &R) { |
12267 | // We cannot use `isBetterOverloadCandidate` because it is defined |
12268 | // according to the C++ standard and provides a partial order, but we need |
12269 | // a total order as this function is used in sort. |
12270 | assert(L.Conversions.size() == R.Conversions.size()); |
12271 | for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) { |
12272 | auto LS = L.IgnoreObjectArgument && I == 0 |
12273 | ? ConversionSignals::ForObjectArgument() |
12274 | : ConversionSignals::ForSequence(Seq&: L.Conversions[I]); |
12275 | auto RS = R.IgnoreObjectArgument |
12276 | ? ConversionSignals::ForObjectArgument() |
12277 | : ConversionSignals::ForSequence(Seq&: R.Conversions[I]); |
12278 | if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank)) |
12279 | return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank) |
12280 | ? -1 |
12281 | : 1; |
12282 | } |
12283 | // FIXME: find a way to compare templates for being more or less |
12284 | // specialized that provides a strict weak ordering. |
12285 | return 0; |
12286 | } |
12287 | }; |
12288 | } |
12289 | |
12290 | /// CompleteNonViableCandidate - Normally, overload resolution only |
12291 | /// computes up to the first bad conversion. Produces the FixIt set if |
12292 | /// possible. |
12293 | static void |
12294 | CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, |
12295 | ArrayRef<Expr *> Args, |
12296 | OverloadCandidateSet::CandidateSetKind CSK) { |
12297 | assert(!Cand->Viable); |
12298 | |
12299 | // Don't do anything on failures other than bad conversion. |
12300 | if (Cand->FailureKind != ovl_fail_bad_conversion) |
12301 | return; |
12302 | |
12303 | // We only want the FixIts if all the arguments can be corrected. |
12304 | bool Unfixable = false; |
12305 | // Use a implicit copy initialization to check conversion fixes. |
12306 | Cand->Fix.setConversionChecker(TryCopyInitialization); |
12307 | |
12308 | // Attempt to fix the bad conversion. |
12309 | unsigned ConvCount = Cand->Conversions.size(); |
12310 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; |
12311 | ++ConvIdx) { |
12312 | assert(ConvIdx != ConvCount && "no bad conversion in candidate" ); |
12313 | if (Cand->Conversions[ConvIdx].isInitialized() && |
12314 | Cand->Conversions[ConvIdx].isBad()) { |
12315 | Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S); |
12316 | break; |
12317 | } |
12318 | } |
12319 | |
12320 | // FIXME: this should probably be preserved from the overload |
12321 | // operation somehow. |
12322 | bool SuppressUserConversions = false; |
12323 | |
12324 | unsigned ConvIdx = 0; |
12325 | unsigned ArgIdx = 0; |
12326 | ArrayRef<QualType> ParamTypes; |
12327 | bool Reversed = Cand->isReversed(); |
12328 | |
12329 | if (Cand->IsSurrogate) { |
12330 | QualType ConvType |
12331 | = Cand->Surrogate->getConversionType().getNonReferenceType(); |
12332 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
12333 | ConvType = ConvPtrType->getPointeeType(); |
12334 | ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); |
12335 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
12336 | ConvIdx = 1; |
12337 | } else if (Cand->Function) { |
12338 | ParamTypes = |
12339 | Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); |
12340 | if (isa<CXXMethodDecl>(Val: Cand->Function) && |
12341 | !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed) { |
12342 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
12343 | ConvIdx = 1; |
12344 | if (CSK == OverloadCandidateSet::CSK_Operator && |
12345 | Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && |
12346 | Cand->Function->getDeclName().getCXXOverloadedOperator() != |
12347 | OO_Subscript) |
12348 | // Argument 0 is 'this', which doesn't have a corresponding parameter. |
12349 | ArgIdx = 1; |
12350 | } |
12351 | } else { |
12352 | // Builtin operator. |
12353 | assert(ConvCount <= 3); |
12354 | ParamTypes = Cand->BuiltinParamTypes; |
12355 | } |
12356 | |
12357 | // Fill in the rest of the conversions. |
12358 | for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; |
12359 | ConvIdx != ConvCount; |
12360 | ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { |
12361 | assert(ArgIdx < Args.size() && "no argument for this arg conversion" ); |
12362 | if (Cand->Conversions[ConvIdx].isInitialized()) { |
12363 | // We've already checked this conversion. |
12364 | } else if (ParamIdx < ParamTypes.size()) { |
12365 | if (ParamTypes[ParamIdx]->isDependentType()) |
12366 | Cand->Conversions[ConvIdx].setAsIdentityConversion( |
12367 | Args[ArgIdx]->getType()); |
12368 | else { |
12369 | Cand->Conversions[ConvIdx] = |
12370 | TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx], |
12371 | SuppressUserConversions, |
12372 | /*InOverloadResolution=*/true, |
12373 | /*AllowObjCWritebackConversion=*/ |
12374 | S.getLangOpts().ObjCAutoRefCount); |
12375 | // Store the FixIt in the candidate if it exists. |
12376 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) |
12377 | Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S); |
12378 | } |
12379 | } else |
12380 | Cand->Conversions[ConvIdx].setEllipsis(); |
12381 | } |
12382 | } |
12383 | |
12384 | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( |
12385 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
12386 | SourceLocation OpLoc, |
12387 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
12388 | // Sort the candidates by viability and position. Sorting directly would |
12389 | // be prohibitive, so we make a set of pointers and sort those. |
12390 | SmallVector<OverloadCandidate*, 32> Cands; |
12391 | if (OCD == OCD_AllCandidates) Cands.reserve(N: size()); |
12392 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
12393 | if (!Filter(*Cand)) |
12394 | continue; |
12395 | switch (OCD) { |
12396 | case OCD_AllCandidates: |
12397 | if (!Cand->Viable) { |
12398 | if (!Cand->Function && !Cand->IsSurrogate) { |
12399 | // This a non-viable builtin candidate. We do not, in general, |
12400 | // want to list every possible builtin candidate. |
12401 | continue; |
12402 | } |
12403 | CompleteNonViableCandidate(S, Cand, Args, CSK: Kind); |
12404 | } |
12405 | break; |
12406 | |
12407 | case OCD_ViableCandidates: |
12408 | if (!Cand->Viable) |
12409 | continue; |
12410 | break; |
12411 | |
12412 | case OCD_AmbiguousCandidates: |
12413 | if (!Cand->Best) |
12414 | continue; |
12415 | break; |
12416 | } |
12417 | |
12418 | Cands.push_back(Elt: Cand); |
12419 | } |
12420 | |
12421 | llvm::stable_sort( |
12422 | Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); |
12423 | |
12424 | return Cands; |
12425 | } |
12426 | |
12427 | bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, |
12428 | SourceLocation OpLoc) { |
12429 | bool DeferHint = false; |
12430 | if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { |
12431 | // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or |
12432 | // host device candidates. |
12433 | auto WrongSidedCands = |
12434 | CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { |
12435 | return (Cand.Viable == false && |
12436 | Cand.FailureKind == ovl_fail_bad_target) || |
12437 | (Cand.Function && |
12438 | Cand.Function->template hasAttr<CUDAHostAttr>() && |
12439 | Cand.Function->template hasAttr<CUDADeviceAttr>()); |
12440 | }); |
12441 | DeferHint = !WrongSidedCands.empty(); |
12442 | } |
12443 | return DeferHint; |
12444 | } |
12445 | |
12446 | /// When overload resolution fails, prints diagnostic messages containing the |
12447 | /// candidates in the candidate set. |
12448 | void OverloadCandidateSet::NoteCandidates( |
12449 | PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, |
12450 | ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, |
12451 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
12452 | |
12453 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); |
12454 | |
12455 | S.Diag(Loc: PD.first, PD: PD.second, DeferHint: shouldDeferDiags(S, Args, OpLoc)); |
12456 | |
12457 | // In WebAssembly we don't want to emit further diagnostics if a table is |
12458 | // passed as an argument to a function. |
12459 | bool NoteCands = true; |
12460 | for (const Expr *Arg : Args) { |
12461 | if (Arg->getType()->isWebAssemblyTableType()) |
12462 | NoteCands = false; |
12463 | } |
12464 | |
12465 | if (NoteCands) |
12466 | NoteCandidates(S, Args, Cands, Opc, OpLoc); |
12467 | |
12468 | if (OCD == OCD_AmbiguousCandidates) |
12469 | MaybeDiagnoseAmbiguousConstraints(S, Cands: {begin(), end()}); |
12470 | } |
12471 | |
12472 | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, |
12473 | ArrayRef<OverloadCandidate *> Cands, |
12474 | StringRef Opc, SourceLocation OpLoc) { |
12475 | bool ReportedAmbiguousConversions = false; |
12476 | |
12477 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12478 | unsigned CandsShown = 0; |
12479 | auto I = Cands.begin(), E = Cands.end(); |
12480 | for (; I != E; ++I) { |
12481 | OverloadCandidate *Cand = *I; |
12482 | |
12483 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && |
12484 | ShowOverloads == Ovl_Best) { |
12485 | break; |
12486 | } |
12487 | ++CandsShown; |
12488 | |
12489 | if (Cand->Function) |
12490 | NoteFunctionCandidate(S, Cand, NumArgs: Args.size(), |
12491 | /*TakingCandidateAddress=*/false, CtorDestAS: DestAS); |
12492 | else if (Cand->IsSurrogate) |
12493 | NoteSurrogateCandidate(S, Cand); |
12494 | else { |
12495 | assert(Cand->Viable && |
12496 | "Non-viable built-in candidates are not added to Cands." ); |
12497 | // Generally we only see ambiguities including viable builtin |
12498 | // operators if overload resolution got screwed up by an |
12499 | // ambiguous user-defined conversion. |
12500 | // |
12501 | // FIXME: It's quite possible for different conversions to see |
12502 | // different ambiguities, though. |
12503 | if (!ReportedAmbiguousConversions) { |
12504 | NoteAmbiguousUserConversions(S, OpLoc, Cand); |
12505 | ReportedAmbiguousConversions = true; |
12506 | } |
12507 | |
12508 | // If this is a viable builtin, print it. |
12509 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); |
12510 | } |
12511 | } |
12512 | |
12513 | // Inform S.Diags that we've shown an overload set with N elements. This may |
12514 | // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). |
12515 | S.Diags.overloadCandidatesShown(N: CandsShown); |
12516 | |
12517 | if (I != E) |
12518 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates, |
12519 | shouldDeferDiags(S, Args, OpLoc)) |
12520 | << int(E - I); |
12521 | } |
12522 | |
12523 | static SourceLocation |
12524 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { |
12525 | return Cand->Specialization ? Cand->Specialization->getLocation() |
12526 | : SourceLocation(); |
12527 | } |
12528 | |
12529 | namespace { |
12530 | struct CompareTemplateSpecCandidatesForDisplay { |
12531 | Sema &S; |
12532 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} |
12533 | |
12534 | bool operator()(const TemplateSpecCandidate *L, |
12535 | const TemplateSpecCandidate *R) { |
12536 | // Fast-path this check. |
12537 | if (L == R) |
12538 | return false; |
12539 | |
12540 | // Assuming that both candidates are not matches... |
12541 | |
12542 | // Sort by the ranking of deduction failures. |
12543 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
12544 | return RankDeductionFailure(DFI: L->DeductionFailure) < |
12545 | RankDeductionFailure(DFI: R->DeductionFailure); |
12546 | |
12547 | // Sort everything else by location. |
12548 | SourceLocation LLoc = GetLocationForCandidate(Cand: L); |
12549 | SourceLocation RLoc = GetLocationForCandidate(Cand: R); |
12550 | |
12551 | // Put candidates without locations (e.g. builtins) at the end. |
12552 | if (LLoc.isInvalid()) |
12553 | return false; |
12554 | if (RLoc.isInvalid()) |
12555 | return true; |
12556 | |
12557 | return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc); |
12558 | } |
12559 | }; |
12560 | } |
12561 | |
12562 | /// Diagnose a template argument deduction failure. |
12563 | /// We are treating these failures as overload failures due to bad |
12564 | /// deductions. |
12565 | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, |
12566 | bool ForTakingAddress) { |
12567 | DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern |
12568 | DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress); |
12569 | } |
12570 | |
12571 | void TemplateSpecCandidateSet::destroyCandidates() { |
12572 | for (iterator i = begin(), e = end(); i != e; ++i) { |
12573 | i->DeductionFailure.Destroy(); |
12574 | } |
12575 | } |
12576 | |
12577 | void TemplateSpecCandidateSet::clear() { |
12578 | destroyCandidates(); |
12579 | Candidates.clear(); |
12580 | } |
12581 | |
12582 | /// NoteCandidates - When no template specialization match is found, prints |
12583 | /// diagnostic messages containing the non-matching specializations that form |
12584 | /// the candidate set. |
12585 | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with |
12586 | /// OCD == OCD_AllCandidates and Cand->Viable == false. |
12587 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { |
12588 | // Sort the candidates by position (assuming no candidate is a match). |
12589 | // Sorting directly would be prohibitive, so we make a set of pointers |
12590 | // and sort those. |
12591 | SmallVector<TemplateSpecCandidate *, 32> Cands; |
12592 | Cands.reserve(N: size()); |
12593 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
12594 | if (Cand->Specialization) |
12595 | Cands.push_back(Elt: Cand); |
12596 | // Otherwise, this is a non-matching builtin candidate. We do not, |
12597 | // in general, want to list every possible builtin candidate. |
12598 | } |
12599 | |
12600 | llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S)); |
12601 | |
12602 | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() |
12603 | // for generalization purposes (?). |
12604 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12605 | |
12606 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; |
12607 | unsigned CandsShown = 0; |
12608 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
12609 | TemplateSpecCandidate *Cand = *I; |
12610 | |
12611 | // Set an arbitrary limit on the number of candidates we'll spam |
12612 | // the user with. FIXME: This limit should depend on details of the |
12613 | // candidate list. |
12614 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) |
12615 | break; |
12616 | ++CandsShown; |
12617 | |
12618 | assert(Cand->Specialization && |
12619 | "Non-matching built-in candidates are not added to Cands." ); |
12620 | Cand->NoteDeductionFailure(S, ForTakingAddress); |
12621 | } |
12622 | |
12623 | if (I != E) |
12624 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); |
12625 | } |
12626 | |
12627 | // [PossiblyAFunctionType] --> [Return] |
12628 | // NonFunctionType --> NonFunctionType |
12629 | // R (A) --> R(A) |
12630 | // R (*)(A) --> R (A) |
12631 | // R (&)(A) --> R (A) |
12632 | // R (S::*)(A) --> R (A) |
12633 | QualType Sema::(QualType PossiblyAFunctionType) { |
12634 | QualType Ret = PossiblyAFunctionType; |
12635 | if (const PointerType *ToTypePtr = |
12636 | PossiblyAFunctionType->getAs<PointerType>()) |
12637 | Ret = ToTypePtr->getPointeeType(); |
12638 | else if (const ReferenceType *ToTypeRef = |
12639 | PossiblyAFunctionType->getAs<ReferenceType>()) |
12640 | Ret = ToTypeRef->getPointeeType(); |
12641 | else if (const MemberPointerType *MemTypePtr = |
12642 | PossiblyAFunctionType->getAs<MemberPointerType>()) |
12643 | Ret = MemTypePtr->getPointeeType(); |
12644 | Ret = |
12645 | Context.getCanonicalType(T: Ret).getUnqualifiedType(); |
12646 | return Ret; |
12647 | } |
12648 | |
12649 | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, |
12650 | bool Complain = true) { |
12651 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
12652 | S.DeduceReturnType(FD, Loc, Diagnose: Complain)) |
12653 | return true; |
12654 | |
12655 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
12656 | if (S.getLangOpts().CPlusPlus17 && |
12657 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && |
12658 | !S.ResolveExceptionSpec(Loc, FPT: FPT)) |
12659 | return true; |
12660 | |
12661 | return false; |
12662 | } |
12663 | |
12664 | namespace { |
12665 | // A helper class to help with address of function resolution |
12666 | // - allows us to avoid passing around all those ugly parameters |
12667 | class AddressOfFunctionResolver { |
12668 | Sema& S; |
12669 | Expr* SourceExpr; |
12670 | const QualType& TargetType; |
12671 | QualType TargetFunctionType; // Extracted function type from target type |
12672 | |
12673 | bool Complain; |
12674 | //DeclAccessPair& ResultFunctionAccessPair; |
12675 | ASTContext& Context; |
12676 | |
12677 | bool TargetTypeIsNonStaticMemberFunction; |
12678 | bool FoundNonTemplateFunction; |
12679 | bool StaticMemberFunctionFromBoundPointer; |
12680 | bool HasComplained; |
12681 | |
12682 | OverloadExpr::FindResult OvlExprInfo; |
12683 | OverloadExpr *OvlExpr; |
12684 | TemplateArgumentListInfo OvlExplicitTemplateArgs; |
12685 | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; |
12686 | TemplateSpecCandidateSet FailedCandidates; |
12687 | |
12688 | public: |
12689 | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, |
12690 | const QualType &TargetType, bool Complain) |
12691 | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), |
12692 | Complain(Complain), Context(S.getASTContext()), |
12693 | TargetTypeIsNonStaticMemberFunction( |
12694 | !!TargetType->getAs<MemberPointerType>()), |
12695 | FoundNonTemplateFunction(false), |
12696 | StaticMemberFunctionFromBoundPointer(false), |
12697 | HasComplained(false), |
12698 | OvlExprInfo(OverloadExpr::find(E: SourceExpr)), |
12699 | OvlExpr(OvlExprInfo.Expression), |
12700 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { |
12701 | ExtractUnqualifiedFunctionTypeFromTargetType(); |
12702 | |
12703 | if (TargetFunctionType->isFunctionType()) { |
12704 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr)) |
12705 | if (!UME->isImplicitAccess() && |
12706 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) |
12707 | StaticMemberFunctionFromBoundPointer = true; |
12708 | } else if (OvlExpr->hasExplicitTemplateArgs()) { |
12709 | DeclAccessPair dap; |
12710 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( |
12711 | ovl: OvlExpr, Complain: false, Found: &dap)) { |
12712 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) |
12713 | if (!Method->isStatic()) { |
12714 | // If the target type is a non-function type and the function found |
12715 | // is a non-static member function, pretend as if that was the |
12716 | // target, it's the only possible type to end up with. |
12717 | TargetTypeIsNonStaticMemberFunction = true; |
12718 | |
12719 | // And skip adding the function if its not in the proper form. |
12720 | // We'll diagnose this due to an empty set of functions. |
12721 | if (!OvlExprInfo.HasFormOfMemberPointer) |
12722 | return; |
12723 | } |
12724 | |
12725 | Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn)); |
12726 | } |
12727 | return; |
12728 | } |
12729 | |
12730 | if (OvlExpr->hasExplicitTemplateArgs()) |
12731 | OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs); |
12732 | |
12733 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { |
12734 | // C++ [over.over]p4: |
12735 | // If more than one function is selected, [...] |
12736 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { |
12737 | if (FoundNonTemplateFunction) |
12738 | EliminateAllTemplateMatches(); |
12739 | else |
12740 | EliminateAllExceptMostSpecializedTemplate(); |
12741 | } |
12742 | } |
12743 | |
12744 | if (S.getLangOpts().CUDA && Matches.size() > 1) |
12745 | EliminateSuboptimalCudaMatches(); |
12746 | } |
12747 | |
12748 | bool hasComplained() const { return HasComplained; } |
12749 | |
12750 | private: |
12751 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { |
12752 | QualType Discard; |
12753 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || |
12754 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); |
12755 | } |
12756 | |
12757 | /// \return true if A is considered a better overload candidate for the |
12758 | /// desired type than B. |
12759 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { |
12760 | // If A doesn't have exactly the correct type, we don't want to classify it |
12761 | // as "better" than anything else. This way, the user is required to |
12762 | // disambiguate for us if there are multiple candidates and no exact match. |
12763 | return candidateHasExactlyCorrectType(FD: A) && |
12764 | (!candidateHasExactlyCorrectType(FD: B) || |
12765 | compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better); |
12766 | } |
12767 | |
12768 | /// \return true if we were able to eliminate all but one overload candidate, |
12769 | /// false otherwise. |
12770 | bool eliminiateSuboptimalOverloadCandidates() { |
12771 | // Same algorithm as overload resolution -- one pass to pick the "best", |
12772 | // another pass to be sure that nothing is better than the best. |
12773 | auto Best = Matches.begin(); |
12774 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) |
12775 | if (isBetterCandidate(A: I->second, B: Best->second)) |
12776 | Best = I; |
12777 | |
12778 | const FunctionDecl *BestFn = Best->second; |
12779 | auto IsBestOrInferiorToBest = [this, BestFn]( |
12780 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { |
12781 | return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second); |
12782 | }; |
12783 | |
12784 | // Note: We explicitly leave Matches unmodified if there isn't a clear best |
12785 | // option, so we can potentially give the user a better error |
12786 | if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest)) |
12787 | return false; |
12788 | Matches[0] = *Best; |
12789 | Matches.resize(N: 1); |
12790 | return true; |
12791 | } |
12792 | |
12793 | bool isTargetTypeAFunction() const { |
12794 | return TargetFunctionType->isFunctionType(); |
12795 | } |
12796 | |
12797 | // [ToType] [Return] |
12798 | |
12799 | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false |
12800 | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false |
12801 | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true |
12802 | void inline () { |
12803 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); |
12804 | } |
12805 | |
12806 | // return true if any matching specializations were found |
12807 | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, |
12808 | const DeclAccessPair& CurAccessFunPair) { |
12809 | if (CXXMethodDecl *Method |
12810 | = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) { |
12811 | // Skip non-static function templates when converting to pointer, and |
12812 | // static when converting to member pointer. |
12813 | bool CanConvertToFunctionPointer = |
12814 | Method->isStatic() || Method->isExplicitObjectMemberFunction(); |
12815 | if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) |
12816 | return false; |
12817 | } |
12818 | else if (TargetTypeIsNonStaticMemberFunction) |
12819 | return false; |
12820 | |
12821 | // C++ [over.over]p2: |
12822 | // If the name is a function template, template argument deduction is |
12823 | // done (14.8.2.2), and if the argument deduction succeeds, the |
12824 | // resulting template argument list is used to generate a single |
12825 | // function template specialization, which is added to the set of |
12826 | // overloaded functions considered. |
12827 | FunctionDecl *Specialization = nullptr; |
12828 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
12829 | if (TemplateDeductionResult Result = S.DeduceTemplateArguments( |
12830 | FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType, |
12831 | Specialization, Info, /*IsAddressOfFunction*/ true); |
12832 | Result != TemplateDeductionResult::Success) { |
12833 | // Make a note of the failed deduction for diagnostics. |
12834 | FailedCandidates.addCandidate() |
12835 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), |
12836 | MakeDeductionFailureInfo(Context, TDK: Result, Info)); |
12837 | return false; |
12838 | } |
12839 | |
12840 | // Template argument deduction ensures that we have an exact match or |
12841 | // compatible pointer-to-function arguments that would be adjusted by ICS. |
12842 | // This function template specicalization works. |
12843 | assert(S.isSameOrCompatibleFunctionType( |
12844 | Context.getCanonicalType(Specialization->getType()), |
12845 | Context.getCanonicalType(TargetFunctionType))); |
12846 | |
12847 | if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization)) |
12848 | return false; |
12849 | |
12850 | Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization)); |
12851 | return true; |
12852 | } |
12853 | |
12854 | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, |
12855 | const DeclAccessPair& CurAccessFunPair) { |
12856 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) { |
12857 | // Skip non-static functions when converting to pointer, and static |
12858 | // when converting to member pointer. |
12859 | bool CanConvertToFunctionPointer = |
12860 | Method->isStatic() || Method->isExplicitObjectMemberFunction(); |
12861 | if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) |
12862 | return false; |
12863 | } |
12864 | else if (TargetTypeIsNonStaticMemberFunction) |
12865 | return false; |
12866 | |
12867 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) { |
12868 | if (S.getLangOpts().CUDA) { |
12869 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
12870 | if (!(Caller && Caller->isImplicit()) && |
12871 | !S.IsAllowedCUDACall(Caller, Callee: FunDecl)) |
12872 | return false; |
12873 | } |
12874 | if (FunDecl->isMultiVersion()) { |
12875 | const auto *TA = FunDecl->getAttr<TargetAttr>(); |
12876 | if (TA && !TA->isDefaultVersion()) |
12877 | return false; |
12878 | const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); |
12879 | if (TVA && !TVA->isDefaultVersion()) |
12880 | return false; |
12881 | } |
12882 | |
12883 | // If any candidate has a placeholder return type, trigger its deduction |
12884 | // now. |
12885 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), |
12886 | Complain)) { |
12887 | HasComplained |= Complain; |
12888 | return false; |
12889 | } |
12890 | |
12891 | if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl)) |
12892 | return false; |
12893 | |
12894 | // If we're in C, we need to support types that aren't exactly identical. |
12895 | if (!S.getLangOpts().CPlusPlus || |
12896 | candidateHasExactlyCorrectType(FD: FunDecl)) { |
12897 | Matches.push_back(Elt: std::make_pair( |
12898 | x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl()))); |
12899 | FoundNonTemplateFunction = true; |
12900 | return true; |
12901 | } |
12902 | } |
12903 | |
12904 | return false; |
12905 | } |
12906 | |
12907 | bool FindAllFunctionsThatMatchTargetTypeExactly() { |
12908 | bool Ret = false; |
12909 | |
12910 | // If the overload expression doesn't have the form of a pointer to |
12911 | // member, don't try to convert it to a pointer-to-member type. |
12912 | if (IsInvalidFormOfPointerToMemberFunction()) |
12913 | return false; |
12914 | |
12915 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
12916 | E = OvlExpr->decls_end(); |
12917 | I != E; ++I) { |
12918 | // Look through any using declarations to find the underlying function. |
12919 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); |
12920 | |
12921 | // C++ [over.over]p3: |
12922 | // Non-member functions and static member functions match |
12923 | // targets of type "pointer-to-function" or "reference-to-function." |
12924 | // Nonstatic member functions match targets of |
12925 | // type "pointer-to-member-function." |
12926 | // Note that according to DR 247, the containing class does not matter. |
12927 | if (FunctionTemplateDecl *FunctionTemplate |
12928 | = dyn_cast<FunctionTemplateDecl>(Val: Fn)) { |
12929 | if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair())) |
12930 | Ret = true; |
12931 | } |
12932 | // If we have explicit template arguments supplied, skip non-templates. |
12933 | else if (!OvlExpr->hasExplicitTemplateArgs() && |
12934 | AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair())) |
12935 | Ret = true; |
12936 | } |
12937 | assert(Ret || Matches.empty()); |
12938 | return Ret; |
12939 | } |
12940 | |
12941 | void EliminateAllExceptMostSpecializedTemplate() { |
12942 | // [...] and any given function template specialization F1 is |
12943 | // eliminated if the set contains a second function template |
12944 | // specialization whose function template is more specialized |
12945 | // than the function template of F1 according to the partial |
12946 | // ordering rules of 14.5.5.2. |
12947 | |
12948 | // The algorithm specified above is quadratic. We instead use a |
12949 | // two-pass algorithm (similar to the one used to identify the |
12950 | // best viable function in an overload set) that identifies the |
12951 | // best function template (if it exists). |
12952 | |
12953 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! |
12954 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) |
12955 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); |
12956 | |
12957 | // TODO: It looks like FailedCandidates does not serve much purpose |
12958 | // here, since the no_viable diagnostic has index 0. |
12959 | UnresolvedSetIterator Result = S.getMostSpecialized( |
12960 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, |
12961 | SourceExpr->getBeginLoc(), S.PDiag(), |
12962 | S.PDiag(diag::err_addr_ovl_ambiguous) |
12963 | << Matches[0].second->getDeclName(), |
12964 | S.PDiag(diag::note_ovl_candidate) |
12965 | << (unsigned)oc_function << (unsigned)ocs_described_template, |
12966 | Complain, TargetFunctionType); |
12967 | |
12968 | if (Result != MatchesCopy.end()) { |
12969 | // Make it the first and only element |
12970 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; |
12971 | Matches[0].second = cast<FunctionDecl>(Val: *Result); |
12972 | Matches.resize(N: 1); |
12973 | } else |
12974 | HasComplained |= Complain; |
12975 | } |
12976 | |
12977 | void EliminateAllTemplateMatches() { |
12978 | // [...] any function template specializations in the set are |
12979 | // eliminated if the set also contains a non-template function, [...] |
12980 | for (unsigned I = 0, N = Matches.size(); I != N; ) { |
12981 | if (Matches[I].second->getPrimaryTemplate() == nullptr) |
12982 | ++I; |
12983 | else { |
12984 | Matches[I] = Matches[--N]; |
12985 | Matches.resize(N); |
12986 | } |
12987 | } |
12988 | } |
12989 | |
12990 | void EliminateSuboptimalCudaMatches() { |
12991 | S.EraseUnwantedCUDAMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true), |
12992 | Matches); |
12993 | } |
12994 | |
12995 | public: |
12996 | void ComplainNoMatchesFound() const { |
12997 | assert(Matches.empty()); |
12998 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) |
12999 | << OvlExpr->getName() << TargetFunctionType |
13000 | << OvlExpr->getSourceRange(); |
13001 | if (FailedCandidates.empty()) |
13002 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
13003 | /*TakingAddress=*/true); |
13004 | else { |
13005 | // We have some deduction failure messages. Use them to diagnose |
13006 | // the function templates, and diagnose the non-template candidates |
13007 | // normally. |
13008 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
13009 | IEnd = OvlExpr->decls_end(); |
13010 | I != IEnd; ++I) |
13011 | if (FunctionDecl *Fun = |
13012 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) |
13013 | if (!functionHasPassObjectSizeParams(Fun)) |
13014 | S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, |
13015 | /*TakingAddress=*/true); |
13016 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); |
13017 | } |
13018 | } |
13019 | |
13020 | bool IsInvalidFormOfPointerToMemberFunction() const { |
13021 | return TargetTypeIsNonStaticMemberFunction && |
13022 | !OvlExprInfo.HasFormOfMemberPointer; |
13023 | } |
13024 | |
13025 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { |
13026 | // TODO: Should we condition this on whether any functions might |
13027 | // have matched, or is it more appropriate to do that in callers? |
13028 | // TODO: a fixit wouldn't hurt. |
13029 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) |
13030 | << TargetType << OvlExpr->getSourceRange(); |
13031 | } |
13032 | |
13033 | bool IsStaticMemberFunctionFromBoundPointer() const { |
13034 | return StaticMemberFunctionFromBoundPointer; |
13035 | } |
13036 | |
13037 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { |
13038 | S.Diag(OvlExpr->getBeginLoc(), |
13039 | diag::err_invalid_form_pointer_member_function) |
13040 | << OvlExpr->getSourceRange(); |
13041 | } |
13042 | |
13043 | void ComplainOfInvalidConversion() const { |
13044 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) |
13045 | << OvlExpr->getName() << TargetType; |
13046 | } |
13047 | |
13048 | void ComplainMultipleMatchesFound() const { |
13049 | assert(Matches.size() > 1); |
13050 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) |
13051 | << OvlExpr->getName() << OvlExpr->getSourceRange(); |
13052 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
13053 | /*TakingAddress=*/true); |
13054 | } |
13055 | |
13056 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } |
13057 | |
13058 | int getNumMatches() const { return Matches.size(); } |
13059 | |
13060 | FunctionDecl* getMatchingFunctionDecl() const { |
13061 | if (Matches.size() != 1) return nullptr; |
13062 | return Matches[0].second; |
13063 | } |
13064 | |
13065 | const DeclAccessPair* getMatchingFunctionAccessPair() const { |
13066 | if (Matches.size() != 1) return nullptr; |
13067 | return &Matches[0].first; |
13068 | } |
13069 | }; |
13070 | } |
13071 | |
13072 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of |
13073 | /// an overloaded function (C++ [over.over]), where @p From is an |
13074 | /// expression with overloaded function type and @p ToType is the type |
13075 | /// we're trying to resolve to. For example: |
13076 | /// |
13077 | /// @code |
13078 | /// int f(double); |
13079 | /// int f(int); |
13080 | /// |
13081 | /// int (*pfd)(double) = f; // selects f(double) |
13082 | /// @endcode |
13083 | /// |
13084 | /// This routine returns the resulting FunctionDecl if it could be |
13085 | /// resolved, and NULL otherwise. When @p Complain is true, this |
13086 | /// routine will emit diagnostics if there is an error. |
13087 | FunctionDecl * |
13088 | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
13089 | QualType TargetType, |
13090 | bool Complain, |
13091 | DeclAccessPair &FoundResult, |
13092 | bool *pHadMultipleCandidates) { |
13093 | assert(AddressOfExpr->getType() == Context.OverloadTy); |
13094 | |
13095 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, |
13096 | Complain); |
13097 | int NumMatches = Resolver.getNumMatches(); |
13098 | FunctionDecl *Fn = nullptr; |
13099 | bool ShouldComplain = Complain && !Resolver.hasComplained(); |
13100 | if (NumMatches == 0 && ShouldComplain) { |
13101 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) |
13102 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); |
13103 | else |
13104 | Resolver.ComplainNoMatchesFound(); |
13105 | } |
13106 | else if (NumMatches > 1 && ShouldComplain) |
13107 | Resolver.ComplainMultipleMatchesFound(); |
13108 | else if (NumMatches == 1) { |
13109 | Fn = Resolver.getMatchingFunctionDecl(); |
13110 | assert(Fn); |
13111 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
13112 | ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT: FPT); |
13113 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); |
13114 | if (Complain) { |
13115 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) |
13116 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); |
13117 | else |
13118 | CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult); |
13119 | } |
13120 | } |
13121 | |
13122 | if (pHadMultipleCandidates) |
13123 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); |
13124 | return Fn; |
13125 | } |
13126 | |
13127 | /// Given an expression that refers to an overloaded function, try to |
13128 | /// resolve that function to a single function that can have its address taken. |
13129 | /// This will modify `Pair` iff it returns non-null. |
13130 | /// |
13131 | /// This routine can only succeed if from all of the candidates in the overload |
13132 | /// set for SrcExpr that can have their addresses taken, there is one candidate |
13133 | /// that is more constrained than the rest. |
13134 | FunctionDecl * |
13135 | Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { |
13136 | OverloadExpr::FindResult R = OverloadExpr::find(E); |
13137 | OverloadExpr *Ovl = R.Expression; |
13138 | bool IsResultAmbiguous = false; |
13139 | FunctionDecl *Result = nullptr; |
13140 | DeclAccessPair DAP; |
13141 | SmallVector<FunctionDecl *, 2> AmbiguousDecls; |
13142 | |
13143 | // Return positive for better, negative for worse, 0 for equal preference. |
13144 | auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) { |
13145 | FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
13146 | return static_cast<int>(IdentifyCUDAPreference(Caller, Callee: FD1)) - |
13147 | static_cast<int>(IdentifyCUDAPreference(Caller, Callee: FD2)); |
13148 | }; |
13149 | |
13150 | auto CheckMoreConstrained = [&](FunctionDecl *FD1, |
13151 | FunctionDecl *FD2) -> std::optional<bool> { |
13152 | if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) |
13153 | FD1 = MF; |
13154 | if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) |
13155 | FD2 = MF; |
13156 | SmallVector<const Expr *, 1> AC1, AC2; |
13157 | FD1->getAssociatedConstraints(AC&: AC1); |
13158 | FD2->getAssociatedConstraints(AC&: AC2); |
13159 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
13160 | if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) |
13161 | return std::nullopt; |
13162 | if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) |
13163 | return std::nullopt; |
13164 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
13165 | return std::nullopt; |
13166 | return AtLeastAsConstrained1; |
13167 | }; |
13168 | |
13169 | // Don't use the AddressOfResolver because we're specifically looking for |
13170 | // cases where we have one overload candidate that lacks |
13171 | // enable_if/pass_object_size/... |
13172 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { |
13173 | auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl()); |
13174 | if (!FD) |
13175 | return nullptr; |
13176 | |
13177 | if (!checkAddressOfFunctionIsAvailable(Function: FD)) |
13178 | continue; |
13179 | |
13180 | // If we found a better result, update Result. |
13181 | auto FoundBetter = [&]() { |
13182 | IsResultAmbiguous = false; |
13183 | DAP = I.getPair(); |
13184 | Result = FD; |
13185 | }; |
13186 | |
13187 | // We have more than one result - see if it is more constrained than the |
13188 | // previous one. |
13189 | if (Result) { |
13190 | // Check CUDA preference first. If the candidates have differennt CUDA |
13191 | // preference, choose the one with higher CUDA preference. Otherwise, |
13192 | // choose the one with more constraints. |
13193 | if (getLangOpts().CUDA) { |
13194 | int PreferenceByCUDA = CheckCUDAPreference(FD, Result); |
13195 | // FD has different preference than Result. |
13196 | if (PreferenceByCUDA != 0) { |
13197 | // FD is more preferable than Result. |
13198 | if (PreferenceByCUDA > 0) |
13199 | FoundBetter(); |
13200 | continue; |
13201 | } |
13202 | } |
13203 | // FD has the same CUDA prefernece than Result. Continue check |
13204 | // constraints. |
13205 | std::optional<bool> MoreConstrainedThanPrevious = |
13206 | CheckMoreConstrained(FD, Result); |
13207 | if (!MoreConstrainedThanPrevious) { |
13208 | IsResultAmbiguous = true; |
13209 | AmbiguousDecls.push_back(Elt: FD); |
13210 | continue; |
13211 | } |
13212 | if (!*MoreConstrainedThanPrevious) |
13213 | continue; |
13214 | // FD is more constrained - replace Result with it. |
13215 | } |
13216 | FoundBetter(); |
13217 | } |
13218 | |
13219 | if (IsResultAmbiguous) |
13220 | return nullptr; |
13221 | |
13222 | if (Result) { |
13223 | SmallVector<const Expr *, 1> ResultAC; |
13224 | // We skipped over some ambiguous declarations which might be ambiguous with |
13225 | // the selected result. |
13226 | for (FunctionDecl *Skipped : AmbiguousDecls) { |
13227 | // If skipped candidate has different CUDA preference than the result, |
13228 | // there is no ambiguity. Otherwise check whether they have different |
13229 | // constraints. |
13230 | if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0) |
13231 | continue; |
13232 | if (!CheckMoreConstrained(Skipped, Result)) |
13233 | return nullptr; |
13234 | } |
13235 | Pair = DAP; |
13236 | } |
13237 | return Result; |
13238 | } |
13239 | |
13240 | /// Given an overloaded function, tries to turn it into a non-overloaded |
13241 | /// function reference using resolveAddressOfSingleOverloadCandidate. This |
13242 | /// will perform access checks, diagnose the use of the resultant decl, and, if |
13243 | /// requested, potentially perform a function-to-pointer decay. |
13244 | /// |
13245 | /// Returns false if resolveAddressOfSingleOverloadCandidate fails. |
13246 | /// Otherwise, returns true. This may emit diagnostics and return true. |
13247 | bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( |
13248 | ExprResult &SrcExpr, bool DoFunctionPointerConversion) { |
13249 | Expr *E = SrcExpr.get(); |
13250 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload" ); |
13251 | |
13252 | DeclAccessPair DAP; |
13253 | FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP); |
13254 | if (!Found || Found->isCPUDispatchMultiVersion() || |
13255 | Found->isCPUSpecificMultiVersion()) |
13256 | return false; |
13257 | |
13258 | // Emitting multiple diagnostics for a function that is both inaccessible and |
13259 | // unavailable is consistent with our behavior elsewhere. So, always check |
13260 | // for both. |
13261 | DiagnoseUseOfDecl(Found, E->getExprLoc()); |
13262 | CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP); |
13263 | ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found); |
13264 | if (Res.isInvalid()) |
13265 | return false; |
13266 | Expr *Fixed = Res.get(); |
13267 | if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) |
13268 | SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false); |
13269 | else |
13270 | SrcExpr = Fixed; |
13271 | return true; |
13272 | } |
13273 | |
13274 | /// Given an expression that refers to an overloaded function, try to |
13275 | /// resolve that overloaded function expression down to a single function. |
13276 | /// |
13277 | /// This routine can only resolve template-ids that refer to a single function |
13278 | /// template, where that template-id refers to a single template whose template |
13279 | /// arguments are either provided by the template-id or have defaults, |
13280 | /// as described in C++0x [temp.arg.explicit]p3. |
13281 | /// |
13282 | /// If no template-ids are found, no diagnostics are emitted and NULL is |
13283 | /// returned. |
13284 | FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( |
13285 | OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult, |
13286 | TemplateSpecCandidateSet *FailedTSC) { |
13287 | // C++ [over.over]p1: |
13288 | // [...] [Note: any redundant set of parentheses surrounding the |
13289 | // overloaded function name is ignored (5.1). ] |
13290 | // C++ [over.over]p1: |
13291 | // [...] The overloaded function name can be preceded by the & |
13292 | // operator. |
13293 | |
13294 | // If we didn't actually find any template-ids, we're done. |
13295 | if (!ovl->hasExplicitTemplateArgs()) |
13296 | return nullptr; |
13297 | |
13298 | TemplateArgumentListInfo ExplicitTemplateArgs; |
13299 | ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs); |
13300 | |
13301 | // Look through all of the overloaded functions, searching for one |
13302 | // whose type matches exactly. |
13303 | FunctionDecl *Matched = nullptr; |
13304 | for (UnresolvedSetIterator I = ovl->decls_begin(), |
13305 | E = ovl->decls_end(); I != E; ++I) { |
13306 | // C++0x [temp.arg.explicit]p3: |
13307 | // [...] In contexts where deduction is done and fails, or in contexts |
13308 | // where deduction is not done, if a template argument list is |
13309 | // specified and it, along with any default template arguments, |
13310 | // identifies a single function template specialization, then the |
13311 | // template-id is an lvalue for the function template specialization. |
13312 | FunctionTemplateDecl *FunctionTemplate |
13313 | = cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()); |
13314 | |
13315 | // C++ [over.over]p2: |
13316 | // If the name is a function template, template argument deduction is |
13317 | // done (14.8.2.2), and if the argument deduction succeeds, the |
13318 | // resulting template argument list is used to generate a single |
13319 | // function template specialization, which is added to the set of |
13320 | // overloaded functions considered. |
13321 | FunctionDecl *Specialization = nullptr; |
13322 | TemplateDeductionInfo Info(ovl->getNameLoc()); |
13323 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
13324 | FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info, |
13325 | /*IsAddressOfFunction*/ true); |
13326 | Result != TemplateDeductionResult::Success) { |
13327 | // Make a note of the failed deduction for diagnostics. |
13328 | if (FailedTSC) |
13329 | FailedTSC->addCandidate().set( |
13330 | I.getPair(), FunctionTemplate->getTemplatedDecl(), |
13331 | MakeDeductionFailureInfo(Context, TDK: Result, Info)); |
13332 | continue; |
13333 | } |
13334 | |
13335 | assert(Specialization && "no specialization and no error?" ); |
13336 | |
13337 | // Multiple matches; we can't resolve to a single declaration. |
13338 | if (Matched) { |
13339 | if (Complain) { |
13340 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) |
13341 | << ovl->getName(); |
13342 | NoteAllOverloadCandidates(ovl); |
13343 | } |
13344 | return nullptr; |
13345 | } |
13346 | |
13347 | Matched = Specialization; |
13348 | if (FoundResult) *FoundResult = I.getPair(); |
13349 | } |
13350 | |
13351 | if (Matched && |
13352 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) |
13353 | return nullptr; |
13354 | |
13355 | return Matched; |
13356 | } |
13357 | |
13358 | // Resolve and fix an overloaded expression that can be resolved |
13359 | // because it identifies a single function template specialization. |
13360 | // |
13361 | // Last three arguments should only be supplied if Complain = true |
13362 | // |
13363 | // Return true if it was logically possible to so resolve the |
13364 | // expression, regardless of whether or not it succeeded. Always |
13365 | // returns true if 'complain' is set. |
13366 | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( |
13367 | ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, |
13368 | SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, |
13369 | unsigned DiagIDForComplaining) { |
13370 | assert(SrcExpr.get()->getType() == Context.OverloadTy); |
13371 | |
13372 | OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get()); |
13373 | |
13374 | DeclAccessPair found; |
13375 | ExprResult SingleFunctionExpression; |
13376 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( |
13377 | ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) { |
13378 | if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) { |
13379 | SrcExpr = ExprError(); |
13380 | return true; |
13381 | } |
13382 | |
13383 | // It is only correct to resolve to an instance method if we're |
13384 | // resolving a form that's permitted to be a pointer to member. |
13385 | // Otherwise we'll end up making a bound member expression, which |
13386 | // is illegal in all the contexts we resolve like this. |
13387 | if (!ovl.HasFormOfMemberPointer && |
13388 | isa<CXXMethodDecl>(Val: fn) && |
13389 | cast<CXXMethodDecl>(Val: fn)->isInstance()) { |
13390 | if (!complain) return false; |
13391 | |
13392 | Diag(ovl.Expression->getExprLoc(), |
13393 | diag::err_bound_member_function) |
13394 | << 0 << ovl.Expression->getSourceRange(); |
13395 | |
13396 | // TODO: I believe we only end up here if there's a mix of |
13397 | // static and non-static candidates (otherwise the expression |
13398 | // would have 'bound member' type, not 'overload' type). |
13399 | // Ideally we would note which candidate was chosen and why |
13400 | // the static candidates were rejected. |
13401 | SrcExpr = ExprError(); |
13402 | return true; |
13403 | } |
13404 | |
13405 | // Fix the expression to refer to 'fn'. |
13406 | SingleFunctionExpression = |
13407 | FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn); |
13408 | |
13409 | // If desired, do function-to-pointer decay. |
13410 | if (doFunctionPointerConversion) { |
13411 | SingleFunctionExpression = |
13412 | DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get()); |
13413 | if (SingleFunctionExpression.isInvalid()) { |
13414 | SrcExpr = ExprError(); |
13415 | return true; |
13416 | } |
13417 | } |
13418 | } |
13419 | |
13420 | if (!SingleFunctionExpression.isUsable()) { |
13421 | if (complain) { |
13422 | Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining) |
13423 | << ovl.Expression->getName() |
13424 | << DestTypeForComplaining |
13425 | << OpRangeForComplaining |
13426 | << ovl.Expression->getQualifierLoc().getSourceRange(); |
13427 | NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get()); |
13428 | |
13429 | SrcExpr = ExprError(); |
13430 | return true; |
13431 | } |
13432 | |
13433 | return false; |
13434 | } |
13435 | |
13436 | SrcExpr = SingleFunctionExpression; |
13437 | return true; |
13438 | } |
13439 | |
13440 | /// Add a single candidate to the overload set. |
13441 | static void AddOverloadedCallCandidate(Sema &S, |
13442 | DeclAccessPair FoundDecl, |
13443 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
13444 | ArrayRef<Expr *> Args, |
13445 | OverloadCandidateSet &CandidateSet, |
13446 | bool PartialOverloading, |
13447 | bool KnownValid) { |
13448 | NamedDecl *Callee = FoundDecl.getDecl(); |
13449 | if (isa<UsingShadowDecl>(Val: Callee)) |
13450 | Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl(); |
13451 | |
13452 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) { |
13453 | if (ExplicitTemplateArgs) { |
13454 | assert(!KnownValid && "Explicit template arguments?" ); |
13455 | return; |
13456 | } |
13457 | // Prevent ill-formed function decls to be added as overload candidates. |
13458 | if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) |
13459 | return; |
13460 | |
13461 | S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet, |
13462 | /*SuppressUserConversions=*/false, |
13463 | PartialOverloading); |
13464 | return; |
13465 | } |
13466 | |
13467 | if (FunctionTemplateDecl *FuncTemplate |
13468 | = dyn_cast<FunctionTemplateDecl>(Val: Callee)) { |
13469 | S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl, |
13470 | ExplicitTemplateArgs, Args, CandidateSet, |
13471 | /*SuppressUserConversions=*/false, |
13472 | PartialOverloading); |
13473 | return; |
13474 | } |
13475 | |
13476 | assert(!KnownValid && "unhandled case in overloaded call candidate" ); |
13477 | } |
13478 | |
13479 | /// Add the overload candidates named by callee and/or found by argument |
13480 | /// dependent lookup to the given overload set. |
13481 | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
13482 | ArrayRef<Expr *> Args, |
13483 | OverloadCandidateSet &CandidateSet, |
13484 | bool PartialOverloading) { |
13485 | |
13486 | #ifndef NDEBUG |
13487 | // Verify that ArgumentDependentLookup is consistent with the rules |
13488 | // in C++0x [basic.lookup.argdep]p3: |
13489 | // |
13490 | // Let X be the lookup set produced by unqualified lookup (3.4.1) |
13491 | // and let Y be the lookup set produced by argument dependent |
13492 | // lookup (defined as follows). If X contains |
13493 | // |
13494 | // -- a declaration of a class member, or |
13495 | // |
13496 | // -- a block-scope function declaration that is not a |
13497 | // using-declaration, or |
13498 | // |
13499 | // -- a declaration that is neither a function or a function |
13500 | // template |
13501 | // |
13502 | // then Y is empty. |
13503 | |
13504 | if (ULE->requiresADL()) { |
13505 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13506 | E = ULE->decls_end(); I != E; ++I) { |
13507 | assert(!(*I)->getDeclContext()->isRecord()); |
13508 | assert(isa<UsingShadowDecl>(*I) || |
13509 | !(*I)->getDeclContext()->isFunctionOrMethod()); |
13510 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); |
13511 | } |
13512 | } |
13513 | #endif |
13514 | |
13515 | // It would be nice to avoid this copy. |
13516 | TemplateArgumentListInfo TABuffer; |
13517 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13518 | if (ULE->hasExplicitTemplateArgs()) { |
13519 | ULE->copyTemplateArgumentsInto(TABuffer); |
13520 | ExplicitTemplateArgs = &TABuffer; |
13521 | } |
13522 | |
13523 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13524 | E = ULE->decls_end(); I != E; ++I) |
13525 | AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args, |
13526 | CandidateSet, PartialOverloading, |
13527 | /*KnownValid*/ true); |
13528 | |
13529 | if (ULE->requiresADL()) |
13530 | AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(), |
13531 | Args, ExplicitTemplateArgs, |
13532 | CandidateSet, PartialOverloading); |
13533 | } |
13534 | |
13535 | /// Add the call candidates from the given set of lookup results to the given |
13536 | /// overload set. Non-function lookup results are ignored. |
13537 | void Sema::AddOverloadedCallCandidates( |
13538 | LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, |
13539 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { |
13540 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) |
13541 | AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args, |
13542 | CandidateSet, PartialOverloading: false, /*KnownValid*/ false); |
13543 | } |
13544 | |
13545 | /// Determine whether a declaration with the specified name could be moved into |
13546 | /// a different namespace. |
13547 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { |
13548 | switch (Name.getCXXOverloadedOperator()) { |
13549 | case OO_New: case OO_Array_New: |
13550 | case OO_Delete: case OO_Array_Delete: |
13551 | return false; |
13552 | |
13553 | default: |
13554 | return true; |
13555 | } |
13556 | } |
13557 | |
13558 | /// Attempt to recover from an ill-formed use of a non-dependent name in a |
13559 | /// template, where the non-dependent name was declared after the template |
13560 | /// was defined. This is common in code written for a compilers which do not |
13561 | /// correctly implement two-stage name lookup. |
13562 | /// |
13563 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13564 | static bool DiagnoseTwoPhaseLookup( |
13565 | Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, |
13566 | LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, |
13567 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
13568 | CXXRecordDecl **FoundInClass = nullptr) { |
13569 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) |
13570 | return false; |
13571 | |
13572 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { |
13573 | if (DC->isTransparentContext()) |
13574 | continue; |
13575 | |
13576 | SemaRef.LookupQualifiedName(R, LookupCtx: DC); |
13577 | |
13578 | if (!R.empty()) { |
13579 | R.suppressDiagnostics(); |
13580 | |
13581 | OverloadCandidateSet Candidates(FnLoc, CSK); |
13582 | SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, |
13583 | CandidateSet&: Candidates); |
13584 | |
13585 | OverloadCandidateSet::iterator Best; |
13586 | OverloadingResult OR = |
13587 | Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best); |
13588 | |
13589 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) { |
13590 | // We either found non-function declarations or a best viable function |
13591 | // at class scope. A class-scope lookup result disables ADL. Don't |
13592 | // look past this, but let the caller know that we found something that |
13593 | // either is, or might be, usable in this class. |
13594 | if (FoundInClass) { |
13595 | *FoundInClass = RD; |
13596 | if (OR == OR_Success) { |
13597 | R.clear(); |
13598 | R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess()); |
13599 | R.resolveKind(); |
13600 | } |
13601 | } |
13602 | return false; |
13603 | } |
13604 | |
13605 | if (OR != OR_Success) { |
13606 | // There wasn't a unique best function or function template. |
13607 | return false; |
13608 | } |
13609 | |
13610 | // Find the namespaces where ADL would have looked, and suggest |
13611 | // declaring the function there instead. |
13612 | Sema::AssociatedNamespaceSet AssociatedNamespaces; |
13613 | Sema::AssociatedClassSet AssociatedClasses; |
13614 | SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args, |
13615 | AssociatedNamespaces, |
13616 | AssociatedClasses); |
13617 | Sema::AssociatedNamespaceSet SuggestedNamespaces; |
13618 | if (canBeDeclaredInNamespace(Name: R.getLookupName())) { |
13619 | DeclContext *Std = SemaRef.getStdNamespace(); |
13620 | for (Sema::AssociatedNamespaceSet::iterator |
13621 | it = AssociatedNamespaces.begin(), |
13622 | end = AssociatedNamespaces.end(); it != end; ++it) { |
13623 | // Never suggest declaring a function within namespace 'std'. |
13624 | if (Std && Std->Encloses(DC: *it)) |
13625 | continue; |
13626 | |
13627 | // Never suggest declaring a function within a namespace with a |
13628 | // reserved name, like __gnu_cxx. |
13629 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it); |
13630 | if (NS && |
13631 | NS->getQualifiedNameAsString().find("__" ) != std::string::npos) |
13632 | continue; |
13633 | |
13634 | SuggestedNamespaces.insert(X: *it); |
13635 | } |
13636 | } |
13637 | |
13638 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) |
13639 | << R.getLookupName(); |
13640 | if (SuggestedNamespaces.empty()) { |
13641 | SemaRef.Diag(Best->Function->getLocation(), |
13642 | diag::note_not_found_by_two_phase_lookup) |
13643 | << R.getLookupName() << 0; |
13644 | } else if (SuggestedNamespaces.size() == 1) { |
13645 | SemaRef.Diag(Best->Function->getLocation(), |
13646 | diag::note_not_found_by_two_phase_lookup) |
13647 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); |
13648 | } else { |
13649 | // FIXME: It would be useful to list the associated namespaces here, |
13650 | // but the diagnostics infrastructure doesn't provide a way to produce |
13651 | // a localized representation of a list of items. |
13652 | SemaRef.Diag(Best->Function->getLocation(), |
13653 | diag::note_not_found_by_two_phase_lookup) |
13654 | << R.getLookupName() << 2; |
13655 | } |
13656 | |
13657 | // Try to recover by calling this function. |
13658 | return true; |
13659 | } |
13660 | |
13661 | R.clear(); |
13662 | } |
13663 | |
13664 | return false; |
13665 | } |
13666 | |
13667 | /// Attempt to recover from ill-formed use of a non-dependent operator in a |
13668 | /// template, where the non-dependent operator was declared after the template |
13669 | /// was defined. |
13670 | /// |
13671 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13672 | static bool |
13673 | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, |
13674 | SourceLocation OpLoc, |
13675 | ArrayRef<Expr *> Args) { |
13676 | DeclarationName OpName = |
13677 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); |
13678 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); |
13679 | return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R, |
13680 | CSK: OverloadCandidateSet::CSK_Operator, |
13681 | /*ExplicitTemplateArgs=*/nullptr, Args); |
13682 | } |
13683 | |
13684 | namespace { |
13685 | class BuildRecoveryCallExprRAII { |
13686 | Sema &SemaRef; |
13687 | Sema::SatisfactionStackResetRAII SatStack; |
13688 | |
13689 | public: |
13690 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { |
13691 | assert(SemaRef.IsBuildingRecoveryCallExpr == false); |
13692 | SemaRef.IsBuildingRecoveryCallExpr = true; |
13693 | } |
13694 | |
13695 | ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } |
13696 | }; |
13697 | } |
13698 | |
13699 | /// Attempts to recover from a call where no functions were found. |
13700 | /// |
13701 | /// This function will do one of three things: |
13702 | /// * Diagnose, recover, and return a recovery expression. |
13703 | /// * Diagnose, fail to recover, and return ExprError(). |
13704 | /// * Do not diagnose, do not recover, and return ExprResult(). The caller is |
13705 | /// expected to diagnose as appropriate. |
13706 | static ExprResult |
13707 | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13708 | UnresolvedLookupExpr *ULE, |
13709 | SourceLocation LParenLoc, |
13710 | MutableArrayRef<Expr *> Args, |
13711 | SourceLocation RParenLoc, |
13712 | bool EmptyLookup, bool AllowTypoCorrection) { |
13713 | // Do not try to recover if it is already building a recovery call. |
13714 | // This stops infinite loops for template instantiations like |
13715 | // |
13716 | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} |
13717 | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} |
13718 | if (SemaRef.IsBuildingRecoveryCallExpr) |
13719 | return ExprResult(); |
13720 | BuildRecoveryCallExprRAII RCE(SemaRef); |
13721 | |
13722 | CXXScopeSpec SS; |
13723 | SS.Adopt(Other: ULE->getQualifierLoc()); |
13724 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); |
13725 | |
13726 | TemplateArgumentListInfo TABuffer; |
13727 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13728 | if (ULE->hasExplicitTemplateArgs()) { |
13729 | ULE->copyTemplateArgumentsInto(TABuffer); |
13730 | ExplicitTemplateArgs = &TABuffer; |
13731 | } |
13732 | |
13733 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), |
13734 | Sema::LookupOrdinaryName); |
13735 | CXXRecordDecl *FoundInClass = nullptr; |
13736 | if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R, |
13737 | CSK: OverloadCandidateSet::CSK_Normal, |
13738 | ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) { |
13739 | // OK, diagnosed a two-phase lookup issue. |
13740 | } else if (EmptyLookup) { |
13741 | // Try to recover from an empty lookup with typo correction. |
13742 | R.clear(); |
13743 | NoTypoCorrectionCCC NoTypoValidator{}; |
13744 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), |
13745 | ExplicitTemplateArgs != nullptr, |
13746 | dyn_cast<MemberExpr>(Val: Fn)); |
13747 | CorrectionCandidateCallback &Validator = |
13748 | AllowTypoCorrection |
13749 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) |
13750 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); |
13751 | if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs, |
13752 | Args)) |
13753 | return ExprError(); |
13754 | } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { |
13755 | // We found a usable declaration of the name in a dependent base of some |
13756 | // enclosing class. |
13757 | // FIXME: We should also explain why the candidates found by name lookup |
13758 | // were not viable. |
13759 | if (SemaRef.DiagnoseDependentMemberLookup(R)) |
13760 | return ExprError(); |
13761 | } else { |
13762 | // We had viable candidates and couldn't recover; let the caller diagnose |
13763 | // this. |
13764 | return ExprResult(); |
13765 | } |
13766 | |
13767 | // If we get here, we should have issued a diagnostic and formed a recovery |
13768 | // lookup result. |
13769 | assert(!R.empty() && "lookup results empty despite recovery" ); |
13770 | |
13771 | // If recovery created an ambiguity, just bail out. |
13772 | if (R.isAmbiguous()) { |
13773 | R.suppressDiagnostics(); |
13774 | return ExprError(); |
13775 | } |
13776 | |
13777 | // Build an implicit member call if appropriate. Just drop the |
13778 | // casts and such from the call, we don't really care. |
13779 | ExprResult NewFn = ExprError(); |
13780 | if ((*R.begin())->isCXXClassMember()) |
13781 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, |
13782 | TemplateArgs: ExplicitTemplateArgs, S); |
13783 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) |
13784 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false, |
13785 | TemplateArgs: ExplicitTemplateArgs); |
13786 | else |
13787 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false); |
13788 | |
13789 | if (NewFn.isInvalid()) |
13790 | return ExprError(); |
13791 | |
13792 | // This shouldn't cause an infinite loop because we're giving it |
13793 | // an expression with viable lookup results, which should never |
13794 | // end up here. |
13795 | return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc, |
13796 | ArgExprs: MultiExprArg(Args.data(), Args.size()), |
13797 | RParenLoc); |
13798 | } |
13799 | |
13800 | /// Constructs and populates an OverloadedCandidateSet from |
13801 | /// the given function. |
13802 | /// \returns true when an the ExprResult output parameter has been set. |
13803 | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, |
13804 | UnresolvedLookupExpr *ULE, |
13805 | MultiExprArg Args, |
13806 | SourceLocation RParenLoc, |
13807 | OverloadCandidateSet *CandidateSet, |
13808 | ExprResult *Result) { |
13809 | #ifndef NDEBUG |
13810 | if (ULE->requiresADL()) { |
13811 | // To do ADL, we must have found an unqualified name. |
13812 | assert(!ULE->getQualifier() && "qualified name with ADL" ); |
13813 | |
13814 | // We don't perform ADL for implicit declarations of builtins. |
13815 | // Verify that this was correctly set up. |
13816 | FunctionDecl *F; |
13817 | if (ULE->decls_begin() != ULE->decls_end() && |
13818 | ULE->decls_begin() + 1 == ULE->decls_end() && |
13819 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && |
13820 | F->getBuiltinID() && F->isImplicit()) |
13821 | llvm_unreachable("performing ADL for builtin" ); |
13822 | |
13823 | // We don't perform ADL in C. |
13824 | assert(getLangOpts().CPlusPlus && "ADL enabled in C" ); |
13825 | } |
13826 | #endif |
13827 | |
13828 | UnbridgedCastsSet UnbridgedCasts; |
13829 | if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) { |
13830 | *Result = ExprError(); |
13831 | return true; |
13832 | } |
13833 | |
13834 | // Add the functions denoted by the callee to the set of candidate |
13835 | // functions, including those from argument-dependent lookup. |
13836 | AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet); |
13837 | |
13838 | if (getLangOpts().MSVCCompat && |
13839 | CurContext->isDependentContext() && !isSFINAEContext() && |
13840 | (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) { |
13841 | |
13842 | OverloadCandidateSet::iterator Best; |
13843 | if (CandidateSet->empty() || |
13844 | CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) == |
13845 | OR_No_Viable_Function) { |
13846 | // In Microsoft mode, if we are inside a template class member function |
13847 | // then create a type dependent CallExpr. The goal is to postpone name |
13848 | // lookup to instantiation time to be able to search into type dependent |
13849 | // base classes. |
13850 | CallExpr *CE = |
13851 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue, |
13852 | RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
13853 | CE->markDependentForPostponedNameLookup(); |
13854 | *Result = CE; |
13855 | return true; |
13856 | } |
13857 | } |
13858 | |
13859 | if (CandidateSet->empty()) |
13860 | return false; |
13861 | |
13862 | UnbridgedCasts.restore(); |
13863 | return false; |
13864 | } |
13865 | |
13866 | // Guess at what the return type for an unresolvable overload should be. |
13867 | static QualType chooseRecoveryType(OverloadCandidateSet &CS, |
13868 | OverloadCandidateSet::iterator *Best) { |
13869 | std::optional<QualType> Result; |
13870 | // Adjust Type after seeing a candidate. |
13871 | auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { |
13872 | if (!Candidate.Function) |
13873 | return; |
13874 | if (Candidate.Function->isInvalidDecl()) |
13875 | return; |
13876 | QualType T = Candidate.Function->getReturnType(); |
13877 | if (T.isNull()) |
13878 | return; |
13879 | if (!Result) |
13880 | Result = T; |
13881 | else if (Result != T) |
13882 | Result = QualType(); |
13883 | }; |
13884 | |
13885 | // Look for an unambiguous type from a progressively larger subset. |
13886 | // e.g. if types disagree, but all *viable* overloads return int, choose int. |
13887 | // |
13888 | // First, consider only the best candidate. |
13889 | if (Best && *Best != CS.end()) |
13890 | ConsiderCandidate(**Best); |
13891 | // Next, consider only viable candidates. |
13892 | if (!Result) |
13893 | for (const auto &C : CS) |
13894 | if (C.Viable) |
13895 | ConsiderCandidate(C); |
13896 | // Finally, consider all candidates. |
13897 | if (!Result) |
13898 | for (const auto &C : CS) |
13899 | ConsiderCandidate(C); |
13900 | |
13901 | if (!Result) |
13902 | return QualType(); |
13903 | auto Value = *Result; |
13904 | if (Value.isNull() || Value->isUndeducedType()) |
13905 | return QualType(); |
13906 | return Value; |
13907 | } |
13908 | |
13909 | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns |
13910 | /// the completed call expression. If overload resolution fails, emits |
13911 | /// diagnostics and returns ExprError() |
13912 | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13913 | UnresolvedLookupExpr *ULE, |
13914 | SourceLocation LParenLoc, |
13915 | MultiExprArg Args, |
13916 | SourceLocation RParenLoc, |
13917 | Expr *ExecConfig, |
13918 | OverloadCandidateSet *CandidateSet, |
13919 | OverloadCandidateSet::iterator *Best, |
13920 | OverloadingResult OverloadResult, |
13921 | bool AllowTypoCorrection) { |
13922 | switch (OverloadResult) { |
13923 | case OR_Success: { |
13924 | FunctionDecl *FDecl = (*Best)->Function; |
13925 | SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl); |
13926 | if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc())) |
13927 | return ExprError(); |
13928 | ExprResult Res = |
13929 | SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl); |
13930 | if (Res.isInvalid()) |
13931 | return ExprError(); |
13932 | return SemaRef.BuildResolvedCallExpr( |
13933 | Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, |
13934 | /*IsExecConfig=*/false, (*Best)->IsADLCandidate); |
13935 | } |
13936 | |
13937 | case OR_No_Viable_Function: { |
13938 | // Try to recover by looking for viable functions which the user might |
13939 | // have meant to call. |
13940 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, |
13941 | Args, RParenLoc, |
13942 | EmptyLookup: CandidateSet->empty(), |
13943 | AllowTypoCorrection); |
13944 | if (Recovery.isInvalid() || Recovery.isUsable()) |
13945 | return Recovery; |
13946 | |
13947 | // If the user passes in a function that we can't take the address of, we |
13948 | // generally end up emitting really bad error messages. Here, we attempt to |
13949 | // emit better ones. |
13950 | for (const Expr *Arg : Args) { |
13951 | if (!Arg->getType()->isFunctionType()) |
13952 | continue; |
13953 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) { |
13954 | auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()); |
13955 | if (FD && |
13956 | !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
13957 | Loc: Arg->getExprLoc())) |
13958 | return ExprError(); |
13959 | } |
13960 | } |
13961 | |
13962 | CandidateSet->NoteCandidates( |
13963 | PartialDiagnosticAt( |
13964 | Fn->getBeginLoc(), |
13965 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) |
13966 | << ULE->getName() << Fn->getSourceRange()), |
13967 | SemaRef, OCD_AllCandidates, Args); |
13968 | break; |
13969 | } |
13970 | |
13971 | case OR_Ambiguous: |
13972 | CandidateSet->NoteCandidates( |
13973 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13974 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) |
13975 | << ULE->getName() << Fn->getSourceRange()), |
13976 | SemaRef, OCD_AmbiguousCandidates, Args); |
13977 | break; |
13978 | |
13979 | case OR_Deleted: { |
13980 | CandidateSet->NoteCandidates( |
13981 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13982 | SemaRef.PDiag(diag::err_ovl_deleted_call) |
13983 | << ULE->getName() << Fn->getSourceRange()), |
13984 | SemaRef, OCD_AllCandidates, Args); |
13985 | |
13986 | // We emitted an error for the unavailable/deleted function call but keep |
13987 | // the call in the AST. |
13988 | FunctionDecl *FDecl = (*Best)->Function; |
13989 | ExprResult Res = |
13990 | SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl); |
13991 | if (Res.isInvalid()) |
13992 | return ExprError(); |
13993 | return SemaRef.BuildResolvedCallExpr( |
13994 | Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, |
13995 | /*IsExecConfig=*/false, (*Best)->IsADLCandidate); |
13996 | } |
13997 | } |
13998 | |
13999 | // Overload resolution failed, try to recover. |
14000 | SmallVector<Expr *, 8> SubExprs = {Fn}; |
14001 | SubExprs.append(in_start: Args.begin(), in_end: Args.end()); |
14002 | return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs, |
14003 | T: chooseRecoveryType(CS&: *CandidateSet, Best)); |
14004 | } |
14005 | |
14006 | static void markUnaddressableCandidatesUnviable(Sema &S, |
14007 | OverloadCandidateSet &CS) { |
14008 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { |
14009 | if (I->Viable && |
14010 | !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) { |
14011 | I->Viable = false; |
14012 | I->FailureKind = ovl_fail_addr_not_available; |
14013 | } |
14014 | } |
14015 | } |
14016 | |
14017 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn |
14018 | /// (which eventually refers to the declaration Func) and the call |
14019 | /// arguments Args/NumArgs, attempt to resolve the function call down |
14020 | /// to a specific function. If overload resolution succeeds, returns |
14021 | /// the call expression produced by overload resolution. |
14022 | /// Otherwise, emits diagnostics and returns ExprError. |
14023 | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
14024 | UnresolvedLookupExpr *ULE, |
14025 | SourceLocation LParenLoc, |
14026 | MultiExprArg Args, |
14027 | SourceLocation RParenLoc, |
14028 | Expr *ExecConfig, |
14029 | bool AllowTypoCorrection, |
14030 | bool CalleesAddressIsTaken) { |
14031 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), |
14032 | OverloadCandidateSet::CSK_Normal); |
14033 | ExprResult result; |
14034 | |
14035 | if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet, |
14036 | Result: &result)) |
14037 | return result; |
14038 | |
14039 | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that |
14040 | // functions that aren't addressible are considered unviable. |
14041 | if (CalleesAddressIsTaken) |
14042 | markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet); |
14043 | |
14044 | OverloadCandidateSet::iterator Best; |
14045 | OverloadingResult OverloadResult = |
14046 | CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best); |
14047 | |
14048 | // Model the case with a call to a templated function whose definition |
14049 | // encloses the call and whose return type contains a placeholder type as if |
14050 | // the UnresolvedLookupExpr was type-dependent. |
14051 | if (OverloadResult == OR_Success) { |
14052 | const FunctionDecl *FDecl = Best->Function; |
14053 | if (FDecl && FDecl->isTemplateInstantiation() && |
14054 | FDecl->getReturnType()->isUndeducedType()) { |
14055 | if (const auto *TP = |
14056 | FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false); |
14057 | TP && TP->willHaveBody()) { |
14058 | return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, |
14059 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
14060 | } |
14061 | } |
14062 | } |
14063 | |
14064 | return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc, |
14065 | ExecConfig, CandidateSet: &CandidateSet, Best: &Best, |
14066 | OverloadResult, AllowTypoCorrection); |
14067 | } |
14068 | |
14069 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { |
14070 | return Functions.size() > 1 || |
14071 | (Functions.size() == 1 && |
14072 | isa<FunctionTemplateDecl>(Val: (*Functions.begin())->getUnderlyingDecl())); |
14073 | } |
14074 | |
14075 | ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, |
14076 | NestedNameSpecifierLoc NNSLoc, |
14077 | DeclarationNameInfo DNI, |
14078 | const UnresolvedSetImpl &Fns, |
14079 | bool PerformADL) { |
14080 | return UnresolvedLookupExpr::Create(Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, |
14081 | RequiresADL: PerformADL, Overloaded: IsOverloaded(Functions: Fns), |
14082 | Begin: Fns.begin(), End: Fns.end()); |
14083 | } |
14084 | |
14085 | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, |
14086 | CXXConversionDecl *Method, |
14087 | bool HadMultipleCandidates) { |
14088 | // Convert the expression to match the conversion function's implicit object |
14089 | // parameter. |
14090 | ExprResult Exp; |
14091 | if (Method->isExplicitObjectMemberFunction()) |
14092 | Exp = InitializeExplicitObjectArgument(*this, E, Method); |
14093 | else |
14094 | Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr, |
14095 | FoundDecl, Method); |
14096 | if (Exp.isInvalid()) |
14097 | return true; |
14098 | |
14099 | if (Method->getParent()->isLambda() && |
14100 | Method->getConversionType()->isBlockPointerType()) { |
14101 | // This is a lambda conversion to block pointer; check if the argument |
14102 | // was a LambdaExpr. |
14103 | Expr *SubE = E; |
14104 | auto *CE = dyn_cast<CastExpr>(Val: SubE); |
14105 | if (CE && CE->getCastKind() == CK_NoOp) |
14106 | SubE = CE->getSubExpr(); |
14107 | SubE = SubE->IgnoreParens(); |
14108 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE)) |
14109 | SubE = BE->getSubExpr(); |
14110 | if (isa<LambdaExpr>(Val: SubE)) { |
14111 | // For the conversion to block pointer on a lambda expression, we |
14112 | // construct a special BlockLiteral instead; this doesn't really make |
14113 | // a difference in ARC, but outside of ARC the resulting block literal |
14114 | // follows the normal lifetime rules for block literals instead of being |
14115 | // autoreleased. |
14116 | PushExpressionEvaluationContext( |
14117 | NewContext: ExpressionEvaluationContext::PotentiallyEvaluated); |
14118 | ExprResult BlockExp = BuildBlockForLambdaConversion( |
14119 | CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get()); |
14120 | PopExpressionEvaluationContext(); |
14121 | |
14122 | // FIXME: This note should be produced by a CodeSynthesisContext. |
14123 | if (BlockExp.isInvalid()) |
14124 | Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); |
14125 | return BlockExp; |
14126 | } |
14127 | } |
14128 | CallExpr *CE; |
14129 | QualType ResultType = Method->getReturnType(); |
14130 | ExprValueKind VK = Expr::getValueKindForType(T: ResultType); |
14131 | ResultType = ResultType.getNonLValueExprType(Context); |
14132 | if (Method->isExplicitObjectMemberFunction()) { |
14133 | ExprResult FnExpr = |
14134 | CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(), |
14135 | HadMultipleCandidates, E->getBeginLoc()); |
14136 | if (FnExpr.isInvalid()) |
14137 | return ExprError(); |
14138 | Expr *ObjectParam = Exp.get(); |
14139 | CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1), |
14140 | Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(), |
14141 | FPFeatures: CurFPFeatureOverrides()); |
14142 | } else { |
14143 | MemberExpr *ME = |
14144 | BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), |
14145 | NestedNameSpecifierLoc(), SourceLocation(), Method, |
14146 | DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()), |
14147 | HadMultipleCandidates, DeclarationNameInfo(), |
14148 | Context.BoundMemberTy, VK_PRValue, OK_Ordinary); |
14149 | |
14150 | CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK, |
14151 | RP: Exp.get()->getEndLoc(), |
14152 | FPFeatures: CurFPFeatureOverrides()); |
14153 | } |
14154 | |
14155 | if (CheckFunctionCall(FDecl: Method, TheCall: CE, |
14156 | Proto: Method->getType()->castAs<FunctionProtoType>())) |
14157 | return ExprError(); |
14158 | |
14159 | return CheckForImmediateInvocation(CE, CE->getDirectCallee()); |
14160 | } |
14161 | |
14162 | /// Create a unary operation that may resolve to an overloaded |
14163 | /// operator. |
14164 | /// |
14165 | /// \param OpLoc The location of the operator itself (e.g., '*'). |
14166 | /// |
14167 | /// \param Opc The UnaryOperatorKind that describes this operator. |
14168 | /// |
14169 | /// \param Fns The set of non-member functions that will be |
14170 | /// considered by overload resolution. The caller needs to build this |
14171 | /// set based on the context using, e.g., |
14172 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
14173 | /// set should not contain any member functions; those will be added |
14174 | /// by CreateOverloadedUnaryOp(). |
14175 | /// |
14176 | /// \param Input The input argument. |
14177 | ExprResult |
14178 | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
14179 | const UnresolvedSetImpl &Fns, |
14180 | Expr *Input, bool PerformADL) { |
14181 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); |
14182 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator" ); |
14183 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14184 | // TODO: provide better source location info. |
14185 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
14186 | |
14187 | if (checkPlaceholderForOverload(S&: *this, E&: Input)) |
14188 | return ExprError(); |
14189 | |
14190 | Expr *Args[2] = { Input, nullptr }; |
14191 | unsigned NumArgs = 1; |
14192 | |
14193 | // For post-increment and post-decrement, add the implicit '0' as |
14194 | // the second argument, so that we know this is a post-increment or |
14195 | // post-decrement. |
14196 | if (Opc == UO_PostInc || Opc == UO_PostDec) { |
14197 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
14198 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, |
14199 | SourceLocation()); |
14200 | NumArgs = 2; |
14201 | } |
14202 | |
14203 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); |
14204 | |
14205 | if (Input->isTypeDependent()) { |
14206 | if (Fns.empty()) |
14207 | return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, |
14208 | VK: VK_PRValue, OK: OK_Ordinary, l: OpLoc, CanOverflow: false, |
14209 | FPFeatures: CurFPFeatureOverrides()); |
14210 | |
14211 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
14212 | ExprResult Fn = CreateUnresolvedLookupExpr( |
14213 | NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns); |
14214 | if (Fn.isInvalid()) |
14215 | return ExprError(); |
14216 | return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray, |
14217 | Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc, |
14218 | FPFeatures: CurFPFeatureOverrides()); |
14219 | } |
14220 | |
14221 | // Build an empty overload set. |
14222 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); |
14223 | |
14224 | // Add the candidates from the given function set. |
14225 | AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet); |
14226 | |
14227 | // Add operator candidates that are member functions. |
14228 | AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet); |
14229 | |
14230 | // Add candidates from ADL. |
14231 | if (PerformADL) { |
14232 | AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray, |
14233 | /*ExplicitTemplateArgs*/nullptr, |
14234 | CandidateSet); |
14235 | } |
14236 | |
14237 | // Add builtin operator candidates. |
14238 | AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet); |
14239 | |
14240 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14241 | |
14242 | // Perform overload resolution. |
14243 | OverloadCandidateSet::iterator Best; |
14244 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) { |
14245 | case OR_Success: { |
14246 | // We found a built-in operator or an overloaded operator. |
14247 | FunctionDecl *FnDecl = Best->Function; |
14248 | |
14249 | if (FnDecl) { |
14250 | Expr *Base = nullptr; |
14251 | // We matched an overloaded operator. Build a call to that |
14252 | // operator. |
14253 | |
14254 | // Convert the arguments. |
14255 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) { |
14256 | CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl); |
14257 | |
14258 | ExprResult InputInit; |
14259 | if (Method->isExplicitObjectMemberFunction()) |
14260 | InputInit = InitializeExplicitObjectArgument(*this, Input, Method); |
14261 | else |
14262 | InputInit = PerformImplicitObjectArgumentInitialization( |
14263 | From: Input, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method); |
14264 | if (InputInit.isInvalid()) |
14265 | return ExprError(); |
14266 | Base = Input = InputInit.get(); |
14267 | } else { |
14268 | // Convert the arguments. |
14269 | ExprResult InputInit |
14270 | = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter( |
14271 | Context, |
14272 | Parm: FnDecl->getParamDecl(i: 0)), |
14273 | EqualLoc: SourceLocation(), |
14274 | Init: Input); |
14275 | if (InputInit.isInvalid()) |
14276 | return ExprError(); |
14277 | Input = InputInit.get(); |
14278 | } |
14279 | |
14280 | // Build the actual expression node. |
14281 | ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, |
14282 | Base, HadMultipleCandidates, |
14283 | Loc: OpLoc); |
14284 | if (FnExpr.isInvalid()) |
14285 | return ExprError(); |
14286 | |
14287 | // Determine the result type. |
14288 | QualType ResultTy = FnDecl->getReturnType(); |
14289 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
14290 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14291 | |
14292 | Args[0] = Input; |
14293 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
14294 | Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc, |
14295 | FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate); |
14296 | |
14297 | if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl)) |
14298 | return ExprError(); |
14299 | |
14300 | if (CheckFunctionCall(FDecl: FnDecl, TheCall, |
14301 | Proto: FnDecl->getType()->castAs<FunctionProtoType>())) |
14302 | return ExprError(); |
14303 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), Decl: FnDecl); |
14304 | } else { |
14305 | // We matched a built-in operator. Convert the arguments, then |
14306 | // break out so that we will build the appropriate built-in |
14307 | // operator node. |
14308 | ExprResult InputRes = PerformImplicitConversion( |
14309 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, |
14310 | CCK_ForBuiltinOverloadedOp); |
14311 | if (InputRes.isInvalid()) |
14312 | return ExprError(); |
14313 | Input = InputRes.get(); |
14314 | break; |
14315 | } |
14316 | } |
14317 | |
14318 | case OR_No_Viable_Function: |
14319 | // This is an erroneous use of an operator which can be overloaded by |
14320 | // a non-member function. Check for non-member operators which were |
14321 | // defined too late to be candidates. |
14322 | if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray)) |
14323 | // FIXME: Recover by calling the found function. |
14324 | return ExprError(); |
14325 | |
14326 | // No viable function; fall through to handling this as a |
14327 | // built-in operator, which will produce an error message for us. |
14328 | break; |
14329 | |
14330 | case OR_Ambiguous: |
14331 | CandidateSet.NoteCandidates( |
14332 | PartialDiagnosticAt(OpLoc, |
14333 | PDiag(diag::err_ovl_ambiguous_oper_unary) |
14334 | << UnaryOperator::getOpcodeStr(Opc) |
14335 | << Input->getType() << Input->getSourceRange()), |
14336 | *this, OCD_AmbiguousCandidates, ArgsArray, |
14337 | UnaryOperator::getOpcodeStr(Opc), OpLoc); |
14338 | return ExprError(); |
14339 | |
14340 | case OR_Deleted: |
14341 | // CreateOverloadedUnaryOp fills the first element of ArgsArray with the |
14342 | // object whose method was called. Later in NoteCandidates size of ArgsArray |
14343 | // is passed further and it eventually ends up compared to number of |
14344 | // function candidate parameters which never includes the object parameter, |
14345 | // so slice ArgsArray to make sure apples are compared to apples. |
14346 | CandidateSet.NoteCandidates( |
14347 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
14348 | << UnaryOperator::getOpcodeStr(Opc) |
14349 | << Input->getSourceRange()), |
14350 | *this, OCD_AllCandidates, ArgsArray.drop_front(), |
14351 | UnaryOperator::getOpcodeStr(Opc), OpLoc); |
14352 | return ExprError(); |
14353 | } |
14354 | |
14355 | // Either we found no viable overloaded operator or we matched a |
14356 | // built-in operator. In either case, fall through to trying to |
14357 | // build a built-in operation. |
14358 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
14359 | } |
14360 | |
14361 | /// Perform lookup for an overloaded binary operator. |
14362 | void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, |
14363 | OverloadedOperatorKind Op, |
14364 | const UnresolvedSetImpl &Fns, |
14365 | ArrayRef<Expr *> Args, bool PerformADL) { |
14366 | SourceLocation OpLoc = CandidateSet.getLocation(); |
14367 | |
14368 | OverloadedOperatorKind = |
14369 | CandidateSet.getRewriteInfo().AllowRewrittenCandidates |
14370 | ? getRewrittenOverloadedOperator(Kind: Op) |
14371 | : OO_None; |
14372 | |
14373 | // Add the candidates from the given function set. This also adds the |
14374 | // rewritten candidates using these functions if necessary. |
14375 | AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); |
14376 | |
14377 | // Add operator candidates that are member functions. |
14378 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
14379 | if (CandidateSet.getRewriteInfo().allowsReversed(Op)) |
14380 | AddMemberOperatorCandidates(Op, OpLoc, Args: {Args[1], Args[0]}, CandidateSet, |
14381 | PO: OverloadCandidateParamOrder::Reversed); |
14382 | |
14383 | // In C++20, also add any rewritten member candidates. |
14384 | if (ExtraOp) { |
14385 | AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet); |
14386 | if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp)) |
14387 | AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: {Args[1], Args[0]}, |
14388 | CandidateSet, |
14389 | PO: OverloadCandidateParamOrder::Reversed); |
14390 | } |
14391 | |
14392 | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not |
14393 | // performed for an assignment operator (nor for operator[] nor operator->, |
14394 | // which don't get here). |
14395 | if (Op != OO_Equal && PerformADL) { |
14396 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14397 | AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args, |
14398 | /*ExplicitTemplateArgs*/ nullptr, |
14399 | CandidateSet); |
14400 | if (ExtraOp) { |
14401 | DeclarationName = |
14402 | Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp); |
14403 | AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args, |
14404 | /*ExplicitTemplateArgs*/ nullptr, |
14405 | CandidateSet); |
14406 | } |
14407 | } |
14408 | |
14409 | // Add builtin operator candidates. |
14410 | // |
14411 | // FIXME: We don't add any rewritten candidates here. This is strictly |
14412 | // incorrect; a builtin candidate could be hidden by a non-viable candidate, |
14413 | // resulting in our selecting a rewritten builtin candidate. For example: |
14414 | // |
14415 | // enum class E { e }; |
14416 | // bool operator!=(E, E) requires false; |
14417 | // bool k = E::e != E::e; |
14418 | // |
14419 | // ... should select the rewritten builtin candidate 'operator==(E, E)'. But |
14420 | // it seems unreasonable to consider rewritten builtin candidates. A core |
14421 | // issue has been filed proposing to removed this requirement. |
14422 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
14423 | } |
14424 | |
14425 | /// Create a binary operation that may resolve to an overloaded |
14426 | /// operator. |
14427 | /// |
14428 | /// \param OpLoc The location of the operator itself (e.g., '+'). |
14429 | /// |
14430 | /// \param Opc The BinaryOperatorKind that describes this operator. |
14431 | /// |
14432 | /// \param Fns The set of non-member functions that will be |
14433 | /// considered by overload resolution. The caller needs to build this |
14434 | /// set based on the context using, e.g., |
14435 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
14436 | /// set should not contain any member functions; those will be added |
14437 | /// by CreateOverloadedBinOp(). |
14438 | /// |
14439 | /// \param LHS Left-hand argument. |
14440 | /// \param RHS Right-hand argument. |
14441 | /// \param PerformADL Whether to consider operator candidates found by ADL. |
14442 | /// \param AllowRewrittenCandidates Whether to consider candidates found by |
14443 | /// C++20 operator rewrites. |
14444 | /// \param DefaultedFn If we are synthesizing a defaulted operator function, |
14445 | /// the function in question. Such a function is never a candidate in |
14446 | /// our overload resolution. This also enables synthesizing a three-way |
14447 | /// comparison from < and == as described in C++20 [class.spaceship]p1. |
14448 | ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, |
14449 | BinaryOperatorKind Opc, |
14450 | const UnresolvedSetImpl &Fns, Expr *LHS, |
14451 | Expr *RHS, bool PerformADL, |
14452 | bool AllowRewrittenCandidates, |
14453 | FunctionDecl *DefaultedFn) { |
14454 | Expr *Args[2] = { LHS, RHS }; |
14455 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple |
14456 | |
14457 | if (!getLangOpts().CPlusPlus20) |
14458 | AllowRewrittenCandidates = false; |
14459 | |
14460 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); |
14461 | |
14462 | // If either side is type-dependent, create an appropriate dependent |
14463 | // expression. |
14464 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { |
14465 | if (Fns.empty()) { |
14466 | // If there are no functions to store, just build a dependent |
14467 | // BinaryOperator or CompoundAssignment. |
14468 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
14469 | return CompoundAssignOperator::Create( |
14470 | C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue, |
14471 | OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy, |
14472 | CompResultType: Context.DependentTy); |
14473 | return BinaryOperator::Create( |
14474 | C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue, |
14475 | OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
14476 | } |
14477 | |
14478 | // FIXME: save results of ADL from here? |
14479 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
14480 | // TODO: provide better source location info in DNLoc component. |
14481 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14482 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
14483 | ExprResult Fn = CreateUnresolvedLookupExpr( |
14484 | NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL); |
14485 | if (Fn.isInvalid()) |
14486 | return ExprError(); |
14487 | return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args, |
14488 | Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc, |
14489 | FPFeatures: CurFPFeatureOverrides()); |
14490 | } |
14491 | |
14492 | // Always do placeholder-like conversions on the RHS. |
14493 | if (checkPlaceholderForOverload(S&: *this, E&: Args[1])) |
14494 | return ExprError(); |
14495 | |
14496 | // Do placeholder-like conversion on the LHS; note that we should |
14497 | // not get here with a PseudoObject LHS. |
14498 | assert(Args[0]->getObjectKind() != OK_ObjCProperty); |
14499 | if (checkPlaceholderForOverload(S&: *this, E&: Args[0])) |
14500 | return ExprError(); |
14501 | |
14502 | // If this is the assignment operator, we only perform overload resolution |
14503 | // if the left-hand side is a class or enumeration type. This is actually |
14504 | // a hack. The standard requires that we do overload resolution between the |
14505 | // various built-in candidates, but as DR507 points out, this can lead to |
14506 | // problems. So we do it this way, which pretty much follows what GCC does. |
14507 | // Note that we go the traditional code path for compound assignment forms. |
14508 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) |
14509 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]); |
14510 | |
14511 | // If this is the .* operator, which is not overloadable, just |
14512 | // create a built-in binary operator. |
14513 | if (Opc == BO_PtrMemD) |
14514 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]); |
14515 | |
14516 | // Build the overload set. |
14517 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, |
14518 | OverloadCandidateSet::OperatorRewriteInfo( |
14519 | Op, OpLoc, AllowRewrittenCandidates)); |
14520 | if (DefaultedFn) |
14521 | CandidateSet.exclude(DefaultedFn); |
14522 | LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); |
14523 | |
14524 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14525 | |
14526 | // Perform overload resolution. |
14527 | OverloadCandidateSet::iterator Best; |
14528 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) { |
14529 | case OR_Success: { |
14530 | // We found a built-in operator or an overloaded operator. |
14531 | FunctionDecl *FnDecl = Best->Function; |
14532 | |
14533 | bool IsReversed = Best->isReversed(); |
14534 | if (IsReversed) |
14535 | std::swap(a&: Args[0], b&: Args[1]); |
14536 | |
14537 | if (FnDecl) { |
14538 | |
14539 | if (FnDecl->isInvalidDecl()) |
14540 | return ExprError(); |
14541 | |
14542 | Expr *Base = nullptr; |
14543 | // We matched an overloaded operator. Build a call to that |
14544 | // operator. |
14545 | |
14546 | OverloadedOperatorKind ChosenOp = |
14547 | FnDecl->getDeclName().getCXXOverloadedOperator(); |
14548 | |
14549 | // C++2a [over.match.oper]p9: |
14550 | // If a rewritten operator== candidate is selected by overload |
14551 | // resolution for an operator@, its return type shall be cv bool |
14552 | if (Best->RewriteKind && ChosenOp == OO_EqualEqual && |
14553 | !FnDecl->getReturnType()->isBooleanType()) { |
14554 | bool IsExtension = |
14555 | FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); |
14556 | Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool |
14557 | : diag::err_ovl_rewrite_equalequal_not_bool) |
14558 | << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) |
14559 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14560 | Diag(FnDecl->getLocation(), diag::note_declared_at); |
14561 | if (!IsExtension) |
14562 | return ExprError(); |
14563 | } |
14564 | |
14565 | if (AllowRewrittenCandidates && !IsReversed && |
14566 | CandidateSet.getRewriteInfo().isReversible()) { |
14567 | // We could have reversed this operator, but didn't. Check if some |
14568 | // reversed form was a viable candidate, and if so, if it had a |
14569 | // better conversion for either parameter. If so, this call is |
14570 | // formally ambiguous, and allowing it is an extension. |
14571 | llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; |
14572 | for (OverloadCandidate &Cand : CandidateSet) { |
14573 | if (Cand.Viable && Cand.Function && Cand.isReversed() && |
14574 | allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) { |
14575 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
14576 | if (CompareImplicitConversionSequences( |
14577 | S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx], |
14578 | ICS2: Best->Conversions[ArgIdx]) == |
14579 | ImplicitConversionSequence::Better) { |
14580 | AmbiguousWith.push_back(Elt: Cand.Function); |
14581 | break; |
14582 | } |
14583 | } |
14584 | } |
14585 | } |
14586 | |
14587 | if (!AmbiguousWith.empty()) { |
14588 | bool AmbiguousWithSelf = |
14589 | AmbiguousWith.size() == 1 && |
14590 | declaresSameEntity(AmbiguousWith.front(), FnDecl); |
14591 | Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) |
14592 | << BinaryOperator::getOpcodeStr(Opc) |
14593 | << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf |
14594 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14595 | if (AmbiguousWithSelf) { |
14596 | Diag(FnDecl->getLocation(), |
14597 | diag::note_ovl_ambiguous_oper_binary_reversed_self); |
14598 | // Mark member== const or provide matching != to disallow reversed |
14599 | // args. Eg. |
14600 | // struct S { bool operator==(const S&); }; |
14601 | // S()==S(); |
14602 | if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) |
14603 | if (Op == OverloadedOperatorKind::OO_EqualEqual && |
14604 | !MD->isConst() && |
14605 | !MD->hasCXXExplicitFunctionObjectParameter() && |
14606 | Context.hasSameUnqualifiedType( |
14607 | MD->getFunctionObjectParameterType(), |
14608 | MD->getParamDecl(0)->getType().getNonReferenceType()) && |
14609 | Context.hasSameUnqualifiedType( |
14610 | MD->getFunctionObjectParameterType(), |
14611 | Args[0]->getType()) && |
14612 | Context.hasSameUnqualifiedType( |
14613 | MD->getFunctionObjectParameterType(), |
14614 | Args[1]->getType())) |
14615 | Diag(FnDecl->getLocation(), |
14616 | diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); |
14617 | } else { |
14618 | Diag(FnDecl->getLocation(), |
14619 | diag::note_ovl_ambiguous_oper_binary_selected_candidate); |
14620 | for (auto *F : AmbiguousWith) |
14621 | Diag(F->getLocation(), |
14622 | diag::note_ovl_ambiguous_oper_binary_reversed_candidate); |
14623 | } |
14624 | } |
14625 | } |
14626 | |
14627 | // Convert the arguments. |
14628 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) { |
14629 | // Best->Access is only meaningful for class members. |
14630 | CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl); |
14631 | |
14632 | ExprResult Arg0, Arg1; |
14633 | unsigned ParamIdx = 0; |
14634 | if (Method->isExplicitObjectMemberFunction()) { |
14635 | Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl); |
14636 | ParamIdx = 1; |
14637 | } else { |
14638 | Arg0 = PerformImplicitObjectArgumentInitialization( |
14639 | From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method); |
14640 | } |
14641 | Arg1 = PerformCopyInitialization( |
14642 | Entity: InitializedEntity::InitializeParameter( |
14643 | Context, Parm: FnDecl->getParamDecl(i: ParamIdx)), |
14644 | EqualLoc: SourceLocation(), Init: Args[1]); |
14645 | if (Arg0.isInvalid() || Arg1.isInvalid()) |
14646 | return ExprError(); |
14647 | |
14648 | Base = Args[0] = Arg0.getAs<Expr>(); |
14649 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14650 | } else { |
14651 | // Convert the arguments. |
14652 | ExprResult Arg0 = PerformCopyInitialization( |
14653 | Entity: InitializedEntity::InitializeParameter(Context, |
14654 | Parm: FnDecl->getParamDecl(i: 0)), |
14655 | EqualLoc: SourceLocation(), Init: Args[0]); |
14656 | if (Arg0.isInvalid()) |
14657 | return ExprError(); |
14658 | |
14659 | ExprResult Arg1 = |
14660 | PerformCopyInitialization( |
14661 | Entity: InitializedEntity::InitializeParameter(Context, |
14662 | Parm: FnDecl->getParamDecl(i: 1)), |
14663 | EqualLoc: SourceLocation(), Init: Args[1]); |
14664 | if (Arg1.isInvalid()) |
14665 | return ExprError(); |
14666 | Args[0] = LHS = Arg0.getAs<Expr>(); |
14667 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14668 | } |
14669 | |
14670 | // Build the actual expression node. |
14671 | ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, |
14672 | FoundDecl: Best->FoundDecl, Base, |
14673 | HadMultipleCandidates, Loc: OpLoc); |
14674 | if (FnExpr.isInvalid()) |
14675 | return ExprError(); |
14676 | |
14677 | // Determine the result type. |
14678 | QualType ResultTy = FnDecl->getReturnType(); |
14679 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
14680 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14681 | |
14682 | CallExpr *TheCall; |
14683 | ArrayRef<const Expr *> ArgsArray(Args, 2); |
14684 | const Expr *ImplicitThis = nullptr; |
14685 | |
14686 | // We always create a CXXOperatorCallExpr, even for explicit object |
14687 | // members; CodeGen should take care not to emit the this pointer. |
14688 | TheCall = CXXOperatorCallExpr::Create( |
14689 | Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc, |
14690 | FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate); |
14691 | |
14692 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl); |
14693 | Method && Method->isImplicitObjectMemberFunction()) { |
14694 | // Cut off the implicit 'this'. |
14695 | ImplicitThis = ArgsArray[0]; |
14696 | ArgsArray = ArgsArray.slice(N: 1); |
14697 | } |
14698 | |
14699 | if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, |
14700 | FD: FnDecl)) |
14701 | return ExprError(); |
14702 | |
14703 | // Check for a self move. |
14704 | if (Op == OO_Equal) |
14705 | DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc); |
14706 | |
14707 | if (ImplicitThis) { |
14708 | QualType ThisType = Context.getPointerType(T: ImplicitThis->getType()); |
14709 | QualType ThisTypeFromDecl = Context.getPointerType( |
14710 | T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType()); |
14711 | |
14712 | CheckArgAlignment(OpLoc, FnDecl, "'this'" , ThisType, |
14713 | ThisTypeFromDecl); |
14714 | } |
14715 | |
14716 | checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray, |
14717 | IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(), |
14718 | CallType: VariadicDoesNotApply); |
14719 | |
14720 | ExprResult R = MaybeBindToTemporary(TheCall); |
14721 | if (R.isInvalid()) |
14722 | return ExprError(); |
14723 | |
14724 | R = CheckForImmediateInvocation(E: R, Decl: FnDecl); |
14725 | if (R.isInvalid()) |
14726 | return ExprError(); |
14727 | |
14728 | // For a rewritten candidate, we've already reversed the arguments |
14729 | // if needed. Perform the rest of the rewrite now. |
14730 | if ((Best->RewriteKind & CRK_DifferentOperator) || |
14731 | (Op == OO_Spaceship && IsReversed)) { |
14732 | if (Op == OO_ExclaimEqual) { |
14733 | assert(ChosenOp == OO_EqualEqual && "unexpected operator name" ); |
14734 | R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get()); |
14735 | } else { |
14736 | assert(ChosenOp == OO_Spaceship && "unexpected operator name" ); |
14737 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
14738 | Expr *ZeroLiteral = |
14739 | IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); |
14740 | |
14741 | Sema::CodeSynthesisContext Ctx; |
14742 | Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; |
14743 | Ctx.Entity = FnDecl; |
14744 | pushCodeSynthesisContext(Ctx); |
14745 | |
14746 | R = CreateOverloadedBinOp( |
14747 | OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(), |
14748 | RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, |
14749 | /*AllowRewrittenCandidates=*/false); |
14750 | |
14751 | popCodeSynthesisContext(); |
14752 | } |
14753 | if (R.isInvalid()) |
14754 | return ExprError(); |
14755 | } else { |
14756 | assert(ChosenOp == Op && "unexpected operator name" ); |
14757 | } |
14758 | |
14759 | // Make a note in the AST if we did any rewriting. |
14760 | if (Best->RewriteKind != CRK_None) |
14761 | R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); |
14762 | |
14763 | return R; |
14764 | } else { |
14765 | // We matched a built-in operator. Convert the arguments, then |
14766 | // break out so that we will build the appropriate built-in |
14767 | // operator node. |
14768 | ExprResult ArgsRes0 = PerformImplicitConversion( |
14769 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
14770 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14771 | if (ArgsRes0.isInvalid()) |
14772 | return ExprError(); |
14773 | Args[0] = ArgsRes0.get(); |
14774 | |
14775 | ExprResult ArgsRes1 = PerformImplicitConversion( |
14776 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
14777 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14778 | if (ArgsRes1.isInvalid()) |
14779 | return ExprError(); |
14780 | Args[1] = ArgsRes1.get(); |
14781 | break; |
14782 | } |
14783 | } |
14784 | |
14785 | case OR_No_Viable_Function: { |
14786 | // C++ [over.match.oper]p9: |
14787 | // If the operator is the operator , [...] and there are no |
14788 | // viable functions, then the operator is assumed to be the |
14789 | // built-in operator and interpreted according to clause 5. |
14790 | if (Opc == BO_Comma) |
14791 | break; |
14792 | |
14793 | // When defaulting an 'operator<=>', we can try to synthesize a three-way |
14794 | // compare result using '==' and '<'. |
14795 | if (DefaultedFn && Opc == BO_Cmp) { |
14796 | ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0], |
14797 | RHS: Args[1], DefaultedFn); |
14798 | if (E.isInvalid() || E.isUsable()) |
14799 | return E; |
14800 | } |
14801 | |
14802 | // For class as left operand for assignment or compound assignment |
14803 | // operator do not fall through to handling in built-in, but report that |
14804 | // no overloaded assignment operator found |
14805 | ExprResult Result = ExprError(); |
14806 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc); |
14807 | auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, |
14808 | Args, OpLoc); |
14809 | DeferDiagsRAII DDR(*this, |
14810 | CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc)); |
14811 | if (Args[0]->getType()->isRecordType() && |
14812 | Opc >= BO_Assign && Opc <= BO_OrAssign) { |
14813 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
14814 | << BinaryOperator::getOpcodeStr(Opc) |
14815 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14816 | if (Args[0]->getType()->isIncompleteType()) { |
14817 | Diag(OpLoc, diag::note_assign_lhs_incomplete) |
14818 | << Args[0]->getType() |
14819 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14820 | } |
14821 | } else { |
14822 | // This is an erroneous use of an operator which can be overloaded by |
14823 | // a non-member function. Check for non-member operators which were |
14824 | // defined too late to be candidates. |
14825 | if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args)) |
14826 | // FIXME: Recover by calling the found function. |
14827 | return ExprError(); |
14828 | |
14829 | // No viable function; try to create a built-in operation, which will |
14830 | // produce an error. Then, show the non-viable candidates. |
14831 | Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]); |
14832 | } |
14833 | assert(Result.isInvalid() && |
14834 | "C++ binary operator overloading is missing candidates!" ); |
14835 | CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc); |
14836 | return Result; |
14837 | } |
14838 | |
14839 | case OR_Ambiguous: |
14840 | CandidateSet.NoteCandidates( |
14841 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
14842 | << BinaryOperator::getOpcodeStr(Opc) |
14843 | << Args[0]->getType() |
14844 | << Args[1]->getType() |
14845 | << Args[0]->getSourceRange() |
14846 | << Args[1]->getSourceRange()), |
14847 | *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14848 | OpLoc); |
14849 | return ExprError(); |
14850 | |
14851 | case OR_Deleted: |
14852 | if (isImplicitlyDeleted(FD: Best->Function)) { |
14853 | FunctionDecl *DeletedFD = Best->Function; |
14854 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD); |
14855 | if (DFK.isSpecialMember()) { |
14856 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) |
14857 | << Args[0]->getType() << DFK.asSpecialMember(); |
14858 | } else { |
14859 | assert(DFK.isComparison()); |
14860 | Diag(OpLoc, diag::err_ovl_deleted_comparison) |
14861 | << Args[0]->getType() << DeletedFD; |
14862 | } |
14863 | |
14864 | // The user probably meant to call this special member. Just |
14865 | // explain why it's deleted. |
14866 | NoteDeletedFunction(FD: DeletedFD); |
14867 | return ExprError(); |
14868 | } |
14869 | CandidateSet.NoteCandidates( |
14870 | PartialDiagnosticAt( |
14871 | OpLoc, PDiag(diag::err_ovl_deleted_oper) |
14872 | << getOperatorSpelling(Best->Function->getDeclName() |
14873 | .getCXXOverloadedOperator()) |
14874 | << Args[0]->getSourceRange() |
14875 | << Args[1]->getSourceRange()), |
14876 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14877 | OpLoc); |
14878 | return ExprError(); |
14879 | } |
14880 | |
14881 | // We matched a built-in operator; build it. |
14882 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]); |
14883 | } |
14884 | |
14885 | ExprResult Sema::BuildSynthesizedThreeWayComparison( |
14886 | SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, |
14887 | FunctionDecl *DefaultedFn) { |
14888 | const ComparisonCategoryInfo *Info = |
14889 | Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType()); |
14890 | // If we're not producing a known comparison category type, we can't |
14891 | // synthesize a three-way comparison. Let the caller diagnose this. |
14892 | if (!Info) |
14893 | return ExprResult((Expr*)nullptr); |
14894 | |
14895 | // If we ever want to perform this synthesis more generally, we will need to |
14896 | // apply the temporary materialization conversion to the operands. |
14897 | assert(LHS->isGLValue() && RHS->isGLValue() && |
14898 | "cannot use prvalue expressions more than once" ); |
14899 | Expr *OrigLHS = LHS; |
14900 | Expr *OrigRHS = RHS; |
14901 | |
14902 | // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to |
14903 | // each of them multiple times below. |
14904 | LHS = new (Context) |
14905 | OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), |
14906 | LHS->getObjectKind(), LHS); |
14907 | RHS = new (Context) |
14908 | OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), |
14909 | RHS->getObjectKind(), RHS); |
14910 | |
14911 | ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true, |
14912 | DefaultedFn); |
14913 | if (Eq.isInvalid()) |
14914 | return ExprError(); |
14915 | |
14916 | ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true, |
14917 | AllowRewrittenCandidates: true, DefaultedFn); |
14918 | if (Less.isInvalid()) |
14919 | return ExprError(); |
14920 | |
14921 | ExprResult Greater; |
14922 | if (Info->isPartial()) { |
14923 | Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true, |
14924 | DefaultedFn); |
14925 | if (Greater.isInvalid()) |
14926 | return ExprError(); |
14927 | } |
14928 | |
14929 | // Form the list of comparisons we're going to perform. |
14930 | struct Comparison { |
14931 | ExprResult Cmp; |
14932 | ComparisonCategoryResult Result; |
14933 | } Comparisons[4] = |
14934 | { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal |
14935 | : ComparisonCategoryResult::Equivalent}, |
14936 | {.Cmp: Less, .Result: ComparisonCategoryResult::Less}, |
14937 | {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater}, |
14938 | {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered}, |
14939 | }; |
14940 | |
14941 | int I = Info->isPartial() ? 3 : 2; |
14942 | |
14943 | // Combine the comparisons with suitable conditional expressions. |
14944 | ExprResult Result; |
14945 | for (; I >= 0; --I) { |
14946 | // Build a reference to the comparison category constant. |
14947 | auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result); |
14948 | // FIXME: Missing a constant for a comparison category. Diagnose this? |
14949 | if (!VI) |
14950 | return ExprResult((Expr*)nullptr); |
14951 | ExprResult ThisResult = |
14952 | BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); |
14953 | if (ThisResult.isInvalid()) |
14954 | return ExprError(); |
14955 | |
14956 | // Build a conditional unless this is the final case. |
14957 | if (Result.get()) { |
14958 | Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(), |
14959 | LHSExpr: ThisResult.get(), RHSExpr: Result.get()); |
14960 | if (Result.isInvalid()) |
14961 | return ExprError(); |
14962 | } else { |
14963 | Result = ThisResult; |
14964 | } |
14965 | } |
14966 | |
14967 | // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to |
14968 | // bind the OpaqueValueExprs before they're (repeatedly) used. |
14969 | Expr *SyntacticForm = BinaryOperator::Create( |
14970 | C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(), |
14971 | VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc, |
14972 | FPFeatures: CurFPFeatureOverrides()); |
14973 | Expr *SemanticForm[] = {LHS, RHS, Result.get()}; |
14974 | return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2); |
14975 | } |
14976 | |
14977 | static bool PrepareArgumentsForCallToObjectOfClassType( |
14978 | Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, |
14979 | MultiExprArg Args, SourceLocation LParenLoc) { |
14980 | |
14981 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
14982 | unsigned NumParams = Proto->getNumParams(); |
14983 | unsigned NumArgsSlots = |
14984 | MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams); |
14985 | // Build the full argument list for the method call (the implicit object |
14986 | // parameter is placed at the beginning of the list). |
14987 | MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots); |
14988 | bool IsError = false; |
14989 | // Initialize the implicit object parameter. |
14990 | // Check the argument types. |
14991 | for (unsigned i = 0; i != NumParams; i++) { |
14992 | Expr *Arg; |
14993 | if (i < Args.size()) { |
14994 | Arg = Args[i]; |
14995 | ExprResult InputInit = |
14996 | S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter( |
14997 | S.Context, Method->getParamDecl(i)), |
14998 | EqualLoc: SourceLocation(), Init: Arg); |
14999 | IsError |= InputInit.isInvalid(); |
15000 | Arg = InputInit.getAs<Expr>(); |
15001 | } else { |
15002 | ExprResult DefArg = |
15003 | S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i)); |
15004 | if (DefArg.isInvalid()) { |
15005 | IsError = true; |
15006 | break; |
15007 | } |
15008 | Arg = DefArg.getAs<Expr>(); |
15009 | } |
15010 | |
15011 | MethodArgs.push_back(Elt: Arg); |
15012 | } |
15013 | return IsError; |
15014 | } |
15015 | |
15016 | ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
15017 | SourceLocation RLoc, |
15018 | Expr *Base, |
15019 | MultiExprArg ArgExpr) { |
15020 | SmallVector<Expr *, 2> Args; |
15021 | Args.push_back(Elt: Base); |
15022 | for (auto *e : ArgExpr) { |
15023 | Args.push_back(Elt: e); |
15024 | } |
15025 | DeclarationName OpName = |
15026 | Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript); |
15027 | |
15028 | SourceRange Range = ArgExpr.empty() |
15029 | ? SourceRange{} |
15030 | : SourceRange(ArgExpr.front()->getBeginLoc(), |
15031 | ArgExpr.back()->getEndLoc()); |
15032 | |
15033 | // If either side is type-dependent, create an appropriate dependent |
15034 | // expression. |
15035 | if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) { |
15036 | |
15037 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
15038 | // CHECKME: no 'operator' keyword? |
15039 | DeclarationNameInfo OpNameInfo(OpName, LLoc); |
15040 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
15041 | ExprResult Fn = CreateUnresolvedLookupExpr( |
15042 | NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>()); |
15043 | if (Fn.isInvalid()) |
15044 | return ExprError(); |
15045 | // Can't add any actual overloads yet |
15046 | |
15047 | return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args, |
15048 | Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc, |
15049 | FPFeatures: CurFPFeatureOverrides()); |
15050 | } |
15051 | |
15052 | // Handle placeholders |
15053 | UnbridgedCastsSet UnbridgedCasts; |
15054 | if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) { |
15055 | return ExprError(); |
15056 | } |
15057 | // Build an empty overload set. |
15058 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); |
15059 | |
15060 | // Subscript can only be overloaded as a member function. |
15061 | |
15062 | // Add operator candidates that are member functions. |
15063 | AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet); |
15064 | |
15065 | // Add builtin operator candidates. |
15066 | if (Args.size() == 2) |
15067 | AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet); |
15068 | |
15069 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15070 | |
15071 | // Perform overload resolution. |
15072 | OverloadCandidateSet::iterator Best; |
15073 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) { |
15074 | case OR_Success: { |
15075 | // We found a built-in operator or an overloaded operator. |
15076 | FunctionDecl *FnDecl = Best->Function; |
15077 | |
15078 | if (FnDecl) { |
15079 | // We matched an overloaded operator. Build a call to that |
15080 | // operator. |
15081 | |
15082 | CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl); |
15083 | |
15084 | // Convert the arguments. |
15085 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl); |
15086 | SmallVector<Expr *, 2> MethodArgs; |
15087 | |
15088 | // Initialize the object parameter. |
15089 | if (Method->isExplicitObjectMemberFunction()) { |
15090 | ExprResult Res = |
15091 | InitializeExplicitObjectArgument(*this, Args[0], Method); |
15092 | if (Res.isInvalid()) |
15093 | return ExprError(); |
15094 | Args[0] = Res.get(); |
15095 | ArgExpr = Args; |
15096 | } else { |
15097 | ExprResult Arg0 = PerformImplicitObjectArgumentInitialization( |
15098 | From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method); |
15099 | if (Arg0.isInvalid()) |
15100 | return ExprError(); |
15101 | |
15102 | MethodArgs.push_back(Elt: Arg0.get()); |
15103 | } |
15104 | |
15105 | bool IsError = PrepareArgumentsForCallToObjectOfClassType( |
15106 | S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc); |
15107 | if (IsError) |
15108 | return ExprError(); |
15109 | |
15110 | // Build the actual expression node. |
15111 | DeclarationNameInfo OpLocInfo(OpName, LLoc); |
15112 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
15113 | ExprResult FnExpr = CreateFunctionRefExpr( |
15114 | S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates, |
15115 | Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo()); |
15116 | if (FnExpr.isInvalid()) |
15117 | return ExprError(); |
15118 | |
15119 | // Determine the result type |
15120 | QualType ResultTy = FnDecl->getReturnType(); |
15121 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
15122 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15123 | |
15124 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
15125 | Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc, |
15126 | FPFeatures: CurFPFeatureOverrides()); |
15127 | |
15128 | if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl)) |
15129 | return ExprError(); |
15130 | |
15131 | if (CheckFunctionCall(FDecl: Method, TheCall, |
15132 | Proto: Method->getType()->castAs<FunctionProtoType>())) |
15133 | return ExprError(); |
15134 | |
15135 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), |
15136 | Decl: FnDecl); |
15137 | } else { |
15138 | // We matched a built-in operator. Convert the arguments, then |
15139 | // break out so that we will build the appropriate built-in |
15140 | // operator node. |
15141 | ExprResult ArgsRes0 = PerformImplicitConversion( |
15142 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
15143 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
15144 | if (ArgsRes0.isInvalid()) |
15145 | return ExprError(); |
15146 | Args[0] = ArgsRes0.get(); |
15147 | |
15148 | ExprResult ArgsRes1 = PerformImplicitConversion( |
15149 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
15150 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
15151 | if (ArgsRes1.isInvalid()) |
15152 | return ExprError(); |
15153 | Args[1] = ArgsRes1.get(); |
15154 | |
15155 | break; |
15156 | } |
15157 | } |
15158 | |
15159 | case OR_No_Viable_Function: { |
15160 | PartialDiagnostic PD = |
15161 | CandidateSet.empty() |
15162 | ? (PDiag(diag::err_ovl_no_oper) |
15163 | << Args[0]->getType() << /*subscript*/ 0 |
15164 | << Args[0]->getSourceRange() << Range) |
15165 | : (PDiag(diag::err_ovl_no_viable_subscript) |
15166 | << Args[0]->getType() << Args[0]->getSourceRange() << Range); |
15167 | CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this, |
15168 | OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]" , OpLoc: LLoc); |
15169 | return ExprError(); |
15170 | } |
15171 | |
15172 | case OR_Ambiguous: |
15173 | if (Args.size() == 2) { |
15174 | CandidateSet.NoteCandidates( |
15175 | PartialDiagnosticAt( |
15176 | LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
15177 | << "[]" << Args[0]->getType() << Args[1]->getType() |
15178 | << Args[0]->getSourceRange() << Range), |
15179 | *this, OCD_AmbiguousCandidates, Args, "[]" , LLoc); |
15180 | } else { |
15181 | CandidateSet.NoteCandidates( |
15182 | PartialDiagnosticAt(LLoc, |
15183 | PDiag(diag::err_ovl_ambiguous_subscript_call) |
15184 | << Args[0]->getType() |
15185 | << Args[0]->getSourceRange() << Range), |
15186 | *this, OCD_AmbiguousCandidates, Args, "[]" , LLoc); |
15187 | } |
15188 | return ExprError(); |
15189 | |
15190 | case OR_Deleted: |
15191 | CandidateSet.NoteCandidates( |
15192 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) |
15193 | << "[]" << Args[0]->getSourceRange() |
15194 | << Range), |
15195 | *this, OCD_AllCandidates, Args, "[]" , LLoc); |
15196 | return ExprError(); |
15197 | } |
15198 | |
15199 | // We matched a built-in operator; build it. |
15200 | return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc); |
15201 | } |
15202 | |
15203 | /// BuildCallToMemberFunction - Build a call to a member |
15204 | /// function. MemExpr is the expression that refers to the member |
15205 | /// function (and includes the object parameter), Args/NumArgs are the |
15206 | /// arguments to the function call (not including the object |
15207 | /// parameter). The caller needs to validate that the member |
15208 | /// expression refers to a non-static member function or an overloaded |
15209 | /// member function. |
15210 | ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, |
15211 | SourceLocation LParenLoc, |
15212 | MultiExprArg Args, |
15213 | SourceLocation RParenLoc, |
15214 | Expr *ExecConfig, bool IsExecConfig, |
15215 | bool AllowRecovery) { |
15216 | assert(MemExprE->getType() == Context.BoundMemberTy || |
15217 | MemExprE->getType() == Context.OverloadTy); |
15218 | |
15219 | // Dig out the member expression. This holds both the object |
15220 | // argument and the member function we're referring to. |
15221 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); |
15222 | |
15223 | // Determine whether this is a call to a pointer-to-member function. |
15224 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) { |
15225 | assert(op->getType() == Context.BoundMemberTy); |
15226 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); |
15227 | |
15228 | QualType fnType = |
15229 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); |
15230 | |
15231 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); |
15232 | QualType resultType = proto->getCallResultType(Context); |
15233 | ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType()); |
15234 | |
15235 | // Check that the object type isn't more qualified than the |
15236 | // member function we're calling. |
15237 | Qualifiers funcQuals = proto->getMethodQuals(); |
15238 | |
15239 | QualType objectType = op->getLHS()->getType(); |
15240 | if (op->getOpcode() == BO_PtrMemI) |
15241 | objectType = objectType->castAs<PointerType>()->getPointeeType(); |
15242 | Qualifiers objectQuals = objectType.getQualifiers(); |
15243 | |
15244 | Qualifiers difference = objectQuals - funcQuals; |
15245 | difference.removeObjCGCAttr(); |
15246 | difference.removeAddressSpace(); |
15247 | if (difference) { |
15248 | std::string qualsString = difference.getAsString(); |
15249 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) |
15250 | << fnType.getUnqualifiedType() |
15251 | << qualsString |
15252 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); |
15253 | } |
15254 | |
15255 | CXXMemberCallExpr *call = CXXMemberCallExpr::Create( |
15256 | Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc, |
15257 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams()); |
15258 | |
15259 | if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(), |
15260 | CE: call, FD: nullptr)) |
15261 | return ExprError(); |
15262 | |
15263 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) |
15264 | return ExprError(); |
15265 | |
15266 | if (CheckOtherCall(call, proto)) |
15267 | return ExprError(); |
15268 | |
15269 | return MaybeBindToTemporary(call); |
15270 | } |
15271 | |
15272 | // We only try to build a recovery expr at this level if we can preserve |
15273 | // the return type, otherwise we return ExprError() and let the caller |
15274 | // recover. |
15275 | auto BuildRecoveryExpr = [&](QualType Type) { |
15276 | if (!AllowRecovery) |
15277 | return ExprError(); |
15278 | std::vector<Expr *> SubExprs = {MemExprE}; |
15279 | llvm::append_range(C&: SubExprs, R&: Args); |
15280 | return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, |
15281 | Type); |
15282 | }; |
15283 | if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr)) |
15284 | return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue, |
15285 | RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
15286 | |
15287 | UnbridgedCastsSet UnbridgedCasts; |
15288 | if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) |
15289 | return ExprError(); |
15290 | |
15291 | MemberExpr *MemExpr; |
15292 | CXXMethodDecl *Method = nullptr; |
15293 | bool HadMultipleCandidates = false; |
15294 | DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public); |
15295 | NestedNameSpecifier *Qualifier = nullptr; |
15296 | if (isa<MemberExpr>(Val: NakedMemExpr)) { |
15297 | MemExpr = cast<MemberExpr>(Val: NakedMemExpr); |
15298 | Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl()); |
15299 | FoundDecl = MemExpr->getFoundDecl(); |
15300 | Qualifier = MemExpr->getQualifier(); |
15301 | UnbridgedCasts.restore(); |
15302 | } else { |
15303 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr); |
15304 | Qualifier = UnresExpr->getQualifier(); |
15305 | |
15306 | QualType ObjectType = UnresExpr->getBaseType(); |
15307 | Expr::Classification ObjectClassification |
15308 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() |
15309 | : UnresExpr->getBase()->Classify(Ctx&: Context); |
15310 | |
15311 | // Add overload candidates |
15312 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), |
15313 | OverloadCandidateSet::CSK_Normal); |
15314 | |
15315 | // FIXME: avoid copy. |
15316 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
15317 | if (UnresExpr->hasExplicitTemplateArgs()) { |
15318 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
15319 | TemplateArgs = &TemplateArgsBuffer; |
15320 | } |
15321 | |
15322 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), |
15323 | E = UnresExpr->decls_end(); I != E; ++I) { |
15324 | |
15325 | QualType ExplicitObjectType = ObjectType; |
15326 | |
15327 | NamedDecl *Func = *I; |
15328 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); |
15329 | if (isa<UsingShadowDecl>(Val: Func)) |
15330 | Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl(); |
15331 | |
15332 | bool HasExplicitParameter = false; |
15333 | if (const auto *M = dyn_cast<FunctionDecl>(Val: Func); |
15334 | M && M->hasCXXExplicitFunctionObjectParameter()) |
15335 | HasExplicitParameter = true; |
15336 | else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func); |
15337 | M && |
15338 | M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter()) |
15339 | HasExplicitParameter = true; |
15340 | |
15341 | if (HasExplicitParameter) |
15342 | ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr); |
15343 | |
15344 | // Microsoft supports direct constructor calls. |
15345 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) { |
15346 | AddOverloadCandidate(cast<CXXConstructorDecl>(Val: Func), I.getPair(), Args, |
15347 | CandidateSet, |
15348 | /*SuppressUserConversions*/ false); |
15349 | } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) { |
15350 | // If explicit template arguments were provided, we can't call a |
15351 | // non-template member function. |
15352 | if (TemplateArgs) |
15353 | continue; |
15354 | |
15355 | AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType, |
15356 | ObjectClassification, Args, CandidateSet, |
15357 | /*SuppressUserConversions=*/false); |
15358 | } else { |
15359 | AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func), |
15360 | FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs, |
15361 | ObjectType: ExplicitObjectType, ObjectClassification, |
15362 | Args, CandidateSet, |
15363 | /*SuppressUserConversions=*/false); |
15364 | } |
15365 | } |
15366 | |
15367 | HadMultipleCandidates = (CandidateSet.size() > 1); |
15368 | |
15369 | DeclarationName DeclName = UnresExpr->getMemberName(); |
15370 | |
15371 | UnbridgedCasts.restore(); |
15372 | |
15373 | OverloadCandidateSet::iterator Best; |
15374 | bool Succeeded = false; |
15375 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(), |
15376 | Best)) { |
15377 | case OR_Success: |
15378 | Method = cast<CXXMethodDecl>(Val: Best->Function); |
15379 | FoundDecl = Best->FoundDecl; |
15380 | CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl); |
15381 | if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc())) |
15382 | break; |
15383 | // If FoundDecl is different from Method (such as if one is a template |
15384 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
15385 | // called on both. |
15386 | // FIXME: This would be more comprehensively addressed by modifying |
15387 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
15388 | // being used. |
15389 | if (Method != FoundDecl.getDecl() && |
15390 | DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc())) |
15391 | break; |
15392 | Succeeded = true; |
15393 | break; |
15394 | |
15395 | case OR_No_Viable_Function: |
15396 | CandidateSet.NoteCandidates( |
15397 | PartialDiagnosticAt( |
15398 | UnresExpr->getMemberLoc(), |
15399 | PDiag(diag::err_ovl_no_viable_member_function_in_call) |
15400 | << DeclName << MemExprE->getSourceRange()), |
15401 | *this, OCD_AllCandidates, Args); |
15402 | break; |
15403 | case OR_Ambiguous: |
15404 | CandidateSet.NoteCandidates( |
15405 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
15406 | PDiag(diag::err_ovl_ambiguous_member_call) |
15407 | << DeclName << MemExprE->getSourceRange()), |
15408 | *this, OCD_AmbiguousCandidates, Args); |
15409 | break; |
15410 | case OR_Deleted: |
15411 | CandidateSet.NoteCandidates( |
15412 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
15413 | PDiag(diag::err_ovl_deleted_member_call) |
15414 | << DeclName << MemExprE->getSourceRange()), |
15415 | *this, OCD_AllCandidates, Args); |
15416 | break; |
15417 | } |
15418 | // Overload resolution fails, try to recover. |
15419 | if (!Succeeded) |
15420 | return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best)); |
15421 | |
15422 | ExprResult Res = |
15423 | FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); |
15424 | if (Res.isInvalid()) |
15425 | return ExprError(); |
15426 | MemExprE = Res.get(); |
15427 | |
15428 | // If overload resolution picked a static member |
15429 | // build a non-member call based on that function. |
15430 | if (Method->isStatic()) { |
15431 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, |
15432 | ExecConfig, IsExecConfig); |
15433 | } |
15434 | |
15435 | MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens()); |
15436 | } |
15437 | |
15438 | QualType ResultType = Method->getReturnType(); |
15439 | ExprValueKind VK = Expr::getValueKindForType(T: ResultType); |
15440 | ResultType = ResultType.getNonLValueExprType(Context); |
15441 | |
15442 | assert(Method && "Member call to something that isn't a method?" ); |
15443 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
15444 | |
15445 | CallExpr *TheCall = nullptr; |
15446 | llvm::SmallVector<Expr *, 8> NewArgs; |
15447 | if (Method->isExplicitObjectMemberFunction()) { |
15448 | PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args, |
15449 | NewArgs); |
15450 | // Build the actual expression node. |
15451 | ExprResult FnExpr = |
15452 | CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr, |
15453 | HadMultipleCandidates, MemExpr->getExprLoc()); |
15454 | if (FnExpr.isInvalid()) |
15455 | return ExprError(); |
15456 | |
15457 | TheCall = |
15458 | CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc, |
15459 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams()); |
15460 | } else { |
15461 | // Convert the object argument (for a non-static member function call). |
15462 | // We only need to do this if there was actually an overload; otherwise |
15463 | // it was done at lookup. |
15464 | ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization( |
15465 | From: MemExpr->getBase(), Qualifier, FoundDecl, Method); |
15466 | if (ObjectArg.isInvalid()) |
15467 | return ExprError(); |
15468 | MemExpr->setBase(ObjectArg.get()); |
15469 | TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK, |
15470 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), |
15471 | MinNumArgs: Proto->getNumParams()); |
15472 | } |
15473 | |
15474 | // Check for a valid return type. |
15475 | if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(), |
15476 | CE: TheCall, FD: Method)) |
15477 | return BuildRecoveryExpr(ResultType); |
15478 | |
15479 | // Convert the rest of the arguments |
15480 | if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto: Proto, Args, |
15481 | RParenLoc)) |
15482 | return BuildRecoveryExpr(ResultType); |
15483 | |
15484 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
15485 | |
15486 | if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto)) |
15487 | return ExprError(); |
15488 | |
15489 | // In the case the method to call was not selected by the overloading |
15490 | // resolution process, we still need to handle the enable_if attribute. Do |
15491 | // that here, so it will not hide previous -- and more relevant -- errors. |
15492 | if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) { |
15493 | if (const EnableIfAttr *Attr = |
15494 | CheckEnableIf(Method, LParenLoc, Args, true)) { |
15495 | Diag(MemE->getMemberLoc(), |
15496 | diag::err_ovl_no_viable_member_function_in_call) |
15497 | << Method << Method->getSourceRange(); |
15498 | Diag(Method->getLocation(), |
15499 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
15500 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
15501 | return ExprError(); |
15502 | } |
15503 | } |
15504 | |
15505 | if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) && |
15506 | TheCall->getDirectCallee()->isPureVirtual()) { |
15507 | const FunctionDecl *MD = TheCall->getDirectCallee(); |
15508 | |
15509 | if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) && |
15510 | MemExpr->performsVirtualDispatch(LO: getLangOpts())) { |
15511 | Diag(MemExpr->getBeginLoc(), |
15512 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) |
15513 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) |
15514 | << MD->getParent(); |
15515 | |
15516 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); |
15517 | if (getLangOpts().AppleKext) |
15518 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) |
15519 | << MD->getParent() << MD->getDeclName(); |
15520 | } |
15521 | } |
15522 | |
15523 | if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) { |
15524 | // a->A::f() doesn't go through the vtable, except in AppleKext mode. |
15525 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; |
15526 | CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false, |
15527 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, |
15528 | DtorLoc: MemExpr->getMemberLoc()); |
15529 | } |
15530 | |
15531 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), |
15532 | Decl: TheCall->getDirectCallee()); |
15533 | } |
15534 | |
15535 | /// BuildCallToObjectOfClassType - Build a call to an object of class |
15536 | /// type (C++ [over.call.object]), which can end up invoking an |
15537 | /// overloaded function call operator (@c operator()) or performing a |
15538 | /// user-defined conversion on the object argument. |
15539 | ExprResult |
15540 | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, |
15541 | SourceLocation LParenLoc, |
15542 | MultiExprArg Args, |
15543 | SourceLocation RParenLoc) { |
15544 | if (checkPlaceholderForOverload(S&: *this, E&: Obj)) |
15545 | return ExprError(); |
15546 | ExprResult Object = Obj; |
15547 | |
15548 | UnbridgedCastsSet UnbridgedCasts; |
15549 | if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) |
15550 | return ExprError(); |
15551 | |
15552 | assert(Object.get()->getType()->isRecordType() && |
15553 | "Requires object type argument" ); |
15554 | |
15555 | // C++ [over.call.object]p1: |
15556 | // If the primary-expression E in the function call syntax |
15557 | // evaluates to a class object of type "cv T", then the set of |
15558 | // candidate functions includes at least the function call |
15559 | // operators of T. The function call operators of T are obtained by |
15560 | // ordinary lookup of the name operator() in the context of |
15561 | // (E).operator(). |
15562 | OverloadCandidateSet CandidateSet(LParenLoc, |
15563 | OverloadCandidateSet::CSK_Operator); |
15564 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call); |
15565 | |
15566 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), |
15567 | diag::err_incomplete_object_call, Object.get())) |
15568 | return true; |
15569 | |
15570 | const auto *Record = Object.get()->getType()->castAs<RecordType>(); |
15571 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); |
15572 | LookupQualifiedName(R, Record->getDecl()); |
15573 | R.suppressAccessDiagnostics(); |
15574 | |
15575 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
15576 | Oper != OperEnd; ++Oper) { |
15577 | AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(), |
15578 | ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet, |
15579 | /*SuppressUserConversion=*/SuppressUserConversions: false); |
15580 | } |
15581 | |
15582 | // When calling a lambda, both the call operator, and |
15583 | // the conversion operator to function pointer |
15584 | // are considered. But when constraint checking |
15585 | // on the call operator fails, it will also fail on the |
15586 | // conversion operator as the constraints are always the same. |
15587 | // As the user probably does not intend to perform a surrogate call, |
15588 | // we filter them out to produce better error diagnostics, ie to avoid |
15589 | // showing 2 failed overloads instead of one. |
15590 | bool IgnoreSurrogateFunctions = false; |
15591 | if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) { |
15592 | const OverloadCandidate &Candidate = *CandidateSet.begin(); |
15593 | if (!Candidate.Viable && |
15594 | Candidate.FailureKind == ovl_fail_constraints_not_satisfied) |
15595 | IgnoreSurrogateFunctions = true; |
15596 | } |
15597 | |
15598 | // C++ [over.call.object]p2: |
15599 | // In addition, for each (non-explicit in C++0x) conversion function |
15600 | // declared in T of the form |
15601 | // |
15602 | // operator conversion-type-id () cv-qualifier; |
15603 | // |
15604 | // where cv-qualifier is the same cv-qualification as, or a |
15605 | // greater cv-qualification than, cv, and where conversion-type-id |
15606 | // denotes the type "pointer to function of (P1,...,Pn) returning |
15607 | // R", or the type "reference to pointer to function of |
15608 | // (P1,...,Pn) returning R", or the type "reference to function |
15609 | // of (P1,...,Pn) returning R", a surrogate call function [...] |
15610 | // is also considered as a candidate function. Similarly, |
15611 | // surrogate call functions are added to the set of candidate |
15612 | // functions for each conversion function declared in an |
15613 | // accessible base class provided the function is not hidden |
15614 | // within T by another intervening declaration. |
15615 | const auto &Conversions = |
15616 | cast<CXXRecordDecl>(Val: Record->getDecl())->getVisibleConversionFunctions(); |
15617 | for (auto I = Conversions.begin(), E = Conversions.end(); |
15618 | !IgnoreSurrogateFunctions && I != E; ++I) { |
15619 | NamedDecl *D = *I; |
15620 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
15621 | if (isa<UsingShadowDecl>(Val: D)) |
15622 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
15623 | |
15624 | // Skip over templated conversion functions; they aren't |
15625 | // surrogates. |
15626 | if (isa<FunctionTemplateDecl>(Val: D)) |
15627 | continue; |
15628 | |
15629 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D); |
15630 | if (!Conv->isExplicit()) { |
15631 | // Strip the reference type (if any) and then the pointer type (if |
15632 | // any) to get down to what might be a function type. |
15633 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); |
15634 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
15635 | ConvType = ConvPtrType->getPointeeType(); |
15636 | |
15637 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) |
15638 | { |
15639 | AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto, |
15640 | Object: Object.get(), Args, CandidateSet); |
15641 | } |
15642 | } |
15643 | } |
15644 | |
15645 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15646 | |
15647 | // Perform overload resolution. |
15648 | OverloadCandidateSet::iterator Best; |
15649 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(), |
15650 | Best)) { |
15651 | case OR_Success: |
15652 | // Overload resolution succeeded; we'll build the appropriate call |
15653 | // below. |
15654 | break; |
15655 | |
15656 | case OR_No_Viable_Function: { |
15657 | PartialDiagnostic PD = |
15658 | CandidateSet.empty() |
15659 | ? (PDiag(diag::err_ovl_no_oper) |
15660 | << Object.get()->getType() << /*call*/ 1 |
15661 | << Object.get()->getSourceRange()) |
15662 | : (PDiag(diag::err_ovl_no_viable_object_call) |
15663 | << Object.get()->getType() << Object.get()->getSourceRange()); |
15664 | CandidateSet.NoteCandidates( |
15665 | PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this, |
15666 | OCD: OCD_AllCandidates, Args); |
15667 | break; |
15668 | } |
15669 | case OR_Ambiguous: |
15670 | if (!R.isAmbiguous()) |
15671 | CandidateSet.NoteCandidates( |
15672 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15673 | PDiag(diag::err_ovl_ambiguous_object_call) |
15674 | << Object.get()->getType() |
15675 | << Object.get()->getSourceRange()), |
15676 | *this, OCD_AmbiguousCandidates, Args); |
15677 | break; |
15678 | |
15679 | case OR_Deleted: |
15680 | CandidateSet.NoteCandidates( |
15681 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15682 | PDiag(diag::err_ovl_deleted_object_call) |
15683 | << Object.get()->getType() |
15684 | << Object.get()->getSourceRange()), |
15685 | *this, OCD_AllCandidates, Args); |
15686 | break; |
15687 | } |
15688 | |
15689 | if (Best == CandidateSet.end()) |
15690 | return true; |
15691 | |
15692 | UnbridgedCasts.restore(); |
15693 | |
15694 | if (Best->Function == nullptr) { |
15695 | // Since there is no function declaration, this is one of the |
15696 | // surrogate candidates. Dig out the conversion function. |
15697 | CXXConversionDecl *Conv |
15698 | = cast<CXXConversionDecl>( |
15699 | Val: Best->Conversions[0].UserDefined.ConversionFunction); |
15700 | |
15701 | CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, |
15702 | FoundDecl: Best->FoundDecl); |
15703 | if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc)) |
15704 | return ExprError(); |
15705 | assert(Conv == Best->FoundDecl.getDecl() && |
15706 | "Found Decl & conversion-to-functionptr should be same, right?!" ); |
15707 | // We selected one of the surrogate functions that converts the |
15708 | // object parameter to a function pointer. Perform the conversion |
15709 | // on the object argument, then let BuildCallExpr finish the job. |
15710 | |
15711 | // Create an implicit member expr to refer to the conversion operator. |
15712 | // and then call it. |
15713 | ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl, |
15714 | Method: Conv, HadMultipleCandidates); |
15715 | if (Call.isInvalid()) |
15716 | return ExprError(); |
15717 | // Record usage of conversion in an implicit cast. |
15718 | Call = ImplicitCastExpr::Create( |
15719 | Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(), |
15720 | BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides()); |
15721 | |
15722 | return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc); |
15723 | } |
15724 | |
15725 | CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl); |
15726 | |
15727 | // We found an overloaded operator(). Build a CXXOperatorCallExpr |
15728 | // that calls this method, using Object for the implicit object |
15729 | // parameter and passing along the remaining arguments. |
15730 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function); |
15731 | |
15732 | // An error diagnostic has already been printed when parsing the declaration. |
15733 | if (Method->isInvalidDecl()) |
15734 | return ExprError(); |
15735 | |
15736 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
15737 | unsigned NumParams = Proto->getNumParams(); |
15738 | |
15739 | DeclarationNameInfo OpLocInfo( |
15740 | Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc); |
15741 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); |
15742 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15743 | Obj, HadMultipleCandidates, |
15744 | OpLocInfo.getLoc(), |
15745 | OpLocInfo.getInfo()); |
15746 | if (NewFn.isInvalid()) |
15747 | return true; |
15748 | |
15749 | SmallVector<Expr *, 8> MethodArgs; |
15750 | MethodArgs.reserve(N: NumParams + 1); |
15751 | |
15752 | bool IsError = false; |
15753 | |
15754 | // Initialize the object parameter. |
15755 | llvm::SmallVector<Expr *, 8> NewArgs; |
15756 | if (Method->isExplicitObjectMemberFunction()) { |
15757 | // FIXME: we should do that during the definition of the lambda when we can. |
15758 | DiagnoseInvalidExplicitObjectParameterInLambda(Method); |
15759 | PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs); |
15760 | } else { |
15761 | ExprResult ObjRes = PerformImplicitObjectArgumentInitialization( |
15762 | From: Object.get(), /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method); |
15763 | if (ObjRes.isInvalid()) |
15764 | IsError = true; |
15765 | else |
15766 | Object = ObjRes; |
15767 | MethodArgs.push_back(Elt: Object.get()); |
15768 | } |
15769 | |
15770 | IsError |= PrepareArgumentsForCallToObjectOfClassType( |
15771 | S&: *this, MethodArgs, Method, Args, LParenLoc); |
15772 | |
15773 | // If this is a variadic call, handle args passed through "...". |
15774 | if (Proto->isVariadic()) { |
15775 | // Promote the arguments (C99 6.5.2.2p7). |
15776 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { |
15777 | ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod, |
15778 | FDecl: nullptr); |
15779 | IsError |= Arg.isInvalid(); |
15780 | MethodArgs.push_back(Elt: Arg.get()); |
15781 | } |
15782 | } |
15783 | |
15784 | if (IsError) |
15785 | return true; |
15786 | |
15787 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
15788 | |
15789 | // Once we've built TheCall, all of the expressions are properly owned. |
15790 | QualType ResultTy = Method->getReturnType(); |
15791 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
15792 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15793 | |
15794 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
15795 | Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc, |
15796 | FPFeatures: CurFPFeatureOverrides()); |
15797 | |
15798 | if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method)) |
15799 | return true; |
15800 | |
15801 | if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto)) |
15802 | return true; |
15803 | |
15804 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15805 | } |
15806 | |
15807 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> |
15808 | /// (if one exists), where @c Base is an expression of class type and |
15809 | /// @c Member is the name of the member we're trying to find. |
15810 | ExprResult |
15811 | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, |
15812 | bool *NoArrowOperatorFound) { |
15813 | assert(Base->getType()->isRecordType() && |
15814 | "left-hand side must have class type" ); |
15815 | |
15816 | if (checkPlaceholderForOverload(S&: *this, E&: Base)) |
15817 | return ExprError(); |
15818 | |
15819 | SourceLocation Loc = Base->getExprLoc(); |
15820 | |
15821 | // C++ [over.ref]p1: |
15822 | // |
15823 | // [...] An expression x->m is interpreted as (x.operator->())->m |
15824 | // for a class object x of type T if T::operator->() exists and if |
15825 | // the operator is selected as the best match function by the |
15826 | // overload resolution mechanism (13.3). |
15827 | DeclarationName OpName = |
15828 | Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow); |
15829 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); |
15830 | |
15831 | if (RequireCompleteType(Loc, Base->getType(), |
15832 | diag::err_typecheck_incomplete_tag, Base)) |
15833 | return ExprError(); |
15834 | |
15835 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); |
15836 | LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); |
15837 | R.suppressAccessDiagnostics(); |
15838 | |
15839 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
15840 | Oper != OperEnd; ++Oper) { |
15841 | AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context), |
15842 | Args: std::nullopt, CandidateSet, |
15843 | /*SuppressUserConversion=*/SuppressUserConversions: false); |
15844 | } |
15845 | |
15846 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15847 | |
15848 | // Perform overload resolution. |
15849 | OverloadCandidateSet::iterator Best; |
15850 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) { |
15851 | case OR_Success: |
15852 | // Overload resolution succeeded; we'll build the call below. |
15853 | break; |
15854 | |
15855 | case OR_No_Viable_Function: { |
15856 | auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base); |
15857 | if (CandidateSet.empty()) { |
15858 | QualType BaseType = Base->getType(); |
15859 | if (NoArrowOperatorFound) { |
15860 | // Report this specific error to the caller instead of emitting a |
15861 | // diagnostic, as requested. |
15862 | *NoArrowOperatorFound = true; |
15863 | return ExprError(); |
15864 | } |
15865 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
15866 | << BaseType << Base->getSourceRange(); |
15867 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { |
15868 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) |
15869 | << FixItHint::CreateReplacement(OpLoc, "." ); |
15870 | } |
15871 | } else |
15872 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
15873 | << "operator->" << Base->getSourceRange(); |
15874 | CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands); |
15875 | return ExprError(); |
15876 | } |
15877 | case OR_Ambiguous: |
15878 | if (!R.isAmbiguous()) |
15879 | CandidateSet.NoteCandidates( |
15880 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) |
15881 | << "->" << Base->getType() |
15882 | << Base->getSourceRange()), |
15883 | *this, OCD_AmbiguousCandidates, Base); |
15884 | return ExprError(); |
15885 | |
15886 | case OR_Deleted: |
15887 | CandidateSet.NoteCandidates( |
15888 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
15889 | << "->" << Base->getSourceRange()), |
15890 | *this, OCD_AllCandidates, Base); |
15891 | return ExprError(); |
15892 | } |
15893 | |
15894 | CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl); |
15895 | |
15896 | // Convert the object parameter. |
15897 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function); |
15898 | |
15899 | if (Method->isExplicitObjectMemberFunction()) { |
15900 | ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method); |
15901 | if (R.isInvalid()) |
15902 | return ExprError(); |
15903 | Base = R.get(); |
15904 | } else { |
15905 | ExprResult BaseResult = PerformImplicitObjectArgumentInitialization( |
15906 | From: Base, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method); |
15907 | if (BaseResult.isInvalid()) |
15908 | return ExprError(); |
15909 | Base = BaseResult.get(); |
15910 | } |
15911 | |
15912 | // Build the operator call. |
15913 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15914 | Base, HadMultipleCandidates, OpLoc); |
15915 | if (FnExpr.isInvalid()) |
15916 | return ExprError(); |
15917 | |
15918 | QualType ResultTy = Method->getReturnType(); |
15919 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
15920 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15921 | |
15922 | CallExpr *TheCall = |
15923 | CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base, |
15924 | Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15925 | |
15926 | if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method)) |
15927 | return ExprError(); |
15928 | |
15929 | if (CheckFunctionCall(FDecl: Method, TheCall, |
15930 | Proto: Method->getType()->castAs<FunctionProtoType>())) |
15931 | return ExprError(); |
15932 | |
15933 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15934 | } |
15935 | |
15936 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to |
15937 | /// a literal operator described by the provided lookup results. |
15938 | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, |
15939 | DeclarationNameInfo &SuffixInfo, |
15940 | ArrayRef<Expr*> Args, |
15941 | SourceLocation LitEndLoc, |
15942 | TemplateArgumentListInfo *TemplateArgs) { |
15943 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); |
15944 | |
15945 | OverloadCandidateSet CandidateSet(UDSuffixLoc, |
15946 | OverloadCandidateSet::CSK_Normal); |
15947 | AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet, |
15948 | ExplicitTemplateArgs: TemplateArgs); |
15949 | |
15950 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15951 | |
15952 | // Perform overload resolution. This will usually be trivial, but might need |
15953 | // to perform substitutions for a literal operator template. |
15954 | OverloadCandidateSet::iterator Best; |
15955 | switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) { |
15956 | case OR_Success: |
15957 | case OR_Deleted: |
15958 | break; |
15959 | |
15960 | case OR_No_Viable_Function: |
15961 | CandidateSet.NoteCandidates( |
15962 | PartialDiagnosticAt(UDSuffixLoc, |
15963 | PDiag(diag::err_ovl_no_viable_function_in_call) |
15964 | << R.getLookupName()), |
15965 | *this, OCD_AllCandidates, Args); |
15966 | return ExprError(); |
15967 | |
15968 | case OR_Ambiguous: |
15969 | CandidateSet.NoteCandidates( |
15970 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) |
15971 | << R.getLookupName()), |
15972 | *this, OCD_AmbiguousCandidates, Args); |
15973 | return ExprError(); |
15974 | } |
15975 | |
15976 | FunctionDecl *FD = Best->Function; |
15977 | ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl, |
15978 | Base: nullptr, HadMultipleCandidates, |
15979 | Loc: SuffixInfo.getLoc(), |
15980 | LocInfo: SuffixInfo.getInfo()); |
15981 | if (Fn.isInvalid()) |
15982 | return true; |
15983 | |
15984 | // Check the argument types. This should almost always be a no-op, except |
15985 | // that array-to-pointer decay is applied to string literals. |
15986 | Expr *ConvArgs[2]; |
15987 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
15988 | ExprResult InputInit = PerformCopyInitialization( |
15989 | Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)), |
15990 | EqualLoc: SourceLocation(), Init: Args[ArgIdx]); |
15991 | if (InputInit.isInvalid()) |
15992 | return true; |
15993 | ConvArgs[ArgIdx] = InputInit.get(); |
15994 | } |
15995 | |
15996 | QualType ResultTy = FD->getReturnType(); |
15997 | ExprValueKind VK = Expr::getValueKindForType(T: ResultTy); |
15998 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15999 | |
16000 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( |
16001 | Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK, |
16002 | LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides()); |
16003 | |
16004 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) |
16005 | return ExprError(); |
16006 | |
16007 | if (CheckFunctionCall(FD, UDL, nullptr)) |
16008 | return ExprError(); |
16009 | |
16010 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(UDL), Decl: FD); |
16011 | } |
16012 | |
16013 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the |
16014 | /// given LookupResult is non-empty, it is assumed to describe a member which |
16015 | /// will be invoked. Otherwise, the function will be found via argument |
16016 | /// dependent lookup. |
16017 | /// CallExpr is set to a valid expression and FRS_Success returned on success, |
16018 | /// otherwise CallExpr is set to ExprError() and some non-success value |
16019 | /// is returned. |
16020 | Sema::ForRangeStatus |
16021 | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, |
16022 | SourceLocation RangeLoc, |
16023 | const DeclarationNameInfo &NameInfo, |
16024 | LookupResult &MemberLookup, |
16025 | OverloadCandidateSet *CandidateSet, |
16026 | Expr *Range, ExprResult *CallExpr) { |
16027 | Scope *S = nullptr; |
16028 | |
16029 | CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal); |
16030 | if (!MemberLookup.empty()) { |
16031 | ExprResult MemberRef = |
16032 | BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc, |
16033 | /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(), |
16034 | /*TemplateKWLoc=*/SourceLocation(), |
16035 | /*FirstQualifierInScope=*/nullptr, |
16036 | R&: MemberLookup, |
16037 | /*TemplateArgs=*/nullptr, S); |
16038 | if (MemberRef.isInvalid()) { |
16039 | *CallExpr = ExprError(); |
16040 | return FRS_DiagnosticIssued; |
16041 | } |
16042 | *CallExpr = |
16043 | BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc, ExecConfig: nullptr); |
16044 | if (CallExpr->isInvalid()) { |
16045 | *CallExpr = ExprError(); |
16046 | return FRS_DiagnosticIssued; |
16047 | } |
16048 | } else { |
16049 | ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, |
16050 | NNSLoc: NestedNameSpecifierLoc(), |
16051 | DNI: NameInfo, Fns: UnresolvedSet<0>()); |
16052 | if (FnR.isInvalid()) |
16053 | return FRS_DiagnosticIssued; |
16054 | UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get()); |
16055 | |
16056 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, |
16057 | CandidateSet, CallExpr); |
16058 | if (CandidateSet->empty() || CandidateSetError) { |
16059 | *CallExpr = ExprError(); |
16060 | return FRS_NoViableFunction; |
16061 | } |
16062 | OverloadCandidateSet::iterator Best; |
16063 | OverloadingResult OverloadResult = |
16064 | CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best); |
16065 | |
16066 | if (OverloadResult == OR_No_Viable_Function) { |
16067 | *CallExpr = ExprError(); |
16068 | return FRS_NoViableFunction; |
16069 | } |
16070 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, |
16071 | Loc, nullptr, CandidateSet, &Best, |
16072 | OverloadResult, |
16073 | /*AllowTypoCorrection=*/false); |
16074 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { |
16075 | *CallExpr = ExprError(); |
16076 | return FRS_DiagnosticIssued; |
16077 | } |
16078 | } |
16079 | return FRS_Success; |
16080 | } |
16081 | |
16082 | |
16083 | /// FixOverloadedFunctionReference - E is an expression that refers to |
16084 | /// a C++ overloaded function (possibly with some parentheses and |
16085 | /// perhaps a '&' around it). We have resolved the overloaded function |
16086 | /// to the function declaration Fn, so patch up the expression E to |
16087 | /// refer (possibly indirectly) to Fn. Returns the new expr. |
16088 | ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, |
16089 | FunctionDecl *Fn) { |
16090 | if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) { |
16091 | ExprResult SubExpr = |
16092 | FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn); |
16093 | if (SubExpr.isInvalid()) |
16094 | return ExprError(); |
16095 | if (SubExpr.get() == PE->getSubExpr()) |
16096 | return PE; |
16097 | |
16098 | return new (Context) |
16099 | ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); |
16100 | } |
16101 | |
16102 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
16103 | ExprResult SubExpr = |
16104 | FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn); |
16105 | if (SubExpr.isInvalid()) |
16106 | return ExprError(); |
16107 | assert(Context.hasSameType(ICE->getSubExpr()->getType(), |
16108 | SubExpr.get()->getType()) && |
16109 | "Implicit cast type cannot be determined from overload" ); |
16110 | assert(ICE->path_empty() && "fixing up hierarchy conversion?" ); |
16111 | if (SubExpr.get() == ICE->getSubExpr()) |
16112 | return ICE; |
16113 | |
16114 | return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(), |
16115 | Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(), |
16116 | FPO: CurFPFeatureOverrides()); |
16117 | } |
16118 | |
16119 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) { |
16120 | if (!GSE->isResultDependent()) { |
16121 | ExprResult SubExpr = |
16122 | FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn); |
16123 | if (SubExpr.isInvalid()) |
16124 | return ExprError(); |
16125 | if (SubExpr.get() == GSE->getResultExpr()) |
16126 | return GSE; |
16127 | |
16128 | // Replace the resulting type information before rebuilding the generic |
16129 | // selection expression. |
16130 | ArrayRef<Expr *> A = GSE->getAssocExprs(); |
16131 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); |
16132 | unsigned ResultIdx = GSE->getResultIndex(); |
16133 | AssocExprs[ResultIdx] = SubExpr.get(); |
16134 | |
16135 | if (GSE->isExprPredicate()) |
16136 | return GenericSelectionExpr::Create( |
16137 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), |
16138 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
16139 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
16140 | ResultIdx); |
16141 | return GenericSelectionExpr::Create( |
16142 | Context, GSE->getGenericLoc(), GSE->getControllingType(), |
16143 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
16144 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
16145 | ResultIdx); |
16146 | } |
16147 | // Rather than fall through to the unreachable, return the original generic |
16148 | // selection expression. |
16149 | return GSE; |
16150 | } |
16151 | |
16152 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) { |
16153 | assert(UnOp->getOpcode() == UO_AddrOf && |
16154 | "Can only take the address of an overloaded function" ); |
16155 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) { |
16156 | if (Method->isStatic()) { |
16157 | // Do nothing: static member functions aren't any different |
16158 | // from non-member functions. |
16159 | } else { |
16160 | // Fix the subexpression, which really has to be an |
16161 | // UnresolvedLookupExpr holding an overloaded member function |
16162 | // or template. |
16163 | ExprResult SubExpr = |
16164 | FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn); |
16165 | if (SubExpr.isInvalid()) |
16166 | return ExprError(); |
16167 | if (SubExpr.get() == UnOp->getSubExpr()) |
16168 | return UnOp; |
16169 | |
16170 | if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(), |
16171 | Op: SubExpr.get(), MD: Method)) |
16172 | return ExprError(); |
16173 | |
16174 | assert(isa<DeclRefExpr>(SubExpr.get()) && |
16175 | "fixed to something other than a decl ref" ); |
16176 | assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() && |
16177 | "fixed to a member ref with no nested name qualifier" ); |
16178 | |
16179 | // We have taken the address of a pointer to member |
16180 | // function. Perform the computation here so that we get the |
16181 | // appropriate pointer to member type. |
16182 | QualType ClassType |
16183 | = Context.getTypeDeclType(Decl: cast<RecordDecl>(Method->getDeclContext())); |
16184 | QualType MemPtrType |
16185 | = Context.getMemberPointerType(T: Fn->getType(), Cls: ClassType.getTypePtr()); |
16186 | // Under the MS ABI, lock down the inheritance model now. |
16187 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
16188 | (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType); |
16189 | |
16190 | return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf, |
16191 | type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary, |
16192 | l: UnOp->getOperatorLoc(), CanOverflow: false, |
16193 | FPFeatures: CurFPFeatureOverrides()); |
16194 | } |
16195 | } |
16196 | ExprResult SubExpr = |
16197 | FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn); |
16198 | if (SubExpr.isInvalid()) |
16199 | return ExprError(); |
16200 | if (SubExpr.get() == UnOp->getSubExpr()) |
16201 | return UnOp; |
16202 | |
16203 | return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf, |
16204 | InputExpr: SubExpr.get()); |
16205 | } |
16206 | |
16207 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) { |
16208 | // FIXME: avoid copy. |
16209 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
16210 | if (ULE->hasExplicitTemplateArgs()) { |
16211 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); |
16212 | TemplateArgs = &TemplateArgsBuffer; |
16213 | } |
16214 | |
16215 | QualType Type = Fn->getType(); |
16216 | ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; |
16217 | |
16218 | // FIXME: Duplicated from BuildDeclarationNameExpr. |
16219 | if (unsigned BID = Fn->getBuiltinID()) { |
16220 | if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) { |
16221 | Type = Context.BuiltinFnTy; |
16222 | ValueKind = VK_PRValue; |
16223 | } |
16224 | } |
16225 | |
16226 | DeclRefExpr *DRE = BuildDeclRefExpr( |
16227 | Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), |
16228 | Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); |
16229 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); |
16230 | return DRE; |
16231 | } |
16232 | |
16233 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) { |
16234 | // FIXME: avoid copy. |
16235 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
16236 | if (MemExpr->hasExplicitTemplateArgs()) { |
16237 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
16238 | TemplateArgs = &TemplateArgsBuffer; |
16239 | } |
16240 | |
16241 | Expr *Base; |
16242 | |
16243 | // If we're filling in a static method where we used to have an |
16244 | // implicit member access, rewrite to a simple decl ref. |
16245 | if (MemExpr->isImplicitAccess()) { |
16246 | if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) { |
16247 | DeclRefExpr *DRE = BuildDeclRefExpr( |
16248 | Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), |
16249 | MemExpr->getQualifierLoc(), Found.getDecl(), |
16250 | MemExpr->getTemplateKeywordLoc(), TemplateArgs); |
16251 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); |
16252 | return DRE; |
16253 | } else { |
16254 | SourceLocation Loc = MemExpr->getMemberLoc(); |
16255 | if (MemExpr->getQualifier()) |
16256 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); |
16257 | Base = |
16258 | BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true); |
16259 | } |
16260 | } else |
16261 | Base = MemExpr->getBase(); |
16262 | |
16263 | ExprValueKind valueKind; |
16264 | QualType type; |
16265 | if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) { |
16266 | valueKind = VK_LValue; |
16267 | type = Fn->getType(); |
16268 | } else { |
16269 | valueKind = VK_PRValue; |
16270 | type = Context.BoundMemberTy; |
16271 | } |
16272 | |
16273 | return BuildMemberExpr( |
16274 | Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), |
16275 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, |
16276 | /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), |
16277 | type, valueKind, OK_Ordinary, TemplateArgs); |
16278 | } |
16279 | |
16280 | llvm_unreachable("Invalid reference to overloaded function" ); |
16281 | } |
16282 | |
16283 | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, |
16284 | DeclAccessPair Found, |
16285 | FunctionDecl *Fn) { |
16286 | return FixOverloadedFunctionReference(E: E.get(), Found, Fn); |
16287 | } |
16288 | |
16289 | bool clang::shouldEnforceArgLimit(bool PartialOverloading, |
16290 | FunctionDecl *Function) { |
16291 | if (!PartialOverloading || !Function) |
16292 | return true; |
16293 | if (Function->isVariadic()) |
16294 | return false; |
16295 | if (const auto *Proto = |
16296 | dyn_cast<FunctionProtoType>(Function->getFunctionType())) |
16297 | if (Proto->isTemplateVariadic()) |
16298 | return false; |
16299 | if (auto *Pattern = Function->getTemplateInstantiationPattern()) |
16300 | if (const auto *Proto = |
16301 | dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) |
16302 | if (Proto->isTemplateVariadic()) |
16303 | return false; |
16304 | return true; |
16305 | } |
16306 | |