File: | build/source/clang/lib/Sema/SemaOverload.cpp |
Warning: | line 14067, column 21 Although the value stored to 'LHS' is used in the enclosing expression, the value is never actually read from 'LHS' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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/CXXInheritance.h" |
15 | #include "clang/AST/DeclCXX.h" |
16 | #include "clang/AST/DeclObjC.h" |
17 | #include "clang/AST/DependenceFlags.h" |
18 | #include "clang/AST/Expr.h" |
19 | #include "clang/AST/ExprCXX.h" |
20 | #include "clang/AST/ExprObjC.h" |
21 | #include "clang/AST/Type.h" |
22 | #include "clang/AST/TypeOrdering.h" |
23 | #include "clang/Basic/Diagnostic.h" |
24 | #include "clang/Basic/DiagnosticOptions.h" |
25 | #include "clang/Basic/OperatorKinds.h" |
26 | #include "clang/Basic/PartialDiagnostic.h" |
27 | #include "clang/Basic/SourceManager.h" |
28 | #include "clang/Basic/TargetInfo.h" |
29 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
30 | #include "clang/Sema/Initialization.h" |
31 | #include "clang/Sema/Lookup.h" |
32 | #include "clang/Sema/Overload.h" |
33 | #include "clang/Sema/SemaInternal.h" |
34 | #include "clang/Sema/Template.h" |
35 | #include "clang/Sema/TemplateDeduction.h" |
36 | #include "llvm/ADT/DenseSet.h" |
37 | #include "llvm/ADT/STLExtras.h" |
38 | #include "llvm/ADT/SmallPtrSet.h" |
39 | #include "llvm/ADT/SmallString.h" |
40 | #include "llvm/Support/Casting.h" |
41 | #include <algorithm> |
42 | #include <cstdlib> |
43 | #include <optional> |
44 | |
45 | using namespace clang; |
46 | using namespace sema; |
47 | |
48 | using AllowedExplicit = Sema::AllowedExplicit; |
49 | |
50 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { |
51 | return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { |
52 | return P->hasAttr<PassObjectSizeAttr>(); |
53 | }); |
54 | } |
55 | |
56 | /// A convenience routine for creating a decayed reference to a function. |
57 | static ExprResult CreateFunctionRefExpr( |
58 | Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, |
59 | bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), |
60 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { |
61 | if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) |
62 | return ExprError(); |
63 | // If FoundDecl is different from Fn (such as if one is a template |
64 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
65 | // called on both. |
66 | // FIXME: This would be more comprehensively addressed by modifying |
67 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
68 | // being used. |
69 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) |
70 | return ExprError(); |
71 | DeclRefExpr *DRE = new (S.Context) |
72 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); |
73 | if (HadMultipleCandidates) |
74 | DRE->setHadMultipleCandidates(true); |
75 | |
76 | S.MarkDeclRefReferenced(DRE, Base); |
77 | if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { |
78 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { |
79 | S.ResolveExceptionSpec(Loc, FPT); |
80 | DRE->setType(Fn->getType()); |
81 | } |
82 | } |
83 | return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), |
84 | CK_FunctionToPointerDecay); |
85 | } |
86 | |
87 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
88 | bool InOverloadResolution, |
89 | StandardConversionSequence &SCS, |
90 | bool CStyle, |
91 | bool AllowObjCWritebackConversion); |
92 | |
93 | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
94 | QualType &ToType, |
95 | bool InOverloadResolution, |
96 | StandardConversionSequence &SCS, |
97 | bool CStyle); |
98 | static OverloadingResult |
99 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
100 | UserDefinedConversionSequence& User, |
101 | OverloadCandidateSet& Conversions, |
102 | AllowedExplicit AllowExplicit, |
103 | bool AllowObjCConversionOnExplicit); |
104 | |
105 | static ImplicitConversionSequence::CompareKind |
106 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
107 | const StandardConversionSequence& SCS1, |
108 | const StandardConversionSequence& SCS2); |
109 | |
110 | static ImplicitConversionSequence::CompareKind |
111 | CompareQualificationConversions(Sema &S, |
112 | const StandardConversionSequence& SCS1, |
113 | const StandardConversionSequence& SCS2); |
114 | |
115 | static ImplicitConversionSequence::CompareKind |
116 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
117 | const StandardConversionSequence& SCS1, |
118 | const StandardConversionSequence& SCS2); |
119 | |
120 | /// GetConversionRank - Retrieve the implicit conversion rank |
121 | /// corresponding to the given implicit conversion kind. |
122 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { |
123 | static const ImplicitConversionRank |
124 | Rank[] = { |
125 | ICR_Exact_Match, |
126 | ICR_Exact_Match, |
127 | ICR_Exact_Match, |
128 | ICR_Exact_Match, |
129 | ICR_Exact_Match, |
130 | ICR_Exact_Match, |
131 | ICR_Promotion, |
132 | ICR_Promotion, |
133 | ICR_Promotion, |
134 | ICR_Conversion, |
135 | ICR_Conversion, |
136 | ICR_Conversion, |
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_OCL_Scalar_Widening, |
147 | ICR_Complex_Real_Conversion, |
148 | ICR_Conversion, |
149 | ICR_Conversion, |
150 | ICR_Writeback_Conversion, |
151 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- |
152 | // it was omitted by the patch that added |
153 | // ICK_Zero_Event_Conversion |
154 | ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- |
155 | // it was omitted by the patch that added |
156 | // ICK_Zero_Queue_Conversion |
157 | ICR_C_Conversion, |
158 | ICR_C_Conversion_Extension |
159 | }; |
160 | static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); |
161 | return Rank[(int)Kind]; |
162 | } |
163 | |
164 | /// GetImplicitConversionName - Return the name of this kind of |
165 | /// implicit conversion. |
166 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { |
167 | static const char* const Name[] = { |
168 | "No conversion", |
169 | "Lvalue-to-rvalue", |
170 | "Array-to-pointer", |
171 | "Function-to-pointer", |
172 | "Function pointer conversion", |
173 | "Qualification", |
174 | "Integral promotion", |
175 | "Floating point promotion", |
176 | "Complex promotion", |
177 | "Integral conversion", |
178 | "Floating conversion", |
179 | "Complex conversion", |
180 | "Floating-integral conversion", |
181 | "Pointer conversion", |
182 | "Pointer-to-member conversion", |
183 | "Boolean conversion", |
184 | "Compatible-types conversion", |
185 | "Derived-to-base conversion", |
186 | "Vector conversion", |
187 | "SVE Vector conversion", |
188 | "RVV Vector conversion", |
189 | "Vector splat", |
190 | "Complex-real conversion", |
191 | "Block Pointer conversion", |
192 | "Transparent Union Conversion", |
193 | "Writeback conversion", |
194 | "OpenCL Zero Event Conversion", |
195 | "OpenCL Zero Queue Conversion", |
196 | "C specific type conversion", |
197 | "Incompatible pointer conversion" |
198 | }; |
199 | static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); |
200 | return Name[Kind]; |
201 | } |
202 | |
203 | /// StandardConversionSequence - Set the standard conversion |
204 | /// sequence to the identity conversion. |
205 | void StandardConversionSequence::setAsIdentityConversion() { |
206 | First = ICK_Identity; |
207 | Second = ICK_Identity; |
208 | Third = ICK_Identity; |
209 | DeprecatedStringLiteralToCharPtr = false; |
210 | QualificationIncludesObjCLifetime = false; |
211 | ReferenceBinding = false; |
212 | DirectBinding = false; |
213 | IsLvalueReference = true; |
214 | BindsToFunctionLvalue = false; |
215 | BindsToRvalue = false; |
216 | BindsImplicitObjectArgumentWithoutRefQualifier = false; |
217 | ObjCLifetimeConversionBinding = false; |
218 | CopyConstructor = nullptr; |
219 | } |
220 | |
221 | /// getRank - Retrieve the rank of this standard conversion sequence |
222 | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the |
223 | /// implicit conversions. |
224 | ImplicitConversionRank StandardConversionSequence::getRank() const { |
225 | ImplicitConversionRank Rank = ICR_Exact_Match; |
226 | if (GetConversionRank(First) > Rank) |
227 | Rank = GetConversionRank(First); |
228 | if (GetConversionRank(Second) > Rank) |
229 | Rank = GetConversionRank(Second); |
230 | if (GetConversionRank(Third) > Rank) |
231 | Rank = GetConversionRank(Third); |
232 | return Rank; |
233 | } |
234 | |
235 | /// isPointerConversionToBool - Determines whether this conversion is |
236 | /// a conversion of a pointer or pointer-to-member to bool. This is |
237 | /// used as part of the ranking of standard conversion sequences |
238 | /// (C++ 13.3.3.2p4). |
239 | bool StandardConversionSequence::isPointerConversionToBool() const { |
240 | // Note that FromType has not necessarily been transformed by the |
241 | // array-to-pointer or function-to-pointer implicit conversions, so |
242 | // check for their presence as well as checking whether FromType is |
243 | // a pointer. |
244 | if (getToType(1)->isBooleanType() && |
245 | (getFromType()->isPointerType() || |
246 | getFromType()->isMemberPointerType() || |
247 | getFromType()->isObjCObjectPointerType() || |
248 | getFromType()->isBlockPointerType() || |
249 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) |
250 | return true; |
251 | |
252 | return false; |
253 | } |
254 | |
255 | /// isPointerConversionToVoidPointer - Determines whether this |
256 | /// conversion is a conversion of a pointer to a void pointer. This is |
257 | /// used as part of the ranking of standard conversion sequences (C++ |
258 | /// 13.3.3.2p4). |
259 | bool |
260 | StandardConversionSequence:: |
261 | isPointerConversionToVoidPointer(ASTContext& Context) const { |
262 | QualType FromType = getFromType(); |
263 | QualType ToType = getToType(1); |
264 | |
265 | // Note that FromType has not necessarily been transformed by the |
266 | // array-to-pointer implicit conversion, so check for its presence |
267 | // and redo the conversion to get a pointer. |
268 | if (First == ICK_Array_To_Pointer) |
269 | FromType = Context.getArrayDecayedType(FromType); |
270 | |
271 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) |
272 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) |
273 | return ToPtrType->getPointeeType()->isVoidType(); |
274 | |
275 | return false; |
276 | } |
277 | |
278 | /// Skip any implicit casts which could be either part of a narrowing conversion |
279 | /// or after one in an implicit conversion. |
280 | static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, |
281 | const Expr *Converted) { |
282 | // We can have cleanups wrapping the converted expression; these need to be |
283 | // preserved so that destructors run if necessary. |
284 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { |
285 | Expr *Inner = |
286 | const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); |
287 | return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), |
288 | EWC->getObjects()); |
289 | } |
290 | |
291 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { |
292 | switch (ICE->getCastKind()) { |
293 | case CK_NoOp: |
294 | case CK_IntegralCast: |
295 | case CK_IntegralToBoolean: |
296 | case CK_IntegralToFloating: |
297 | case CK_BooleanToSignedIntegral: |
298 | case CK_FloatingToIntegral: |
299 | case CK_FloatingToBoolean: |
300 | case CK_FloatingCast: |
301 | Converted = ICE->getSubExpr(); |
302 | continue; |
303 | |
304 | default: |
305 | return Converted; |
306 | } |
307 | } |
308 | |
309 | return Converted; |
310 | } |
311 | |
312 | /// Check if this standard conversion sequence represents a narrowing |
313 | /// conversion, according to C++11 [dcl.init.list]p7. |
314 | /// |
315 | /// \param Ctx The AST context. |
316 | /// \param Converted The result of applying this standard conversion sequence. |
317 | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the |
318 | /// value of the expression prior to the narrowing conversion. |
319 | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the |
320 | /// type of the expression prior to the narrowing conversion. |
321 | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions |
322 | /// from floating point types to integral types should be ignored. |
323 | NarrowingKind StandardConversionSequence::getNarrowingKind( |
324 | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, |
325 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { |
326 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\"" , "clang/lib/Sema/SemaOverload.cpp", 326, __extension__ __PRETTY_FUNCTION__ )); |
327 | |
328 | // C++11 [dcl.init.list]p7: |
329 | // A narrowing conversion is an implicit conversion ... |
330 | QualType FromType = getToType(0); |
331 | QualType ToType = getToType(1); |
332 | |
333 | // A conversion to an enumeration type is narrowing if the conversion to |
334 | // the underlying type is narrowing. This only arises for expressions of |
335 | // the form 'Enum{init}'. |
336 | if (auto *ET = ToType->getAs<EnumType>()) |
337 | ToType = ET->getDecl()->getIntegerType(); |
338 | |
339 | switch (Second) { |
340 | // 'bool' is an integral type; dispatch to the right place to handle it. |
341 | case ICK_Boolean_Conversion: |
342 | if (FromType->isRealFloatingType()) |
343 | goto FloatingIntegralConversion; |
344 | if (FromType->isIntegralOrUnscopedEnumerationType()) |
345 | goto IntegralConversion; |
346 | // -- from a pointer type or pointer-to-member type to bool, or |
347 | return NK_Type_Narrowing; |
348 | |
349 | // -- from a floating-point type to an integer type, or |
350 | // |
351 | // -- from an integer type or unscoped enumeration type to a floating-point |
352 | // type, except where the source is a constant expression and the actual |
353 | // value after conversion will fit into the target type and will produce |
354 | // the original value when converted back to the original type, or |
355 | case ICK_Floating_Integral: |
356 | FloatingIntegralConversion: |
357 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { |
358 | return NK_Type_Narrowing; |
359 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
360 | ToType->isRealFloatingType()) { |
361 | if (IgnoreFloatToIntegralConversion) |
362 | return NK_Not_Narrowing; |
363 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
364 | assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression" ) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\"" , "clang/lib/Sema/SemaOverload.cpp", 364, __extension__ __PRETTY_FUNCTION__ )); |
365 | |
366 | // If it's value-dependent, we can't tell whether it's narrowing. |
367 | if (Initializer->isValueDependent()) |
368 | return NK_Dependent_Narrowing; |
369 | |
370 | if (std::optional<llvm::APSInt> IntConstantValue = |
371 | Initializer->getIntegerConstantExpr(Ctx)) { |
372 | // Convert the integer to the floating type. |
373 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); |
374 | Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), |
375 | llvm::APFloat::rmNearestTiesToEven); |
376 | // And back. |
377 | llvm::APSInt ConvertedValue = *IntConstantValue; |
378 | bool ignored; |
379 | Result.convertToInteger(ConvertedValue, |
380 | llvm::APFloat::rmTowardZero, &ignored); |
381 | // If the resulting value is different, this was a narrowing conversion. |
382 | if (*IntConstantValue != ConvertedValue) { |
383 | ConstantValue = APValue(*IntConstantValue); |
384 | ConstantType = Initializer->getType(); |
385 | return NK_Constant_Narrowing; |
386 | } |
387 | } else { |
388 | // Variables are always narrowings. |
389 | return NK_Variable_Narrowing; |
390 | } |
391 | } |
392 | return NK_Not_Narrowing; |
393 | |
394 | // -- from long double to double or float, or from double to float, except |
395 | // where the source is a constant expression and the actual value after |
396 | // conversion is within the range of values that can be represented (even |
397 | // if it cannot be represented exactly), or |
398 | case ICK_Floating_Conversion: |
399 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && |
400 | Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { |
401 | // FromType is larger than ToType. |
402 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
403 | |
404 | // If it's value-dependent, we can't tell whether it's narrowing. |
405 | if (Initializer->isValueDependent()) |
406 | return NK_Dependent_Narrowing; |
407 | |
408 | if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { |
409 | // Constant! |
410 | assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0 ) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp" , 410, __extension__ __PRETTY_FUNCTION__)); |
411 | llvm::APFloat FloatVal = ConstantValue.getFloat(); |
412 | // Convert the source value into the target type. |
413 | bool ignored; |
414 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( |
415 | Ctx.getFloatTypeSemantics(ToType), |
416 | llvm::APFloat::rmNearestTiesToEven, &ignored); |
417 | // If there was no overflow, the source value is within the range of |
418 | // values that can be represented. |
419 | if (ConvertStatus & llvm::APFloat::opOverflow) { |
420 | ConstantType = Initializer->getType(); |
421 | return NK_Constant_Narrowing; |
422 | } |
423 | } else { |
424 | return NK_Variable_Narrowing; |
425 | } |
426 | } |
427 | return NK_Not_Narrowing; |
428 | |
429 | // -- from an integer type or unscoped enumeration type to an integer type |
430 | // that cannot represent all the values of the original type, except where |
431 | // the source is a constant expression and the actual value after |
432 | // conversion will fit into the target type and will produce the original |
433 | // value when converted back to the original type. |
434 | case ICK_Integral_Conversion: |
435 | IntegralConversion: { |
436 | assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType ()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()" , "clang/lib/Sema/SemaOverload.cpp", 436, __extension__ __PRETTY_FUNCTION__ )); |
437 | assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType ()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()" , "clang/lib/Sema/SemaOverload.cpp", 437, __extension__ __PRETTY_FUNCTION__ )); |
438 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); |
439 | const unsigned FromWidth = Ctx.getIntWidth(FromType); |
440 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); |
441 | const unsigned ToWidth = Ctx.getIntWidth(ToType); |
442 | |
443 | if (FromWidth > ToWidth || |
444 | (FromWidth == ToWidth && FromSigned != ToSigned) || |
445 | (FromSigned && !ToSigned)) { |
446 | // Not all values of FromType can be represented in ToType. |
447 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
448 | |
449 | // If it's value-dependent, we can't tell whether it's narrowing. |
450 | if (Initializer->isValueDependent()) |
451 | return NK_Dependent_Narrowing; |
452 | |
453 | std::optional<llvm::APSInt> OptInitializerValue; |
454 | if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { |
455 | // Such conversions on variables are always narrowing. |
456 | return NK_Variable_Narrowing; |
457 | } |
458 | llvm::APSInt &InitializerValue = *OptInitializerValue; |
459 | bool Narrowing = false; |
460 | if (FromWidth < ToWidth) { |
461 | // Negative -> unsigned is narrowing. Otherwise, more bits is never |
462 | // narrowing. |
463 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) |
464 | Narrowing = true; |
465 | } else { |
466 | // Add a bit to the InitializerValue so we don't have to worry about |
467 | // signed vs. unsigned comparisons. |
468 | InitializerValue = InitializerValue.extend( |
469 | InitializerValue.getBitWidth() + 1); |
470 | // Convert the initializer to and from the target width and signed-ness. |
471 | llvm::APSInt ConvertedValue = InitializerValue; |
472 | ConvertedValue = ConvertedValue.trunc(ToWidth); |
473 | ConvertedValue.setIsSigned(ToSigned); |
474 | ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); |
475 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); |
476 | // If the result is different, this was a narrowing conversion. |
477 | if (ConvertedValue != InitializerValue) |
478 | Narrowing = true; |
479 | } |
480 | if (Narrowing) { |
481 | ConstantType = Initializer->getType(); |
482 | ConstantValue = APValue(InitializerValue); |
483 | return NK_Constant_Narrowing; |
484 | } |
485 | } |
486 | return NK_Not_Narrowing; |
487 | } |
488 | |
489 | default: |
490 | // Other kinds of conversions are not narrowings. |
491 | return NK_Not_Narrowing; |
492 | } |
493 | } |
494 | |
495 | /// dump - Print this standard conversion sequence to standard |
496 | /// error. Useful for debugging overloading issues. |
497 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const { |
498 | raw_ostream &OS = llvm::errs(); |
499 | bool PrintedSomething = false; |
500 | if (First != ICK_Identity) { |
501 | OS << GetImplicitConversionName(First); |
502 | PrintedSomething = true; |
503 | } |
504 | |
505 | if (Second != ICK_Identity) { |
506 | if (PrintedSomething) { |
507 | OS << " -> "; |
508 | } |
509 | OS << GetImplicitConversionName(Second); |
510 | |
511 | if (CopyConstructor) { |
512 | OS << " (by copy constructor)"; |
513 | } else if (DirectBinding) { |
514 | OS << " (direct reference binding)"; |
515 | } else if (ReferenceBinding) { |
516 | OS << " (reference binding)"; |
517 | } |
518 | PrintedSomething = true; |
519 | } |
520 | |
521 | if (Third != ICK_Identity) { |
522 | if (PrintedSomething) { |
523 | OS << " -> "; |
524 | } |
525 | OS << GetImplicitConversionName(Third); |
526 | PrintedSomething = true; |
527 | } |
528 | |
529 | if (!PrintedSomething) { |
530 | OS << "No conversions required"; |
531 | } |
532 | } |
533 | |
534 | /// dump - Print this user-defined conversion sequence to standard |
535 | /// error. Useful for debugging overloading issues. |
536 | void UserDefinedConversionSequence::dump() const { |
537 | raw_ostream &OS = llvm::errs(); |
538 | if (Before.First || Before.Second || Before.Third) { |
539 | Before.dump(); |
540 | OS << " -> "; |
541 | } |
542 | if (ConversionFunction) |
543 | OS << '\'' << *ConversionFunction << '\''; |
544 | else |
545 | OS << "aggregate initialization"; |
546 | if (After.First || After.Second || After.Third) { |
547 | OS << " -> "; |
548 | After.dump(); |
549 | } |
550 | } |
551 | |
552 | /// dump - Print this implicit conversion sequence to standard |
553 | /// error. Useful for debugging overloading issues. |
554 | void ImplicitConversionSequence::dump() const { |
555 | raw_ostream &OS = llvm::errs(); |
556 | if (hasInitializerListContainerType()) |
557 | OS << "Worst list element conversion: "; |
558 | switch (ConversionKind) { |
559 | case StandardConversion: |
560 | OS << "Standard conversion: "; |
561 | Standard.dump(); |
562 | break; |
563 | case UserDefinedConversion: |
564 | OS << "User-defined conversion: "; |
565 | UserDefined.dump(); |
566 | break; |
567 | case EllipsisConversion: |
568 | OS << "Ellipsis conversion"; |
569 | break; |
570 | case AmbiguousConversion: |
571 | OS << "Ambiguous conversion"; |
572 | break; |
573 | case BadConversion: |
574 | OS << "Bad conversion"; |
575 | break; |
576 | } |
577 | |
578 | OS << "\n"; |
579 | } |
580 | |
581 | void AmbiguousConversionSequence::construct() { |
582 | new (&conversions()) ConversionSet(); |
583 | } |
584 | |
585 | void AmbiguousConversionSequence::destruct() { |
586 | conversions().~ConversionSet(); |
587 | } |
588 | |
589 | void |
590 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { |
591 | FromTypePtr = O.FromTypePtr; |
592 | ToTypePtr = O.ToTypePtr; |
593 | new (&conversions()) ConversionSet(O.conversions()); |
594 | } |
595 | |
596 | namespace { |
597 | // Structure used by DeductionFailureInfo to store |
598 | // template argument information. |
599 | struct DFIArguments { |
600 | TemplateArgument FirstArg; |
601 | TemplateArgument SecondArg; |
602 | }; |
603 | // Structure used by DeductionFailureInfo to store |
604 | // template parameter and template argument information. |
605 | struct DFIParamWithArguments : DFIArguments { |
606 | TemplateParameter Param; |
607 | }; |
608 | // Structure used by DeductionFailureInfo to store template argument |
609 | // information and the index of the problematic call argument. |
610 | struct DFIDeducedMismatchArgs : DFIArguments { |
611 | TemplateArgumentList *TemplateArgs; |
612 | unsigned CallArgIndex; |
613 | }; |
614 | // Structure used by DeductionFailureInfo to store information about |
615 | // unsatisfied constraints. |
616 | struct CNSInfo { |
617 | TemplateArgumentList *TemplateArgs; |
618 | ConstraintSatisfaction Satisfaction; |
619 | }; |
620 | } |
621 | |
622 | /// Convert from Sema's representation of template deduction information |
623 | /// to the form used in overload-candidate information. |
624 | DeductionFailureInfo |
625 | clang::MakeDeductionFailureInfo(ASTContext &Context, |
626 | Sema::TemplateDeductionResult TDK, |
627 | TemplateDeductionInfo &Info) { |
628 | DeductionFailureInfo Result; |
629 | Result.Result = static_cast<unsigned>(TDK); |
630 | Result.HasDiagnostic = false; |
631 | switch (TDK) { |
632 | case Sema::TDK_Invalid: |
633 | case Sema::TDK_InstantiationDepth: |
634 | case Sema::TDK_TooManyArguments: |
635 | case Sema::TDK_TooFewArguments: |
636 | case Sema::TDK_MiscellaneousDeductionFailure: |
637 | case Sema::TDK_CUDATargetMismatch: |
638 | Result.Data = nullptr; |
639 | break; |
640 | |
641 | case Sema::TDK_Incomplete: |
642 | case Sema::TDK_InvalidExplicitArguments: |
643 | Result.Data = Info.Param.getOpaqueValue(); |
644 | break; |
645 | |
646 | case Sema::TDK_DeducedMismatch: |
647 | case Sema::TDK_DeducedMismatchNested: { |
648 | // FIXME: Should allocate from normal heap so that we can free this later. |
649 | auto *Saved = new (Context) DFIDeducedMismatchArgs; |
650 | Saved->FirstArg = Info.FirstArg; |
651 | Saved->SecondArg = Info.SecondArg; |
652 | Saved->TemplateArgs = Info.takeSugared(); |
653 | Saved->CallArgIndex = Info.CallArgIndex; |
654 | Result.Data = Saved; |
655 | break; |
656 | } |
657 | |
658 | case Sema::TDK_NonDeducedMismatch: { |
659 | // FIXME: Should allocate from normal heap so that we can free this later. |
660 | DFIArguments *Saved = new (Context) DFIArguments; |
661 | Saved->FirstArg = Info.FirstArg; |
662 | Saved->SecondArg = Info.SecondArg; |
663 | Result.Data = Saved; |
664 | break; |
665 | } |
666 | |
667 | case Sema::TDK_IncompletePack: |
668 | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. |
669 | case Sema::TDK_Inconsistent: |
670 | case Sema::TDK_Underqualified: { |
671 | // FIXME: Should allocate from normal heap so that we can free this later. |
672 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; |
673 | Saved->Param = Info.Param; |
674 | Saved->FirstArg = Info.FirstArg; |
675 | Saved->SecondArg = Info.SecondArg; |
676 | Result.Data = Saved; |
677 | break; |
678 | } |
679 | |
680 | case Sema::TDK_SubstitutionFailure: |
681 | Result.Data = Info.takeSugared(); |
682 | if (Info.hasSFINAEDiagnostic()) { |
683 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( |
684 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); |
685 | Info.takeSFINAEDiagnostic(*Diag); |
686 | Result.HasDiagnostic = true; |
687 | } |
688 | break; |
689 | |
690 | case Sema::TDK_ConstraintsNotSatisfied: { |
691 | CNSInfo *Saved = new (Context) CNSInfo; |
692 | Saved->TemplateArgs = Info.takeSugared(); |
693 | Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; |
694 | Result.Data = Saved; |
695 | break; |
696 | } |
697 | |
698 | case Sema::TDK_Success: |
699 | case Sema::TDK_NonDependentConversionFailure: |
700 | case Sema::TDK_AlreadyDiagnosed: |
701 | llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "clang/lib/Sema/SemaOverload.cpp" , 701); |
702 | } |
703 | |
704 | return Result; |
705 | } |
706 | |
707 | void DeductionFailureInfo::Destroy() { |
708 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
709 | case Sema::TDK_Success: |
710 | case Sema::TDK_Invalid: |
711 | case Sema::TDK_InstantiationDepth: |
712 | case Sema::TDK_Incomplete: |
713 | case Sema::TDK_TooManyArguments: |
714 | case Sema::TDK_TooFewArguments: |
715 | case Sema::TDK_InvalidExplicitArguments: |
716 | case Sema::TDK_CUDATargetMismatch: |
717 | case Sema::TDK_NonDependentConversionFailure: |
718 | break; |
719 | |
720 | case Sema::TDK_IncompletePack: |
721 | case Sema::TDK_Inconsistent: |
722 | case Sema::TDK_Underqualified: |
723 | case Sema::TDK_DeducedMismatch: |
724 | case Sema::TDK_DeducedMismatchNested: |
725 | case Sema::TDK_NonDeducedMismatch: |
726 | // FIXME: Destroy the data? |
727 | Data = nullptr; |
728 | break; |
729 | |
730 | case Sema::TDK_SubstitutionFailure: |
731 | // FIXME: Destroy the template argument list? |
732 | Data = nullptr; |
733 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
734 | Diag->~PartialDiagnosticAt(); |
735 | HasDiagnostic = false; |
736 | } |
737 | break; |
738 | |
739 | case Sema::TDK_ConstraintsNotSatisfied: |
740 | // FIXME: Destroy the template argument list? |
741 | Data = nullptr; |
742 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
743 | Diag->~PartialDiagnosticAt(); |
744 | HasDiagnostic = false; |
745 | } |
746 | break; |
747 | |
748 | // Unhandled |
749 | case Sema::TDK_MiscellaneousDeductionFailure: |
750 | case Sema::TDK_AlreadyDiagnosed: |
751 | break; |
752 | } |
753 | } |
754 | |
755 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { |
756 | if (HasDiagnostic) |
757 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); |
758 | return nullptr; |
759 | } |
760 | |
761 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { |
762 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
763 | case Sema::TDK_Success: |
764 | case Sema::TDK_Invalid: |
765 | case Sema::TDK_InstantiationDepth: |
766 | case Sema::TDK_TooManyArguments: |
767 | case Sema::TDK_TooFewArguments: |
768 | case Sema::TDK_SubstitutionFailure: |
769 | case Sema::TDK_DeducedMismatch: |
770 | case Sema::TDK_DeducedMismatchNested: |
771 | case Sema::TDK_NonDeducedMismatch: |
772 | case Sema::TDK_CUDATargetMismatch: |
773 | case Sema::TDK_NonDependentConversionFailure: |
774 | case Sema::TDK_ConstraintsNotSatisfied: |
775 | return TemplateParameter(); |
776 | |
777 | case Sema::TDK_Incomplete: |
778 | case Sema::TDK_InvalidExplicitArguments: |
779 | return TemplateParameter::getFromOpaqueValue(Data); |
780 | |
781 | case Sema::TDK_IncompletePack: |
782 | case Sema::TDK_Inconsistent: |
783 | case Sema::TDK_Underqualified: |
784 | return static_cast<DFIParamWithArguments*>(Data)->Param; |
785 | |
786 | // Unhandled |
787 | case Sema::TDK_MiscellaneousDeductionFailure: |
788 | case Sema::TDK_AlreadyDiagnosed: |
789 | break; |
790 | } |
791 | |
792 | return TemplateParameter(); |
793 | } |
794 | |
795 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { |
796 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
797 | case Sema::TDK_Success: |
798 | case Sema::TDK_Invalid: |
799 | case Sema::TDK_InstantiationDepth: |
800 | case Sema::TDK_TooManyArguments: |
801 | case Sema::TDK_TooFewArguments: |
802 | case Sema::TDK_Incomplete: |
803 | case Sema::TDK_IncompletePack: |
804 | case Sema::TDK_InvalidExplicitArguments: |
805 | case Sema::TDK_Inconsistent: |
806 | case Sema::TDK_Underqualified: |
807 | case Sema::TDK_NonDeducedMismatch: |
808 | case Sema::TDK_CUDATargetMismatch: |
809 | case Sema::TDK_NonDependentConversionFailure: |
810 | return nullptr; |
811 | |
812 | case Sema::TDK_DeducedMismatch: |
813 | case Sema::TDK_DeducedMismatchNested: |
814 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; |
815 | |
816 | case Sema::TDK_SubstitutionFailure: |
817 | return static_cast<TemplateArgumentList*>(Data); |
818 | |
819 | case Sema::TDK_ConstraintsNotSatisfied: |
820 | return static_cast<CNSInfo*>(Data)->TemplateArgs; |
821 | |
822 | // Unhandled |
823 | case Sema::TDK_MiscellaneousDeductionFailure: |
824 | case Sema::TDK_AlreadyDiagnosed: |
825 | break; |
826 | } |
827 | |
828 | return nullptr; |
829 | } |
830 | |
831 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { |
832 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
833 | case Sema::TDK_Success: |
834 | case Sema::TDK_Invalid: |
835 | case Sema::TDK_InstantiationDepth: |
836 | case Sema::TDK_Incomplete: |
837 | case Sema::TDK_TooManyArguments: |
838 | case Sema::TDK_TooFewArguments: |
839 | case Sema::TDK_InvalidExplicitArguments: |
840 | case Sema::TDK_SubstitutionFailure: |
841 | case Sema::TDK_CUDATargetMismatch: |
842 | case Sema::TDK_NonDependentConversionFailure: |
843 | case Sema::TDK_ConstraintsNotSatisfied: |
844 | return nullptr; |
845 | |
846 | case Sema::TDK_IncompletePack: |
847 | case Sema::TDK_Inconsistent: |
848 | case Sema::TDK_Underqualified: |
849 | case Sema::TDK_DeducedMismatch: |
850 | case Sema::TDK_DeducedMismatchNested: |
851 | case Sema::TDK_NonDeducedMismatch: |
852 | return &static_cast<DFIArguments*>(Data)->FirstArg; |
853 | |
854 | // Unhandled |
855 | case Sema::TDK_MiscellaneousDeductionFailure: |
856 | case Sema::TDK_AlreadyDiagnosed: |
857 | break; |
858 | } |
859 | |
860 | return nullptr; |
861 | } |
862 | |
863 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { |
864 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
865 | case Sema::TDK_Success: |
866 | case Sema::TDK_Invalid: |
867 | case Sema::TDK_InstantiationDepth: |
868 | case Sema::TDK_Incomplete: |
869 | case Sema::TDK_IncompletePack: |
870 | case Sema::TDK_TooManyArguments: |
871 | case Sema::TDK_TooFewArguments: |
872 | case Sema::TDK_InvalidExplicitArguments: |
873 | case Sema::TDK_SubstitutionFailure: |
874 | case Sema::TDK_CUDATargetMismatch: |
875 | case Sema::TDK_NonDependentConversionFailure: |
876 | case Sema::TDK_ConstraintsNotSatisfied: |
877 | return nullptr; |
878 | |
879 | case Sema::TDK_Inconsistent: |
880 | case Sema::TDK_Underqualified: |
881 | case Sema::TDK_DeducedMismatch: |
882 | case Sema::TDK_DeducedMismatchNested: |
883 | case Sema::TDK_NonDeducedMismatch: |
884 | return &static_cast<DFIArguments*>(Data)->SecondArg; |
885 | |
886 | // Unhandled |
887 | case Sema::TDK_MiscellaneousDeductionFailure: |
888 | case Sema::TDK_AlreadyDiagnosed: |
889 | break; |
890 | } |
891 | |
892 | return nullptr; |
893 | } |
894 | |
895 | std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { |
896 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
897 | case Sema::TDK_DeducedMismatch: |
898 | case Sema::TDK_DeducedMismatchNested: |
899 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; |
900 | |
901 | default: |
902 | return std::nullopt; |
903 | } |
904 | } |
905 | |
906 | static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, |
907 | const FunctionDecl *Y) { |
908 | if (!X || !Y) |
909 | return false; |
910 | if (X->getNumParams() != Y->getNumParams()) |
911 | return false; |
912 | for (unsigned I = 0; I < X->getNumParams(); ++I) |
913 | if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(), |
914 | Y->getParamDecl(I)->getType())) |
915 | return false; |
916 | if (auto *FTX = X->getDescribedFunctionTemplate()) { |
917 | auto *FTY = Y->getDescribedFunctionTemplate(); |
918 | if (!FTY) |
919 | return false; |
920 | if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(), |
921 | FTY->getTemplateParameters())) |
922 | return false; |
923 | } |
924 | return true; |
925 | } |
926 | |
927 | static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, |
928 | Expr *FirstOperand, FunctionDecl *EqFD) { |
929 | assert(EqFD->getOverloadedOperator() ==(static_cast <bool> (EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail ("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual" , "clang/lib/Sema/SemaOverload.cpp", 930, __extension__ __PRETTY_FUNCTION__ )) |
930 | OverloadedOperatorKind::OO_EqualEqual)(static_cast <bool> (EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail ("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual" , "clang/lib/Sema/SemaOverload.cpp", 930, __extension__ __PRETTY_FUNCTION__ )); |
931 | // C++2a [over.match.oper]p4: |
932 | // A non-template function or function template F named operator== is a |
933 | // rewrite target with first operand o unless a search for the name operator!= |
934 | // in the scope S from the instantiation context of the operator expression |
935 | // finds a function or function template that would correspond |
936 | // ([basic.scope.scope]) to F if its name were operator==, where S is the |
937 | // scope of the class type of o if F is a class member, and the namespace |
938 | // scope of which F is a member otherwise. A function template specialization |
939 | // named operator== is a rewrite target if its function template is a rewrite |
940 | // target. |
941 | DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( |
942 | OverloadedOperatorKind::OO_ExclaimEqual); |
943 | if (isa<CXXMethodDecl>(EqFD)) { |
944 | // If F is a class member, search scope is class type of first operand. |
945 | QualType RHS = FirstOperand->getType(); |
946 | auto *RHSRec = RHS->getAs<RecordType>(); |
947 | if (!RHSRec) |
948 | return true; |
949 | LookupResult Members(S, NotEqOp, OpLoc, |
950 | Sema::LookupNameKind::LookupMemberName); |
951 | S.LookupQualifiedName(Members, RHSRec->getDecl()); |
952 | Members.suppressDiagnostics(); |
953 | for (NamedDecl *Op : Members) |
954 | if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) |
955 | return false; |
956 | return true; |
957 | } |
958 | // Otherwise the search scope is the namespace scope of which F is a member. |
959 | LookupResult NonMembers(S, NotEqOp, OpLoc, |
960 | Sema::LookupNameKind::LookupOperatorName); |
961 | S.LookupName(NonMembers, |
962 | S.getScopeForContext(EqFD->getEnclosingNamespaceContext())); |
963 | NonMembers.suppressDiagnostics(); |
964 | for (NamedDecl *Op : NonMembers) { |
965 | auto *FD = Op->getAsFunction(); |
966 | if(auto* UD = dyn_cast<UsingShadowDecl>(Op)) |
967 | FD = UD->getUnderlyingDecl()->getAsFunction(); |
968 | if (FunctionsCorrespond(S.Context, EqFD, FD) && |
969 | declaresSameEntity(cast<Decl>(EqFD->getDeclContext()), |
970 | cast<Decl>(Op->getDeclContext()))) |
971 | return false; |
972 | } |
973 | return true; |
974 | } |
975 | |
976 | bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( |
977 | OverloadedOperatorKind Op) { |
978 | if (!AllowRewrittenCandidates) |
979 | return false; |
980 | return Op == OO_EqualEqual || Op == OO_Spaceship; |
981 | } |
982 | |
983 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( |
984 | Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { |
985 | auto Op = FD->getOverloadedOperator(); |
986 | if (!allowsReversed(Op)) |
987 | return false; |
988 | if (Op == OverloadedOperatorKind::OO_EqualEqual) { |
989 | assert(OriginalArgs.size() == 2)(static_cast <bool> (OriginalArgs.size() == 2) ? void ( 0) : __assert_fail ("OriginalArgs.size() == 2", "clang/lib/Sema/SemaOverload.cpp" , 989, __extension__ __PRETTY_FUNCTION__)); |
990 | if (!shouldAddReversedEqEq( |
991 | S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD)) |
992 | return false; |
993 | } |
994 | // Don't bother adding a reversed candidate that can never be a better |
995 | // match than the non-reversed version. |
996 | return FD->getNumParams() != 2 || |
997 | !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), |
998 | FD->getParamDecl(1)->getType()) || |
999 | FD->hasAttr<EnableIfAttr>(); |
1000 | } |
1001 | |
1002 | void OverloadCandidateSet::destroyCandidates() { |
1003 | for (iterator i = begin(), e = end(); i != e; ++i) { |
1004 | for (auto &C : i->Conversions) |
1005 | C.~ImplicitConversionSequence(); |
1006 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) |
1007 | i->DeductionFailure.Destroy(); |
1008 | } |
1009 | } |
1010 | |
1011 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { |
1012 | destroyCandidates(); |
1013 | SlabAllocator.Reset(); |
1014 | NumInlineBytesUsed = 0; |
1015 | Candidates.clear(); |
1016 | Functions.clear(); |
1017 | Kind = CSK; |
1018 | } |
1019 | |
1020 | namespace { |
1021 | class UnbridgedCastsSet { |
1022 | struct Entry { |
1023 | Expr **Addr; |
1024 | Expr *Saved; |
1025 | }; |
1026 | SmallVector<Entry, 2> Entries; |
1027 | |
1028 | public: |
1029 | void save(Sema &S, Expr *&E) { |
1030 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType ::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)" , "clang/lib/Sema/SemaOverload.cpp", 1030, __extension__ __PRETTY_FUNCTION__ )); |
1031 | Entry entry = { &E, E }; |
1032 | Entries.push_back(entry); |
1033 | E = S.stripARCUnbridgedCast(E); |
1034 | } |
1035 | |
1036 | void restore() { |
1037 | for (SmallVectorImpl<Entry>::iterator |
1038 | i = Entries.begin(), e = Entries.end(); i != e; ++i) |
1039 | *i->Addr = i->Saved; |
1040 | } |
1041 | }; |
1042 | } |
1043 | |
1044 | /// checkPlaceholderForOverload - Do any interesting placeholder-like |
1045 | /// preprocessing on the given expression. |
1046 | /// |
1047 | /// \param unbridgedCasts a collection to which to add unbridged casts; |
1048 | /// without this, they will be immediately diagnosed as errors |
1049 | /// |
1050 | /// Return true on unrecoverable error. |
1051 | static bool |
1052 | checkPlaceholderForOverload(Sema &S, Expr *&E, |
1053 | UnbridgedCastsSet *unbridgedCasts = nullptr) { |
1054 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { |
1055 | // We can't handle overloaded expressions here because overload |
1056 | // resolution might reasonably tweak them. |
1057 | if (placeholder->getKind() == BuiltinType::Overload) return false; |
1058 | |
1059 | // If the context potentially accepts unbridged ARC casts, strip |
1060 | // the unbridged cast and add it to the collection for later restoration. |
1061 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && |
1062 | unbridgedCasts) { |
1063 | unbridgedCasts->save(S, E); |
1064 | return false; |
1065 | } |
1066 | |
1067 | // Go ahead and check everything else. |
1068 | ExprResult result = S.CheckPlaceholderExpr(E); |
1069 | if (result.isInvalid()) |
1070 | return true; |
1071 | |
1072 | E = result.get(); |
1073 | return false; |
1074 | } |
1075 | |
1076 | // Nothing to do. |
1077 | return false; |
1078 | } |
1079 | |
1080 | /// checkArgPlaceholdersForOverload - Check a set of call operands for |
1081 | /// placeholders. |
1082 | static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, |
1083 | UnbridgedCastsSet &unbridged) { |
1084 | for (unsigned i = 0, e = Args.size(); i != e; ++i) |
1085 | if (checkPlaceholderForOverload(S, Args[i], &unbridged)) |
1086 | return true; |
1087 | |
1088 | return false; |
1089 | } |
1090 | |
1091 | /// Determine whether the given New declaration is an overload of the |
1092 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if |
1093 | /// New and Old cannot be overloaded, e.g., if New has the same signature as |
1094 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't |
1095 | /// functions (or function templates) at all. When it does return Ovl_Match or |
1096 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be |
1097 | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying |
1098 | /// declaration. |
1099 | /// |
1100 | /// Example: Given the following input: |
1101 | /// |
1102 | /// void f(int, float); // #1 |
1103 | /// void f(int, int); // #2 |
1104 | /// int f(int, int); // #3 |
1105 | /// |
1106 | /// When we process #1, there is no previous declaration of "f", so IsOverload |
1107 | /// will not be used. |
1108 | /// |
1109 | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing |
1110 | /// the parameter types, we see that #1 and #2 are overloaded (since they have |
1111 | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is |
1112 | /// unchanged. |
1113 | /// |
1114 | /// When we process #3, Old is an overload set containing #1 and #2. We compare |
1115 | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then |
1116 | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of |
1117 | /// functions are not part of the signature), IsOverload returns Ovl_Match and |
1118 | /// MatchedDecl will be set to point to the FunctionDecl for #2. |
1119 | /// |
1120 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class |
1121 | /// by a using declaration. The rules for whether to hide shadow declarations |
1122 | /// ignore some properties which otherwise figure into a function template's |
1123 | /// signature. |
1124 | Sema::OverloadKind |
1125 | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, |
1126 | NamedDecl *&Match, bool NewIsUsingDecl) { |
1127 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); |
1128 | I != E; ++I) { |
1129 | NamedDecl *OldD = *I; |
1130 | |
1131 | bool OldIsUsingDecl = false; |
1132 | if (isa<UsingShadowDecl>(OldD)) { |
1133 | OldIsUsingDecl = true; |
1134 | |
1135 | // We can always introduce two using declarations into the same |
1136 | // context, even if they have identical signatures. |
1137 | if (NewIsUsingDecl) continue; |
1138 | |
1139 | OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); |
1140 | } |
1141 | |
1142 | // A using-declaration does not conflict with another declaration |
1143 | // if one of them is hidden. |
1144 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) |
1145 | continue; |
1146 | |
1147 | // If either declaration was introduced by a using declaration, |
1148 | // we'll need to use slightly different rules for matching. |
1149 | // Essentially, these rules are the normal rules, except that |
1150 | // function templates hide function templates with different |
1151 | // return types or template parameter lists. |
1152 | bool UseMemberUsingDeclRules = |
1153 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && |
1154 | !New->getFriendObjectKind(); |
1155 | |
1156 | if (FunctionDecl *OldF = OldD->getAsFunction()) { |
1157 | if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { |
1158 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { |
1159 | HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); |
1160 | continue; |
1161 | } |
1162 | |
1163 | if (!isa<FunctionTemplateDecl>(OldD) && |
1164 | !shouldLinkPossiblyHiddenDecl(*I, New)) |
1165 | continue; |
1166 | |
1167 | Match = *I; |
1168 | return Ovl_Match; |
1169 | } |
1170 | |
1171 | // Builtins that have custom typechecking or have a reference should |
1172 | // not be overloadable or redeclarable. |
1173 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { |
1174 | Match = *I; |
1175 | return Ovl_NonFunction; |
1176 | } |
1177 | } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { |
1178 | // We can overload with these, which can show up when doing |
1179 | // redeclaration checks for UsingDecls. |
1180 | assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName ) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName" , "clang/lib/Sema/SemaOverload.cpp", 1180, __extension__ __PRETTY_FUNCTION__ )); |
1181 | } else if (isa<TagDecl>(OldD)) { |
1182 | // We can always overload with tags by hiding them. |
1183 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { |
1184 | // Optimistically assume that an unresolved using decl will |
1185 | // overload; if it doesn't, we'll have to diagnose during |
1186 | // template instantiation. |
1187 | // |
1188 | // Exception: if the scope is dependent and this is not a class |
1189 | // member, the using declaration can only introduce an enumerator. |
1190 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { |
1191 | Match = *I; |
1192 | return Ovl_NonFunction; |
1193 | } |
1194 | } else { |
1195 | // (C++ 13p1): |
1196 | // Only function declarations can be overloaded; object and type |
1197 | // declarations cannot be overloaded. |
1198 | Match = *I; |
1199 | return Ovl_NonFunction; |
1200 | } |
1201 | } |
1202 | |
1203 | // C++ [temp.friend]p1: |
1204 | // For a friend function declaration that is not a template declaration: |
1205 | // -- if the name of the friend is a qualified or unqualified template-id, |
1206 | // [...], otherwise |
1207 | // -- if the name of the friend is a qualified-id and a matching |
1208 | // non-template function is found in the specified class or namespace, |
1209 | // the friend declaration refers to that function, otherwise, |
1210 | // -- if the name of the friend is a qualified-id and a matching function |
1211 | // template is found in the specified class or namespace, the friend |
1212 | // declaration refers to the deduced specialization of that function |
1213 | // template, otherwise |
1214 | // -- the name shall be an unqualified-id [...] |
1215 | // If we get here for a qualified friend declaration, we've just reached the |
1216 | // third bullet. If the type of the friend is dependent, skip this lookup |
1217 | // until instantiation. |
1218 | if (New->getFriendObjectKind() && New->getQualifier() && |
1219 | !New->getDescribedFunctionTemplate() && |
1220 | !New->getDependentSpecializationInfo() && |
1221 | !New->getType()->isDependentType()) { |
1222 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); |
1223 | TemplateSpecResult.addAllDecls(Old); |
1224 | if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, |
1225 | /*QualifiedFriend*/true)) { |
1226 | New->setInvalidDecl(); |
1227 | return Ovl_Overload; |
1228 | } |
1229 | |
1230 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); |
1231 | return Ovl_Match; |
1232 | } |
1233 | |
1234 | return Ovl_Overload; |
1235 | } |
1236 | |
1237 | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, |
1238 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, |
1239 | bool ConsiderRequiresClauses) { |
1240 | // C++ [basic.start.main]p2: This function shall not be overloaded. |
1241 | if (New->isMain()) |
1242 | return false; |
1243 | |
1244 | // MSVCRT user defined entry points cannot be overloaded. |
1245 | if (New->isMSVCRTEntryPoint()) |
1246 | return false; |
1247 | |
1248 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); |
1249 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); |
1250 | |
1251 | // C++ [temp.fct]p2: |
1252 | // A function template can be overloaded with other function templates |
1253 | // and with normal (non-template) functions. |
1254 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) |
1255 | return true; |
1256 | |
1257 | // Is the function New an overload of the function Old? |
1258 | QualType OldQType = Context.getCanonicalType(Old->getType()); |
1259 | QualType NewQType = Context.getCanonicalType(New->getType()); |
1260 | |
1261 | // Compare the signatures (C++ 1.3.10) of the two functions to |
1262 | // determine whether they are overloads. If we find any mismatch |
1263 | // in the signature, they are overloads. |
1264 | |
1265 | // If either of these functions is a K&R-style function (no |
1266 | // prototype), then we consider them to have matching signatures. |
1267 | if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || |
1268 | isa<FunctionNoProtoType>(NewQType.getTypePtr())) |
1269 | return false; |
1270 | |
1271 | const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); |
1272 | const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); |
1273 | |
1274 | // The signature of a function includes the types of its |
1275 | // parameters (C++ 1.3.10), which includes the presence or absence |
1276 | // of the ellipsis; see C++ DR 357). |
1277 | if (OldQType != NewQType && |
1278 | (OldType->getNumParams() != NewType->getNumParams() || |
1279 | OldType->isVariadic() != NewType->isVariadic() || |
1280 | !FunctionParamTypesAreEqual(OldType, NewType))) |
1281 | return true; |
1282 | |
1283 | // For member-like friends, the enclosing class is part of the signature. |
1284 | if ((New->isMemberLikeConstrainedFriend() || |
1285 | Old->isMemberLikeConstrainedFriend()) && |
1286 | !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) |
1287 | return true; |
1288 | |
1289 | if (NewTemplate) { |
1290 | // C++ [temp.over.link]p4: |
1291 | // The signature of a function template consists of its function |
1292 | // signature, its return type and its template parameter list. The names |
1293 | // of the template parameters are significant only for establishing the |
1294 | // relationship between the template parameters and the rest of the |
1295 | // signature. |
1296 | // |
1297 | // We check the return type and template parameter lists for function |
1298 | // templates first; the remaining checks follow. |
1299 | bool SameTemplateParameterList = TemplateParameterListsAreEqual( |
1300 | NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, |
1301 | OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch); |
1302 | bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(), |
1303 | New->getDeclaredReturnType()); |
1304 | // FIXME(GH58571): Match template parameter list even for non-constrained |
1305 | // template heads. This currently ensures that the code prior to C++20 is |
1306 | // not newly broken. |
1307 | bool ConstraintsInTemplateHead = |
1308 | NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || |
1309 | OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); |
1310 | // C++ [namespace.udecl]p11: |
1311 | // The set of declarations named by a using-declarator that inhabits a |
1312 | // class C does not include member functions and member function |
1313 | // templates of a base class that "correspond" to (and thus would |
1314 | // conflict with) a declaration of a function or function template in |
1315 | // C. |
1316 | // Comparing return types is not required for the "correspond" check to |
1317 | // decide whether a member introduced by a shadow declaration is hidden. |
1318 | if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && |
1319 | !SameTemplateParameterList) |
1320 | return true; |
1321 | if (!UseMemberUsingDeclRules && |
1322 | (!SameTemplateParameterList || !SameReturnType)) |
1323 | return true; |
1324 | } |
1325 | |
1326 | if (ConsiderRequiresClauses) { |
1327 | Expr *NewRC = New->getTrailingRequiresClause(), |
1328 | *OldRC = Old->getTrailingRequiresClause(); |
1329 | if ((NewRC != nullptr) != (OldRC != nullptr)) |
1330 | return true; |
1331 | |
1332 | if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC)) |
1333 | return true; |
1334 | } |
1335 | |
1336 | // If the function is a class member, its signature includes the |
1337 | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. |
1338 | // |
1339 | // As part of this, also check whether one of the member functions |
1340 | // is static, in which case they are not overloads (C++ |
1341 | // 13.1p2). While not part of the definition of the signature, |
1342 | // this check is important to determine whether these functions |
1343 | // can be overloaded. |
1344 | CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); |
1345 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); |
1346 | if (OldMethod && NewMethod && |
1347 | !OldMethod->isStatic() && !NewMethod->isStatic()) { |
1348 | if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { |
1349 | if (!UseMemberUsingDeclRules && |
1350 | (OldMethod->getRefQualifier() == RQ_None || |
1351 | NewMethod->getRefQualifier() == RQ_None)) { |
1352 | // C++20 [over.load]p2: |
1353 | // - Member function declarations with the same name, the same |
1354 | // parameter-type-list, and the same trailing requires-clause (if |
1355 | // any), as well as member function template declarations with the |
1356 | // same name, the same parameter-type-list, the same trailing |
1357 | // requires-clause (if any), and the same template-head, cannot be |
1358 | // overloaded if any of them, but not all, have a ref-qualifier. |
1359 | Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) |
1360 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); |
1361 | Diag(OldMethod->getLocation(), diag::note_previous_declaration); |
1362 | } |
1363 | return true; |
1364 | } |
1365 | |
1366 | // We may not have applied the implicit const for a constexpr member |
1367 | // function yet (because we haven't yet resolved whether this is a static |
1368 | // or non-static member function). Add it now, on the assumption that this |
1369 | // is a redeclaration of OldMethod. |
1370 | auto OldQuals = OldMethod->getMethodQualifiers(); |
1371 | auto NewQuals = NewMethod->getMethodQualifiers(); |
1372 | if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && |
1373 | !isa<CXXConstructorDecl>(NewMethod)) |
1374 | NewQuals.addConst(); |
1375 | // We do not allow overloading based off of '__restrict'. |
1376 | OldQuals.removeRestrict(); |
1377 | NewQuals.removeRestrict(); |
1378 | if (OldQuals != NewQuals) |
1379 | return true; |
1380 | } |
1381 | |
1382 | // Though pass_object_size is placed on parameters and takes an argument, we |
1383 | // consider it to be a function-level modifier for the sake of function |
1384 | // identity. Either the function has one or more parameters with |
1385 | // pass_object_size or it doesn't. |
1386 | if (functionHasPassObjectSizeParams(New) != |
1387 | functionHasPassObjectSizeParams(Old)) |
1388 | return true; |
1389 | |
1390 | // enable_if attributes are an order-sensitive part of the signature. |
1391 | for (specific_attr_iterator<EnableIfAttr> |
1392 | NewI = New->specific_attr_begin<EnableIfAttr>(), |
1393 | NewE = New->specific_attr_end<EnableIfAttr>(), |
1394 | OldI = Old->specific_attr_begin<EnableIfAttr>(), |
1395 | OldE = Old->specific_attr_end<EnableIfAttr>(); |
1396 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { |
1397 | if (NewI == NewE || OldI == OldE) |
1398 | return true; |
1399 | llvm::FoldingSetNodeID NewID, OldID; |
1400 | NewI->getCond()->Profile(NewID, Context, true); |
1401 | OldI->getCond()->Profile(OldID, Context, true); |
1402 | if (NewID != OldID) |
1403 | return true; |
1404 | } |
1405 | |
1406 | if (getLangOpts().CUDA && ConsiderCudaAttrs) { |
1407 | // Don't allow overloading of destructors. (In theory we could, but it |
1408 | // would be a giant change to clang.) |
1409 | if (!isa<CXXDestructorDecl>(New)) { |
1410 | CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), |
1411 | OldTarget = IdentifyCUDATarget(Old); |
1412 | if (NewTarget != CFT_InvalidTarget) { |
1413 | assert((OldTarget != CFT_InvalidTarget) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "clang/lib/Sema/SemaOverload.cpp", 1414, __extension__ __PRETTY_FUNCTION__ )) |
1414 | "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "clang/lib/Sema/SemaOverload.cpp", 1414, __extension__ __PRETTY_FUNCTION__ )); |
1415 | |
1416 | // Allow overloading of functions with same signature and different CUDA |
1417 | // target attributes. |
1418 | if (NewTarget != OldTarget) |
1419 | return true; |
1420 | } |
1421 | } |
1422 | } |
1423 | |
1424 | // The signatures match; this is not an overload. |
1425 | return false; |
1426 | } |
1427 | |
1428 | /// Tries a user-defined conversion from From to ToType. |
1429 | /// |
1430 | /// Produces an implicit conversion sequence for when a standard conversion |
1431 | /// is not an option. See TryImplicitConversion for more information. |
1432 | static ImplicitConversionSequence |
1433 | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
1434 | bool SuppressUserConversions, |
1435 | AllowedExplicit AllowExplicit, |
1436 | bool InOverloadResolution, |
1437 | bool CStyle, |
1438 | bool AllowObjCWritebackConversion, |
1439 | bool AllowObjCConversionOnExplicit) { |
1440 | ImplicitConversionSequence ICS; |
1441 | |
1442 | if (SuppressUserConversions) { |
1443 | // We're not in the case above, so there is no conversion that |
1444 | // we can perform. |
1445 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1446 | return ICS; |
1447 | } |
1448 | |
1449 | // Attempt user-defined conversion. |
1450 | OverloadCandidateSet Conversions(From->getExprLoc(), |
1451 | OverloadCandidateSet::CSK_Normal); |
1452 | switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, |
1453 | Conversions, AllowExplicit, |
1454 | AllowObjCConversionOnExplicit)) { |
1455 | case OR_Success: |
1456 | case OR_Deleted: |
1457 | ICS.setUserDefined(); |
1458 | // C++ [over.ics.user]p4: |
1459 | // A conversion of an expression of class type to the same class |
1460 | // type is given Exact Match rank, and a conversion of an |
1461 | // expression of class type to a base class of that type is |
1462 | // given Conversion rank, in spite of the fact that a copy |
1463 | // constructor (i.e., a user-defined conversion function) is |
1464 | // called for those cases. |
1465 | if (CXXConstructorDecl *Constructor |
1466 | = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { |
1467 | QualType FromCanon |
1468 | = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); |
1469 | QualType ToCanon |
1470 | = S.Context.getCanonicalType(ToType).getUnqualifiedType(); |
1471 | if (Constructor->isCopyConstructor() && |
1472 | (FromCanon == ToCanon || |
1473 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { |
1474 | // Turn this into a "standard" conversion sequence, so that it |
1475 | // gets ranked with standard conversion sequences. |
1476 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; |
1477 | ICS.setStandard(); |
1478 | ICS.Standard.setAsIdentityConversion(); |
1479 | ICS.Standard.setFromType(From->getType()); |
1480 | ICS.Standard.setAllToTypes(ToType); |
1481 | ICS.Standard.CopyConstructor = Constructor; |
1482 | ICS.Standard.FoundCopyConstructor = Found; |
1483 | if (ToCanon != FromCanon) |
1484 | ICS.Standard.Second = ICK_Derived_To_Base; |
1485 | } |
1486 | } |
1487 | break; |
1488 | |
1489 | case OR_Ambiguous: |
1490 | ICS.setAmbiguous(); |
1491 | ICS.Ambiguous.setFromType(From->getType()); |
1492 | ICS.Ambiguous.setToType(ToType); |
1493 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); |
1494 | Cand != Conversions.end(); ++Cand) |
1495 | if (Cand->Best) |
1496 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
1497 | break; |
1498 | |
1499 | // Fall through. |
1500 | case OR_No_Viable_Function: |
1501 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1502 | break; |
1503 | } |
1504 | |
1505 | return ICS; |
1506 | } |
1507 | |
1508 | /// TryImplicitConversion - Attempt to perform an implicit conversion |
1509 | /// from the given expression (Expr) to the given type (ToType). This |
1510 | /// function returns an implicit conversion sequence that can be used |
1511 | /// to perform the initialization. Given |
1512 | /// |
1513 | /// void f(float f); |
1514 | /// void g(int i) { f(i); } |
1515 | /// |
1516 | /// this routine would produce an implicit conversion sequence to |
1517 | /// describe the initialization of f from i, which will be a standard |
1518 | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ |
1519 | /// 4.1) followed by a floating-integral conversion (C++ 4.9). |
1520 | // |
1521 | /// Note that this routine only determines how the conversion can be |
1522 | /// performed; it does not actually perform the conversion. As such, |
1523 | /// it will not produce any diagnostics if no conversion is available, |
1524 | /// but will instead return an implicit conversion sequence of kind |
1525 | /// "BadConversion". |
1526 | /// |
1527 | /// If @p SuppressUserConversions, then user-defined conversions are |
1528 | /// not permitted. |
1529 | /// If @p AllowExplicit, then explicit user-defined conversions are |
1530 | /// permitted. |
1531 | /// |
1532 | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C |
1533 | /// writeback conversion, which allows __autoreleasing id* parameters to |
1534 | /// be initialized with __strong id* or __weak id* arguments. |
1535 | static ImplicitConversionSequence |
1536 | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, |
1537 | bool SuppressUserConversions, |
1538 | AllowedExplicit AllowExplicit, |
1539 | bool InOverloadResolution, |
1540 | bool CStyle, |
1541 | bool AllowObjCWritebackConversion, |
1542 | bool AllowObjCConversionOnExplicit) { |
1543 | ImplicitConversionSequence ICS; |
1544 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, |
1545 | ICS.Standard, CStyle, AllowObjCWritebackConversion)){ |
1546 | ICS.setStandard(); |
1547 | return ICS; |
1548 | } |
1549 | |
1550 | if (!S.getLangOpts().CPlusPlus) { |
1551 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1552 | return ICS; |
1553 | } |
1554 | |
1555 | // C++ [over.ics.user]p4: |
1556 | // A conversion of an expression of class type to the same class |
1557 | // type is given Exact Match rank, and a conversion of an |
1558 | // expression of class type to a base class of that type is |
1559 | // given Conversion rank, in spite of the fact that a copy/move |
1560 | // constructor (i.e., a user-defined conversion function) is |
1561 | // called for those cases. |
1562 | QualType FromType = From->getType(); |
1563 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && |
1564 | (S.Context.hasSameUnqualifiedType(FromType, ToType) || |
1565 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { |
1566 | ICS.setStandard(); |
1567 | ICS.Standard.setAsIdentityConversion(); |
1568 | ICS.Standard.setFromType(FromType); |
1569 | ICS.Standard.setAllToTypes(ToType); |
1570 | |
1571 | // We don't actually check at this point whether there is a valid |
1572 | // copy/move constructor, since overloading just assumes that it |
1573 | // exists. When we actually perform initialization, we'll find the |
1574 | // appropriate constructor to copy the returned object, if needed. |
1575 | ICS.Standard.CopyConstructor = nullptr; |
1576 | |
1577 | // Determine whether this is considered a derived-to-base conversion. |
1578 | if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1579 | ICS.Standard.Second = ICK_Derived_To_Base; |
1580 | |
1581 | return ICS; |
1582 | } |
1583 | |
1584 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
1585 | AllowExplicit, InOverloadResolution, CStyle, |
1586 | AllowObjCWritebackConversion, |
1587 | AllowObjCConversionOnExplicit); |
1588 | } |
1589 | |
1590 | ImplicitConversionSequence |
1591 | Sema::TryImplicitConversion(Expr *From, QualType ToType, |
1592 | bool SuppressUserConversions, |
1593 | AllowedExplicit AllowExplicit, |
1594 | bool InOverloadResolution, |
1595 | bool CStyle, |
1596 | bool AllowObjCWritebackConversion) { |
1597 | return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, |
1598 | AllowExplicit, InOverloadResolution, CStyle, |
1599 | AllowObjCWritebackConversion, |
1600 | /*AllowObjCConversionOnExplicit=*/false); |
1601 | } |
1602 | |
1603 | /// PerformImplicitConversion - Perform an implicit conversion of the |
1604 | /// expression From to the type ToType. Returns the |
1605 | /// converted expression. Flavor is the kind of conversion we're |
1606 | /// performing, used in the error message. If @p AllowExplicit, |
1607 | /// explicit user-defined conversions are permitted. |
1608 | ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
1609 | AssignmentAction Action, |
1610 | bool AllowExplicit) { |
1611 | if (checkPlaceholderForOverload(*this, From)) |
1612 | return ExprError(); |
1613 | |
1614 | // Objective-C ARC: Determine whether we will allow the writeback conversion. |
1615 | bool AllowObjCWritebackConversion |
1616 | = getLangOpts().ObjCAutoRefCount && |
1617 | (Action == AA_Passing || Action == AA_Sending); |
1618 | if (getLangOpts().ObjC) |
1619 | CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, |
1620 | From->getType(), From); |
1621 | ImplicitConversionSequence ICS = ::TryImplicitConversion( |
1622 | *this, From, ToType, |
1623 | /*SuppressUserConversions=*/false, |
1624 | AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, |
1625 | /*InOverloadResolution=*/false, |
1626 | /*CStyle=*/false, AllowObjCWritebackConversion, |
1627 | /*AllowObjCConversionOnExplicit=*/false); |
1628 | return PerformImplicitConversion(From, ToType, ICS, Action); |
1629 | } |
1630 | |
1631 | /// Determine whether the conversion from FromType to ToType is a valid |
1632 | /// conversion that strips "noexcept" or "noreturn" off the nested function |
1633 | /// type. |
1634 | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, |
1635 | QualType &ResultTy) { |
1636 | if (Context.hasSameUnqualifiedType(FromType, ToType)) |
1637 | return false; |
1638 | |
1639 | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) |
1640 | // or F(t noexcept) -> F(t) |
1641 | // where F adds one of the following at most once: |
1642 | // - a pointer |
1643 | // - a member pointer |
1644 | // - a block pointer |
1645 | // Changes here need matching changes in FindCompositePointerType. |
1646 | CanQualType CanTo = Context.getCanonicalType(ToType); |
1647 | CanQualType CanFrom = Context.getCanonicalType(FromType); |
1648 | Type::TypeClass TyClass = CanTo->getTypeClass(); |
1649 | if (TyClass != CanFrom->getTypeClass()) return false; |
1650 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { |
1651 | if (TyClass == Type::Pointer) { |
1652 | CanTo = CanTo.castAs<PointerType>()->getPointeeType(); |
1653 | CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); |
1654 | } else if (TyClass == Type::BlockPointer) { |
1655 | CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); |
1656 | CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); |
1657 | } else if (TyClass == Type::MemberPointer) { |
1658 | auto ToMPT = CanTo.castAs<MemberPointerType>(); |
1659 | auto FromMPT = CanFrom.castAs<MemberPointerType>(); |
1660 | // A function pointer conversion cannot change the class of the function. |
1661 | if (ToMPT->getClass() != FromMPT->getClass()) |
1662 | return false; |
1663 | CanTo = ToMPT->getPointeeType(); |
1664 | CanFrom = FromMPT->getPointeeType(); |
1665 | } else { |
1666 | return false; |
1667 | } |
1668 | |
1669 | TyClass = CanTo->getTypeClass(); |
1670 | if (TyClass != CanFrom->getTypeClass()) return false; |
1671 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) |
1672 | return false; |
1673 | } |
1674 | |
1675 | const auto *FromFn = cast<FunctionType>(CanFrom); |
1676 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
1677 | |
1678 | const auto *ToFn = cast<FunctionType>(CanTo); |
1679 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
1680 | |
1681 | bool Changed = false; |
1682 | |
1683 | // Drop 'noreturn' if not present in target type. |
1684 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { |
1685 | FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); |
1686 | Changed = true; |
1687 | } |
1688 | |
1689 | // Drop 'noexcept' if not present in target type. |
1690 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { |
1691 | const auto *ToFPT = cast<FunctionProtoType>(ToFn); |
1692 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { |
1693 | FromFn = cast<FunctionType>( |
1694 | Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), |
1695 | EST_None) |
1696 | .getTypePtr()); |
1697 | Changed = true; |
1698 | } |
1699 | |
1700 | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid |
1701 | // only if the ExtParameterInfo lists of the two function prototypes can be |
1702 | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. |
1703 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
1704 | bool CanUseToFPT, CanUseFromFPT; |
1705 | if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, |
1706 | CanUseFromFPT, NewParamInfos) && |
1707 | CanUseToFPT && !CanUseFromFPT) { |
1708 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); |
1709 | ExtInfo.ExtParameterInfos = |
1710 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); |
1711 | QualType QT = Context.getFunctionType(FromFPT->getReturnType(), |
1712 | FromFPT->getParamTypes(), ExtInfo); |
1713 | FromFn = QT->getAs<FunctionType>(); |
1714 | Changed = true; |
1715 | } |
1716 | } |
1717 | |
1718 | if (!Changed) |
1719 | return false; |
1720 | |
1721 | assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical()) ? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()" , "clang/lib/Sema/SemaOverload.cpp", 1721, __extension__ __PRETTY_FUNCTION__ )); |
1722 | if (QualType(FromFn, 0) != CanTo) return false; |
1723 | |
1724 | ResultTy = ToType; |
1725 | return true; |
1726 | } |
1727 | |
1728 | /// Determine whether the conversion from FromType to ToType is a valid |
1729 | /// vector conversion. |
1730 | /// |
1731 | /// \param ICK Will be set to the vector conversion kind, if this is a vector |
1732 | /// conversion. |
1733 | static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, |
1734 | ImplicitConversionKind &ICK, Expr *From, |
1735 | bool InOverloadResolution, bool CStyle) { |
1736 | // We need at least one of these types to be a vector type to have a vector |
1737 | // conversion. |
1738 | if (!ToType->isVectorType() && !FromType->isVectorType()) |
1739 | return false; |
1740 | |
1741 | // Identical types require no conversions. |
1742 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1743 | return false; |
1744 | |
1745 | // There are no conversions between extended vector types, only identity. |
1746 | if (ToType->isExtVectorType()) { |
1747 | // There are no conversions between extended vector types other than the |
1748 | // identity conversion. |
1749 | if (FromType->isExtVectorType()) |
1750 | return false; |
1751 | |
1752 | // Vector splat from any arithmetic type to a vector. |
1753 | if (FromType->isArithmeticType()) { |
1754 | ICK = ICK_Vector_Splat; |
1755 | return true; |
1756 | } |
1757 | } |
1758 | |
1759 | if (ToType->isSVESizelessBuiltinType() || |
1760 | FromType->isSVESizelessBuiltinType()) |
1761 | if (S.Context.areCompatibleSveTypes(FromType, ToType) || |
1762 | S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { |
1763 | ICK = ICK_SVE_Vector_Conversion; |
1764 | return true; |
1765 | } |
1766 | |
1767 | if (ToType->isRVVSizelessBuiltinType() || |
1768 | FromType->isRVVSizelessBuiltinType()) |
1769 | if (S.Context.areCompatibleRVVTypes(FromType, ToType) || |
1770 | S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) { |
1771 | ICK = ICK_RVV_Vector_Conversion; |
1772 | return true; |
1773 | } |
1774 | |
1775 | // We can perform the conversion between vector types in the following cases: |
1776 | // 1)vector types are equivalent AltiVec and GCC vector types |
1777 | // 2)lax vector conversions are permitted and the vector types are of the |
1778 | // same size |
1779 | // 3)the destination type does not have the ARM MVE strict-polymorphism |
1780 | // attribute, which inhibits lax vector conversion for overload resolution |
1781 | // only |
1782 | if (ToType->isVectorType() && FromType->isVectorType()) { |
1783 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || |
1784 | (S.isLaxVectorConversion(FromType, ToType) && |
1785 | !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { |
1786 | if (S.getASTContext().getTargetInfo().getTriple().isPPC() && |
1787 | S.isLaxVectorConversion(FromType, ToType) && |
1788 | S.anyAltivecTypes(FromType, ToType) && |
1789 | !S.Context.areCompatibleVectorTypes(FromType, ToType) && |
1790 | !InOverloadResolution && !CStyle) { |
1791 | S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) |
1792 | << FromType << ToType; |
1793 | } |
1794 | ICK = ICK_Vector_Conversion; |
1795 | return true; |
1796 | } |
1797 | } |
1798 | |
1799 | return false; |
1800 | } |
1801 | |
1802 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
1803 | bool InOverloadResolution, |
1804 | StandardConversionSequence &SCS, |
1805 | bool CStyle); |
1806 | |
1807 | /// IsStandardConversion - Determines whether there is a standard |
1808 | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the |
1809 | /// expression From to the type ToType. Standard conversion sequences |
1810 | /// only consider non-class types; for conversions that involve class |
1811 | /// types, use TryImplicitConversion. If a conversion exists, SCS will |
1812 | /// contain the standard conversion sequence required to perform this |
1813 | /// conversion and this routine will return true. Otherwise, this |
1814 | /// routine will return false and the value of SCS is unspecified. |
1815 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
1816 | bool InOverloadResolution, |
1817 | StandardConversionSequence &SCS, |
1818 | bool CStyle, |
1819 | bool AllowObjCWritebackConversion) { |
1820 | QualType FromType = From->getType(); |
1821 | |
1822 | // Standard conversions (C++ [conv]) |
1823 | SCS.setAsIdentityConversion(); |
1824 | SCS.IncompatibleObjC = false; |
1825 | SCS.setFromType(FromType); |
1826 | SCS.CopyConstructor = nullptr; |
1827 | |
1828 | // There are no standard conversions for class types in C++, so |
1829 | // abort early. When overloading in C, however, we do permit them. |
1830 | if (S.getLangOpts().CPlusPlus && |
1831 | (FromType->isRecordType() || ToType->isRecordType())) |
1832 | return false; |
1833 | |
1834 | // The first conversion can be an lvalue-to-rvalue conversion, |
1835 | // array-to-pointer conversion, or function-to-pointer conversion |
1836 | // (C++ 4p1). |
1837 | |
1838 | if (FromType == S.Context.OverloadTy) { |
1839 | DeclAccessPair AccessPair; |
1840 | if (FunctionDecl *Fn |
1841 | = S.ResolveAddressOfOverloadedFunction(From, ToType, false, |
1842 | AccessPair)) { |
1843 | // We were able to resolve the address of the overloaded function, |
1844 | // so we can convert to the type of that function. |
1845 | FromType = Fn->getType(); |
1846 | SCS.setFromType(FromType); |
1847 | |
1848 | // we can sometimes resolve &foo<int> regardless of ToType, so check |
1849 | // if the type matches (identity) or we are converting to bool |
1850 | if (!S.Context.hasSameUnqualifiedType( |
1851 | S.ExtractUnqualifiedFunctionType(ToType), FromType)) { |
1852 | QualType resultTy; |
1853 | // if the function type matches except for [[noreturn]], it's ok |
1854 | if (!S.IsFunctionConversion(FromType, |
1855 | S.ExtractUnqualifiedFunctionType(ToType), resultTy)) |
1856 | // otherwise, only a boolean conversion is standard |
1857 | if (!ToType->isBooleanType()) |
1858 | return false; |
1859 | } |
1860 | |
1861 | // Check if the "from" expression is taking the address of an overloaded |
1862 | // function and recompute the FromType accordingly. Take advantage of the |
1863 | // fact that non-static member functions *must* have such an address-of |
1864 | // expression. |
1865 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); |
1866 | if (Method && !Method->isStatic()) { |
1867 | assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From-> IgnoreParens()) && "Non-unary operator on non-static member address" ) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1868, __extension__ __PRETTY_FUNCTION__ )) |
1868 | "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From-> IgnoreParens()) && "Non-unary operator on non-static member address" ) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1868, __extension__ __PRETTY_FUNCTION__ )); |
1869 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__ )) |
1870 | == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__ )) |
1871 | "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__ )); |
1872 | const Type *ClassType |
1873 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); |
1874 | FromType = S.Context.getMemberPointerType(FromType, ClassType); |
1875 | } else if (isa<UnaryOperator>(From->IgnoreParens())) { |
1876 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__ )) |
1877 | UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__ )) |
1878 | "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__ )); |
1879 | FromType = S.Context.getPointerType(FromType); |
1880 | } |
1881 | } else { |
1882 | return false; |
1883 | } |
1884 | } |
1885 | // Lvalue-to-rvalue conversion (C++11 4.1): |
1886 | // A glvalue (3.10) of a non-function, non-array type T can |
1887 | // be converted to a prvalue. |
1888 | bool argIsLValue = From->isGLValue(); |
1889 | if (argIsLValue && |
1890 | !FromType->isFunctionType() && !FromType->isArrayType() && |
1891 | S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { |
1892 | SCS.First = ICK_Lvalue_To_Rvalue; |
1893 | |
1894 | // C11 6.3.2.1p2: |
1895 | // ... if the lvalue has atomic type, the value has the non-atomic version |
1896 | // of the type of the lvalue ... |
1897 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) |
1898 | FromType = Atomic->getValueType(); |
1899 | |
1900 | // If T is a non-class type, the type of the rvalue is the |
1901 | // cv-unqualified version of T. Otherwise, the type of the rvalue |
1902 | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we |
1903 | // just strip the qualifiers because they don't matter. |
1904 | FromType = FromType.getUnqualifiedType(); |
1905 | } else if (FromType->isArrayType()) { |
1906 | // Array-to-pointer conversion (C++ 4.2) |
1907 | SCS.First = ICK_Array_To_Pointer; |
1908 | |
1909 | // An lvalue or rvalue of type "array of N T" or "array of unknown |
1910 | // bound of T" can be converted to an rvalue of type "pointer to |
1911 | // T" (C++ 4.2p1). |
1912 | FromType = S.Context.getArrayDecayedType(FromType); |
1913 | |
1914 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { |
1915 | // This conversion is deprecated in C++03 (D.4) |
1916 | SCS.DeprecatedStringLiteralToCharPtr = true; |
1917 | |
1918 | // For the purpose of ranking in overload resolution |
1919 | // (13.3.3.1.1), this conversion is considered an |
1920 | // array-to-pointer conversion followed by a qualification |
1921 | // conversion (4.4). (C++ 4.2p2) |
1922 | SCS.Second = ICK_Identity; |
1923 | SCS.Third = ICK_Qualification; |
1924 | SCS.QualificationIncludesObjCLifetime = false; |
1925 | SCS.setAllToTypes(FromType); |
1926 | return true; |
1927 | } |
1928 | } else if (FromType->isFunctionType() && argIsLValue) { |
1929 | // Function-to-pointer conversion (C++ 4.3). |
1930 | SCS.First = ICK_Function_To_Pointer; |
1931 | |
1932 | if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) |
1933 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) |
1934 | if (!S.checkAddressOfFunctionIsAvailable(FD)) |
1935 | return false; |
1936 | |
1937 | // An lvalue of function type T can be converted to an rvalue of |
1938 | // type "pointer to T." The result is a pointer to the |
1939 | // function. (C++ 4.3p1). |
1940 | FromType = S.Context.getPointerType(FromType); |
1941 | } else { |
1942 | // We don't require any conversions for the first step. |
1943 | SCS.First = ICK_Identity; |
1944 | } |
1945 | SCS.setToType(0, FromType); |
1946 | |
1947 | // The second conversion can be an integral promotion, floating |
1948 | // point promotion, integral conversion, floating point conversion, |
1949 | // floating-integral conversion, pointer conversion, |
1950 | // pointer-to-member conversion, or boolean conversion (C++ 4p1). |
1951 | // For overloading in C, this can also be a "compatible-type" |
1952 | // conversion. |
1953 | bool IncompatibleObjC = false; |
1954 | ImplicitConversionKind SecondICK = ICK_Identity; |
1955 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { |
1956 | // The unqualified versions of the types are the same: there's no |
1957 | // conversion to do. |
1958 | SCS.Second = ICK_Identity; |
1959 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { |
1960 | // Integral promotion (C++ 4.5). |
1961 | SCS.Second = ICK_Integral_Promotion; |
1962 | FromType = ToType.getUnqualifiedType(); |
1963 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { |
1964 | // Floating point promotion (C++ 4.6). |
1965 | SCS.Second = ICK_Floating_Promotion; |
1966 | FromType = ToType.getUnqualifiedType(); |
1967 | } else if (S.IsComplexPromotion(FromType, ToType)) { |
1968 | // Complex promotion (Clang extension) |
1969 | SCS.Second = ICK_Complex_Promotion; |
1970 | FromType = ToType.getUnqualifiedType(); |
1971 | } else if (ToType->isBooleanType() && |
1972 | (FromType->isArithmeticType() || |
1973 | FromType->isAnyPointerType() || |
1974 | FromType->isBlockPointerType() || |
1975 | FromType->isMemberPointerType())) { |
1976 | // Boolean conversions (C++ 4.12). |
1977 | SCS.Second = ICK_Boolean_Conversion; |
1978 | FromType = S.Context.BoolTy; |
1979 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
1980 | ToType->isIntegralType(S.Context)) { |
1981 | // Integral conversions (C++ 4.7). |
1982 | SCS.Second = ICK_Integral_Conversion; |
1983 | FromType = ToType.getUnqualifiedType(); |
1984 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { |
1985 | // Complex conversions (C99 6.3.1.6) |
1986 | SCS.Second = ICK_Complex_Conversion; |
1987 | FromType = ToType.getUnqualifiedType(); |
1988 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || |
1989 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { |
1990 | // Complex-real conversions (C99 6.3.1.7) |
1991 | SCS.Second = ICK_Complex_Real; |
1992 | FromType = ToType.getUnqualifiedType(); |
1993 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { |
1994 | // FIXME: disable conversions between long double, __ibm128 and __float128 |
1995 | // if their representation is different until there is back end support |
1996 | // We of course allow this conversion if long double is really double. |
1997 | |
1998 | // Conversions between bfloat and other floats are not permitted. |
1999 | if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) |
2000 | return false; |
2001 | |
2002 | // Conversions between IEEE-quad and IBM-extended semantics are not |
2003 | // permitted. |
2004 | const llvm::fltSemantics &FromSem = |
2005 | S.Context.getFloatTypeSemantics(FromType); |
2006 | const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); |
2007 | if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && |
2008 | &ToSem == &llvm::APFloat::IEEEquad()) || |
2009 | (&FromSem == &llvm::APFloat::IEEEquad() && |
2010 | &ToSem == &llvm::APFloat::PPCDoubleDouble())) |
2011 | return false; |
2012 | |
2013 | // Floating point conversions (C++ 4.8). |
2014 | SCS.Second = ICK_Floating_Conversion; |
2015 | FromType = ToType.getUnqualifiedType(); |
2016 | } else if ((FromType->isRealFloatingType() && |
2017 | ToType->isIntegralType(S.Context)) || |
2018 | (FromType->isIntegralOrUnscopedEnumerationType() && |
2019 | ToType->isRealFloatingType())) { |
2020 | // Conversions between bfloat and int are not permitted. |
2021 | if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) |
2022 | return false; |
2023 | |
2024 | // Floating-integral conversions (C++ 4.9). |
2025 | SCS.Second = ICK_Floating_Integral; |
2026 | FromType = ToType.getUnqualifiedType(); |
2027 | } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { |
2028 | SCS.Second = ICK_Block_Pointer_Conversion; |
2029 | } else if (AllowObjCWritebackConversion && |
2030 | S.isObjCWritebackConversion(FromType, ToType, FromType)) { |
2031 | SCS.Second = ICK_Writeback_Conversion; |
2032 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, |
2033 | FromType, IncompatibleObjC)) { |
2034 | // Pointer conversions (C++ 4.10). |
2035 | SCS.Second = ICK_Pointer_Conversion; |
2036 | SCS.IncompatibleObjC = IncompatibleObjC; |
2037 | FromType = FromType.getUnqualifiedType(); |
2038 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, |
2039 | InOverloadResolution, FromType)) { |
2040 | // Pointer to member conversions (4.11). |
2041 | SCS.Second = ICK_Pointer_Member; |
2042 | } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, |
2043 | InOverloadResolution, CStyle)) { |
2044 | SCS.Second = SecondICK; |
2045 | FromType = ToType.getUnqualifiedType(); |
2046 | } else if (!S.getLangOpts().CPlusPlus && |
2047 | S.Context.typesAreCompatible(ToType, FromType)) { |
2048 | // Compatible conversions (Clang extension for C function overloading) |
2049 | SCS.Second = ICK_Compatible_Conversion; |
2050 | FromType = ToType.getUnqualifiedType(); |
2051 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, |
2052 | InOverloadResolution, |
2053 | SCS, CStyle)) { |
2054 | SCS.Second = ICK_TransparentUnionConversion; |
2055 | FromType = ToType; |
2056 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, |
2057 | CStyle)) { |
2058 | // tryAtomicConversion has updated the standard conversion sequence |
2059 | // appropriately. |
2060 | return true; |
2061 | } else if (ToType->isEventT() && |
2062 | From->isIntegerConstantExpr(S.getASTContext()) && |
2063 | From->EvaluateKnownConstInt(S.getASTContext()) == 0) { |
2064 | SCS.Second = ICK_Zero_Event_Conversion; |
2065 | FromType = ToType; |
2066 | } else if (ToType->isQueueT() && |
2067 | From->isIntegerConstantExpr(S.getASTContext()) && |
2068 | (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { |
2069 | SCS.Second = ICK_Zero_Queue_Conversion; |
2070 | FromType = ToType; |
2071 | } else if (ToType->isSamplerT() && |
2072 | From->isIntegerConstantExpr(S.getASTContext())) { |
2073 | SCS.Second = ICK_Compatible_Conversion; |
2074 | FromType = ToType; |
2075 | } else { |
2076 | // No second conversion required. |
2077 | SCS.Second = ICK_Identity; |
2078 | } |
2079 | SCS.setToType(1, FromType); |
2080 | |
2081 | // The third conversion can be a function pointer conversion or a |
2082 | // qualification conversion (C++ [conv.fctptr], [conv.qual]). |
2083 | bool ObjCLifetimeConversion; |
2084 | if (S.IsFunctionConversion(FromType, ToType, FromType)) { |
2085 | // Function pointer conversions (removing 'noexcept') including removal of |
2086 | // 'noreturn' (Clang extension). |
2087 | SCS.Third = ICK_Function_Conversion; |
2088 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, |
2089 | ObjCLifetimeConversion)) { |
2090 | SCS.Third = ICK_Qualification; |
2091 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; |
2092 | FromType = ToType; |
2093 | } else { |
2094 | // No conversion required |
2095 | SCS.Third = ICK_Identity; |
2096 | } |
2097 | |
2098 | // C++ [over.best.ics]p6: |
2099 | // [...] Any difference in top-level cv-qualification is |
2100 | // subsumed by the initialization itself and does not constitute |
2101 | // a conversion. [...] |
2102 | QualType CanonFrom = S.Context.getCanonicalType(FromType); |
2103 | QualType CanonTo = S.Context.getCanonicalType(ToType); |
2104 | if (CanonFrom.getLocalUnqualifiedType() |
2105 | == CanonTo.getLocalUnqualifiedType() && |
2106 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { |
2107 | FromType = ToType; |
2108 | CanonFrom = CanonTo; |
2109 | } |
2110 | |
2111 | SCS.setToType(2, FromType); |
2112 | |
2113 | if (CanonFrom == CanonTo) |
2114 | return true; |
2115 | |
2116 | // If we have not converted the argument type to the parameter type, |
2117 | // this is a bad conversion sequence, unless we're resolving an overload in C. |
2118 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) |
2119 | return false; |
2120 | |
2121 | ExprResult ER = ExprResult{From}; |
2122 | Sema::AssignConvertType Conv = |
2123 | S.CheckSingleAssignmentConstraints(ToType, ER, |
2124 | /*Diagnose=*/false, |
2125 | /*DiagnoseCFAudited=*/false, |
2126 | /*ConvertRHS=*/false); |
2127 | ImplicitConversionKind SecondConv; |
2128 | switch (Conv) { |
2129 | case Sema::Compatible: |
2130 | SecondConv = ICK_C_Only_Conversion; |
2131 | break; |
2132 | // For our purposes, discarding qualifiers is just as bad as using an |
2133 | // incompatible pointer. Note that an IncompatiblePointer conversion can drop |
2134 | // qualifiers, as well. |
2135 | case Sema::CompatiblePointerDiscardsQualifiers: |
2136 | case Sema::IncompatiblePointer: |
2137 | case Sema::IncompatiblePointerSign: |
2138 | SecondConv = ICK_Incompatible_Pointer_Conversion; |
2139 | break; |
2140 | default: |
2141 | return false; |
2142 | } |
2143 | |
2144 | // First can only be an lvalue conversion, so we pretend that this was the |
2145 | // second conversion. First should already be valid from earlier in the |
2146 | // function. |
2147 | SCS.Second = SecondConv; |
2148 | SCS.setToType(1, ToType); |
2149 | |
2150 | // Third is Identity, because Second should rank us worse than any other |
2151 | // conversion. This could also be ICK_Qualification, but it's simpler to just |
2152 | // lump everything in with the second conversion, and we don't gain anything |
2153 | // from making this ICK_Qualification. |
2154 | SCS.Third = ICK_Identity; |
2155 | SCS.setToType(2, ToType); |
2156 | return true; |
2157 | } |
2158 | |
2159 | static bool |
2160 | IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
2161 | QualType &ToType, |
2162 | bool InOverloadResolution, |
2163 | StandardConversionSequence &SCS, |
2164 | bool CStyle) { |
2165 | |
2166 | const RecordType *UT = ToType->getAsUnionType(); |
2167 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
2168 | return false; |
2169 | // The field to initialize within the transparent union. |
2170 | RecordDecl *UD = UT->getDecl(); |
2171 | // It's compatible if the expression matches any of the fields. |
2172 | for (const auto *it : UD->fields()) { |
2173 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, |
2174 | CStyle, /*AllowObjCWritebackConversion=*/false)) { |
2175 | ToType = it->getType(); |
2176 | return true; |
2177 | } |
2178 | } |
2179 | return false; |
2180 | } |
2181 | |
2182 | /// IsIntegralPromotion - Determines whether the conversion from the |
2183 | /// expression From (whose potentially-adjusted type is FromType) to |
2184 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and |
2185 | /// sets PromotedType to the promoted type. |
2186 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { |
2187 | const BuiltinType *To = ToType->getAs<BuiltinType>(); |
2188 | // All integers are built-in. |
2189 | if (!To) { |
2190 | return false; |
2191 | } |
2192 | |
2193 | // An rvalue of type char, signed char, unsigned char, short int, or |
2194 | // unsigned short int can be converted to an rvalue of type int if |
2195 | // int can represent all the values of the source type; otherwise, |
2196 | // the source rvalue can be converted to an rvalue of type unsigned |
2197 | // int (C++ 4.5p1). |
2198 | if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() && |
2199 | !FromType->isEnumeralType()) { |
2200 | if ( // We can promote any signed, promotable integer type to an int |
2201 | (FromType->isSignedIntegerType() || |
2202 | // We can promote any unsigned integer type whose size is |
2203 | // less than int to an int. |
2204 | Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { |
2205 | return To->getKind() == BuiltinType::Int; |
2206 | } |
2207 | |
2208 | return To->getKind() == BuiltinType::UInt; |
2209 | } |
2210 | |
2211 | // C++11 [conv.prom]p3: |
2212 | // A prvalue of an unscoped enumeration type whose underlying type is not |
2213 | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the |
2214 | // following types that can represent all the values of the enumeration |
2215 | // (i.e., the values in the range bmin to bmax as described in 7.2): int, |
2216 | // unsigned int, long int, unsigned long int, long long int, or unsigned |
2217 | // long long int. If none of the types in that list can represent all the |
2218 | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration |
2219 | // type can be converted to an rvalue a prvalue of the extended integer type |
2220 | // with lowest integer conversion rank (4.13) greater than the rank of long |
2221 | // long in which all the values of the enumeration can be represented. If |
2222 | // there are two such extended types, the signed one is chosen. |
2223 | // C++11 [conv.prom]p4: |
2224 | // A prvalue of an unscoped enumeration type whose underlying type is fixed |
2225 | // can be converted to a prvalue of its underlying type. Moreover, if |
2226 | // integral promotion can be applied to its underlying type, a prvalue of an |
2227 | // unscoped enumeration type whose underlying type is fixed can also be |
2228 | // converted to a prvalue of the promoted underlying type. |
2229 | if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { |
2230 | // C++0x 7.2p9: Note that this implicit enum to int conversion is not |
2231 | // provided for a scoped enumeration. |
2232 | if (FromEnumType->getDecl()->isScoped()) |
2233 | return false; |
2234 | |
2235 | // We can perform an integral promotion to the underlying type of the enum, |
2236 | // even if that's not the promoted type. Note that the check for promoting |
2237 | // the underlying type is based on the type alone, and does not consider |
2238 | // the bitfield-ness of the actual source expression. |
2239 | if (FromEnumType->getDecl()->isFixed()) { |
2240 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); |
2241 | return Context.hasSameUnqualifiedType(Underlying, ToType) || |
2242 | IsIntegralPromotion(nullptr, Underlying, ToType); |
2243 | } |
2244 | |
2245 | // We have already pre-calculated the promotion type, so this is trivial. |
2246 | if (ToType->isIntegerType() && |
2247 | isCompleteType(From->getBeginLoc(), FromType)) |
2248 | return Context.hasSameUnqualifiedType( |
2249 | ToType, FromEnumType->getDecl()->getPromotionType()); |
2250 | |
2251 | // C++ [conv.prom]p5: |
2252 | // If the bit-field has an enumerated type, it is treated as any other |
2253 | // value of that type for promotion purposes. |
2254 | // |
2255 | // ... so do not fall through into the bit-field checks below in C++. |
2256 | if (getLangOpts().CPlusPlus) |
2257 | return false; |
2258 | } |
2259 | |
2260 | // C++0x [conv.prom]p2: |
2261 | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted |
2262 | // to an rvalue a prvalue of the first of the following types that can |
2263 | // represent all the values of its underlying type: int, unsigned int, |
2264 | // long int, unsigned long int, long long int, or unsigned long long int. |
2265 | // If none of the types in that list can represent all the values of its |
2266 | // underlying type, an rvalue a prvalue of type char16_t, char32_t, |
2267 | // or wchar_t can be converted to an rvalue a prvalue of its underlying |
2268 | // type. |
2269 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && |
2270 | ToType->isIntegerType()) { |
2271 | // Determine whether the type we're converting from is signed or |
2272 | // unsigned. |
2273 | bool FromIsSigned = FromType->isSignedIntegerType(); |
2274 | uint64_t FromSize = Context.getTypeSize(FromType); |
2275 | |
2276 | // The types we'll try to promote to, in the appropriate |
2277 | // order. Try each of these types. |
2278 | QualType PromoteTypes[6] = { |
2279 | Context.IntTy, Context.UnsignedIntTy, |
2280 | Context.LongTy, Context.UnsignedLongTy , |
2281 | Context.LongLongTy, Context.UnsignedLongLongTy |
2282 | }; |
2283 | for (int Idx = 0; Idx < 6; ++Idx) { |
2284 | uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); |
2285 | if (FromSize < ToSize || |
2286 | (FromSize == ToSize && |
2287 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { |
2288 | // We found the type that we can promote to. If this is the |
2289 | // type we wanted, we have a promotion. Otherwise, no |
2290 | // promotion. |
2291 | return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); |
2292 | } |
2293 | } |
2294 | } |
2295 | |
2296 | // An rvalue for an integral bit-field (9.6) can be converted to an |
2297 | // rvalue of type int if int can represent all the values of the |
2298 | // bit-field; otherwise, it can be converted to unsigned int if |
2299 | // unsigned int can represent all the values of the bit-field. If |
2300 | // the bit-field is larger yet, no integral promotion applies to |
2301 | // it. If the bit-field has an enumerated type, it is treated as any |
2302 | // other value of that type for promotion purposes (C++ 4.5p3). |
2303 | // FIXME: We should delay checking of bit-fields until we actually perform the |
2304 | // conversion. |
2305 | // |
2306 | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be |
2307 | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum |
2308 | // bit-fields and those whose underlying type is larger than int) for GCC |
2309 | // compatibility. |
2310 | if (From) { |
2311 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { |
2312 | std::optional<llvm::APSInt> BitWidth; |
2313 | if (FromType->isIntegralType(Context) && |
2314 | (BitWidth = |
2315 | MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { |
2316 | llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); |
2317 | ToSize = Context.getTypeSize(ToType); |
2318 | |
2319 | // Are we promoting to an int from a bitfield that fits in an int? |
2320 | if (*BitWidth < ToSize || |
2321 | (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { |
2322 | return To->getKind() == BuiltinType::Int; |
2323 | } |
2324 | |
2325 | // Are we promoting to an unsigned int from an unsigned bitfield |
2326 | // that fits into an unsigned int? |
2327 | if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { |
2328 | return To->getKind() == BuiltinType::UInt; |
2329 | } |
2330 | |
2331 | return false; |
2332 | } |
2333 | } |
2334 | } |
2335 | |
2336 | // An rvalue of type bool can be converted to an rvalue of type int, |
2337 | // with false becoming zero and true becoming one (C++ 4.5p4). |
2338 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { |
2339 | return true; |
2340 | } |
2341 | |
2342 | return false; |
2343 | } |
2344 | |
2345 | /// IsFloatingPointPromotion - Determines whether the conversion from |
2346 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, |
2347 | /// returns true and sets PromotedType to the promoted type. |
2348 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { |
2349 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) |
2350 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { |
2351 | /// An rvalue of type float can be converted to an rvalue of type |
2352 | /// double. (C++ 4.6p1). |
2353 | if (FromBuiltin->getKind() == BuiltinType::Float && |
2354 | ToBuiltin->getKind() == BuiltinType::Double) |
2355 | return true; |
2356 | |
2357 | // C99 6.3.1.5p1: |
2358 | // When a float is promoted to double or long double, or a |
2359 | // double is promoted to long double [...]. |
2360 | if (!getLangOpts().CPlusPlus && |
2361 | (FromBuiltin->getKind() == BuiltinType::Float || |
2362 | FromBuiltin->getKind() == BuiltinType::Double) && |
2363 | (ToBuiltin->getKind() == BuiltinType::LongDouble || |
2364 | ToBuiltin->getKind() == BuiltinType::Float128 || |
2365 | ToBuiltin->getKind() == BuiltinType::Ibm128)) |
2366 | return true; |
2367 | |
2368 | // Half can be promoted to float. |
2369 | if (!getLangOpts().NativeHalfType && |
2370 | FromBuiltin->getKind() == BuiltinType::Half && |
2371 | ToBuiltin->getKind() == BuiltinType::Float) |
2372 | return true; |
2373 | } |
2374 | |
2375 | return false; |
2376 | } |
2377 | |
2378 | /// Determine if a conversion is a complex promotion. |
2379 | /// |
2380 | /// A complex promotion is defined as a complex -> complex conversion |
2381 | /// where the conversion between the underlying real types is a |
2382 | /// floating-point or integral promotion. |
2383 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { |
2384 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); |
2385 | if (!FromComplex) |
2386 | return false; |
2387 | |
2388 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); |
2389 | if (!ToComplex) |
2390 | return false; |
2391 | |
2392 | return IsFloatingPointPromotion(FromComplex->getElementType(), |
2393 | ToComplex->getElementType()) || |
2394 | IsIntegralPromotion(nullptr, FromComplex->getElementType(), |
2395 | ToComplex->getElementType()); |
2396 | } |
2397 | |
2398 | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from |
2399 | /// the pointer type FromPtr to a pointer to type ToPointee, with the |
2400 | /// same type qualifiers as FromPtr has on its pointee type. ToType, |
2401 | /// if non-empty, will be a pointer to ToType that may or may not have |
2402 | /// the right set of qualifiers on its pointee. |
2403 | /// |
2404 | static QualType |
2405 | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, |
2406 | QualType ToPointee, QualType ToType, |
2407 | ASTContext &Context, |
2408 | bool StripObjCLifetime = false) { |
2409 | assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__ )) |
2410 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__ )) |
2411 | "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__ )); |
2412 | |
2413 | /// Conversions to 'id' subsume cv-qualifier conversions. |
2414 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) |
2415 | return ToType.getUnqualifiedType(); |
2416 | |
2417 | QualType CanonFromPointee |
2418 | = Context.getCanonicalType(FromPtr->getPointeeType()); |
2419 | QualType CanonToPointee = Context.getCanonicalType(ToPointee); |
2420 | Qualifiers Quals = CanonFromPointee.getQualifiers(); |
2421 | |
2422 | if (StripObjCLifetime) |
2423 | Quals.removeObjCLifetime(); |
2424 | |
2425 | // Exact qualifier match -> return the pointer type we're converting to. |
2426 | if (CanonToPointee.getLocalQualifiers() == Quals) { |
2427 | // ToType is exactly what we need. Return it. |
2428 | if (!ToType.isNull()) |
2429 | return ToType.getUnqualifiedType(); |
2430 | |
2431 | // Build a pointer to ToPointee. It has the right qualifiers |
2432 | // already. |
2433 | if (isa<ObjCObjectPointerType>(ToType)) |
2434 | return Context.getObjCObjectPointerType(ToPointee); |
2435 | return Context.getPointerType(ToPointee); |
2436 | } |
2437 | |
2438 | // Just build a canonical type that has the right qualifiers. |
2439 | QualType QualifiedCanonToPointee |
2440 | = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); |
2441 | |
2442 | if (isa<ObjCObjectPointerType>(ToType)) |
2443 | return Context.getObjCObjectPointerType(QualifiedCanonToPointee); |
2444 | return Context.getPointerType(QualifiedCanonToPointee); |
2445 | } |
2446 | |
2447 | static bool isNullPointerConstantForConversion(Expr *Expr, |
2448 | bool InOverloadResolution, |
2449 | ASTContext &Context) { |
2450 | // Handle value-dependent integral null pointer constants correctly. |
2451 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
2452 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && |
2453 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) |
2454 | return !InOverloadResolution; |
2455 | |
2456 | return Expr->isNullPointerConstant(Context, |
2457 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
2458 | : Expr::NPC_ValueDependentIsNull); |
2459 | } |
2460 | |
2461 | /// IsPointerConversion - Determines whether the conversion of the |
2462 | /// expression From, which has the (possibly adjusted) type FromType, |
2463 | /// can be converted to the type ToType via a pointer conversion (C++ |
2464 | /// 4.10). If so, returns true and places the converted type (that |
2465 | /// might differ from ToType in its cv-qualifiers at some level) into |
2466 | /// ConvertedType. |
2467 | /// |
2468 | /// This routine also supports conversions to and from block pointers |
2469 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and |
2470 | /// pointers to interfaces. FIXME: Once we've determined the |
2471 | /// appropriate overloading rules for Objective-C, we may want to |
2472 | /// split the Objective-C checks into a different routine; however, |
2473 | /// GCC seems to consider all of these conversions to be pointer |
2474 | /// conversions, so for now they live here. IncompatibleObjC will be |
2475 | /// set if the conversion is an allowed Objective-C conversion that |
2476 | /// should result in a warning. |
2477 | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2478 | bool InOverloadResolution, |
2479 | QualType& ConvertedType, |
2480 | bool &IncompatibleObjC) { |
2481 | IncompatibleObjC = false; |
2482 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, |
2483 | IncompatibleObjC)) |
2484 | return true; |
2485 | |
2486 | // Conversion from a null pointer constant to any Objective-C pointer type. |
2487 | if (ToType->isObjCObjectPointerType() && |
2488 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2489 | ConvertedType = ToType; |
2490 | return true; |
2491 | } |
2492 | |
2493 | // Blocks: Block pointers can be converted to void*. |
2494 | if (FromType->isBlockPointerType() && ToType->isPointerType() && |
2495 | ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
2496 | ConvertedType = ToType; |
2497 | return true; |
2498 | } |
2499 | // Blocks: A null pointer constant can be converted to a block |
2500 | // pointer type. |
2501 | if (ToType->isBlockPointerType() && |
2502 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2503 | ConvertedType = ToType; |
2504 | return true; |
2505 | } |
2506 | |
2507 | // If the left-hand-side is nullptr_t, the right side can be a null |
2508 | // pointer constant. |
2509 | if (ToType->isNullPtrType() && |
2510 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2511 | ConvertedType = ToType; |
2512 | return true; |
2513 | } |
2514 | |
2515 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); |
2516 | if (!ToTypePtr) |
2517 | return false; |
2518 | |
2519 | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). |
2520 | if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2521 | ConvertedType = ToType; |
2522 | return true; |
2523 | } |
2524 | |
2525 | // Beyond this point, both types need to be pointers |
2526 | // , including objective-c pointers. |
2527 | QualType ToPointeeType = ToTypePtr->getPointeeType(); |
2528 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && |
2529 | !getLangOpts().ObjCAutoRefCount) { |
2530 | ConvertedType = BuildSimilarlyQualifiedPointerType( |
2531 | FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, |
2532 | Context); |
2533 | return true; |
2534 | } |
2535 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); |
2536 | if (!FromTypePtr) |
2537 | return false; |
2538 | |
2539 | QualType FromPointeeType = FromTypePtr->getPointeeType(); |
2540 | |
2541 | // If the unqualified pointee types are the same, this can't be a |
2542 | // pointer conversion, so don't do all of the work below. |
2543 | if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) |
2544 | return false; |
2545 | |
2546 | // An rvalue of type "pointer to cv T," where T is an object type, |
2547 | // can be converted to an rvalue of type "pointer to cv void" (C++ |
2548 | // 4.10p2). |
2549 | if (FromPointeeType->isIncompleteOrObjectType() && |
2550 | ToPointeeType->isVoidType()) { |
2551 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2552 | ToPointeeType, |
2553 | ToType, Context, |
2554 | /*StripObjCLifetime=*/true); |
2555 | return true; |
2556 | } |
2557 | |
2558 | // MSVC allows implicit function to void* type conversion. |
2559 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && |
2560 | ToPointeeType->isVoidType()) { |
2561 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2562 | ToPointeeType, |
2563 | ToType, Context); |
2564 | return true; |
2565 | } |
2566 | |
2567 | // When we're overloading in C, we allow a special kind of pointer |
2568 | // conversion for compatible-but-not-identical pointee types. |
2569 | if (!getLangOpts().CPlusPlus && |
2570 | Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { |
2571 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2572 | ToPointeeType, |
2573 | ToType, Context); |
2574 | return true; |
2575 | } |
2576 | |
2577 | // C++ [conv.ptr]p3: |
2578 | // |
2579 | // An rvalue of type "pointer to cv D," where D is a class type, |
2580 | // can be converted to an rvalue of type "pointer to cv B," where |
2581 | // B is a base class (clause 10) of D. If B is an inaccessible |
2582 | // (clause 11) or ambiguous (10.2) base class of D, a program that |
2583 | // necessitates this conversion is ill-formed. The result of the |
2584 | // conversion is a pointer to the base class sub-object of the |
2585 | // derived class object. The null pointer value is converted to |
2586 | // the null pointer value of the destination type. |
2587 | // |
2588 | // Note that we do not check for ambiguity or inaccessibility |
2589 | // here. That is handled by CheckPointerConversion. |
2590 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && |
2591 | ToPointeeType->isRecordType() && |
2592 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && |
2593 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { |
2594 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2595 | ToPointeeType, |
2596 | ToType, Context); |
2597 | return true; |
2598 | } |
2599 | |
2600 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && |
2601 | Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { |
2602 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2603 | ToPointeeType, |
2604 | ToType, Context); |
2605 | return true; |
2606 | } |
2607 | |
2608 | return false; |
2609 | } |
2610 | |
2611 | /// Adopt the given qualifiers for the given type. |
2612 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ |
2613 | Qualifiers TQs = T.getQualifiers(); |
2614 | |
2615 | // Check whether qualifiers already match. |
2616 | if (TQs == Qs) |
2617 | return T; |
2618 | |
2619 | if (Qs.compatiblyIncludes(TQs)) |
2620 | return Context.getQualifiedType(T, Qs); |
2621 | |
2622 | return Context.getQualifiedType(T.getUnqualifiedType(), Qs); |
2623 | } |
2624 | |
2625 | /// isObjCPointerConversion - Determines whether this is an |
2626 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, |
2627 | /// with the same arguments and return values. |
2628 | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, |
2629 | QualType& ConvertedType, |
2630 | bool &IncompatibleObjC) { |
2631 | if (!getLangOpts().ObjC) |
2632 | return false; |
2633 | |
2634 | // The set of qualifiers on the type we're converting from. |
2635 | Qualifiers FromQualifiers = FromType.getQualifiers(); |
2636 | |
2637 | // First, we handle all conversions on ObjC object pointer types. |
2638 | const ObjCObjectPointerType* ToObjCPtr = |
2639 | ToType->getAs<ObjCObjectPointerType>(); |
2640 | const ObjCObjectPointerType *FromObjCPtr = |
2641 | FromType->getAs<ObjCObjectPointerType>(); |
2642 | |
2643 | if (ToObjCPtr && FromObjCPtr) { |
2644 | // If the pointee types are the same (ignoring qualifications), |
2645 | // then this is not a pointer conversion. |
2646 | if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), |
2647 | FromObjCPtr->getPointeeType())) |
2648 | return false; |
2649 | |
2650 | // Conversion between Objective-C pointers. |
2651 | if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { |
2652 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); |
2653 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); |
2654 | if (getLangOpts().CPlusPlus && LHS && RHS && |
2655 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( |
2656 | FromObjCPtr->getPointeeType())) |
2657 | return false; |
2658 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2659 | ToObjCPtr->getPointeeType(), |
2660 | ToType, Context); |
2661 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2662 | return true; |
2663 | } |
2664 | |
2665 | if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { |
2666 | // Okay: this is some kind of implicit downcast of Objective-C |
2667 | // interfaces, which is permitted. However, we're going to |
2668 | // complain about it. |
2669 | IncompatibleObjC = true; |
2670 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2671 | ToObjCPtr->getPointeeType(), |
2672 | ToType, Context); |
2673 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2674 | return true; |
2675 | } |
2676 | } |
2677 | // Beyond this point, both types need to be C pointers or block pointers. |
2678 | QualType ToPointeeType; |
2679 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) |
2680 | ToPointeeType = ToCPtr->getPointeeType(); |
2681 | else if (const BlockPointerType *ToBlockPtr = |
2682 | ToType->getAs<BlockPointerType>()) { |
2683 | // Objective C++: We're able to convert from a pointer to any object |
2684 | // to a block pointer type. |
2685 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { |
2686 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2687 | return true; |
2688 | } |
2689 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2690 | } |
2691 | else if (FromType->getAs<BlockPointerType>() && |
2692 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { |
2693 | // Objective C++: We're able to convert from a block pointer type to a |
2694 | // pointer to any object. |
2695 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2696 | return true; |
2697 | } |
2698 | else |
2699 | return false; |
2700 | |
2701 | QualType FromPointeeType; |
2702 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) |
2703 | FromPointeeType = FromCPtr->getPointeeType(); |
2704 | else if (const BlockPointerType *FromBlockPtr = |
2705 | FromType->getAs<BlockPointerType>()) |
2706 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2707 | else |
2708 | return false; |
2709 | |
2710 | // If we have pointers to pointers, recursively check whether this |
2711 | // is an Objective-C conversion. |
2712 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && |
2713 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2714 | IncompatibleObjC)) { |
2715 | // We always complain about this conversion. |
2716 | IncompatibleObjC = true; |
2717 | ConvertedType = Context.getPointerType(ConvertedType); |
2718 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2719 | return true; |
2720 | } |
2721 | // Allow conversion of pointee being objective-c pointer to another one; |
2722 | // as in I* to id. |
2723 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && |
2724 | ToPointeeType->getAs<ObjCObjectPointerType>() && |
2725 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2726 | IncompatibleObjC)) { |
2727 | |
2728 | ConvertedType = Context.getPointerType(ConvertedType); |
2729 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2730 | return true; |
2731 | } |
2732 | |
2733 | // If we have pointers to functions or blocks, check whether the only |
2734 | // differences in the argument and result types are in Objective-C |
2735 | // pointer conversions. If so, we permit the conversion (but |
2736 | // complain about it). |
2737 | const FunctionProtoType *FromFunctionType |
2738 | = FromPointeeType->getAs<FunctionProtoType>(); |
2739 | const FunctionProtoType *ToFunctionType |
2740 | = ToPointeeType->getAs<FunctionProtoType>(); |
2741 | if (FromFunctionType && ToFunctionType) { |
2742 | // If the function types are exactly the same, this isn't an |
2743 | // Objective-C pointer conversion. |
2744 | if (Context.getCanonicalType(FromPointeeType) |
2745 | == Context.getCanonicalType(ToPointeeType)) |
2746 | return false; |
2747 | |
2748 | // Perform the quick checks that will tell us whether these |
2749 | // function types are obviously different. |
2750 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2751 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || |
2752 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) |
2753 | return false; |
2754 | |
2755 | bool HasObjCConversion = false; |
2756 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == |
2757 | Context.getCanonicalType(ToFunctionType->getReturnType())) { |
2758 | // Okay, the types match exactly. Nothing to do. |
2759 | } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), |
2760 | ToFunctionType->getReturnType(), |
2761 | ConvertedType, IncompatibleObjC)) { |
2762 | // Okay, we have an Objective-C pointer conversion. |
2763 | HasObjCConversion = true; |
2764 | } else { |
2765 | // Function types are too different. Abort. |
2766 | return false; |
2767 | } |
2768 | |
2769 | // Check argument types. |
2770 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2771 | ArgIdx != NumArgs; ++ArgIdx) { |
2772 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
2773 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
2774 | if (Context.getCanonicalType(FromArgType) |
2775 | == Context.getCanonicalType(ToArgType)) { |
2776 | // Okay, the types match exactly. Nothing to do. |
2777 | } else if (isObjCPointerConversion(FromArgType, ToArgType, |
2778 | ConvertedType, IncompatibleObjC)) { |
2779 | // Okay, we have an Objective-C pointer conversion. |
2780 | HasObjCConversion = true; |
2781 | } else { |
2782 | // Argument types are too different. Abort. |
2783 | return false; |
2784 | } |
2785 | } |
2786 | |
2787 | if (HasObjCConversion) { |
2788 | // We had an Objective-C conversion. Allow this pointer |
2789 | // conversion, but complain about it. |
2790 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2791 | IncompatibleObjC = true; |
2792 | return true; |
2793 | } |
2794 | } |
2795 | |
2796 | return false; |
2797 | } |
2798 | |
2799 | /// Determine whether this is an Objective-C writeback conversion, |
2800 | /// used for parameter passing when performing automatic reference counting. |
2801 | /// |
2802 | /// \param FromType The type we're converting form. |
2803 | /// |
2804 | /// \param ToType The type we're converting to. |
2805 | /// |
2806 | /// \param ConvertedType The type that will be produced after applying |
2807 | /// this conversion. |
2808 | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, |
2809 | QualType &ConvertedType) { |
2810 | if (!getLangOpts().ObjCAutoRefCount || |
2811 | Context.hasSameUnqualifiedType(FromType, ToType)) |
2812 | return false; |
2813 | |
2814 | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). |
2815 | QualType ToPointee; |
2816 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) |
2817 | ToPointee = ToPointer->getPointeeType(); |
2818 | else |
2819 | return false; |
2820 | |
2821 | Qualifiers ToQuals = ToPointee.getQualifiers(); |
2822 | if (!ToPointee->isObjCLifetimeType() || |
2823 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || |
2824 | !ToQuals.withoutObjCLifetime().empty()) |
2825 | return false; |
2826 | |
2827 | // Argument must be a pointer to __strong to __weak. |
2828 | QualType FromPointee; |
2829 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) |
2830 | FromPointee = FromPointer->getPointeeType(); |
2831 | else |
2832 | return false; |
2833 | |
2834 | Qualifiers FromQuals = FromPointee.getQualifiers(); |
2835 | if (!FromPointee->isObjCLifetimeType() || |
2836 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && |
2837 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) |
2838 | return false; |
2839 | |
2840 | // Make sure that we have compatible qualifiers. |
2841 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); |
2842 | if (!ToQuals.compatiblyIncludes(FromQuals)) |
2843 | return false; |
2844 | |
2845 | // Remove qualifiers from the pointee type we're converting from; they |
2846 | // aren't used in the compatibility check belong, and we'll be adding back |
2847 | // qualifiers (with __autoreleasing) if the compatibility check succeeds. |
2848 | FromPointee = FromPointee.getUnqualifiedType(); |
2849 | |
2850 | // The unqualified form of the pointee types must be compatible. |
2851 | ToPointee = ToPointee.getUnqualifiedType(); |
2852 | bool IncompatibleObjC; |
2853 | if (Context.typesAreCompatible(FromPointee, ToPointee)) |
2854 | FromPointee = ToPointee; |
2855 | else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, |
2856 | IncompatibleObjC)) |
2857 | return false; |
2858 | |
2859 | /// Construct the type we're converting to, which is a pointer to |
2860 | /// __autoreleasing pointee. |
2861 | FromPointee = Context.getQualifiedType(FromPointee, FromQuals); |
2862 | ConvertedType = Context.getPointerType(FromPointee); |
2863 | return true; |
2864 | } |
2865 | |
2866 | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, |
2867 | QualType& ConvertedType) { |
2868 | QualType ToPointeeType; |
2869 | if (const BlockPointerType *ToBlockPtr = |
2870 | ToType->getAs<BlockPointerType>()) |
2871 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2872 | else |
2873 | return false; |
2874 | |
2875 | QualType FromPointeeType; |
2876 | if (const BlockPointerType *FromBlockPtr = |
2877 | FromType->getAs<BlockPointerType>()) |
2878 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2879 | else |
2880 | return false; |
2881 | // We have pointer to blocks, check whether the only |
2882 | // differences in the argument and result types are in Objective-C |
2883 | // pointer conversions. If so, we permit the conversion. |
2884 | |
2885 | const FunctionProtoType *FromFunctionType |
2886 | = FromPointeeType->getAs<FunctionProtoType>(); |
2887 | const FunctionProtoType *ToFunctionType |
2888 | = ToPointeeType->getAs<FunctionProtoType>(); |
2889 | |
2890 | if (!FromFunctionType || !ToFunctionType) |
2891 | return false; |
2892 | |
2893 | if (Context.hasSameType(FromPointeeType, ToPointeeType)) |
2894 | return true; |
2895 | |
2896 | // Perform the quick checks that will tell us whether these |
2897 | // function types are obviously different. |
2898 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2899 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) |
2900 | return false; |
2901 | |
2902 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); |
2903 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); |
2904 | if (FromEInfo != ToEInfo) |
2905 | return false; |
2906 | |
2907 | bool IncompatibleObjC = false; |
2908 | if (Context.hasSameType(FromFunctionType->getReturnType(), |
2909 | ToFunctionType->getReturnType())) { |
2910 | // Okay, the types match exactly. Nothing to do. |
2911 | } else { |
2912 | QualType RHS = FromFunctionType->getReturnType(); |
2913 | QualType LHS = ToFunctionType->getReturnType(); |
2914 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && |
2915 | !RHS.hasQualifiers() && LHS.hasQualifiers()) |
2916 | LHS = LHS.getUnqualifiedType(); |
2917 | |
2918 | if (Context.hasSameType(RHS,LHS)) { |
2919 | // OK exact match. |
2920 | } else if (isObjCPointerConversion(RHS, LHS, |
2921 | ConvertedType, IncompatibleObjC)) { |
2922 | if (IncompatibleObjC) |
2923 | return false; |
2924 | // Okay, we have an Objective-C pointer conversion. |
2925 | } |
2926 | else |
2927 | return false; |
2928 | } |
2929 | |
2930 | // Check argument types. |
2931 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2932 | ArgIdx != NumArgs; ++ArgIdx) { |
2933 | IncompatibleObjC = false; |
2934 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
2935 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
2936 | if (Context.hasSameType(FromArgType, ToArgType)) { |
2937 | // Okay, the types match exactly. Nothing to do. |
2938 | } else if (isObjCPointerConversion(ToArgType, FromArgType, |
2939 | ConvertedType, IncompatibleObjC)) { |
2940 | if (IncompatibleObjC) |
2941 | return false; |
2942 | // Okay, we have an Objective-C pointer conversion. |
2943 | } else |
2944 | // Argument types are too different. Abort. |
2945 | return false; |
2946 | } |
2947 | |
2948 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
2949 | bool CanUseToFPT, CanUseFromFPT; |
2950 | if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, |
2951 | CanUseToFPT, CanUseFromFPT, |
2952 | NewParamInfos)) |
2953 | return false; |
2954 | |
2955 | ConvertedType = ToType; |
2956 | return true; |
2957 | } |
2958 | |
2959 | enum { |
2960 | ft_default, |
2961 | ft_different_class, |
2962 | ft_parameter_arity, |
2963 | ft_parameter_mismatch, |
2964 | ft_return_type, |
2965 | ft_qualifer_mismatch, |
2966 | ft_noexcept |
2967 | }; |
2968 | |
2969 | /// Attempts to get the FunctionProtoType from a Type. Handles |
2970 | /// MemberFunctionPointers properly. |
2971 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { |
2972 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) |
2973 | return FPT; |
2974 | |
2975 | if (auto *MPT = FromType->getAs<MemberPointerType>()) |
2976 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); |
2977 | |
2978 | return nullptr; |
2979 | } |
2980 | |
2981 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing |
2982 | /// function types. Catches different number of parameter, mismatch in |
2983 | /// parameter types, and different return types. |
2984 | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
2985 | QualType FromType, QualType ToType) { |
2986 | // If either type is not valid, include no extra info. |
2987 | if (FromType.isNull() || ToType.isNull()) { |
2988 | PDiag << ft_default; |
2989 | return; |
2990 | } |
2991 | |
2992 | // Get the function type from the pointers. |
2993 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { |
2994 | const auto *FromMember = FromType->castAs<MemberPointerType>(), |
2995 | *ToMember = ToType->castAs<MemberPointerType>(); |
2996 | if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { |
2997 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) |
2998 | << QualType(FromMember->getClass(), 0); |
2999 | return; |
3000 | } |
3001 | FromType = FromMember->getPointeeType(); |
3002 | ToType = ToMember->getPointeeType(); |
3003 | } |
3004 | |
3005 | if (FromType->isPointerType()) |
3006 | FromType = FromType->getPointeeType(); |
3007 | if (ToType->isPointerType()) |
3008 | ToType = ToType->getPointeeType(); |
3009 | |
3010 | // Remove references. |
3011 | FromType = FromType.getNonReferenceType(); |
3012 | ToType = ToType.getNonReferenceType(); |
3013 | |
3014 | // Don't print extra info for non-specialized template functions. |
3015 | if (FromType->isInstantiationDependentType() && |
3016 | !FromType->getAs<TemplateSpecializationType>()) { |
3017 | PDiag << ft_default; |
3018 | return; |
3019 | } |
3020 | |
3021 | // No extra info for same types. |
3022 | if (Context.hasSameType(FromType, ToType)) { |
3023 | PDiag << ft_default; |
3024 | return; |
3025 | } |
3026 | |
3027 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), |
3028 | *ToFunction = tryGetFunctionProtoType(ToType); |
3029 | |
3030 | // Both types need to be function types. |
3031 | if (!FromFunction || !ToFunction) { |
3032 | PDiag << ft_default; |
3033 | return; |
3034 | } |
3035 | |
3036 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { |
3037 | PDiag << ft_parameter_arity << ToFunction->getNumParams() |
3038 | << FromFunction->getNumParams(); |
3039 | return; |
3040 | } |
3041 | |
3042 | // Handle different parameter types. |
3043 | unsigned ArgPos; |
3044 | if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { |
3045 | PDiag << ft_parameter_mismatch << ArgPos + 1 |
3046 | << ToFunction->getParamType(ArgPos) |
3047 | << FromFunction->getParamType(ArgPos); |
3048 | return; |
3049 | } |
3050 | |
3051 | // Handle different return type. |
3052 | if (!Context.hasSameType(FromFunction->getReturnType(), |
3053 | ToFunction->getReturnType())) { |
3054 | PDiag << ft_return_type << ToFunction->getReturnType() |
3055 | << FromFunction->getReturnType(); |
3056 | return; |
3057 | } |
3058 | |
3059 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { |
3060 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() |
3061 | << FromFunction->getMethodQuals(); |
3062 | return; |
3063 | } |
3064 | |
3065 | // Handle exception specification differences on canonical type (in C++17 |
3066 | // onwards). |
3067 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) |
3068 | ->isNothrow() != |
3069 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) |
3070 | ->isNothrow()) { |
3071 | PDiag << ft_noexcept; |
3072 | return; |
3073 | } |
3074 | |
3075 | // Unable to find a difference, so add no extra info. |
3076 | PDiag << ft_default; |
3077 | } |
3078 | |
3079 | /// FunctionParamTypesAreEqual - This routine checks two function proto types |
3080 | /// for equality of their parameter types. Caller has already checked that |
3081 | /// they have same number of parameters. If the parameters are different, |
3082 | /// ArgPos will have the parameter index of the first different parameter. |
3083 | /// If `Reversed` is true, the parameters of `NewType` will be compared in |
3084 | /// reverse order. That's useful if one of the functions is being used as a C++20 |
3085 | /// synthesized operator overload with a reversed parameter order. |
3086 | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
3087 | const FunctionProtoType *NewType, |
3088 | unsigned *ArgPos, bool Reversed) { |
3089 | assert(OldType->getNumParams() == NewType->getNumParams() &&(static_cast <bool> (OldType->getNumParams() == NewType ->getNumParams() && "Can't compare parameters of functions with different number of " "parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\"" , "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__ )) |
3090 | "Can't compare parameters of functions with different number of "(static_cast <bool> (OldType->getNumParams() == NewType ->getNumParams() && "Can't compare parameters of functions with different number of " "parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\"" , "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__ )) |
3091 | "parameters!")(static_cast <bool> (OldType->getNumParams() == NewType ->getNumParams() && "Can't compare parameters of functions with different number of " "parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\"" , "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__ )); |
3092 | for (size_t I = 0; I < OldType->getNumParams(); I++) { |
3093 | // Reverse iterate over the parameters of `OldType` if `Reversed` is true. |
3094 | size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I; |
3095 | |
3096 | // Ignore address spaces in pointee type. This is to disallow overloading |
3097 | // on __ptr32/__ptr64 address spaces. |
3098 | QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType()); |
3099 | QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType()); |
3100 | |
3101 | if (!Context.hasSameType(Old, New)) { |
3102 | if (ArgPos) |
3103 | *ArgPos = I; |
3104 | return false; |
3105 | } |
3106 | } |
3107 | return true; |
3108 | } |
3109 | |
3110 | /// CheckPointerConversion - Check the pointer conversion from the |
3111 | /// expression From to the type ToType. This routine checks for |
3112 | /// ambiguous or inaccessible derived-to-base pointer |
3113 | /// conversions for which IsPointerConversion has already returned |
3114 | /// true. It returns true and produces a diagnostic if there was an |
3115 | /// error, or returns false otherwise. |
3116 | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, |
3117 | CastKind &Kind, |
3118 | CXXCastPath& BasePath, |
3119 | bool IgnoreBaseAccess, |
3120 | bool Diagnose) { |
3121 | QualType FromType = From->getType(); |
3122 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; |
3123 | |
3124 | Kind = CK_BitCast; |
3125 | |
3126 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && |
3127 | From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == |
3128 | Expr::NPCK_ZeroExpression) { |
3129 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) |
3130 | DiagRuntimeBehavior(From->getExprLoc(), From, |
3131 | PDiag(diag::warn_impcast_bool_to_null_pointer) |
3132 | << ToType << From->getSourceRange()); |
3133 | else if (!isUnevaluatedContext()) |
3134 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) |
3135 | << ToType << From->getSourceRange(); |
3136 | } |
3137 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { |
3138 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { |
3139 | QualType FromPointeeType = FromPtrType->getPointeeType(), |
3140 | ToPointeeType = ToPtrType->getPointeeType(); |
3141 | |
3142 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && |
3143 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { |
3144 | // We must have a derived-to-base conversion. Check an |
3145 | // ambiguous or inaccessible conversion. |
3146 | unsigned InaccessibleID = 0; |
3147 | unsigned AmbiguousID = 0; |
3148 | if (Diagnose) { |
3149 | InaccessibleID = diag::err_upcast_to_inaccessible_base; |
3150 | AmbiguousID = diag::err_ambiguous_derived_to_base_conv; |
3151 | } |
3152 | if (CheckDerivedToBaseConversion( |
3153 | FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, |
3154 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), |
3155 | &BasePath, IgnoreBaseAccess)) |
3156 | return true; |
3157 | |
3158 | // The conversion was successful. |
3159 | Kind = CK_DerivedToBase; |
3160 | } |
3161 | |
3162 | if (Diagnose && !IsCStyleOrFunctionalCast && |
3163 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { |
3164 | assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "clang/lib/Sema/SemaOverload.cpp", 3165, __extension__ __PRETTY_FUNCTION__ )) |
3165 | "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "clang/lib/Sema/SemaOverload.cpp", 3165, __extension__ __PRETTY_FUNCTION__ )); |
3166 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) |
3167 | << From->getSourceRange(); |
3168 | } |
3169 | } |
3170 | } else if (const ObjCObjectPointerType *ToPtrType = |
3171 | ToType->getAs<ObjCObjectPointerType>()) { |
3172 | if (const ObjCObjectPointerType *FromPtrType = |
3173 | FromType->getAs<ObjCObjectPointerType>()) { |
3174 | // Objective-C++ conversions are always okay. |
3175 | // FIXME: We should have a different class of conversions for the |
3176 | // Objective-C++ implicit conversions. |
3177 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) |
3178 | return false; |
3179 | } else if (FromType->isBlockPointerType()) { |
3180 | Kind = CK_BlockPointerToObjCPointerCast; |
3181 | } else { |
3182 | Kind = CK_CPointerToObjCPointerCast; |
3183 | } |
3184 | } else if (ToType->isBlockPointerType()) { |
3185 | if (!FromType->isBlockPointerType()) |
3186 | Kind = CK_AnyPointerToBlockPointerCast; |
3187 | } |
3188 | |
3189 | // We shouldn't fall into this case unless it's valid for other |
3190 | // reasons. |
3191 | if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) |
3192 | Kind = CK_NullToPointer; |
3193 | |
3194 | return false; |
3195 | } |
3196 | |
3197 | /// IsMemberPointerConversion - Determines whether the conversion of the |
3198 | /// expression From, which has the (possibly adjusted) type FromType, can be |
3199 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). |
3200 | /// If so, returns true and places the converted type (that might differ from |
3201 | /// ToType in its cv-qualifiers at some level) into ConvertedType. |
3202 | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, |
3203 | QualType ToType, |
3204 | bool InOverloadResolution, |
3205 | QualType &ConvertedType) { |
3206 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); |
3207 | if (!ToTypePtr) |
3208 | return false; |
3209 | |
3210 | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) |
3211 | if (From->isNullPointerConstant(Context, |
3212 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
3213 | : Expr::NPC_ValueDependentIsNull)) { |
3214 | ConvertedType = ToType; |
3215 | return true; |
3216 | } |
3217 | |
3218 | // Otherwise, both types have to be member pointers. |
3219 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); |
3220 | if (!FromTypePtr) |
3221 | return false; |
3222 | |
3223 | // A pointer to member of B can be converted to a pointer to member of D, |
3224 | // where D is derived from B (C++ 4.11p2). |
3225 | QualType FromClass(FromTypePtr->getClass(), 0); |
3226 | QualType ToClass(ToTypePtr->getClass(), 0); |
3227 | |
3228 | if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && |
3229 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { |
3230 | ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), |
3231 | ToClass.getTypePtr()); |
3232 | return true; |
3233 | } |
3234 | |
3235 | return false; |
3236 | } |
3237 | |
3238 | /// CheckMemberPointerConversion - Check the member pointer conversion from the |
3239 | /// expression From to the type ToType. This routine checks for ambiguous or |
3240 | /// virtual or inaccessible base-to-derived member pointer conversions |
3241 | /// for which IsMemberPointerConversion has already returned true. It returns |
3242 | /// true and produces a diagnostic if there was an error, or returns false |
3243 | /// otherwise. |
3244 | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, |
3245 | CastKind &Kind, |
3246 | CXXCastPath &BasePath, |
3247 | bool IgnoreBaseAccess) { |
3248 | QualType FromType = From->getType(); |
3249 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); |
3250 | if (!FromPtrType) { |
3251 | // This must be a null pointer to member pointer conversion |
3252 | assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__ )) |
3253 | Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__ )) |
3254 | "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__ )); |
3255 | Kind = CK_NullToMemberPointer; |
3256 | return false; |
3257 | } |
3258 | |
3259 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); |
3260 | assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? void (0) : __assert_fail ( "ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "clang/lib/Sema/SemaOverload.cpp", 3261, __extension__ __PRETTY_FUNCTION__ )) |
3261 | "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? void (0) : __assert_fail ( "ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "clang/lib/Sema/SemaOverload.cpp", 3261, __extension__ __PRETTY_FUNCTION__ )); |
3262 | |
3263 | QualType FromClass = QualType(FromPtrType->getClass(), 0); |
3264 | QualType ToClass = QualType(ToPtrType->getClass(), 0); |
3265 | |
3266 | // FIXME: What about dependent types? |
3267 | assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() && "Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\"" , "clang/lib/Sema/SemaOverload.cpp", 3267, __extension__ __PRETTY_FUNCTION__ )); |
3268 | assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() && "Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\"" , "clang/lib/Sema/SemaOverload.cpp", 3268, __extension__ __PRETTY_FUNCTION__ )); |
3269 | |
3270 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3271 | /*DetectVirtual=*/true); |
3272 | bool DerivationOkay = |
3273 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); |
3274 | assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK." ) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "clang/lib/Sema/SemaOverload.cpp", 3275, __extension__ __PRETTY_FUNCTION__ )) |
3275 | "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK." ) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "clang/lib/Sema/SemaOverload.cpp", 3275, __extension__ __PRETTY_FUNCTION__ )); |
3276 | (void)DerivationOkay; |
3277 | |
3278 | if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). |
3279 | getUnqualifiedType())) { |
3280 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3281 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) |
3282 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); |
3283 | return true; |
3284 | } |
3285 | |
3286 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { |
3287 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) |
3288 | << FromClass << ToClass << QualType(VBase, 0) |
3289 | << From->getSourceRange(); |
3290 | return true; |
3291 | } |
3292 | |
3293 | if (!IgnoreBaseAccess) |
3294 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, |
3295 | Paths.front(), |
3296 | diag::err_downcast_from_inaccessible_base); |
3297 | |
3298 | // Must be a base to derived member conversion. |
3299 | BuildBasePathArray(Paths, BasePath); |
3300 | Kind = CK_BaseToDerivedMemberPointer; |
3301 | return false; |
3302 | } |
3303 | |
3304 | /// Determine whether the lifetime conversion between the two given |
3305 | /// qualifiers sets is nontrivial. |
3306 | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, |
3307 | Qualifiers ToQuals) { |
3308 | // Converting anything to const __unsafe_unretained is trivial. |
3309 | if (ToQuals.hasConst() && |
3310 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) |
3311 | return false; |
3312 | |
3313 | return true; |
3314 | } |
3315 | |
3316 | /// Perform a single iteration of the loop for checking if a qualification |
3317 | /// conversion is valid. |
3318 | /// |
3319 | /// Specifically, check whether any change between the qualifiers of \p |
3320 | /// FromType and \p ToType is permissible, given knowledge about whether every |
3321 | /// outer layer is const-qualified. |
3322 | static bool isQualificationConversionStep(QualType FromType, QualType ToType, |
3323 | bool CStyle, bool IsTopLevel, |
3324 | bool &PreviousToQualsIncludeConst, |
3325 | bool &ObjCLifetimeConversion) { |
3326 | Qualifiers FromQuals = FromType.getQualifiers(); |
3327 | Qualifiers ToQuals = ToType.getQualifiers(); |
3328 | |
3329 | // Ignore __unaligned qualifier. |
3330 | FromQuals.removeUnaligned(); |
3331 | |
3332 | // Objective-C ARC: |
3333 | // Check Objective-C lifetime conversions. |
3334 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { |
3335 | if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { |
3336 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) |
3337 | ObjCLifetimeConversion = true; |
3338 | FromQuals.removeObjCLifetime(); |
3339 | ToQuals.removeObjCLifetime(); |
3340 | } else { |
3341 | // Qualification conversions cannot cast between different |
3342 | // Objective-C lifetime qualifiers. |
3343 | return false; |
3344 | } |
3345 | } |
3346 | |
3347 | // Allow addition/removal of GC attributes but not changing GC attributes. |
3348 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && |
3349 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { |
3350 | FromQuals.removeObjCGCAttr(); |
3351 | ToQuals.removeObjCGCAttr(); |
3352 | } |
3353 | |
3354 | // -- for every j > 0, if const is in cv 1,j then const is in cv |
3355 | // 2,j, and similarly for volatile. |
3356 | if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) |
3357 | return false; |
3358 | |
3359 | // If address spaces mismatch: |
3360 | // - in top level it is only valid to convert to addr space that is a |
3361 | // superset in all cases apart from C-style casts where we allow |
3362 | // conversions between overlapping address spaces. |
3363 | // - in non-top levels it is not a valid conversion. |
3364 | if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && |
3365 | (!IsTopLevel || |
3366 | !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || |
3367 | (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) |
3368 | return false; |
3369 | |
3370 | // -- if the cv 1,j and cv 2,j are different, then const is in |
3371 | // every cv for 0 < k < j. |
3372 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && |
3373 | !PreviousToQualsIncludeConst) |
3374 | return false; |
3375 | |
3376 | // The following wording is from C++20, where the result of the conversion |
3377 | // is T3, not T2. |
3378 | // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is |
3379 | // "array of unknown bound of" |
3380 | if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) |
3381 | return false; |
3382 | |
3383 | // -- if the resulting P3,i is different from P1,i [...], then const is |
3384 | // added to every cv 3_k for 0 < k < i. |
3385 | if (!CStyle && FromType->isConstantArrayType() && |
3386 | ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) |
3387 | return false; |
3388 | |
3389 | // Keep track of whether all prior cv-qualifiers in the "to" type |
3390 | // include const. |
3391 | PreviousToQualsIncludeConst = |
3392 | PreviousToQualsIncludeConst && ToQuals.hasConst(); |
3393 | return true; |
3394 | } |
3395 | |
3396 | /// IsQualificationConversion - Determines whether the conversion from |
3397 | /// an rvalue of type FromType to ToType is a qualification conversion |
3398 | /// (C++ 4.4). |
3399 | /// |
3400 | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate |
3401 | /// when the qualification conversion involves a change in the Objective-C |
3402 | /// object lifetime. |
3403 | bool |
3404 | Sema::IsQualificationConversion(QualType FromType, QualType ToType, |
3405 | bool CStyle, bool &ObjCLifetimeConversion) { |
3406 | FromType = Context.getCanonicalType(FromType); |
3407 | ToType = Context.getCanonicalType(ToType); |
3408 | ObjCLifetimeConversion = false; |
3409 | |
3410 | // If FromType and ToType are the same type, this is not a |
3411 | // qualification conversion. |
3412 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) |
3413 | return false; |
3414 | |
3415 | // (C++ 4.4p4): |
3416 | // A conversion can add cv-qualifiers at levels other than the first |
3417 | // in multi-level pointers, subject to the following rules: [...] |
3418 | bool PreviousToQualsIncludeConst = true; |
3419 | bool UnwrappedAnyPointer = false; |
3420 | while (Context.UnwrapSimilarTypes(FromType, ToType)) { |
3421 | if (!isQualificationConversionStep( |
3422 | FromType, ToType, CStyle, !UnwrappedAnyPointer, |
3423 | PreviousToQualsIncludeConst, ObjCLifetimeConversion)) |
3424 | return false; |
3425 | UnwrappedAnyPointer = true; |
3426 | } |
3427 | |
3428 | // We are left with FromType and ToType being the pointee types |
3429 | // after unwrapping the original FromType and ToType the same number |
3430 | // of times. If we unwrapped any pointers, and if FromType and |
3431 | // ToType have the same unqualified type (since we checked |
3432 | // qualifiers above), then this is a qualification conversion. |
3433 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); |
3434 | } |
3435 | |
3436 | /// - Determine whether this is a conversion from a scalar type to an |
3437 | /// atomic type. |
3438 | /// |
3439 | /// If successful, updates \c SCS's second and third steps in the conversion |
3440 | /// sequence to finish the conversion. |
3441 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
3442 | bool InOverloadResolution, |
3443 | StandardConversionSequence &SCS, |
3444 | bool CStyle) { |
3445 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); |
3446 | if (!ToAtomic) |
3447 | return false; |
3448 | |
3449 | StandardConversionSequence InnerSCS; |
3450 | if (!IsStandardConversion(S, From, ToAtomic->getValueType(), |
3451 | InOverloadResolution, InnerSCS, |
3452 | CStyle, /*AllowObjCWritebackConversion=*/false)) |
3453 | return false; |
3454 | |
3455 | SCS.Second = InnerSCS.Second; |
3456 | SCS.setToType(1, InnerSCS.getToType(1)); |
3457 | SCS.Third = InnerSCS.Third; |
3458 | SCS.QualificationIncludesObjCLifetime |
3459 | = InnerSCS.QualificationIncludesObjCLifetime; |
3460 | SCS.setToType(2, InnerSCS.getToType(2)); |
3461 | return true; |
3462 | } |
3463 | |
3464 | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, |
3465 | CXXConstructorDecl *Constructor, |
3466 | QualType Type) { |
3467 | const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); |
3468 | if (CtorType->getNumParams() > 0) { |
3469 | QualType FirstArg = CtorType->getParamType(0); |
3470 | if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) |
3471 | return true; |
3472 | } |
3473 | return false; |
3474 | } |
3475 | |
3476 | static OverloadingResult |
3477 | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, |
3478 | CXXRecordDecl *To, |
3479 | UserDefinedConversionSequence &User, |
3480 | OverloadCandidateSet &CandidateSet, |
3481 | bool AllowExplicit) { |
3482 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3483 | for (auto *D : S.LookupConstructors(To)) { |
3484 | auto Info = getConstructorInfo(D); |
3485 | if (!Info) |
3486 | continue; |
3487 | |
3488 | bool Usable = !Info.Constructor->isInvalidDecl() && |
3489 | S.isInitListConstructor(Info.Constructor); |
3490 | if (Usable) { |
3491 | bool SuppressUserConversions = false; |
3492 | if (Info.ConstructorTmpl) |
3493 | S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, |
3494 | /*ExplicitArgs*/ nullptr, From, |
3495 | CandidateSet, SuppressUserConversions, |
3496 | /*PartialOverloading*/ false, |
3497 | AllowExplicit); |
3498 | else |
3499 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, |
3500 | CandidateSet, SuppressUserConversions, |
3501 | /*PartialOverloading*/ false, AllowExplicit); |
3502 | } |
3503 | } |
3504 | |
3505 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3506 | |
3507 | OverloadCandidateSet::iterator Best; |
3508 | switch (auto Result = |
3509 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3510 | case OR_Deleted: |
3511 | case OR_Success: { |
3512 | // Record the standard conversion we used and the conversion function. |
3513 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); |
3514 | QualType ThisType = Constructor->getThisType(); |
3515 | // Initializer lists don't have conversions as such. |
3516 | User.Before.setAsIdentityConversion(); |
3517 | User.HadMultipleCandidates = HadMultipleCandidates; |
3518 | User.ConversionFunction = Constructor; |
3519 | User.FoundConversionFunction = Best->FoundDecl; |
3520 | User.After.setAsIdentityConversion(); |
3521 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); |
3522 | User.After.setAllToTypes(ToType); |
3523 | return Result; |
3524 | } |
3525 | |
3526 | case OR_No_Viable_Function: |
3527 | return OR_No_Viable_Function; |
3528 | case OR_Ambiguous: |
3529 | return OR_Ambiguous; |
3530 | } |
3531 | |
3532 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 3532); |
3533 | } |
3534 | |
3535 | /// Determines whether there is a user-defined conversion sequence |
3536 | /// (C++ [over.ics.user]) that converts expression From to the type |
3537 | /// ToType. If such a conversion exists, User will contain the |
3538 | /// user-defined conversion sequence that performs such a conversion |
3539 | /// and this routine will return true. Otherwise, this routine returns |
3540 | /// false and User is unspecified. |
3541 | /// |
3542 | /// \param AllowExplicit true if the conversion should consider C++0x |
3543 | /// "explicit" conversion functions as well as non-explicit conversion |
3544 | /// functions (C++0x [class.conv.fct]p2). |
3545 | /// |
3546 | /// \param AllowObjCConversionOnExplicit true if the conversion should |
3547 | /// allow an extra Objective-C pointer conversion on uses of explicit |
3548 | /// constructors. Requires \c AllowExplicit to also be set. |
3549 | static OverloadingResult |
3550 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
3551 | UserDefinedConversionSequence &User, |
3552 | OverloadCandidateSet &CandidateSet, |
3553 | AllowedExplicit AllowExplicit, |
3554 | bool AllowObjCConversionOnExplicit) { |
3555 | assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit:: None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit" , "clang/lib/Sema/SemaOverload.cpp", 3556, __extension__ __PRETTY_FUNCTION__ )) |
3556 | !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit:: None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit" , "clang/lib/Sema/SemaOverload.cpp", 3556, __extension__ __PRETTY_FUNCTION__ )); |
3557 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3558 | |
3559 | // Whether we will only visit constructors. |
3560 | bool ConstructorsOnly = false; |
3561 | |
3562 | // If the type we are conversion to is a class type, enumerate its |
3563 | // constructors. |
3564 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { |
3565 | // C++ [over.match.ctor]p1: |
3566 | // When objects of class type are direct-initialized (8.5), or |
3567 | // copy-initialized from an expression of the same or a |
3568 | // derived class type (8.5), overload resolution selects the |
3569 | // constructor. [...] For copy-initialization, the candidate |
3570 | // functions are all the converting constructors (12.3.1) of |
3571 | // that class. The argument list is the expression-list within |
3572 | // the parentheses of the initializer. |
3573 | if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || |
3574 | (From->getType()->getAs<RecordType>() && |
3575 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) |
3576 | ConstructorsOnly = true; |
3577 | |
3578 | if (!S.isCompleteType(From->getExprLoc(), ToType)) { |
3579 | // We're not going to find any constructors. |
3580 | } else if (CXXRecordDecl *ToRecordDecl |
3581 | = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { |
3582 | |
3583 | Expr **Args = &From; |
3584 | unsigned NumArgs = 1; |
3585 | bool ListInitializing = false; |
3586 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { |
3587 | // But first, see if there is an init-list-constructor that will work. |
3588 | OverloadingResult Result = IsInitializerListConstructorConversion( |
3589 | S, From, ToType, ToRecordDecl, User, CandidateSet, |
3590 | AllowExplicit == AllowedExplicit::All); |
3591 | if (Result != OR_No_Viable_Function) |
3592 | return Result; |
3593 | // Never mind. |
3594 | CandidateSet.clear( |
3595 | OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3596 | |
3597 | // If we're list-initializing, we pass the individual elements as |
3598 | // arguments, not the entire list. |
3599 | Args = InitList->getInits(); |
3600 | NumArgs = InitList->getNumInits(); |
3601 | ListInitializing = true; |
3602 | } |
3603 | |
3604 | for (auto *D : S.LookupConstructors(ToRecordDecl)) { |
3605 | auto Info = getConstructorInfo(D); |
3606 | if (!Info) |
3607 | continue; |
3608 | |
3609 | bool Usable = !Info.Constructor->isInvalidDecl(); |
3610 | if (!ListInitializing) |
3611 | Usable = Usable && Info.Constructor->isConvertingConstructor( |
3612 | /*AllowExplicit*/ true); |
3613 | if (Usable) { |
3614 | bool SuppressUserConversions = !ConstructorsOnly; |
3615 | // C++20 [over.best.ics.general]/4.5: |
3616 | // if the target is the first parameter of a constructor [of class |
3617 | // X] and the constructor [...] is a candidate by [...] the second |
3618 | // phase of [over.match.list] when the initializer list has exactly |
3619 | // one element that is itself an initializer list, [...] and the |
3620 | // conversion is to X or reference to cv X, user-defined conversion |
3621 | // sequences are not cnosidered. |
3622 | if (SuppressUserConversions && ListInitializing) { |
3623 | SuppressUserConversions = |
3624 | NumArgs == 1 && isa<InitListExpr>(Args[0]) && |
3625 | isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, |
3626 | ToType); |
3627 | } |
3628 | if (Info.ConstructorTmpl) |
3629 | S.AddTemplateOverloadCandidate( |
3630 | Info.ConstructorTmpl, Info.FoundDecl, |
3631 | /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs), |
3632 | CandidateSet, SuppressUserConversions, |
3633 | /*PartialOverloading*/ false, |
3634 | AllowExplicit == AllowedExplicit::All); |
3635 | else |
3636 | // Allow one user-defined conversion when user specifies a |
3637 | // From->ToType conversion via an static cast (c-style, etc). |
3638 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, |
3639 | llvm::ArrayRef(Args, NumArgs), CandidateSet, |
3640 | SuppressUserConversions, |
3641 | /*PartialOverloading*/ false, |
3642 | AllowExplicit == AllowedExplicit::All); |
3643 | } |
3644 | } |
3645 | } |
3646 | } |
3647 | |
3648 | // Enumerate conversion functions, if we're allowed to. |
3649 | if (ConstructorsOnly || isa<InitListExpr>(From)) { |
3650 | } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { |
3651 | // No conversion functions from incomplete types. |
3652 | } else if (const RecordType *FromRecordType = |
3653 | From->getType()->getAs<RecordType>()) { |
3654 | if (CXXRecordDecl *FromRecordDecl |
3655 | = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { |
3656 | // Add all of the conversion functions as candidates. |
3657 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); |
3658 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
3659 | DeclAccessPair FoundDecl = I.getPair(); |
3660 | NamedDecl *D = FoundDecl.getDecl(); |
3661 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
3662 | if (isa<UsingShadowDecl>(D)) |
3663 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
3664 | |
3665 | CXXConversionDecl *Conv; |
3666 | FunctionTemplateDecl *ConvTemplate; |
3667 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
3668 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
3669 | else |
3670 | Conv = cast<CXXConversionDecl>(D); |
3671 | |
3672 | if (ConvTemplate) |
3673 | S.AddTemplateConversionCandidate( |
3674 | ConvTemplate, FoundDecl, ActingContext, From, ToType, |
3675 | CandidateSet, AllowObjCConversionOnExplicit, |
3676 | AllowExplicit != AllowedExplicit::None); |
3677 | else |
3678 | S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, |
3679 | CandidateSet, AllowObjCConversionOnExplicit, |
3680 | AllowExplicit != AllowedExplicit::None); |
3681 | } |
3682 | } |
3683 | } |
3684 | |
3685 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3686 | |
3687 | OverloadCandidateSet::iterator Best; |
3688 | switch (auto Result = |
3689 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3690 | case OR_Success: |
3691 | case OR_Deleted: |
3692 | // Record the standard conversion we used and the conversion function. |
3693 | if (CXXConstructorDecl *Constructor |
3694 | = dyn_cast<CXXConstructorDecl>(Best->Function)) { |
3695 | // C++ [over.ics.user]p1: |
3696 | // If the user-defined conversion is specified by a |
3697 | // constructor (12.3.1), the initial standard conversion |
3698 | // sequence converts the source type to the type required by |
3699 | // the argument of the constructor. |
3700 | // |
3701 | QualType ThisType = Constructor->getThisType(); |
3702 | if (isa<InitListExpr>(From)) { |
3703 | // Initializer lists don't have conversions as such. |
3704 | User.Before.setAsIdentityConversion(); |
3705 | } else { |
3706 | if (Best->Conversions[0].isEllipsis()) |
3707 | User.EllipsisConversion = true; |
3708 | else { |
3709 | User.Before = Best->Conversions[0].Standard; |
3710 | User.EllipsisConversion = false; |
3711 | } |
3712 | } |
3713 | User.HadMultipleCandidates = HadMultipleCandidates; |
3714 | User.ConversionFunction = Constructor; |
3715 | User.FoundConversionFunction = Best->FoundDecl; |
3716 | User.After.setAsIdentityConversion(); |
3717 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); |
3718 | User.After.setAllToTypes(ToType); |
3719 | return Result; |
3720 | } |
3721 | if (CXXConversionDecl *Conversion |
3722 | = dyn_cast<CXXConversionDecl>(Best->Function)) { |
3723 | // C++ [over.ics.user]p1: |
3724 | // |
3725 | // [...] If the user-defined conversion is specified by a |
3726 | // conversion function (12.3.2), the initial standard |
3727 | // conversion sequence converts the source type to the |
3728 | // implicit object parameter of the conversion function. |
3729 | User.Before = Best->Conversions[0].Standard; |
3730 | User.HadMultipleCandidates = HadMultipleCandidates; |
3731 | User.ConversionFunction = Conversion; |
3732 | User.FoundConversionFunction = Best->FoundDecl; |
3733 | User.EllipsisConversion = false; |
3734 | |
3735 | // C++ [over.ics.user]p2: |
3736 | // The second standard conversion sequence converts the |
3737 | // result of the user-defined conversion to the target type |
3738 | // for the sequence. Since an implicit conversion sequence |
3739 | // is an initialization, the special rules for |
3740 | // initialization by user-defined conversion apply when |
3741 | // selecting the best user-defined conversion for a |
3742 | // user-defined conversion sequence (see 13.3.3 and |
3743 | // 13.3.3.1). |
3744 | User.After = Best->FinalConversion; |
3745 | return Result; |
3746 | } |
3747 | llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?" , "clang/lib/Sema/SemaOverload.cpp", 3747); |
3748 | |
3749 | case OR_No_Viable_Function: |
3750 | return OR_No_Viable_Function; |
3751 | |
3752 | case OR_Ambiguous: |
3753 | return OR_Ambiguous; |
3754 | } |
3755 | |
3756 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 3756); |
3757 | } |
3758 | |
3759 | bool |
3760 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { |
3761 | ImplicitConversionSequence ICS; |
3762 | OverloadCandidateSet CandidateSet(From->getExprLoc(), |
3763 | OverloadCandidateSet::CSK_Normal); |
3764 | OverloadingResult OvResult = |
3765 | IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, |
3766 | CandidateSet, AllowedExplicit::None, false); |
3767 | |
3768 | if (!(OvResult == OR_Ambiguous || |
3769 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) |
3770 | return false; |
3771 | |
3772 | auto Cands = CandidateSet.CompleteCandidates( |
3773 | *this, |
3774 | OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, |
3775 | From); |
3776 | if (OvResult == OR_Ambiguous) |
3777 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) |
3778 | << From->getType() << ToType << From->getSourceRange(); |
3779 | else { // OR_No_Viable_Function && !CandidateSet.empty() |
3780 | if (!RequireCompleteType(From->getBeginLoc(), ToType, |
3781 | diag::err_typecheck_nonviable_condition_incomplete, |
3782 | From->getType(), From->getSourceRange())) |
3783 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) |
3784 | << false << From->getType() << From->getSourceRange() << ToType; |
3785 | } |
3786 | |
3787 | CandidateSet.NoteCandidates( |
3788 | *this, From, Cands); |
3789 | return true; |
3790 | } |
3791 | |
3792 | // Helper for compareConversionFunctions that gets the FunctionType that the |
3793 | // conversion-operator return value 'points' to, or nullptr. |
3794 | static const FunctionType * |
3795 | getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { |
3796 | const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); |
3797 | const PointerType *RetPtrTy = |
3798 | ConvFuncTy->getReturnType()->getAs<PointerType>(); |
3799 | |
3800 | if (!RetPtrTy) |
3801 | return nullptr; |
3802 | |
3803 | return RetPtrTy->getPointeeType()->getAs<FunctionType>(); |
3804 | } |
3805 | |
3806 | /// Compare the user-defined conversion functions or constructors |
3807 | /// of two user-defined conversion sequences to determine whether any ordering |
3808 | /// is possible. |
3809 | static ImplicitConversionSequence::CompareKind |
3810 | compareConversionFunctions(Sema &S, FunctionDecl *Function1, |
3811 | FunctionDecl *Function2) { |
3812 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); |
3813 | CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); |
3814 | if (!Conv1 || !Conv2) |
3815 | return ImplicitConversionSequence::Indistinguishable; |
3816 | |
3817 | if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) |
3818 | return ImplicitConversionSequence::Indistinguishable; |
3819 | |
3820 | // Objective-C++: |
3821 | // If both conversion functions are implicitly-declared conversions from |
3822 | // a lambda closure type to a function pointer and a block pointer, |
3823 | // respectively, always prefer the conversion to a function pointer, |
3824 | // because the function pointer is more lightweight and is more likely |
3825 | // to keep code working. |
3826 | if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { |
3827 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); |
3828 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); |
3829 | if (Block1 != Block2) |
3830 | return Block1 ? ImplicitConversionSequence::Worse |
3831 | : ImplicitConversionSequence::Better; |
3832 | } |
3833 | |
3834 | // In order to support multiple calling conventions for the lambda conversion |
3835 | // operator (such as when the free and member function calling convention is |
3836 | // different), prefer the 'free' mechanism, followed by the calling-convention |
3837 | // of operator(). The latter is in place to support the MSVC-like solution of |
3838 | // defining ALL of the possible conversions in regards to calling-convention. |
3839 | const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); |
3840 | const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); |
3841 | |
3842 | if (Conv1FuncRet && Conv2FuncRet && |
3843 | Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { |
3844 | CallingConv Conv1CC = Conv1FuncRet->getCallConv(); |
3845 | CallingConv Conv2CC = Conv2FuncRet->getCallConv(); |
3846 | |
3847 | CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); |
3848 | const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); |
3849 | |
3850 | CallingConv CallOpCC = |
3851 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
3852 | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( |
3853 | CallOpProto->isVariadic(), /*IsCXXMethod=*/false); |
3854 | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( |
3855 | CallOpProto->isVariadic(), /*IsCXXMethod=*/true); |
3856 | |
3857 | CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; |
3858 | for (CallingConv CC : PrefOrder) { |
3859 | if (Conv1CC == CC) |
3860 | return ImplicitConversionSequence::Better; |
3861 | if (Conv2CC == CC) |
3862 | return ImplicitConversionSequence::Worse; |
3863 | } |
3864 | } |
3865 | |
3866 | return ImplicitConversionSequence::Indistinguishable; |
3867 | } |
3868 | |
3869 | static bool hasDeprecatedStringLiteralToCharPtrConversion( |
3870 | const ImplicitConversionSequence &ICS) { |
3871 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || |
3872 | (ICS.isUserDefined() && |
3873 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); |
3874 | } |
3875 | |
3876 | /// CompareImplicitConversionSequences - Compare two implicit |
3877 | /// conversion sequences to determine whether one is better than the |
3878 | /// other or if they are indistinguishable (C++ 13.3.3.2). |
3879 | static ImplicitConversionSequence::CompareKind |
3880 | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, |
3881 | const ImplicitConversionSequence& ICS1, |
3882 | const ImplicitConversionSequence& ICS2) |
3883 | { |
3884 | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit |
3885 | // conversion sequences (as defined in 13.3.3.1) |
3886 | // -- a standard conversion sequence (13.3.3.1.1) is a better |
3887 | // conversion sequence than a user-defined conversion sequence or |
3888 | // an ellipsis conversion sequence, and |
3889 | // -- a user-defined conversion sequence (13.3.3.1.2) is a better |
3890 | // conversion sequence than an ellipsis conversion sequence |
3891 | // (13.3.3.1.3). |
3892 | // |
3893 | // C++0x [over.best.ics]p10: |
3894 | // For the purpose of ranking implicit conversion sequences as |
3895 | // described in 13.3.3.2, the ambiguous conversion sequence is |
3896 | // treated as a user-defined sequence that is indistinguishable |
3897 | // from any other user-defined conversion sequence. |
3898 | |
3899 | // String literal to 'char *' conversion has been deprecated in C++03. It has |
3900 | // been removed from C++11. We still accept this conversion, if it happens at |
3901 | // the best viable function. Otherwise, this conversion is considered worse |
3902 | // than ellipsis conversion. Consider this as an extension; this is not in the |
3903 | // standard. For example: |
3904 | // |
3905 | // int &f(...); // #1 |
3906 | // void f(char*); // #2 |
3907 | // void g() { int &r = f("foo"); } |
3908 | // |
3909 | // In C++03, we pick #2 as the best viable function. |
3910 | // In C++11, we pick #1 as the best viable function, because ellipsis |
3911 | // conversion is better than string-literal to char* conversion (since there |
3912 | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't |
3913 | // convert arguments, #2 would be the best viable function in C++11. |
3914 | // If the best viable function has this conversion, a warning will be issued |
3915 | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. |
3916 | |
3917 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
3918 | hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != |
3919 | hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && |
3920 | // Ill-formedness must not differ |
3921 | ICS1.isBad() == ICS2.isBad()) |
3922 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) |
3923 | ? ImplicitConversionSequence::Worse |
3924 | : ImplicitConversionSequence::Better; |
3925 | |
3926 | if (ICS1.getKindRank() < ICS2.getKindRank()) |
3927 | return ImplicitConversionSequence::Better; |
3928 | if (ICS2.getKindRank() < ICS1.getKindRank()) |
3929 | return ImplicitConversionSequence::Worse; |
3930 | |
3931 | // The following checks require both conversion sequences to be of |
3932 | // the same kind. |
3933 | if (ICS1.getKind() != ICS2.getKind()) |
3934 | return ImplicitConversionSequence::Indistinguishable; |
3935 | |
3936 | ImplicitConversionSequence::CompareKind Result = |
3937 | ImplicitConversionSequence::Indistinguishable; |
3938 | |
3939 | // Two implicit conversion sequences of the same form are |
3940 | // indistinguishable conversion sequences unless one of the |
3941 | // following rules apply: (C++ 13.3.3.2p3): |
3942 | |
3943 | // List-initialization sequence L1 is a better conversion sequence than |
3944 | // list-initialization sequence L2 if: |
3945 | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, |
3946 | // if not that, |
3947 | // — L1 and L2 convert to arrays of the same element type, and either the |
3948 | // number of elements n_1 initialized by L1 is less than the number of |
3949 | // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to |
3950 | // an array of unknown bound and L1 does not, |
3951 | // even if one of the other rules in this paragraph would otherwise apply. |
3952 | if (!ICS1.isBad()) { |
3953 | bool StdInit1 = false, StdInit2 = false; |
3954 | if (ICS1.hasInitializerListContainerType()) |
3955 | StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), |
3956 | nullptr); |
3957 | if (ICS2.hasInitializerListContainerType()) |
3958 | StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), |
3959 | nullptr); |
3960 | if (StdInit1 != StdInit2) |
3961 | return StdInit1 ? ImplicitConversionSequence::Better |
3962 | : ImplicitConversionSequence::Worse; |
3963 | |
3964 | if (ICS1.hasInitializerListContainerType() && |
3965 | ICS2.hasInitializerListContainerType()) |
3966 | if (auto *CAT1 = S.Context.getAsConstantArrayType( |
3967 | ICS1.getInitializerListContainerType())) |
3968 | if (auto *CAT2 = S.Context.getAsConstantArrayType( |
3969 | ICS2.getInitializerListContainerType())) { |
3970 | if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), |
3971 | CAT2->getElementType())) { |
3972 | // Both to arrays of the same element type |
3973 | if (CAT1->getSize() != CAT2->getSize()) |
3974 | // Different sized, the smaller wins |
3975 | return CAT1->getSize().ult(CAT2->getSize()) |
3976 | ? ImplicitConversionSequence::Better |
3977 | : ImplicitConversionSequence::Worse; |
3978 | if (ICS1.isInitializerListOfIncompleteArray() != |
3979 | ICS2.isInitializerListOfIncompleteArray()) |
3980 | // One is incomplete, it loses |
3981 | return ICS2.isInitializerListOfIncompleteArray() |
3982 | ? ImplicitConversionSequence::Better |
3983 | : ImplicitConversionSequence::Worse; |
3984 | } |
3985 | } |
3986 | } |
3987 | |
3988 | if (ICS1.isStandard()) |
3989 | // Standard conversion sequence S1 is a better conversion sequence than |
3990 | // standard conversion sequence S2 if [...] |
3991 | Result = CompareStandardConversionSequences(S, Loc, |
3992 | ICS1.Standard, ICS2.Standard); |
3993 | else if (ICS1.isUserDefined()) { |
3994 | // User-defined conversion sequence U1 is a better conversion |
3995 | // sequence than another user-defined conversion sequence U2 if |
3996 | // they contain the same user-defined conversion function or |
3997 | // constructor and if the second standard conversion sequence of |
3998 | // U1 is better than the second standard conversion sequence of |
3999 | // U2 (C++ 13.3.3.2p3). |
4000 | if (ICS1.UserDefined.ConversionFunction == |
4001 | ICS2.UserDefined.ConversionFunction) |
4002 | Result = CompareStandardConversionSequences(S, Loc, |
4003 | ICS1.UserDefined.After, |
4004 | ICS2.UserDefined.After); |
4005 | else |
4006 | Result = compareConversionFunctions(S, |
4007 | ICS1.UserDefined.ConversionFunction, |
4008 | ICS2.UserDefined.ConversionFunction); |
4009 | } |
4010 | |
4011 | return Result; |
4012 | } |
4013 | |
4014 | // Per 13.3.3.2p3, compare the given standard conversion sequences to |
4015 | // determine if one is a proper subset of the other. |
4016 | static ImplicitConversionSequence::CompareKind |
4017 | compareStandardConversionSubsets(ASTContext &Context, |
4018 | const StandardConversionSequence& SCS1, |
4019 | const StandardConversionSequence& SCS2) { |
4020 | ImplicitConversionSequence::CompareKind Result |
4021 | = ImplicitConversionSequence::Indistinguishable; |
4022 | |
4023 | // the identity conversion sequence is considered to be a subsequence of |
4024 | // any non-identity conversion sequence |
4025 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) |
4026 | return ImplicitConversionSequence::Better; |
4027 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) |
4028 | return ImplicitConversionSequence::Worse; |
4029 | |
4030 | if (SCS1.Second != SCS2.Second) { |
4031 | if (SCS1.Second == ICK_Identity) |
4032 | Result = ImplicitConversionSequence::Better; |
4033 | else if (SCS2.Second == ICK_Identity) |
4034 | Result = ImplicitConversionSequence::Worse; |
4035 | else |
4036 | return ImplicitConversionSequence::Indistinguishable; |
4037 | } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) |
4038 | return ImplicitConversionSequence::Indistinguishable; |
4039 | |
4040 | if (SCS1.Third == SCS2.Third) { |
4041 | return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result |
4042 | : ImplicitConversionSequence::Indistinguishable; |
4043 | } |
4044 | |
4045 | if (SCS1.Third == ICK_Identity) |
4046 | return Result == ImplicitConversionSequence::Worse |
4047 | ? ImplicitConversionSequence::Indistinguishable |
4048 | : ImplicitConversionSequence::Better; |
4049 | |
4050 | if (SCS2.Third == ICK_Identity) |
4051 | return Result == ImplicitConversionSequence::Better |
4052 | ? ImplicitConversionSequence::Indistinguishable |
4053 | : ImplicitConversionSequence::Worse; |
4054 | |
4055 | return ImplicitConversionSequence::Indistinguishable; |
4056 | } |
4057 | |
4058 | /// Determine whether one of the given reference bindings is better |
4059 | /// than the other based on what kind of bindings they are. |
4060 | static bool |
4061 | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, |
4062 | const StandardConversionSequence &SCS2) { |
4063 | // C++0x [over.ics.rank]p3b4: |
4064 | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an |
4065 | // implicit object parameter of a non-static member function declared |
4066 | // without a ref-qualifier, and *either* S1 binds an rvalue reference |
4067 | // to an rvalue and S2 binds an lvalue reference *or S1 binds an |
4068 | // lvalue reference to a function lvalue and S2 binds an rvalue |
4069 | // reference*. |
4070 | // |
4071 | // FIXME: Rvalue references. We're going rogue with the above edits, |
4072 | // because the semantics in the current C++0x working paper (N3225 at the |
4073 | // time of this writing) break the standard definition of std::forward |
4074 | // and std::reference_wrapper when dealing with references to functions. |
4075 | // Proposed wording changes submitted to CWG for consideration. |
4076 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || |
4077 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) |
4078 | return false; |
4079 | |
4080 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && |
4081 | SCS2.IsLvalueReference) || |
4082 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && |
4083 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); |
4084 | } |
4085 | |
4086 | enum class FixedEnumPromotion { |
4087 | None, |
4088 | ToUnderlyingType, |
4089 | ToPromotedUnderlyingType |
4090 | }; |
4091 | |
4092 | /// Returns kind of fixed enum promotion the \a SCS uses. |
4093 | static FixedEnumPromotion |
4094 | getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { |
4095 | |
4096 | if (SCS.Second != ICK_Integral_Promotion) |
4097 | return FixedEnumPromotion::None; |
4098 | |
4099 | QualType FromType = SCS.getFromType(); |
4100 | if (!FromType->isEnumeralType()) |
4101 | return FixedEnumPromotion::None; |
4102 | |
4103 | EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); |
4104 | if (!Enum->isFixed()) |
4105 | return FixedEnumPromotion::None; |
4106 | |
4107 | QualType UnderlyingType = Enum->getIntegerType(); |
4108 | if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) |
4109 | return FixedEnumPromotion::ToUnderlyingType; |
4110 | |
4111 | return FixedEnumPromotion::ToPromotedUnderlyingType; |
4112 | } |
4113 | |
4114 | /// CompareStandardConversionSequences - Compare two standard |
4115 | /// conversion sequences to determine whether one is better than the |
4116 | /// other or if they are indistinguishable (C++ 13.3.3.2p3). |
4117 | static ImplicitConversionSequence::CompareKind |
4118 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
4119 | const StandardConversionSequence& SCS1, |
4120 | const StandardConversionSequence& SCS2) |
4121 | { |
4122 | // Standard conversion sequence S1 is a better conversion sequence |
4123 | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): |
4124 | |
4125 | // -- S1 is a proper subsequence of S2 (comparing the conversion |
4126 | // sequences in the canonical form defined by 13.3.3.1.1, |
4127 | // excluding any Lvalue Transformation; the identity conversion |
4128 | // sequence is considered to be a subsequence of any |
4129 | // non-identity conversion sequence) or, if not that, |
4130 | if (ImplicitConversionSequence::CompareKind CK |
4131 | = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) |
4132 | return CK; |
4133 | |
4134 | // -- the rank of S1 is better than the rank of S2 (by the rules |
4135 | // defined below), or, if not that, |
4136 | ImplicitConversionRank Rank1 = SCS1.getRank(); |
4137 | ImplicitConversionRank Rank2 = SCS2.getRank(); |
4138 | if (Rank1 < Rank2) |
4139 | return ImplicitConversionSequence::Better; |
4140 | else if (Rank2 < Rank1) |
4141 | return ImplicitConversionSequence::Worse; |
4142 | |
4143 | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank |
4144 | // are indistinguishable unless one of the following rules |
4145 | // applies: |
4146 | |
4147 | // A conversion that is not a conversion of a pointer, or |
4148 | // pointer to member, to bool is better than another conversion |
4149 | // that is such a conversion. |
4150 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) |
4151 | return SCS2.isPointerConversionToBool() |
4152 | ? ImplicitConversionSequence::Better |
4153 | : ImplicitConversionSequence::Worse; |
4154 | |
4155 | // C++14 [over.ics.rank]p4b2: |
4156 | // This is retroactively applied to C++11 by CWG 1601. |
4157 | // |
4158 | // A conversion that promotes an enumeration whose underlying type is fixed |
4159 | // to its underlying type is better than one that promotes to the promoted |
4160 | // underlying type, if the two are different. |
4161 | FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); |
4162 | FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); |
4163 | if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && |
4164 | FEP1 != FEP2) |
4165 | return FEP1 == FixedEnumPromotion::ToUnderlyingType |
4166 | ? ImplicitConversionSequence::Better |
4167 | : ImplicitConversionSequence::Worse; |
4168 | |
4169 | // C++ [over.ics.rank]p4b2: |
4170 | // |
4171 | // If class B is derived directly or indirectly from class A, |
4172 | // conversion of B* to A* is better than conversion of B* to |
4173 | // void*, and conversion of A* to void* is better than conversion |
4174 | // of B* to void*. |
4175 | bool SCS1ConvertsToVoid |
4176 | = SCS1.isPointerConversionToVoidPointer(S.Context); |
4177 | bool SCS2ConvertsToVoid |
4178 | = SCS2.isPointerConversionToVoidPointer(S.Context); |
4179 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { |
4180 | // Exactly one of the conversion sequences is a conversion to |
4181 | // a void pointer; it's the worse conversion. |
4182 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better |
4183 | : ImplicitConversionSequence::Worse; |
4184 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { |
4185 | // Neither conversion sequence converts to a void pointer; compare |
4186 | // their derived-to-base conversions. |
4187 | if (ImplicitConversionSequence::CompareKind DerivedCK |
4188 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) |
4189 | return DerivedCK; |
4190 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && |
4191 | !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { |
4192 | // Both conversion sequences are conversions to void |
4193 | // pointers. Compare the source types to determine if there's an |
4194 | // inheritance relationship in their sources. |
4195 | QualType FromType1 = SCS1.getFromType(); |
4196 | QualType FromType2 = SCS2.getFromType(); |
4197 | |
4198 | // Adjust the types we're converting from via the array-to-pointer |
4199 | // conversion, if we need to. |
4200 | if (SCS1.First == ICK_Array_To_Pointer) |
4201 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
4202 | if (SCS2.First == ICK_Array_To_Pointer) |
4203 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
4204 | |
4205 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); |
4206 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); |
4207 | |
4208 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4209 | return ImplicitConversionSequence::Better; |
4210 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4211 | return ImplicitConversionSequence::Worse; |
4212 | |
4213 | // Objective-C++: If one interface is more specific than the |
4214 | // other, it is the better one. |
4215 | const ObjCObjectPointerType* FromObjCPtr1 |
4216 | = FromType1->getAs<ObjCObjectPointerType>(); |
4217 | const ObjCObjectPointerType* FromObjCPtr2 |
4218 | = FromType2->getAs<ObjCObjectPointerType>(); |
4219 | if (FromObjCPtr1 && FromObjCPtr2) { |
4220 | bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, |
4221 | FromObjCPtr2); |
4222 | bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, |
4223 | FromObjCPtr1); |
4224 | if (AssignLeft != AssignRight) { |
4225 | return AssignLeft? ImplicitConversionSequence::Better |
4226 | : ImplicitConversionSequence::Worse; |
4227 | } |
4228 | } |
4229 | } |
4230 | |
4231 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4232 | // Check for a better reference binding based on the kind of bindings. |
4233 | if (isBetterReferenceBindingKind(SCS1, SCS2)) |
4234 | return ImplicitConversionSequence::Better; |
4235 | else if (isBetterReferenceBindingKind(SCS2, SCS1)) |
4236 | return ImplicitConversionSequence::Worse; |
4237 | } |
4238 | |
4239 | // Compare based on qualification conversions (C++ 13.3.3.2p3, |
4240 | // bullet 3). |
4241 | if (ImplicitConversionSequence::CompareKind QualCK |
4242 | = CompareQualificationConversions(S, SCS1, SCS2)) |
4243 | return QualCK; |
4244 | |
4245 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4246 | // C++ [over.ics.rank]p3b4: |
4247 | // -- S1 and S2 are reference bindings (8.5.3), and the types to |
4248 | // which the references refer are the same type except for |
4249 | // top-level cv-qualifiers, and the type to which the reference |
4250 | // initialized by S2 refers is more cv-qualified than the type |
4251 | // to which the reference initialized by S1 refers. |
4252 | QualType T1 = SCS1.getToType(2); |
4253 | QualType T2 = SCS2.getToType(2); |
4254 | T1 = S.Context.getCanonicalType(T1); |
4255 | T2 = S.Context.getCanonicalType(T2); |
4256 | Qualifiers T1Quals, T2Quals; |
4257 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
4258 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
4259 | if (UnqualT1 == UnqualT2) { |
4260 | // Objective-C++ ARC: If the references refer to objects with different |
4261 | // lifetimes, prefer bindings that don't change lifetime. |
4262 | if (SCS1.ObjCLifetimeConversionBinding != |
4263 | SCS2.ObjCLifetimeConversionBinding) { |
4264 | return SCS1.ObjCLifetimeConversionBinding |
4265 | ? ImplicitConversionSequence::Worse |
4266 | : ImplicitConversionSequence::Better; |
4267 | } |
4268 | |
4269 | // If the type is an array type, promote the element qualifiers to the |
4270 | // type for comparison. |
4271 | if (isa<ArrayType>(T1) && T1Quals) |
4272 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); |
4273 | if (isa<ArrayType>(T2) && T2Quals) |
4274 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); |
4275 | if (T2.isMoreQualifiedThan(T1)) |
4276 | return ImplicitConversionSequence::Better; |
4277 | if (T1.isMoreQualifiedThan(T2)) |
4278 | return ImplicitConversionSequence::Worse; |
4279 | } |
4280 | } |
4281 | |
4282 | // In Microsoft mode (below 19.28), prefer an integral conversion to a |
4283 | // floating-to-integral conversion if the integral conversion |
4284 | // is between types of the same size. |
4285 | // For example: |
4286 | // void f(float); |
4287 | // void f(int); |
4288 | // int main { |
4289 | // long a; |
4290 | // f(a); |
4291 | // } |
4292 | // Here, MSVC will call f(int) instead of generating a compile error |
4293 | // as clang will do in standard mode. |
4294 | if (S.getLangOpts().MSVCCompat && |
4295 | !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && |
4296 | SCS1.Second == ICK_Integral_Conversion && |
4297 | SCS2.Second == ICK_Floating_Integral && |
4298 | S.Context.getTypeSize(SCS1.getFromType()) == |
4299 | S.Context.getTypeSize(SCS1.getToType(2))) |
4300 | return ImplicitConversionSequence::Better; |
4301 | |
4302 | // Prefer a compatible vector conversion over a lax vector conversion |
4303 | // For example: |
4304 | // |
4305 | // typedef float __v4sf __attribute__((__vector_size__(16))); |
4306 | // void f(vector float); |
4307 | // void f(vector signed int); |
4308 | // int main() { |
4309 | // __v4sf a; |
4310 | // f(a); |
4311 | // } |
4312 | // Here, we'd like to choose f(vector float) and not |
4313 | // report an ambiguous call error |
4314 | if (SCS1.Second == ICK_Vector_Conversion && |
4315 | SCS2.Second == ICK_Vector_Conversion) { |
4316 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4317 | SCS1.getFromType(), SCS1.getToType(2)); |
4318 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4319 | SCS2.getFromType(), SCS2.getToType(2)); |
4320 | |
4321 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) |
4322 | return SCS1IsCompatibleVectorConversion |
4323 | ? ImplicitConversionSequence::Better |
4324 | : ImplicitConversionSequence::Worse; |
4325 | } |
4326 | |
4327 | if (SCS1.Second == ICK_SVE_Vector_Conversion && |
4328 | SCS2.Second == ICK_SVE_Vector_Conversion) { |
4329 | bool SCS1IsCompatibleSVEVectorConversion = |
4330 | S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); |
4331 | bool SCS2IsCompatibleSVEVectorConversion = |
4332 | S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); |
4333 | |
4334 | if (SCS1IsCompatibleSVEVectorConversion != |
4335 | SCS2IsCompatibleSVEVectorConversion) |
4336 | return SCS1IsCompatibleSVEVectorConversion |
4337 | ? ImplicitConversionSequence::Better |
4338 | : ImplicitConversionSequence::Worse; |
4339 | } |
4340 | |
4341 | if (SCS1.Second == ICK_RVV_Vector_Conversion && |
4342 | SCS2.Second == ICK_RVV_Vector_Conversion) { |
4343 | bool SCS1IsCompatibleRVVVectorConversion = |
4344 | S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2)); |
4345 | bool SCS2IsCompatibleRVVVectorConversion = |
4346 | S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2)); |
4347 | |
4348 | if (SCS1IsCompatibleRVVVectorConversion != |
4349 | SCS2IsCompatibleRVVVectorConversion) |
4350 | return SCS1IsCompatibleRVVVectorConversion |
4351 | ? ImplicitConversionSequence::Better |
4352 | : ImplicitConversionSequence::Worse; |
4353 | } |
4354 | |
4355 | return ImplicitConversionSequence::Indistinguishable; |
4356 | } |
4357 | |
4358 | /// CompareQualificationConversions - Compares two standard conversion |
4359 | /// sequences to determine whether they can be ranked based on their |
4360 | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). |
4361 | static ImplicitConversionSequence::CompareKind |
4362 | CompareQualificationConversions(Sema &S, |
4363 | const StandardConversionSequence& SCS1, |
4364 | const StandardConversionSequence& SCS2) { |
4365 | // C++ [over.ics.rank]p3: |
4366 | // -- S1 and S2 differ only in their qualification conversion and |
4367 | // yield similar types T1 and T2 (C++ 4.4), respectively, [...] |
4368 | // [C++98] |
4369 | // [...] and the cv-qualification signature of type T1 is a proper subset |
4370 | // of the cv-qualification signature of type T2, and S1 is not the |
4371 | // deprecated string literal array-to-pointer conversion (4.2). |
4372 | // [C++2a] |
4373 | // [...] where T1 can be converted to T2 by a qualification conversion. |
4374 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || |
4375 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) |
4376 | return ImplicitConversionSequence::Indistinguishable; |
4377 | |
4378 | // FIXME: the example in the standard doesn't use a qualification |
4379 | // conversion (!) |
4380 | QualType T1 = SCS1.getToType(2); |
4381 | QualType T2 = SCS2.getToType(2); |
4382 | T1 = S.Context.getCanonicalType(T1); |
4383 | T2 = S.Context.getCanonicalType(T2); |
4384 | assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() && !T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()" , "clang/lib/Sema/SemaOverload.cpp", 4384, __extension__ __PRETTY_FUNCTION__ )); |
4385 | Qualifiers T1Quals, T2Quals; |
4386 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
4387 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
4388 | |
4389 | // If the types are the same, we won't learn anything by unwrapping |
4390 | // them. |
4391 | if (UnqualT1 == UnqualT2) |
4392 | return ImplicitConversionSequence::Indistinguishable; |
4393 | |
4394 | // Don't ever prefer a standard conversion sequence that uses the deprecated |
4395 | // string literal array to pointer conversion. |
4396 | bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; |
4397 | bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; |
4398 | |
4399 | // Objective-C++ ARC: |
4400 | // Prefer qualification conversions not involving a change in lifetime |
4401 | // to qualification conversions that do change lifetime. |
4402 | if (SCS1.QualificationIncludesObjCLifetime && |
4403 | !SCS2.QualificationIncludesObjCLifetime) |
4404 | CanPick1 = false; |
4405 | if (SCS2.QualificationIncludesObjCLifetime && |
4406 | !SCS1.QualificationIncludesObjCLifetime) |
4407 | CanPick2 = false; |
4408 | |
4409 | bool ObjCLifetimeConversion; |
4410 | if (CanPick1 && |
4411 | !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) |
4412 | CanPick1 = false; |
4413 | // FIXME: In Objective-C ARC, we can have qualification conversions in both |
4414 | // directions, so we can't short-cut this second check in general. |
4415 | if (CanPick2 && |
4416 | !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) |
4417 | CanPick2 = false; |
4418 | |
4419 | if (CanPick1 != CanPick2) |
4420 | return CanPick1 ? ImplicitConversionSequence::Better |
4421 | : ImplicitConversionSequence::Worse; |
4422 | return ImplicitConversionSequence::Indistinguishable; |
4423 | } |
4424 | |
4425 | /// CompareDerivedToBaseConversions - Compares two standard conversion |
4426 | /// sequences to determine whether they can be ranked based on their |
4427 | /// various kinds of derived-to-base conversions (C++ |
4428 | /// [over.ics.rank]p4b3). As part of these checks, we also look at |
4429 | /// conversions between Objective-C interface types. |
4430 | static ImplicitConversionSequence::CompareKind |
4431 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
4432 | const StandardConversionSequence& SCS1, |
4433 | const StandardConversionSequence& SCS2) { |
4434 | QualType FromType1 = SCS1.getFromType(); |
4435 | QualType ToType1 = SCS1.getToType(1); |
4436 | QualType FromType2 = SCS2.getFromType(); |
4437 | QualType ToType2 = SCS2.getToType(1); |
4438 | |
4439 | // Adjust the types we're converting from via the array-to-pointer |
4440 | // conversion, if we need to. |
4441 | if (SCS1.First == ICK_Array_To_Pointer) |
4442 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
4443 | if (SCS2.First == ICK_Array_To_Pointer) |
4444 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
4445 | |
4446 | // Canonicalize all of the types. |
4447 | FromType1 = S.Context.getCanonicalType(FromType1); |
4448 | ToType1 = S.Context.getCanonicalType(ToType1); |
4449 | FromType2 = S.Context.getCanonicalType(FromType2); |
4450 | ToType2 = S.Context.getCanonicalType(ToType2); |
4451 | |
4452 | // C++ [over.ics.rank]p4b3: |
4453 | // |
4454 | // If class B is derived directly or indirectly from class A and |
4455 | // class C is derived directly or indirectly from B, |
4456 | // |
4457 | // Compare based on pointer conversions. |
4458 | if (SCS1.Second == ICK_Pointer_Conversion && |
4459 | SCS2.Second == ICK_Pointer_Conversion && |
4460 | /*FIXME: Remove if Objective-C id conversions get their own rank*/ |
4461 | FromType1->isPointerType() && FromType2->isPointerType() && |
4462 | ToType1->isPointerType() && ToType2->isPointerType()) { |
4463 | QualType FromPointee1 = |
4464 | FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4465 | QualType ToPointee1 = |
4466 | ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4467 | QualType FromPointee2 = |
4468 | FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4469 | QualType ToPointee2 = |
4470 | ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4471 | |
4472 | // -- conversion of C* to B* is better than conversion of C* to A*, |
4473 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4474 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4475 | return ImplicitConversionSequence::Better; |
4476 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4477 | return ImplicitConversionSequence::Worse; |
4478 | } |
4479 | |
4480 | // -- conversion of B* to A* is better than conversion of C* to A*, |
4481 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { |
4482 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4483 | return ImplicitConversionSequence::Better; |
4484 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4485 | return ImplicitConversionSequence::Worse; |
4486 | } |
4487 | } else if (SCS1.Second == ICK_Pointer_Conversion && |
4488 | SCS2.Second == ICK_Pointer_Conversion) { |
4489 | const ObjCObjectPointerType *FromPtr1 |
4490 | = FromType1->getAs<ObjCObjectPointerType>(); |
4491 | const ObjCObjectPointerType *FromPtr2 |
4492 | = FromType2->getAs<ObjCObjectPointerType>(); |
4493 | const ObjCObjectPointerType *ToPtr1 |
4494 | = ToType1->getAs<ObjCObjectPointerType>(); |
4495 | const ObjCObjectPointerType *ToPtr2 |
4496 | = ToType2->getAs<ObjCObjectPointerType>(); |
4497 | |
4498 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { |
4499 | // Apply the same conversion ranking rules for Objective-C pointer types |
4500 | // that we do for C++ pointers to class types. However, we employ the |
4501 | // Objective-C pseudo-subtyping relationship used for assignment of |
4502 | // Objective-C pointer types. |
4503 | bool FromAssignLeft |
4504 | = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); |
4505 | bool FromAssignRight |
4506 | = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); |
4507 | bool ToAssignLeft |
4508 | = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); |
4509 | bool ToAssignRight |
4510 | = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); |
4511 | |
4512 | // A conversion to an a non-id object pointer type or qualified 'id' |
4513 | // type is better than a conversion to 'id'. |
4514 | if (ToPtr1->isObjCIdType() && |
4515 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) |
4516 | return ImplicitConversionSequence::Worse; |
4517 | if (ToPtr2->isObjCIdType() && |
4518 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) |
4519 | return ImplicitConversionSequence::Better; |
4520 | |
4521 | // A conversion to a non-id object pointer type is better than a |
4522 | // conversion to a qualified 'id' type |
4523 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) |
4524 | return ImplicitConversionSequence::Worse; |
4525 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) |
4526 | return ImplicitConversionSequence::Better; |
4527 | |
4528 | // A conversion to an a non-Class object pointer type or qualified 'Class' |
4529 | // type is better than a conversion to 'Class'. |
4530 | if (ToPtr1->isObjCClassType() && |
4531 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) |
4532 | return ImplicitConversionSequence::Worse; |
4533 | if (ToPtr2->isObjCClassType() && |
4534 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) |
4535 | return ImplicitConversionSequence::Better; |
4536 | |
4537 | // A conversion to a non-Class object pointer type is better than a |
4538 | // conversion to a qualified 'Class' type. |
4539 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) |
4540 | return ImplicitConversionSequence::Worse; |
4541 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) |
4542 | return ImplicitConversionSequence::Better; |
4543 | |
4544 | // -- "conversion of C* to B* is better than conversion of C* to A*," |
4545 | if (S.Context.hasSameType(FromType1, FromType2) && |
4546 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && |
4547 | (ToAssignLeft != ToAssignRight)) { |
4548 | if (FromPtr1->isSpecialized()) { |
4549 | // "conversion of B<A> * to B * is better than conversion of B * to |
4550 | // C *. |
4551 | bool IsFirstSame = |
4552 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); |
4553 | bool IsSecondSame = |
4554 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); |
4555 | if (IsFirstSame) { |
4556 | if (!IsSecondSame) |
4557 | return ImplicitConversionSequence::Better; |
4558 | } else if (IsSecondSame) |
4559 | return ImplicitConversionSequence::Worse; |
4560 | } |
4561 | return ToAssignLeft? ImplicitConversionSequence::Worse |
4562 | : ImplicitConversionSequence::Better; |
4563 | } |
4564 | |
4565 | // -- "conversion of B* to A* is better than conversion of C* to A*," |
4566 | if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && |
4567 | (FromAssignLeft != FromAssignRight)) |
4568 | return FromAssignLeft? ImplicitConversionSequence::Better |
4569 | : ImplicitConversionSequence::Worse; |
4570 | } |
4571 | } |
4572 | |
4573 | // Ranking of member-pointer types. |
4574 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && |
4575 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && |
4576 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { |
4577 | const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); |
4578 | const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); |
4579 | const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); |
4580 | const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); |
4581 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); |
4582 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); |
4583 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); |
4584 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); |
4585 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); |
4586 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); |
4587 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); |
4588 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); |
4589 | // conversion of A::* to B::* is better than conversion of A::* to C::*, |
4590 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4591 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4592 | return ImplicitConversionSequence::Worse; |
4593 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4594 | return ImplicitConversionSequence::Better; |
4595 | } |
4596 | // conversion of B::* to C::* is better than conversion of A::* to C::* |
4597 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { |
4598 | if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4599 | return ImplicitConversionSequence::Better; |
4600 | else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4601 | return ImplicitConversionSequence::Worse; |
4602 | } |
4603 | } |
4604 | |
4605 | if (SCS1.Second == ICK_Derived_To_Base) { |
4606 | // -- conversion of C to B is better than conversion of C to A, |
4607 | // -- binding of an expression of type C to a reference of type |
4608 | // B& is better than binding an expression of type C to a |
4609 | // reference of type A&, |
4610 | if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4611 | !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4612 | if (S.IsDerivedFrom(Loc, ToType1, ToType2)) |
4613 | return ImplicitConversionSequence::Better; |
4614 | else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) |
4615 | return ImplicitConversionSequence::Worse; |
4616 | } |
4617 | |
4618 | // -- conversion of B to A is better than conversion of C to A. |
4619 | // -- binding of an expression of type B to a reference of type |
4620 | // A& is better than binding an expression of type C to a |
4621 | // reference of type A&, |
4622 | if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4623 | S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4624 | if (S.IsDerivedFrom(Loc, FromType2, FromType1)) |
4625 | return ImplicitConversionSequence::Better; |
4626 | else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) |
4627 | return ImplicitConversionSequence::Worse; |
4628 | } |
4629 | } |
4630 | |
4631 | return ImplicitConversionSequence::Indistinguishable; |
4632 | } |
4633 | |
4634 | static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { |
4635 | if (!T.getQualifiers().hasUnaligned()) |
4636 | return T; |
4637 | |
4638 | Qualifiers Q; |
4639 | T = Ctx.getUnqualifiedArrayType(T, Q); |
4640 | Q.removeUnaligned(); |
4641 | return Ctx.getQualifiedType(T, Q); |
4642 | } |
4643 | |
4644 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to |
4645 | /// determine whether they are reference-compatible, |
4646 | /// reference-related, or incompatible, for use in C++ initialization by |
4647 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference |
4648 | /// type, and the first type (T1) is the pointee type of the reference |
4649 | /// type being initialized. |
4650 | Sema::ReferenceCompareResult |
4651 | Sema::CompareReferenceRelationship(SourceLocation Loc, |
4652 | QualType OrigT1, QualType OrigT2, |
4653 | ReferenceConversions *ConvOut) { |
4654 | assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type") ? void ( 0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4655, __extension__ __PRETTY_FUNCTION__ )) |
4655 | "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type") ? void ( 0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4655, __extension__ __PRETTY_FUNCTION__ )); |
4656 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() && "T2 cannot be a reference type") ? void (0) : __assert_fail ( "!OrigT2->isReferenceType() && \"T2 cannot be a reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4656, __extension__ __PRETTY_FUNCTION__ )); |
4657 | |
4658 | QualType T1 = Context.getCanonicalType(OrigT1); |
4659 | QualType T2 = Context.getCanonicalType(OrigT2); |
4660 | Qualifiers T1Quals, T2Quals; |
4661 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); |
4662 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); |
4663 | |
4664 | ReferenceConversions ConvTmp; |
4665 | ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; |
4666 | Conv = ReferenceConversions(); |
4667 | |
4668 | // C++2a [dcl.init.ref]p4: |
4669 | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is |
4670 | // reference-related to "cv2 T2" if T1 is similar to T2, or |
4671 | // T1 is a base class of T2. |
4672 | // "cv1 T1" is reference-compatible with "cv2 T2" if |
4673 | // a prvalue of type "pointer to cv2 T2" can be converted to the type |
4674 | // "pointer to cv1 T1" via a standard conversion sequence. |
4675 | |
4676 | // Check for standard conversions we can apply to pointers: derived-to-base |
4677 | // conversions, ObjC pointer conversions, and function pointer conversions. |
4678 | // (Qualification conversions are checked last.) |
4679 | QualType ConvertedT2; |
4680 | if (UnqualT1 == UnqualT2) { |
4681 | // Nothing to do. |
4682 | } else if (isCompleteType(Loc, OrigT2) && |
4683 | IsDerivedFrom(Loc, UnqualT2, UnqualT1)) |
4684 | Conv |= ReferenceConversions::DerivedToBase; |
4685 | else if (UnqualT1->isObjCObjectOrInterfaceType() && |
4686 | UnqualT2->isObjCObjectOrInterfaceType() && |
4687 | Context.canBindObjCObjectType(UnqualT1, UnqualT2)) |
4688 | Conv |= ReferenceConversions::ObjC; |
4689 | else if (UnqualT2->isFunctionType() && |
4690 | IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { |
4691 | Conv |= ReferenceConversions::Function; |
4692 | // No need to check qualifiers; function types don't have them. |
4693 | return Ref_Compatible; |
4694 | } |
4695 | bool ConvertedReferent = Conv != 0; |
4696 | |
4697 | // We can have a qualification conversion. Compute whether the types are |
4698 | // similar at the same time. |
4699 | bool PreviousToQualsIncludeConst = true; |
4700 | bool TopLevel = true; |
4701 | do { |
4702 | if (T1 == T2) |
4703 | break; |
4704 | |
4705 | // We will need a qualification conversion. |
4706 | Conv |= ReferenceConversions::Qualification; |
4707 | |
4708 | // Track whether we performed a qualification conversion anywhere other |
4709 | // than the top level. This matters for ranking reference bindings in |
4710 | // overload resolution. |
4711 | if (!TopLevel) |
4712 | Conv |= ReferenceConversions::NestedQualification; |
4713 | |
4714 | // MS compiler ignores __unaligned qualifier for references; do the same. |
4715 | T1 = withoutUnaligned(Context, T1); |
4716 | T2 = withoutUnaligned(Context, T2); |
4717 | |
4718 | // If we find a qualifier mismatch, the types are not reference-compatible, |
4719 | // but are still be reference-related if they're similar. |
4720 | bool ObjCLifetimeConversion = false; |
4721 | if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, |
4722 | PreviousToQualsIncludeConst, |
4723 | ObjCLifetimeConversion)) |
4724 | return (ConvertedReferent || Context.hasSimilarType(T1, T2)) |
4725 | ? Ref_Related |
4726 | : Ref_Incompatible; |
4727 | |
4728 | // FIXME: Should we track this for any level other than the first? |
4729 | if (ObjCLifetimeConversion) |
4730 | Conv |= ReferenceConversions::ObjCLifetime; |
4731 | |
4732 | TopLevel = false; |
4733 | } while (Context.UnwrapSimilarTypes(T1, T2)); |
4734 | |
4735 | // At this point, if the types are reference-related, we must either have the |
4736 | // same inner type (ignoring qualifiers), or must have already worked out how |
4737 | // to convert the referent. |
4738 | return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) |
4739 | ? Ref_Compatible |
4740 | : Ref_Incompatible; |
4741 | } |
4742 | |
4743 | /// Look for a user-defined conversion to a value reference-compatible |
4744 | /// with DeclType. Return true if something definite is found. |
4745 | static bool |
4746 | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, |
4747 | QualType DeclType, SourceLocation DeclLoc, |
4748 | Expr *Init, QualType T2, bool AllowRvalues, |
4749 | bool AllowExplicit) { |
4750 | assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types." ) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\"" , "clang/lib/Sema/SemaOverload.cpp", 4750, __extension__ __PRETTY_FUNCTION__ )); |
4751 | auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); |
4752 | |
4753 | OverloadCandidateSet CandidateSet( |
4754 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
4755 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
4756 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4757 | NamedDecl *D = *I; |
4758 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4759 | if (isa<UsingShadowDecl>(D)) |
4760 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
4761 | |
4762 | FunctionTemplateDecl *ConvTemplate |
4763 | = dyn_cast<FunctionTemplateDecl>(D); |
4764 | CXXConversionDecl *Conv; |
4765 | if (ConvTemplate) |
4766 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
4767 | else |
4768 | Conv = cast<CXXConversionDecl>(D); |
4769 | |
4770 | if (AllowRvalues) { |
4771 | // If we are initializing an rvalue reference, don't permit conversion |
4772 | // functions that return lvalues. |
4773 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { |
4774 | const ReferenceType *RefType |
4775 | = Conv->getConversionType()->getAs<LValueReferenceType>(); |
4776 | if (RefType && !RefType->getPointeeType()->isFunctionType()) |
4777 | continue; |
4778 | } |
4779 | |
4780 | if (!ConvTemplate && |
4781 | S.CompareReferenceRelationship( |
4782 | DeclLoc, |
4783 | Conv->getConversionType() |
4784 | .getNonReferenceType() |
4785 | .getUnqualifiedType(), |
4786 | DeclType.getNonReferenceType().getUnqualifiedType()) == |
4787 | Sema::Ref_Incompatible) |
4788 | continue; |
4789 | } else { |
4790 | // If the conversion function doesn't return a reference type, |
4791 | // it can't be considered for this conversion. An rvalue reference |
4792 | // is only acceptable if its referencee is a function type. |
4793 | |
4794 | const ReferenceType *RefType = |
4795 | Conv->getConversionType()->getAs<ReferenceType>(); |
4796 | if (!RefType || |
4797 | (!RefType->isLValueReferenceType() && |
4798 | !RefType->getPointeeType()->isFunctionType())) |
4799 | continue; |
4800 | } |
4801 | |
4802 | if (ConvTemplate) |
4803 | S.AddTemplateConversionCandidate( |
4804 | ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4805 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4806 | else |
4807 | S.AddConversionCandidate( |
4808 | Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4809 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4810 | } |
4811 | |
4812 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4813 | |
4814 | OverloadCandidateSet::iterator Best; |
4815 | switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { |
4816 | case OR_Success: |
4817 | // C++ [over.ics.ref]p1: |
4818 | // |
4819 | // [...] If the parameter binds directly to the result of |
4820 | // applying a conversion function to the argument |
4821 | // expression, the implicit conversion sequence is a |
4822 | // user-defined conversion sequence (13.3.3.1.2), with the |
4823 | // second standard conversion sequence either an identity |
4824 | // conversion or, if the conversion function returns an |
4825 | // entity of a type that is a derived class of the parameter |
4826 | // type, a derived-to-base Conversion. |
4827 | if (!Best->FinalConversion.DirectBinding) |
4828 | return false; |
4829 | |
4830 | ICS.setUserDefined(); |
4831 | ICS.UserDefined.Before = Best->Conversions[0].Standard; |
4832 | ICS.UserDefined.After = Best->FinalConversion; |
4833 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; |
4834 | ICS.UserDefined.ConversionFunction = Best->Function; |
4835 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; |
4836 | ICS.UserDefined.EllipsisConversion = false; |
4837 | assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__ )) |
4838 | ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__ )) |
4839 | "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__ )); |
4840 | return true; |
4841 | |
4842 | case OR_Ambiguous: |
4843 | ICS.setAmbiguous(); |
4844 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); |
4845 | Cand != CandidateSet.end(); ++Cand) |
4846 | if (Cand->Best) |
4847 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
4848 | return true; |
4849 | |
4850 | case OR_No_Viable_Function: |
4851 | case OR_Deleted: |
4852 | // There was no suitable conversion, or we found a deleted |
4853 | // conversion; continue with other checks. |
4854 | return false; |
4855 | } |
4856 | |
4857 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 4857); |
4858 | } |
4859 | |
4860 | /// Compute an implicit conversion sequence for reference |
4861 | /// initialization. |
4862 | static ImplicitConversionSequence |
4863 | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, |
4864 | SourceLocation DeclLoc, |
4865 | bool SuppressUserConversions, |
4866 | bool AllowExplicit) { |
4867 | assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() && "Reference init needs a reference") ? void (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\"" , "clang/lib/Sema/SemaOverload.cpp", 4867, __extension__ __PRETTY_FUNCTION__ )); |
4868 | |
4869 | // Most paths end in a failed conversion. |
4870 | ImplicitConversionSequence ICS; |
4871 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
4872 | |
4873 | QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); |
4874 | QualType T2 = Init->getType(); |
4875 | |
4876 | // If the initializer is the address of an overloaded function, try |
4877 | // to resolve the overloaded function. If all goes well, T2 is the |
4878 | // type of the resulting function. |
4879 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
4880 | DeclAccessPair Found; |
4881 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, |
4882 | false, Found)) |
4883 | T2 = Fn->getType(); |
4884 | } |
4885 | |
4886 | // Compute some basic properties of the types and the initializer. |
4887 | bool isRValRef = DeclType->isRValueReferenceType(); |
4888 | Expr::Classification InitCategory = Init->Classify(S.Context); |
4889 | |
4890 | Sema::ReferenceConversions RefConv; |
4891 | Sema::ReferenceCompareResult RefRelationship = |
4892 | S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); |
4893 | |
4894 | auto SetAsReferenceBinding = [&](bool BindsDirectly) { |
4895 | ICS.setStandard(); |
4896 | ICS.Standard.First = ICK_Identity; |
4897 | // FIXME: A reference binding can be a function conversion too. We should |
4898 | // consider that when ordering reference-to-function bindings. |
4899 | ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) |
4900 | ? ICK_Derived_To_Base |
4901 | : (RefConv & Sema::ReferenceConversions::ObjC) |
4902 | ? ICK_Compatible_Conversion |
4903 | : ICK_Identity; |
4904 | // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank |
4905 | // a reference binding that performs a non-top-level qualification |
4906 | // conversion as a qualification conversion, not as an identity conversion. |
4907 | ICS.Standard.Third = (RefConv & |
4908 | Sema::ReferenceConversions::NestedQualification) |
4909 | ? ICK_Qualification |
4910 | : ICK_Identity; |
4911 | ICS.Standard.setFromType(T2); |
4912 | ICS.Standard.setToType(0, T2); |
4913 | ICS.Standard.setToType(1, T1); |
4914 | ICS.Standard.setToType(2, T1); |
4915 | ICS.Standard.ReferenceBinding = true; |
4916 | ICS.Standard.DirectBinding = BindsDirectly; |
4917 | ICS.Standard.IsLvalueReference = !isRValRef; |
4918 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); |
4919 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); |
4920 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
4921 | ICS.Standard.ObjCLifetimeConversionBinding = |
4922 | (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; |
4923 | ICS.Standard.CopyConstructor = nullptr; |
4924 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; |
4925 | }; |
4926 | |
4927 | // C++0x [dcl.init.ref]p5: |
4928 | // A reference to type "cv1 T1" is initialized by an expression |
4929 | // of type "cv2 T2" as follows: |
4930 | |
4931 | // -- If reference is an lvalue reference and the initializer expression |
4932 | if (!isRValRef) { |
4933 | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is |
4934 | // reference-compatible with "cv2 T2," or |
4935 | // |
4936 | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. |
4937 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { |
4938 | // C++ [over.ics.ref]p1: |
4939 | // When a parameter of reference type binds directly (8.5.3) |
4940 | // to an argument expression, the implicit conversion sequence |
4941 | // is the identity conversion, unless the argument expression |
4942 | // has a type that is a derived class of the parameter type, |
4943 | // in which case the implicit conversion sequence is a |
4944 | // derived-to-base Conversion (13.3.3.1). |
4945 | SetAsReferenceBinding(/*BindsDirectly=*/true); |
4946 | |
4947 | // Nothing more to do: the inaccessibility/ambiguity check for |
4948 | // derived-to-base conversions is suppressed when we're |
4949 | // computing the implicit conversion sequence (C++ |
4950 | // [over.best.ics]p2). |
4951 | return ICS; |
4952 | } |
4953 | |
4954 | // -- has a class type (i.e., T2 is a class type), where T1 is |
4955 | // not reference-related to T2, and can be implicitly |
4956 | // converted to an lvalue of type "cv3 T3," where "cv1 T1" |
4957 | // is reference-compatible with "cv3 T3" 92) (this |
4958 | // conversion is selected by enumerating the applicable |
4959 | // conversion functions (13.3.1.6) and choosing the best |
4960 | // one through overload resolution (13.3)), |
4961 | if (!SuppressUserConversions && T2->isRecordType() && |
4962 | S.isCompleteType(DeclLoc, T2) && |
4963 | RefRelationship == Sema::Ref_Incompatible) { |
4964 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
4965 | Init, T2, /*AllowRvalues=*/false, |
4966 | AllowExplicit)) |
4967 | return ICS; |
4968 | } |
4969 | } |
4970 | |
4971 | // -- Otherwise, the reference shall be an lvalue reference to a |
4972 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
4973 | // shall be an rvalue reference. |
4974 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { |
4975 | if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) |
4976 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); |
4977 | return ICS; |
4978 | } |
4979 | |
4980 | // -- If the initializer expression |
4981 | // |
4982 | // -- is an xvalue, class prvalue, array prvalue or function |
4983 | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or |
4984 | if (RefRelationship == Sema::Ref_Compatible && |
4985 | (InitCategory.isXValue() || |
4986 | (InitCategory.isPRValue() && |
4987 | (T2->isRecordType() || T2->isArrayType())) || |
4988 | (InitCategory.isLValue() && T2->isFunctionType()))) { |
4989 | // In C++11, this is always a direct binding. In C++98/03, it's a direct |
4990 | // binding unless we're binding to a class prvalue. |
4991 | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we |
4992 | // allow the use of rvalue references in C++98/03 for the benefit of |
4993 | // standard library implementors; therefore, we need the xvalue check here. |
4994 | SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || |
4995 | !(InitCategory.isPRValue() || T2->isRecordType())); |
4996 | return ICS; |
4997 | } |
4998 | |
4999 | // -- has a class type (i.e., T2 is a class type), where T1 is not |
5000 | // reference-related to T2, and can be implicitly converted to |
5001 | // an xvalue, class prvalue, or function lvalue of type |
5002 | // "cv3 T3", where "cv1 T1" is reference-compatible with |
5003 | // "cv3 T3", |
5004 | // |
5005 | // then the reference is bound to the value of the initializer |
5006 | // expression in the first case and to the result of the conversion |
5007 | // in the second case (or, in either case, to an appropriate base |
5008 | // class subobject). |
5009 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5010 | T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && |
5011 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
5012 | Init, T2, /*AllowRvalues=*/true, |
5013 | AllowExplicit)) { |
5014 | // In the second case, if the reference is an rvalue reference |
5015 | // and the second standard conversion sequence of the |
5016 | // user-defined conversion sequence includes an lvalue-to-rvalue |
5017 | // conversion, the program is ill-formed. |
5018 | if (ICS.isUserDefined() && isRValRef && |
5019 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) |
5020 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
5021 | |
5022 | return ICS; |
5023 | } |
5024 | |
5025 | // A temporary of function type cannot be created; don't even try. |
5026 | if (T1->isFunctionType()) |
5027 | return ICS; |
5028 | |
5029 | // -- Otherwise, a temporary of type "cv1 T1" is created and |
5030 | // initialized from the initializer expression using the |
5031 | // rules for a non-reference copy initialization (8.5). The |
5032 | // reference is then bound to the temporary. If T1 is |
5033 | // reference-related to T2, cv1 must be the same |
5034 | // cv-qualification as, or greater cv-qualification than, |
5035 | // cv2; otherwise, the program is ill-formed. |
5036 | if (RefRelationship == Sema::Ref_Related) { |
5037 | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then |
5038 | // we would be reference-compatible or reference-compatible with |
5039 | // added qualification. But that wasn't the case, so the reference |
5040 | // initialization fails. |
5041 | // |
5042 | // Note that we only want to check address spaces and cvr-qualifiers here. |
5043 | // ObjC GC, lifetime and unaligned qualifiers aren't important. |
5044 | Qualifiers T1Quals = T1.getQualifiers(); |
5045 | Qualifiers T2Quals = T2.getQualifiers(); |
5046 | T1Quals.removeObjCGCAttr(); |
5047 | T1Quals.removeObjCLifetime(); |
5048 | T2Quals.removeObjCGCAttr(); |
5049 | T2Quals.removeObjCLifetime(); |
5050 | // MS compiler ignores __unaligned qualifier for references; do the same. |
5051 | T1Quals.removeUnaligned(); |
5052 | T2Quals.removeUnaligned(); |
5053 | if (!T1Quals.compatiblyIncludes(T2Quals)) |
5054 | return ICS; |
5055 | } |
5056 | |
5057 | // If at least one of the types is a class type, the types are not |
5058 | // related, and we aren't allowed any user conversions, the |
5059 | // reference binding fails. This case is important for breaking |
5060 | // recursion, since TryImplicitConversion below will attempt to |
5061 | // create a temporary through the use of a copy constructor. |
5062 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5063 | (T1->isRecordType() || T2->isRecordType())) |
5064 | return ICS; |
5065 | |
5066 | // If T1 is reference-related to T2 and the reference is an rvalue |
5067 | // reference, the initializer expression shall not be an lvalue. |
5068 | if (RefRelationship >= Sema::Ref_Related && isRValRef && |
5069 | Init->Classify(S.Context).isLValue()) { |
5070 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); |
5071 | return ICS; |
5072 | } |
5073 | |
5074 | // C++ [over.ics.ref]p2: |
5075 | // When a parameter of reference type is not bound directly to |
5076 | // an argument expression, the conversion sequence is the one |
5077 | // required to convert the argument expression to the |
5078 | // underlying type of the reference according to |
5079 | // 13.3.3.1. Conceptually, this conversion sequence corresponds |
5080 | // to copy-initializing a temporary of the underlying type with |
5081 | // the argument expression. Any difference in top-level |
5082 | // cv-qualification is subsumed by the initialization itself |
5083 | // and does not constitute a conversion. |
5084 | ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, |
5085 | AllowedExplicit::None, |
5086 | /*InOverloadResolution=*/false, |
5087 | /*CStyle=*/false, |
5088 | /*AllowObjCWritebackConversion=*/false, |
5089 | /*AllowObjCConversionOnExplicit=*/false); |
5090 | |
5091 | // Of course, that's still a reference binding. |
5092 | if (ICS.isStandard()) { |
5093 | ICS.Standard.ReferenceBinding = true; |
5094 | ICS.Standard.IsLvalueReference = !isRValRef; |
5095 | ICS.Standard.BindsToFunctionLvalue = false; |
5096 | ICS.Standard.BindsToRvalue = true; |
5097 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5098 | ICS.Standard.ObjCLifetimeConversionBinding = false; |
5099 | } else if (ICS.isUserDefined()) { |
5100 | const ReferenceType *LValRefType = |
5101 | ICS.UserDefined.ConversionFunction->getReturnType() |
5102 | ->getAs<LValueReferenceType>(); |
5103 | |
5104 | // C++ [over.ics.ref]p3: |
5105 | // Except for an implicit object parameter, for which see 13.3.1, a |
5106 | // standard conversion sequence cannot be formed if it requires [...] |
5107 | // binding an rvalue reference to an lvalue other than a function |
5108 | // lvalue. |
5109 | // Note that the function case is not possible here. |
5110 | if (isRValRef && LValRefType) { |
5111 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
5112 | return ICS; |
5113 | } |
5114 | |
5115 | ICS.UserDefined.After.ReferenceBinding = true; |
5116 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; |
5117 | ICS.UserDefined.After.BindsToFunctionLvalue = false; |
5118 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; |
5119 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5120 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; |
5121 | } |
5122 | |
5123 | return ICS; |
5124 | } |
5125 | |
5126 | static ImplicitConversionSequence |
5127 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5128 | bool SuppressUserConversions, |
5129 | bool InOverloadResolution, |
5130 | bool AllowObjCWritebackConversion, |
5131 | bool AllowExplicit = false); |
5132 | |
5133 | /// TryListConversion - Try to copy-initialize a value of type ToType from the |
5134 | /// initializer list From. |
5135 | static ImplicitConversionSequence |
5136 | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, |
5137 | bool SuppressUserConversions, |
5138 | bool InOverloadResolution, |
5139 | bool AllowObjCWritebackConversion) { |
5140 | // C++11 [over.ics.list]p1: |
5141 | // When an argument is an initializer list, it is not an expression and |
5142 | // special rules apply for converting it to a parameter type. |
5143 | |
5144 | ImplicitConversionSequence Result; |
5145 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); |
5146 | |
5147 | // We need a complete type for what follows. With one C++20 exception, |
5148 | // incomplete types can never be initialized from init lists. |
5149 | QualType InitTy = ToType; |
5150 | const ArrayType *AT = S.Context.getAsArrayType(ToType); |
5151 | if (AT && S.getLangOpts().CPlusPlus20) |
5152 | if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) |
5153 | // C++20 allows list initialization of an incomplete array type. |
5154 | InitTy = IAT->getElementType(); |
5155 | if (!S.isCompleteType(From->getBeginLoc(), InitTy)) |
5156 | return Result; |
5157 | |
5158 | // C++20 [over.ics.list]/2: |
5159 | // If the initializer list is a designated-initializer-list, a conversion |
5160 | // is only possible if the parameter has an aggregate type |
5161 | // |
5162 | // FIXME: The exception for reference initialization here is not part of the |
5163 | // language rules, but follow other compilers in adding it as a tentative DR |
5164 | // resolution. |
5165 | bool IsDesignatedInit = From->hasDesignatedInit(); |
5166 | if (!ToType->isAggregateType() && !ToType->isReferenceType() && |
5167 | IsDesignatedInit) |
5168 | return Result; |
5169 | |
5170 | // Per DR1467: |
5171 | // If the parameter type is a class X and the initializer list has a single |
5172 | // element of type cv U, where U is X or a class derived from X, the |
5173 | // implicit conversion sequence is the one required to convert the element |
5174 | // to the parameter type. |
5175 | // |
5176 | // Otherwise, if the parameter type is a character array [... ] |
5177 | // and the initializer list has a single element that is an |
5178 | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the |
5179 | // implicit conversion sequence is the identity conversion. |
5180 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5181 | if (ToType->isRecordType()) { |
5182 | QualType InitType = From->getInit(0)->getType(); |
5183 | if (S.Context.hasSameUnqualifiedType(InitType, ToType) || |
5184 | S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) |
5185 | return TryCopyInitialization(S, From->getInit(0), ToType, |
5186 | SuppressUserConversions, |
5187 | InOverloadResolution, |
5188 | AllowObjCWritebackConversion); |
5189 | } |
5190 | |
5191 | if (AT && S.IsStringInit(From->getInit(0), AT)) { |
5192 | InitializedEntity Entity = |
5193 | InitializedEntity::InitializeParameter(S.Context, ToType, |
5194 | /*Consumed=*/false); |
5195 | if (S.CanPerformCopyInitialization(Entity, From)) { |
5196 | Result.setStandard(); |
5197 | Result.Standard.setAsIdentityConversion(); |
5198 | Result.Standard.setFromType(ToType); |
5199 | Result.Standard.setAllToTypes(ToType); |
5200 | return Result; |
5201 | } |
5202 | } |
5203 | } |
5204 | |
5205 | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). |
5206 | // C++11 [over.ics.list]p2: |
5207 | // If the parameter type is std::initializer_list<X> or "array of X" and |
5208 | // all the elements can be implicitly converted to X, the implicit |
5209 | // conversion sequence is the worst conversion necessary to convert an |
5210 | // element of the list to X. |
5211 | // |
5212 | // C++14 [over.ics.list]p3: |
5213 | // Otherwise, if the parameter type is "array of N X", if the initializer |
5214 | // list has exactly N elements or if it has fewer than N elements and X is |
5215 | // default-constructible, and if all the elements of the initializer list |
5216 | // can be implicitly converted to X, the implicit conversion sequence is |
5217 | // the worst conversion necessary to convert an element of the list to X. |
5218 | if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) { |
5219 | unsigned e = From->getNumInits(); |
5220 | ImplicitConversionSequence DfltElt; |
5221 | DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), |
5222 | QualType()); |
5223 | QualType ContTy = ToType; |
5224 | bool IsUnbounded = false; |
5225 | if (AT) { |
5226 | InitTy = AT->getElementType(); |
5227 | if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { |
5228 | if (CT->getSize().ult(e)) { |
5229 | // Too many inits, fatally bad |
5230 | Result.setBad(BadConversionSequence::too_many_initializers, From, |
5231 | ToType); |
5232 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5233 | return Result; |
5234 | } |
5235 | if (CT->getSize().ugt(e)) { |
5236 | // Need an init from empty {}, is there one? |
5237 | InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt, |
5238 | From->getEndLoc()); |
5239 | EmptyList.setType(S.Context.VoidTy); |
5240 | DfltElt = TryListConversion( |
5241 | S, &EmptyList, InitTy, SuppressUserConversions, |
5242 | InOverloadResolution, AllowObjCWritebackConversion); |
5243 | if (DfltElt.isBad()) { |
5244 | // No {} init, fatally bad |
5245 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5246 | ToType); |
5247 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5248 | return Result; |
5249 | } |
5250 | } |
5251 | } else { |
5252 | assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT) && "Expected incomplete array") ? void (0) : __assert_fail ("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\"" , "clang/lib/Sema/SemaOverload.cpp", 5252, __extension__ __PRETTY_FUNCTION__ )); |
5253 | IsUnbounded = true; |
5254 | if (!e) { |
5255 | // Cannot convert to zero-sized. |
5256 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5257 | ToType); |
5258 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5259 | return Result; |
5260 | } |
5261 | llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); |
5262 | ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, |
5263 | ArrayType::Normal, 0); |
5264 | } |
5265 | } |
5266 | |
5267 | Result.setStandard(); |
5268 | Result.Standard.setAsIdentityConversion(); |
5269 | Result.Standard.setFromType(InitTy); |
5270 | Result.Standard.setAllToTypes(InitTy); |
5271 | for (unsigned i = 0; i < e; ++i) { |
5272 | Expr *Init = From->getInit(i); |
5273 | ImplicitConversionSequence ICS = TryCopyInitialization( |
5274 | S, Init, InitTy, SuppressUserConversions, InOverloadResolution, |
5275 | AllowObjCWritebackConversion); |
5276 | |
5277 | // Keep the worse conversion seen so far. |
5278 | // FIXME: Sequences are not totally ordered, so 'worse' can be |
5279 | // ambiguous. CWG has been informed. |
5280 | if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, |
5281 | Result) == |
5282 | ImplicitConversionSequence::Worse) { |
5283 | Result = ICS; |
5284 | // Bail as soon as we find something unconvertible. |
5285 | if (Result.isBad()) { |
5286 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5287 | return Result; |
5288 | } |
5289 | } |
5290 | } |
5291 | |
5292 | // If we needed any implicit {} initialization, compare that now. |
5293 | // over.ics.list/6 indicates we should compare that conversion. Again CWG |
5294 | // has been informed that this might not be the best thing. |
5295 | if (!DfltElt.isBad() && CompareImplicitConversionSequences( |
5296 | S, From->getEndLoc(), DfltElt, Result) == |
5297 | ImplicitConversionSequence::Worse) |
5298 | Result = DfltElt; |
5299 | // Record the type being initialized so that we may compare sequences |
5300 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5301 | return Result; |
5302 | } |
5303 | |
5304 | // C++14 [over.ics.list]p4: |
5305 | // C++11 [over.ics.list]p3: |
5306 | // Otherwise, if the parameter is a non-aggregate class X and overload |
5307 | // resolution chooses a single best constructor [...] the implicit |
5308 | // conversion sequence is a user-defined conversion sequence. If multiple |
5309 | // constructors are viable but none is better than the others, the |
5310 | // implicit conversion sequence is a user-defined conversion sequence. |
5311 | if (ToType->isRecordType() && !ToType->isAggregateType()) { |
5312 | // This function can deal with initializer lists. |
5313 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
5314 | AllowedExplicit::None, |
5315 | InOverloadResolution, /*CStyle=*/false, |
5316 | AllowObjCWritebackConversion, |
5317 | /*AllowObjCConversionOnExplicit=*/false); |
5318 | } |
5319 | |
5320 | // C++14 [over.ics.list]p5: |
5321 | // C++11 [over.ics.list]p4: |
5322 | // Otherwise, if the parameter has an aggregate type which can be |
5323 | // initialized from the initializer list [...] the implicit conversion |
5324 | // sequence is a user-defined conversion sequence. |
5325 | if (ToType->isAggregateType()) { |
5326 | // Type is an aggregate, argument is an init list. At this point it comes |
5327 | // down to checking whether the initialization works. |
5328 | // FIXME: Find out whether this parameter is consumed or not. |
5329 | InitializedEntity Entity = |
5330 | InitializedEntity::InitializeParameter(S.Context, ToType, |
5331 | /*Consumed=*/false); |
5332 | if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, |
5333 | From)) { |
5334 | Result.setUserDefined(); |
5335 | Result.UserDefined.Before.setAsIdentityConversion(); |
5336 | // Initializer lists don't have a type. |
5337 | Result.UserDefined.Before.setFromType(QualType()); |
5338 | Result.UserDefined.Before.setAllToTypes(QualType()); |
5339 | |
5340 | Result.UserDefined.After.setAsIdentityConversion(); |
5341 | Result.UserDefined.After.setFromType(ToType); |
5342 | Result.UserDefined.After.setAllToTypes(ToType); |
5343 | Result.UserDefined.ConversionFunction = nullptr; |
5344 | } |
5345 | return Result; |
5346 | } |
5347 | |
5348 | // C++14 [over.ics.list]p6: |
5349 | // C++11 [over.ics.list]p5: |
5350 | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. |
5351 | if (ToType->isReferenceType()) { |
5352 | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't |
5353 | // mention initializer lists in any way. So we go by what list- |
5354 | // initialization would do and try to extrapolate from that. |
5355 | |
5356 | QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); |
5357 | |
5358 | // If the initializer list has a single element that is reference-related |
5359 | // to the parameter type, we initialize the reference from that. |
5360 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5361 | Expr *Init = From->getInit(0); |
5362 | |
5363 | QualType T2 = Init->getType(); |
5364 | |
5365 | // If the initializer is the address of an overloaded function, try |
5366 | // to resolve the overloaded function. If all goes well, T2 is the |
5367 | // type of the resulting function. |
5368 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
5369 | DeclAccessPair Found; |
5370 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( |
5371 | Init, ToType, false, Found)) |
5372 | T2 = Fn->getType(); |
5373 | } |
5374 | |
5375 | // Compute some basic properties of the types and the initializer. |
5376 | Sema::ReferenceCompareResult RefRelationship = |
5377 | S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); |
5378 | |
5379 | if (RefRelationship >= Sema::Ref_Related) { |
5380 | return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), |
5381 | SuppressUserConversions, |
5382 | /*AllowExplicit=*/false); |
5383 | } |
5384 | } |
5385 | |
5386 | // Otherwise, we bind the reference to a temporary created from the |
5387 | // initializer list. |
5388 | Result = TryListConversion(S, From, T1, SuppressUserConversions, |
5389 | InOverloadResolution, |
5390 | AllowObjCWritebackConversion); |
5391 | if (Result.isFailure()) |
5392 | return Result; |
5393 | assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "clang/lib/Sema/SemaOverload.cpp", 5394, __extension__ __PRETTY_FUNCTION__ )) |
5394 | "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "clang/lib/Sema/SemaOverload.cpp", 5394, __extension__ __PRETTY_FUNCTION__ )); |
5395 | |
5396 | // Can we even bind to a temporary? |
5397 | if (ToType->isRValueReferenceType() || |
5398 | (T1.isConstQualified() && !T1.isVolatileQualified())) { |
5399 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : |
5400 | Result.UserDefined.After; |
5401 | SCS.ReferenceBinding = true; |
5402 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); |
5403 | SCS.BindsToRvalue = true; |
5404 | SCS.BindsToFunctionLvalue = false; |
5405 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5406 | SCS.ObjCLifetimeConversionBinding = false; |
5407 | } else |
5408 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, |
5409 | From, ToType); |
5410 | return Result; |
5411 | } |
5412 | |
5413 | // C++14 [over.ics.list]p7: |
5414 | // C++11 [over.ics.list]p6: |
5415 | // Otherwise, if the parameter type is not a class: |
5416 | if (!ToType->isRecordType()) { |
5417 | // - if the initializer list has one element that is not itself an |
5418 | // initializer list, the implicit conversion sequence is the one |
5419 | // required to convert the element to the parameter type. |
5420 | unsigned NumInits = From->getNumInits(); |
5421 | if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) |
5422 | Result = TryCopyInitialization(S, From->getInit(0), ToType, |
5423 | SuppressUserConversions, |
5424 | InOverloadResolution, |
5425 | AllowObjCWritebackConversion); |
5426 | // - if the initializer list has no elements, the implicit conversion |
5427 | // sequence is the identity conversion. |
5428 | else if (NumInits == 0) { |
5429 | Result.setStandard(); |
5430 | Result.Standard.setAsIdentityConversion(); |
5431 | Result.Standard.setFromType(ToType); |
5432 | Result.Standard.setAllToTypes(ToType); |
5433 | } |
5434 | return Result; |
5435 | } |
5436 | |
5437 | // C++14 [over.ics.list]p8: |
5438 | // C++11 [over.ics.list]p7: |
5439 | // In all cases other than those enumerated above, no conversion is possible |
5440 | return Result; |
5441 | } |
5442 | |
5443 | /// TryCopyInitialization - Try to copy-initialize a value of type |
5444 | /// ToType from the expression From. Return the implicit conversion |
5445 | /// sequence required to pass this argument, which may be a bad |
5446 | /// conversion sequence (meaning that the argument cannot be passed to |
5447 | /// a parameter of this type). If @p SuppressUserConversions, then we |
5448 | /// do not permit any user-defined conversion sequences. |
5449 | static ImplicitConversionSequence |
5450 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5451 | bool SuppressUserConversions, |
5452 | bool InOverloadResolution, |
5453 | bool AllowObjCWritebackConversion, |
5454 | bool AllowExplicit) { |
5455 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) |
5456 | return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, |
5457 | InOverloadResolution,AllowObjCWritebackConversion); |
5458 | |
5459 | if (ToType->isReferenceType()) |
5460 | return TryReferenceInit(S, From, ToType, |
5461 | /*FIXME:*/ From->getBeginLoc(), |
5462 | SuppressUserConversions, AllowExplicit); |
5463 | |
5464 | return TryImplicitConversion(S, From, ToType, |
5465 | SuppressUserConversions, |
5466 | AllowedExplicit::None, |
5467 | InOverloadResolution, |
5468 | /*CStyle=*/false, |
5469 | AllowObjCWritebackConversion, |
5470 | /*AllowObjCConversionOnExplicit=*/false); |
5471 | } |
5472 | |
5473 | static bool TryCopyInitialization(const CanQualType FromQTy, |
5474 | const CanQualType ToQTy, |
5475 | Sema &S, |
5476 | SourceLocation Loc, |
5477 | ExprValueKind FromVK) { |
5478 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); |
5479 | ImplicitConversionSequence ICS = |
5480 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); |
5481 | |
5482 | return !ICS.isBad(); |
5483 | } |
5484 | |
5485 | /// TryObjectArgumentInitialization - Try to initialize the object |
5486 | /// parameter of the given member function (@c Method) from the |
5487 | /// expression @p From. |
5488 | static ImplicitConversionSequence |
5489 | TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, |
5490 | Expr::Classification FromClassification, |
5491 | CXXMethodDecl *Method, |
5492 | CXXRecordDecl *ActingContext) { |
5493 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); |
5494 | // [class.dtor]p2: A destructor can be invoked for a const, volatile or |
5495 | // const volatile object. |
5496 | Qualifiers Quals = Method->getMethodQualifiers(); |
5497 | if (isa<CXXDestructorDecl>(Method)) { |
5498 | Quals.addConst(); |
5499 | Quals.addVolatile(); |
5500 | } |
5501 | |
5502 | QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); |
5503 | |
5504 | // Set up the conversion sequence as a "bad" conversion, to allow us |
5505 | // to exit early. |
5506 | ImplicitConversionSequence ICS; |
5507 | |
5508 | // We need to have an object of class type. |
5509 | if (const PointerType *PT = FromType->getAs<PointerType>()) { |
5510 | FromType = PT->getPointeeType(); |
5511 | |
5512 | // When we had a pointer, it's implicitly dereferenced, so we |
5513 | // better have an lvalue. |
5514 | assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void (0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp" , 5514, __extension__ __PRETTY_FUNCTION__)); |
5515 | } |
5516 | |
5517 | assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void (0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp" , 5517, __extension__ __PRETTY_FUNCTION__)); |
5518 | |
5519 | // C++0x [over.match.funcs]p4: |
5520 | // For non-static member functions, the type of the implicit object |
5521 | // parameter is |
5522 | // |
5523 | // - "lvalue reference to cv X" for functions declared without a |
5524 | // ref-qualifier or with the & ref-qualifier |
5525 | // - "rvalue reference to cv X" for functions declared with the && |
5526 | // ref-qualifier |
5527 | // |
5528 | // where X is the class of which the function is a member and cv is the |
5529 | // cv-qualification on the member function declaration. |
5530 | // |
5531 | // However, when finding an implicit conversion sequence for the argument, we |
5532 | // are not allowed to perform user-defined conversions |
5533 | // (C++ [over.match.funcs]p5). We perform a simplified version of |
5534 | // reference binding here, that allows class rvalues to bind to |
5535 | // non-constant references. |
5536 | |
5537 | // First check the qualifiers. |
5538 | QualType FromTypeCanon = S.Context.getCanonicalType(FromType); |
5539 | if (ImplicitParamType.getCVRQualifiers() |
5540 | != FromTypeCanon.getLocalCVRQualifiers() && |
5541 | !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { |
5542 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5543 | FromType, ImplicitParamType); |
5544 | return ICS; |
5545 | } |
5546 | |
5547 | if (FromTypeCanon.hasAddressSpace()) { |
5548 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); |
5549 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); |
5550 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { |
5551 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5552 | FromType, ImplicitParamType); |
5553 | return ICS; |
5554 | } |
5555 | } |
5556 | |
5557 | // Check that we have either the same type or a derived type. It |
5558 | // affects the conversion rank. |
5559 | QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); |
5560 | ImplicitConversionKind SecondKind; |
5561 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { |
5562 | SecondKind = ICK_Identity; |
5563 | } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) |
5564 | SecondKind = ICK_Derived_To_Base; |
5565 | else { |
5566 | ICS.setBad(BadConversionSequence::unrelated_class, |
5567 | FromType, ImplicitParamType); |
5568 | return ICS; |
5569 | } |
5570 | |
5571 | // Check the ref-qualifier. |
5572 | switch (Method->getRefQualifier()) { |
5573 | case RQ_None: |
5574 | // Do nothing; we don't care about lvalueness or rvalueness. |
5575 | break; |
5576 | |
5577 | case RQ_LValue: |
5578 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { |
5579 | // non-const lvalue reference cannot bind to an rvalue |
5580 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, |
5581 | ImplicitParamType); |
5582 | return ICS; |
5583 | } |
5584 | break; |
5585 | |
5586 | case RQ_RValue: |
5587 | if (!FromClassification.isRValue()) { |
5588 | // rvalue reference cannot bind to an lvalue |
5589 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, |
5590 | ImplicitParamType); |
5591 | return ICS; |
5592 | } |
5593 | break; |
5594 | } |
5595 | |
5596 | // Success. Mark this as a reference binding. |
5597 | ICS.setStandard(); |
5598 | ICS.Standard.setAsIdentityConversion(); |
5599 | ICS.Standard.Second = SecondKind; |
5600 | ICS.Standard.setFromType(FromType); |
5601 | ICS.Standard.setAllToTypes(ImplicitParamType); |
5602 | ICS.Standard.ReferenceBinding = true; |
5603 | ICS.Standard.DirectBinding = true; |
5604 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; |
5605 | ICS.Standard.BindsToFunctionLvalue = false; |
5606 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); |
5607 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier |
5608 | = (Method->getRefQualifier() == RQ_None); |
5609 | return ICS; |
5610 | } |
5611 | |
5612 | /// PerformObjectArgumentInitialization - Perform initialization of |
5613 | /// the implicit object parameter for the given Method with the given |
5614 | /// expression. |
5615 | ExprResult |
5616 | Sema::PerformObjectArgumentInitialization(Expr *From, |
5617 | NestedNameSpecifier *Qualifier, |
5618 | NamedDecl *FoundDecl, |
5619 | CXXMethodDecl *Method) { |
5620 | QualType FromRecordType, DestType; |
5621 | QualType ImplicitParamRecordType = |
5622 | Method->getThisType()->castAs<PointerType>()->getPointeeType(); |
5623 | |
5624 | Expr::Classification FromClassification; |
5625 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { |
5626 | FromRecordType = PT->getPointeeType(); |
5627 | DestType = Method->getThisType(); |
5628 | FromClassification = Expr::Classification::makeSimpleLValue(); |
5629 | } else { |
5630 | FromRecordType = From->getType(); |
5631 | DestType = ImplicitParamRecordType; |
5632 | FromClassification = From->Classify(Context); |
5633 | |
5634 | // When performing member access on a prvalue, materialize a temporary. |
5635 | if (From->isPRValue()) { |
5636 | From = CreateMaterializeTemporaryExpr(FromRecordType, From, |
5637 | Method->getRefQualifier() != |
5638 | RefQualifierKind::RQ_RValue); |
5639 | } |
5640 | } |
5641 | |
5642 | // Note that we always use the true parent context when performing |
5643 | // the actual argument initialization. |
5644 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( |
5645 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, |
5646 | Method->getParent()); |
5647 | if (ICS.isBad()) { |
5648 | switch (ICS.Bad.Kind) { |
5649 | case BadConversionSequence::bad_qualifiers: { |
5650 | Qualifiers FromQs = FromRecordType.getQualifiers(); |
5651 | Qualifiers ToQs = DestType.getQualifiers(); |
5652 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
5653 | if (CVR) { |
5654 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) |
5655 | << Method->getDeclName() << FromRecordType << (CVR - 1) |
5656 | << From->getSourceRange(); |
5657 | Diag(Method->getLocation(), diag::note_previous_decl) |
5658 | << Method->getDeclName(); |
5659 | return ExprError(); |
5660 | } |
5661 | break; |
5662 | } |
5663 | |
5664 | case BadConversionSequence::lvalue_ref_to_rvalue: |
5665 | case BadConversionSequence::rvalue_ref_to_lvalue: { |
5666 | bool IsRValueQualified = |
5667 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; |
5668 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) |
5669 | << Method->getDeclName() << FromClassification.isRValue() |
5670 | << IsRValueQualified; |
5671 | Diag(Method->getLocation(), diag::note_previous_decl) |
5672 | << Method->getDeclName(); |
5673 | return ExprError(); |
5674 | } |
5675 | |
5676 | case BadConversionSequence::no_conversion: |
5677 | case BadConversionSequence::unrelated_class: |
5678 | break; |
5679 | |
5680 | case BadConversionSequence::too_few_initializers: |
5681 | case BadConversionSequence::too_many_initializers: |
5682 | llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp" , 5682); |
5683 | } |
5684 | |
5685 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) |
5686 | << ImplicitParamRecordType << FromRecordType |
5687 | << From->getSourceRange(); |
5688 | } |
5689 | |
5690 | if (ICS.Standard.Second == ICK_Derived_To_Base) { |
5691 | ExprResult FromRes = |
5692 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); |
5693 | if (FromRes.isInvalid()) |
5694 | return ExprError(); |
5695 | From = FromRes.get(); |
5696 | } |
5697 | |
5698 | if (!Context.hasSameType(From->getType(), DestType)) { |
5699 | CastKind CK; |
5700 | QualType PteeTy = DestType->getPointeeType(); |
5701 | LangAS DestAS = |
5702 | PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); |
5703 | if (FromRecordType.getAddressSpace() != DestAS) |
5704 | CK = CK_AddressSpaceConversion; |
5705 | else |
5706 | CK = CK_NoOp; |
5707 | From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); |
5708 | } |
5709 | return From; |
5710 | } |
5711 | |
5712 | /// TryContextuallyConvertToBool - Attempt to contextually convert the |
5713 | /// expression From to bool (C++0x [conv]p3). |
5714 | static ImplicitConversionSequence |
5715 | TryContextuallyConvertToBool(Sema &S, Expr *From) { |
5716 | // C++ [dcl.init]/17.8: |
5717 | // - Otherwise, if the initialization is direct-initialization, the source |
5718 | // type is std::nullptr_t, and the destination type is bool, the initial |
5719 | // value of the object being initialized is false. |
5720 | if (From->getType()->isNullPtrType()) |
5721 | return ImplicitConversionSequence::getNullptrToBool(From->getType(), |
5722 | S.Context.BoolTy, |
5723 | From->isGLValue()); |
5724 | |
5725 | // All other direct-initialization of bool is equivalent to an implicit |
5726 | // conversion to bool in which explicit conversions are permitted. |
5727 | return TryImplicitConversion(S, From, S.Context.BoolTy, |
5728 | /*SuppressUserConversions=*/false, |
5729 | AllowedExplicit::Conversions, |
5730 | /*InOverloadResolution=*/false, |
5731 | /*CStyle=*/false, |
5732 | /*AllowObjCWritebackConversion=*/false, |
5733 | /*AllowObjCConversionOnExplicit=*/false); |
5734 | } |
5735 | |
5736 | /// PerformContextuallyConvertToBool - Perform a contextual conversion |
5737 | /// of the expression From to bool (C++0x [conv]p3). |
5738 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { |
5739 | if (checkPlaceholderForOverload(*this, From)) |
5740 | return ExprError(); |
5741 | |
5742 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); |
5743 | if (!ICS.isBad()) |
5744 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); |
5745 | |
5746 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) |
5747 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) |
5748 | << From->getType() << From->getSourceRange(); |
5749 | return ExprError(); |
5750 | } |
5751 | |
5752 | /// Check that the specified conversion is permitted in a converted constant |
5753 | /// expression, according to C++11 [expr.const]p3. Return true if the conversion |
5754 | /// is acceptable. |
5755 | static bool CheckConvertedConstantConversions(Sema &S, |
5756 | StandardConversionSequence &SCS) { |
5757 | // Since we know that the target type is an integral or unscoped enumeration |
5758 | // type, most conversion kinds are impossible. All possible First and Third |
5759 | // conversions are fine. |
5760 | switch (SCS.Second) { |
5761 | case ICK_Identity: |
5762 | case ICK_Integral_Promotion: |
5763 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. |
5764 | case ICK_Zero_Queue_Conversion: |
5765 | return true; |
5766 | |
5767 | case ICK_Boolean_Conversion: |
5768 | // Conversion from an integral or unscoped enumeration type to bool is |
5769 | // classified as ICK_Boolean_Conversion, but it's also arguably an integral |
5770 | // conversion, so we allow it in a converted constant expression. |
5771 | // |
5772 | // FIXME: Per core issue 1407, we should not allow this, but that breaks |
5773 | // a lot of popular code. We should at least add a warning for this |
5774 | // (non-conforming) extension. |
5775 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && |
5776 | SCS.getToType(2)->isBooleanType(); |
5777 | |
5778 | case ICK_Pointer_Conversion: |
5779 | case ICK_Pointer_Member: |
5780 | // C++1z: null pointer conversions and null member pointer conversions are |
5781 | // only permitted if the source type is std::nullptr_t. |
5782 | return SCS.getFromType()->isNullPtrType(); |
5783 | |
5784 | case ICK_Floating_Promotion: |
5785 | case ICK_Complex_Promotion: |
5786 | case ICK_Floating_Conversion: |
5787 | case ICK_Complex_Conversion: |
5788 | case ICK_Floating_Integral: |
5789 | case ICK_Compatible_Conversion: |
5790 | case ICK_Derived_To_Base: |
5791 | case ICK_Vector_Conversion: |
5792 | case ICK_SVE_Vector_Conversion: |
5793 | case ICK_RVV_Vector_Conversion: |
5794 | case ICK_Vector_Splat: |
5795 | case ICK_Complex_Real: |
5796 | case ICK_Block_Pointer_Conversion: |
5797 | case ICK_TransparentUnionConversion: |
5798 | case ICK_Writeback_Conversion: |
5799 | case ICK_Zero_Event_Conversion: |
5800 | case ICK_C_Only_Conversion: |
5801 | case ICK_Incompatible_Pointer_Conversion: |
5802 | return false; |
5803 | |
5804 | case ICK_Lvalue_To_Rvalue: |
5805 | case ICK_Array_To_Pointer: |
5806 | case ICK_Function_To_Pointer: |
5807 | llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second" , "clang/lib/Sema/SemaOverload.cpp", 5807); |
5808 | |
5809 | case ICK_Function_Conversion: |
5810 | case ICK_Qualification: |
5811 | llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second" , "clang/lib/Sema/SemaOverload.cpp", 5811); |
5812 | |
5813 | case ICK_Num_Conversion_Kinds: |
5814 | break; |
5815 | } |
5816 | |
5817 | llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp" , 5817); |
5818 | } |
5819 | |
5820 | /// CheckConvertedConstantExpression - Check that the expression From is a |
5821 | /// converted constant expression of type T, perform the conversion and produce |
5822 | /// the converted expression, per C++11 [expr.const]p3. |
5823 | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, |
5824 | QualType T, APValue &Value, |
5825 | Sema::CCEKind CCE, |
5826 | bool RequireInt, |
5827 | NamedDecl *Dest) { |
5828 | assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "clang/lib/Sema/SemaOverload.cpp", 5829, __extension__ __PRETTY_FUNCTION__ )) |
5829 | "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "clang/lib/Sema/SemaOverload.cpp", 5829, __extension__ __PRETTY_FUNCTION__ )); |
5830 | |
5831 | if (checkPlaceholderForOverload(S, From)) |
5832 | return ExprError(); |
5833 | |
5834 | // C++1z [expr.const]p3: |
5835 | // A converted constant expression of type T is an expression, |
5836 | // implicitly converted to type T, where the converted |
5837 | // expression is a constant expression and the implicit conversion |
5838 | // sequence contains only [... list of conversions ...]. |
5839 | ImplicitConversionSequence ICS = |
5840 | (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) |
5841 | ? TryContextuallyConvertToBool(S, From) |
5842 | : TryCopyInitialization(S, From, T, |
5843 | /*SuppressUserConversions=*/false, |
5844 | /*InOverloadResolution=*/false, |
5845 | /*AllowObjCWritebackConversion=*/false, |
5846 | /*AllowExplicit=*/false); |
5847 | StandardConversionSequence *SCS = nullptr; |
5848 | switch (ICS.getKind()) { |
5849 | case ImplicitConversionSequence::StandardConversion: |
5850 | SCS = &ICS.Standard; |
5851 | break; |
5852 | case ImplicitConversionSequence::UserDefinedConversion: |
5853 | if (T->isRecordType()) |
5854 | SCS = &ICS.UserDefined.Before; |
5855 | else |
5856 | SCS = &ICS.UserDefined.After; |
5857 | break; |
5858 | case ImplicitConversionSequence::AmbiguousConversion: |
5859 | case ImplicitConversionSequence::BadConversion: |
5860 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) |
5861 | return S.Diag(From->getBeginLoc(), |
5862 | diag::err_typecheck_converted_constant_expression) |
5863 | << From->getType() << From->getSourceRange() << T; |
5864 | return ExprError(); |
5865 | |
5866 | case ImplicitConversionSequence::EllipsisConversion: |
5867 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
5868 | llvm_unreachable("bad conversion in converted constant expression")::llvm::llvm_unreachable_internal("bad conversion in converted constant expression" , "clang/lib/Sema/SemaOverload.cpp", 5868); |
5869 | } |
5870 | |
5871 | // Check that we would only use permitted conversions. |
5872 | if (!CheckConvertedConstantConversions(S, *SCS)) { |
5873 | return S.Diag(From->getBeginLoc(), |
5874 | diag::err_typecheck_converted_constant_expression_disallowed) |
5875 | << From->getType() << From->getSourceRange() << T; |
5876 | } |
5877 | // [...] and where the reference binding (if any) binds directly. |
5878 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { |
5879 | return S.Diag(From->getBeginLoc(), |
5880 | diag::err_typecheck_converted_constant_expression_indirect) |
5881 | << From->getType() << From->getSourceRange() << T; |
5882 | } |
5883 | |
5884 | // Usually we can simply apply the ImplicitConversionSequence we formed |
5885 | // earlier, but that's not guaranteed to work when initializing an object of |
5886 | // class type. |
5887 | ExprResult Result; |
5888 | if (T->isRecordType()) { |
5889 | assert(CCE == Sema::CCEK_TemplateArg &&(static_cast <bool> (CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr") ? void (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\"" , "clang/lib/Sema/SemaOverload.cpp", 5890, __extension__ __PRETTY_FUNCTION__ )) |
5890 | "unexpected class type converted constant expr")(static_cast <bool> (CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr") ? void (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\"" , "clang/lib/Sema/SemaOverload.cpp", 5890, __extension__ __PRETTY_FUNCTION__ )); |
5891 | Result = S.PerformCopyInitialization( |
5892 | InitializedEntity::InitializeTemplateParameter( |
5893 | T, cast<NonTypeTemplateParmDecl>(Dest)), |
5894 | SourceLocation(), From); |
5895 | } else { |
5896 | Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); |
5897 | } |
5898 | if (Result.isInvalid()) |
5899 | return Result; |
5900 | |
5901 | // C++2a [intro.execution]p5: |
5902 | // A full-expression is [...] a constant-expression [...] |
5903 | Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), |
5904 | /*DiscardedValue=*/false, /*IsConstexpr=*/true, |
5905 | CCE == Sema::CCEKind::CCEK_TemplateArg); |
5906 | if (Result.isInvalid()) |
5907 | return Result; |
5908 | |
5909 | // Check for a narrowing implicit conversion. |
5910 | bool ReturnPreNarrowingValue = false; |
5911 | APValue PreNarrowingValue; |
5912 | QualType PreNarrowingType; |
5913 | switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, |
5914 | PreNarrowingType)) { |
5915 | case NK_Dependent_Narrowing: |
5916 | // Implicit conversion to a narrower type, but the expression is |
5917 | // value-dependent so we can't tell whether it's actually narrowing. |
5918 | case NK_Variable_Narrowing: |
5919 | // Implicit conversion to a narrower type, and the value is not a constant |
5920 | // expression. We'll diagnose this in a moment. |
5921 | case NK_Not_Narrowing: |
5922 | break; |
5923 | |
5924 | case NK_Constant_Narrowing: |
5925 | if (CCE == Sema::CCEK_ArrayBound && |
5926 | PreNarrowingType->isIntegralOrEnumerationType() && |
5927 | PreNarrowingValue.isInt()) { |
5928 | // Don't diagnose array bound narrowing here; we produce more precise |
5929 | // errors by allowing the un-narrowed value through. |
5930 | ReturnPreNarrowingValue = true; |
5931 | break; |
5932 | } |
5933 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
5934 | << CCE << /*Constant*/ 1 |
5935 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; |
5936 | break; |
5937 | |
5938 | case NK_Type_Narrowing: |
5939 | // FIXME: It would be better to diagnose that the expression is not a |
5940 | // constant expression. |
5941 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
5942 | << CCE << /*Constant*/ 0 << From->getType() << T; |
5943 | break; |
5944 | } |
5945 | |
5946 | if (Result.get()->isValueDependent()) { |
5947 | Value = APValue(); |
5948 | return Result; |
5949 | } |
5950 | |
5951 | // Check the expression is a constant expression. |
5952 | SmallVector<PartialDiagnosticAt, 8> Notes; |
5953 | Expr::EvalResult Eval; |
5954 | Eval.Diag = &Notes; |
5955 | |
5956 | ConstantExprKind Kind; |
5957 | if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) |
5958 | Kind = ConstantExprKind::ClassTemplateArgument; |
5959 | else if (CCE == Sema::CCEK_TemplateArg) |
5960 | Kind = ConstantExprKind::NonClassTemplateArgument; |
5961 | else |
5962 | Kind = ConstantExprKind::Normal; |
5963 | |
5964 | if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || |
5965 | (RequireInt && !Eval.Val.isInt())) { |
5966 | // The expression can't be folded, so we can't keep it at this position in |
5967 | // the AST. |
5968 | Result = ExprError(); |
5969 | } else { |
5970 | Value = Eval.Val; |
5971 | |
5972 | if (Notes.empty()) { |
5973 | // It's a constant expression. |
5974 | Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); |
5975 | if (ReturnPreNarrowingValue) |
5976 | Value = std::move(PreNarrowingValue); |
5977 | return E; |
5978 | } |
5979 | } |
5980 | |
5981 | // It's not a constant expression. Produce an appropriate diagnostic. |
5982 | if (Notes.size() == 1 && |
5983 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { |
5984 | S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; |
5985 | } else if (!Notes.empty() && Notes[0].second.getDiagID() == |
5986 | diag::note_constexpr_invalid_template_arg) { |
5987 | Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); |
5988 | for (unsigned I = 0; I < Notes.size(); ++I) |
5989 | S.Diag(Notes[I].first, Notes[I].second); |
5990 | } else { |
5991 | S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) |
5992 | << CCE << From->getSourceRange(); |
5993 | for (unsigned I = 0; I < Notes.size(); ++I) |
5994 | S.Diag(Notes[I].first, Notes[I].second); |
5995 | } |
5996 | return ExprError(); |
5997 | } |
5998 | |
5999 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6000 | APValue &Value, CCEKind CCE, |
6001 | NamedDecl *Dest) { |
6002 | return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, |
6003 | Dest); |
6004 | } |
6005 | |
6006 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6007 | llvm::APSInt &Value, |
6008 | CCEKind CCE) { |
6009 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType( ) && "unexpected converted const type") ? void (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\"" , "clang/lib/Sema/SemaOverload.cpp", 6009, __extension__ __PRETTY_FUNCTION__ )); |
6010 | |
6011 | APValue V; |
6012 | auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, |
6013 | /*Dest=*/nullptr); |
6014 | if (!R.isInvalid() && !R.get()->isValueDependent()) |
6015 | Value = V.getInt(); |
6016 | return R; |
6017 | } |
6018 | |
6019 | |
6020 | /// dropPointerConversions - If the given standard conversion sequence |
6021 | /// involves any pointer conversions, remove them. This may change |
6022 | /// the result type of the conversion sequence. |
6023 | static void dropPointerConversion(StandardConversionSequence &SCS) { |
6024 | if (SCS.Second == ICK_Pointer_Conversion) { |
6025 | SCS.Second = ICK_Identity; |
6026 | SCS.Third = ICK_Identity; |
6027 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; |
6028 | } |
6029 | } |
6030 | |
6031 | /// TryContextuallyConvertToObjCPointer - Attempt to contextually |
6032 | /// convert the expression From to an Objective-C pointer type. |
6033 | static ImplicitConversionSequence |
6034 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { |
6035 | // Do an implicit conversion to 'id'. |
6036 | QualType Ty = S.Context.getObjCIdType(); |
6037 | ImplicitConversionSequence ICS |
6038 | = TryImplicitConversion(S, From, Ty, |
6039 | // FIXME: Are these flags correct? |
6040 | /*SuppressUserConversions=*/false, |
6041 | AllowedExplicit::Conversions, |
6042 | /*InOverloadResolution=*/false, |
6043 | /*CStyle=*/false, |
6044 | /*AllowObjCWritebackConversion=*/false, |
6045 | /*AllowObjCConversionOnExplicit=*/true); |
6046 | |
6047 | // Strip off any final conversions to 'id'. |
6048 | switch (ICS.getKind()) { |
6049 | case ImplicitConversionSequence::BadConversion: |
6050 | case ImplicitConversionSequence::AmbiguousConversion: |
6051 | case ImplicitConversionSequence::EllipsisConversion: |
6052 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
6053 | break; |
6054 | |
6055 | case ImplicitConversionSequence::UserDefinedConversion: |
6056 | dropPointerConversion(ICS.UserDefined.After); |
6057 | break; |
6058 | |
6059 | case ImplicitConversionSequence::StandardConversion: |
6060 | dropPointerConversion(ICS.Standard); |
6061 | break; |
6062 | } |
6063 | |
6064 | return ICS; |
6065 | } |
6066 | |
6067 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual |
6068 | /// conversion of the expression From to an Objective-C pointer type. |
6069 | /// Returns a valid but null ExprResult if no conversion sequence exists. |
6070 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { |
6071 | if (checkPlaceholderForOverload(*this, From)) |
6072 | return ExprError(); |
6073 | |
6074 | QualType Ty = Context.getObjCIdType(); |
6075 | ImplicitConversionSequence ICS = |
6076 | TryContextuallyConvertToObjCPointer(*this, From); |
6077 | if (!ICS.isBad()) |
6078 | return PerformImplicitConversion(From, Ty, ICS, AA_Converting); |
6079 | return ExprResult(); |
6080 | } |
6081 | |
6082 | /// Determine whether the provided type is an integral type, or an enumeration |
6083 | /// type of a permitted flavor. |
6084 | bool Sema::ICEConvertDiagnoser::match(QualType T) { |
6085 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() |
6086 | : T->isIntegralOrUnscopedEnumerationType(); |
6087 | } |
6088 | |
6089 | static ExprResult |
6090 | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, |
6091 | Sema::ContextualImplicitConverter &Converter, |
6092 | QualType T, UnresolvedSetImpl &ViableConversions) { |
6093 | |
6094 | if (Converter.Suppress) |
6095 | return ExprError(); |
6096 | |
6097 | Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); |
6098 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6099 | CXXConversionDecl *Conv = |
6100 | cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); |
6101 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); |
6102 | Converter.noteAmbiguous(SemaRef, Conv, ConvTy); |
6103 | } |
6104 | return From; |
6105 | } |
6106 | |
6107 | static bool |
6108 | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6109 | Sema::ContextualImplicitConverter &Converter, |
6110 | QualType T, bool HadMultipleCandidates, |
6111 | UnresolvedSetImpl &ExplicitConversions) { |
6112 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { |
6113 | DeclAccessPair Found = ExplicitConversions[0]; |
6114 | CXXConversionDecl *Conversion = |
6115 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
6116 | |
6117 | // The user probably meant to invoke the given explicit |
6118 | // conversion; use it. |
6119 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); |
6120 | std::string TypeStr; |
6121 | ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); |
6122 | |
6123 | Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) |
6124 | << FixItHint::CreateInsertion(From->getBeginLoc(), |
6125 | "static_cast<" + TypeStr + ">(") |
6126 | << FixItHint::CreateInsertion( |
6127 | SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); |
6128 | Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); |
6129 | |
6130 | // If we aren't in a SFINAE context, build a call to the |
6131 | // explicit conversion function. |
6132 | if (SemaRef.isSFINAEContext()) |
6133 | return true; |
6134 | |
6135 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
6136 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
6137 | HadMultipleCandidates); |
6138 | if (Result.isInvalid()) |
6139 | return true; |
6140 | // Record usage of conversion in an implicit cast. |
6141 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
6142 | CK_UserDefinedConversion, Result.get(), |
6143 | nullptr, Result.get()->getValueKind(), |
6144 | SemaRef.CurFPFeatureOverrides()); |
6145 | } |
6146 | return false; |
6147 | } |
6148 | |
6149 | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6150 | Sema::ContextualImplicitConverter &Converter, |
6151 | QualType T, bool HadMultipleCandidates, |
6152 | DeclAccessPair &Found) { |
6153 | CXXConversionDecl *Conversion = |
6154 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
6155 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
6156 | |
6157 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); |
6158 | if (!Converter.SuppressConversion) { |
6159 | if (SemaRef.isSFINAEContext()) |
6160 | return true; |
6161 | |
6162 | Converter.diagnoseConversion(SemaRef, Loc, T, ToType) |
6163 | << From->getSourceRange(); |
6164 | } |
6165 | |
6166 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
6167 | HadMultipleCandidates); |
6168 | if (Result.isInvalid()) |
6169 | return true; |
6170 | // Record usage of conversion in an implicit cast. |
6171 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
6172 | CK_UserDefinedConversion, Result.get(), |
6173 | nullptr, Result.get()->getValueKind(), |
6174 | SemaRef.CurFPFeatureOverrides()); |
6175 | return false; |
6176 | } |
6177 | |
6178 | static ExprResult finishContextualImplicitConversion( |
6179 | Sema &SemaRef, SourceLocation Loc, Expr *From, |
6180 | Sema::ContextualImplicitConverter &Converter) { |
6181 | if (!Converter.match(From->getType()) && !Converter.Suppress) |
6182 | Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) |
6183 | << From->getSourceRange(); |
6184 | |
6185 | return SemaRef.DefaultLvalueConversion(From); |
6186 | } |
6187 | |
6188 | static void |
6189 | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, |
6190 | UnresolvedSetImpl &ViableConversions, |
6191 | OverloadCandidateSet &CandidateSet) { |
6192 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6193 | DeclAccessPair FoundDecl = ViableConversions[I]; |
6194 | NamedDecl *D = FoundDecl.getDecl(); |
6195 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
6196 | if (isa<UsingShadowDecl>(D)) |
6197 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
6198 | |
6199 | CXXConversionDecl *Conv; |
6200 | FunctionTemplateDecl *ConvTemplate; |
6201 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
6202 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
6203 | else |
6204 | Conv = cast<CXXConversionDecl>(D); |
6205 | |
6206 | if (ConvTemplate) |
6207 | SemaRef.AddTemplateConversionCandidate( |
6208 | ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, |
6209 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); |
6210 | else |
6211 | SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, |
6212 | ToType, CandidateSet, |
6213 | /*AllowObjCConversionOnExplicit=*/false, |
6214 | /*AllowExplicit*/ true); |
6215 | } |
6216 | } |
6217 | |
6218 | /// Attempt to convert the given expression to a type which is accepted |
6219 | /// by the given converter. |
6220 | /// |
6221 | /// This routine will attempt to convert an expression of class type to a |
6222 | /// type accepted by the specified converter. In C++11 and before, the class |
6223 | /// must have a single non-explicit conversion function converting to a matching |
6224 | /// type. In C++1y, there can be multiple such conversion functions, but only |
6225 | /// one target type. |
6226 | /// |
6227 | /// \param Loc The source location of the construct that requires the |
6228 | /// conversion. |
6229 | /// |
6230 | /// \param From The expression we're converting from. |
6231 | /// |
6232 | /// \param Converter Used to control and diagnose the conversion process. |
6233 | /// |
6234 | /// \returns The expression, converted to an integral or enumeration type if |
6235 | /// successful. |
6236 | ExprResult Sema::PerformContextualImplicitConversion( |
6237 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { |
6238 | // We can't perform any more checking for type-dependent expressions. |
6239 | if (From->isTypeDependent()) |
6240 | return From; |
6241 | |
6242 | // Process placeholders immediately. |
6243 | if (From->hasPlaceholderType()) { |
6244 | ExprResult result = CheckPlaceholderExpr(From); |
6245 | if (result.isInvalid()) |
6246 | return result; |
6247 | From = result.get(); |
6248 | } |
6249 | |
6250 | // If the expression already has a matching type, we're golden. |
6251 | QualType T = From->getType(); |
6252 | if (Converter.match(T)) |
6253 | return DefaultLvalueConversion(From); |
6254 | |
6255 | // FIXME: Check for missing '()' if T is a function type? |
6256 | |
6257 | // We can only perform contextual implicit conversions on objects of class |
6258 | // type. |
6259 | const RecordType *RecordTy = T->getAs<RecordType>(); |
6260 | if (!RecordTy || !getLangOpts().CPlusPlus) { |
6261 | if (!Converter.Suppress) |
6262 | Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); |
6263 | return From; |
6264 | } |
6265 | |
6266 | // We must have a complete class type. |
6267 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { |
6268 | ContextualImplicitConverter &Converter; |
6269 | Expr *From; |
6270 | |
6271 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) |
6272 | : Converter(Converter), From(From) {} |
6273 | |
6274 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
6275 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); |
6276 | } |
6277 | } IncompleteDiagnoser(Converter, From); |
6278 | |
6279 | if (Converter.Suppress ? !isCompleteType(Loc, T) |
6280 | : RequireCompleteType(Loc, T, IncompleteDiagnoser)) |
6281 | return From; |
6282 | |
6283 | // Look for a conversion to an integral or enumeration type. |
6284 | UnresolvedSet<4> |
6285 | ViableConversions; // These are *potentially* viable in C++1y. |
6286 | UnresolvedSet<4> ExplicitConversions; |
6287 | const auto &Conversions = |
6288 | cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); |
6289 | |
6290 | bool HadMultipleCandidates = |
6291 | (std::distance(Conversions.begin(), Conversions.end()) > 1); |
6292 | |
6293 | // To check that there is only one target type, in C++1y: |
6294 | QualType ToType; |
6295 | bool HasUniqueTargetType = true; |
6296 | |
6297 | // Collect explicit or viable (potentially in C++1y) conversions. |
6298 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
6299 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
6300 | CXXConversionDecl *Conversion; |
6301 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); |
6302 | if (ConvTemplate) { |
6303 | if (getLangOpts().CPlusPlus14) |
6304 | Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
6305 | else |
6306 | continue; // C++11 does not consider conversion operator templates(?). |
6307 | } else |
6308 | Conversion = cast<CXXConversionDecl>(D); |
6309 | |
6310 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6312, __extension__ __PRETTY_FUNCTION__ )) |
6311 | "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6312, __extension__ __PRETTY_FUNCTION__ )) |
6312 | "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6312, __extension__ __PRETTY_FUNCTION__ )); |
6313 | |
6314 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); |
6315 | if (Converter.match(CurToType) || ConvTemplate) { |
6316 | |
6317 | if (Conversion->isExplicit()) { |
6318 | // FIXME: For C++1y, do we need this restriction? |
6319 | // cf. diagnoseNoViableConversion() |
6320 | if (!ConvTemplate) |
6321 | ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); |
6322 | } else { |
6323 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { |
6324 | if (ToType.isNull()) |
6325 | ToType = CurToType.getUnqualifiedType(); |
6326 | else if (HasUniqueTargetType && |
6327 | (CurToType.getUnqualifiedType() != ToType)) |
6328 | HasUniqueTargetType = false; |
6329 | } |
6330 | ViableConversions.addDecl(I.getDecl(), I.getAccess()); |
6331 | } |
6332 | } |
6333 | } |
6334 | |
6335 | if (getLangOpts().CPlusPlus14) { |
6336 | // C++1y [conv]p6: |
6337 | // ... An expression e of class type E appearing in such a context |
6338 | // is said to be contextually implicitly converted to a specified |
6339 | // type T and is well-formed if and only if e can be implicitly |
6340 | // converted to a type T that is determined as follows: E is searched |
6341 | // for conversion functions whose return type is cv T or reference to |
6342 | // cv T such that T is allowed by the context. There shall be |
6343 | // exactly one such T. |
6344 | |
6345 | // If no unique T is found: |
6346 | if (ToType.isNull()) { |
6347 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6348 | HadMultipleCandidates, |
6349 | ExplicitConversions)) |
6350 | return ExprError(); |
6351 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
6352 | } |
6353 | |
6354 | // If more than one unique Ts are found: |
6355 | if (!HasUniqueTargetType) |
6356 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6357 | ViableConversions); |
6358 | |
6359 | // If one unique T is found: |
6360 | // First, build a candidate set from the previously recorded |
6361 | // potentially viable conversions. |
6362 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6363 | collectViableConversionCandidates(*this, From, ToType, ViableConversions, |
6364 | CandidateSet); |
6365 | |
6366 | // Then, perform overload resolution over the candidate set. |
6367 | OverloadCandidateSet::iterator Best; |
6368 | switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { |
6369 | case OR_Success: { |
6370 | // Apply this conversion. |
6371 | DeclAccessPair Found = |
6372 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); |
6373 | if (recordConversion(*this, Loc, From, Converter, T, |
6374 | HadMultipleCandidates, Found)) |
6375 | return ExprError(); |
6376 | break; |
6377 | } |
6378 | case OR_Ambiguous: |
6379 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6380 | ViableConversions); |
6381 | case OR_No_Viable_Function: |
6382 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6383 | HadMultipleCandidates, |
6384 | ExplicitConversions)) |
6385 | return ExprError(); |
6386 | [[fallthrough]]; |
6387 | case OR_Deleted: |
6388 | // We'll complain below about a non-integral condition type. |
6389 | break; |
6390 | } |
6391 | } else { |
6392 | switch (ViableConversions.size()) { |
6393 | case 0: { |
6394 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6395 | HadMultipleCandidates, |
6396 | ExplicitConversions)) |
6397 | return ExprError(); |
6398 | |
6399 | // We'll complain below about a non-integral condition type. |
6400 | break; |
6401 | } |
6402 | case 1: { |
6403 | // Apply this conversion. |
6404 | DeclAccessPair Found = ViableConversions[0]; |
6405 | if (recordConversion(*this, Loc, From, Converter, T, |
6406 | HadMultipleCandidates, Found)) |
6407 | return ExprError(); |
6408 | break; |
6409 | } |
6410 | default: |
6411 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6412 | ViableConversions); |
6413 | } |
6414 | } |
6415 | |
6416 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
6417 | } |
6418 | |
6419 | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is |
6420 | /// an acceptable non-member overloaded operator for a call whose |
6421 | /// arguments have types T1 (and, if non-empty, T2). This routine |
6422 | /// implements the check in C++ [over.match.oper]p3b2 concerning |
6423 | /// enumeration types. |
6424 | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, |
6425 | FunctionDecl *Fn, |
6426 | ArrayRef<Expr *> Args) { |
6427 | QualType T1 = Args[0]->getType(); |
6428 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); |
6429 | |
6430 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) |
6431 | return true; |
6432 | |
6433 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) |
6434 | return true; |
6435 | |
6436 | const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); |
6437 | if (Proto->getNumParams() < 1) |
6438 | return false; |
6439 | |
6440 | if (T1->isEnumeralType()) { |
6441 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); |
6442 | if (Context.hasSameUnqualifiedType(T1, ArgType)) |
6443 | return true; |
6444 | } |
6445 | |
6446 | if (Proto->getNumParams() < 2) |
6447 | return false; |
6448 | |
6449 | if (!T2.isNull() && T2->isEnumeralType()) { |
6450 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); |
6451 | if (Context.hasSameUnqualifiedType(T2, ArgType)) |
6452 | return true; |
6453 | } |
6454 | |
6455 | return false; |
6456 | } |
6457 | |
6458 | /// AddOverloadCandidate - Adds the given function to the set of |
6459 | /// candidate functions, using the given function call arguments. If |
6460 | /// @p SuppressUserConversions, then don't allow user-defined |
6461 | /// conversions via constructors or conversion operators. |
6462 | /// |
6463 | /// \param PartialOverloading true if we are performing "partial" overloading |
6464 | /// based on an incomplete set of function arguments. This feature is used by |
6465 | /// code completion. |
6466 | void Sema::AddOverloadCandidate( |
6467 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, |
6468 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6469 | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, |
6470 | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, |
6471 | OverloadCandidateParamOrder PO) { |
6472 | const FunctionProtoType *Proto |
6473 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); |
6474 | assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded" ) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\"" , "clang/lib/Sema/SemaOverload.cpp", 6474, __extension__ __PRETTY_FUNCTION__ )); |
6475 | assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate () && "Use AddTemplateOverloadCandidate for function templates" ) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "clang/lib/Sema/SemaOverload.cpp", 6476, __extension__ __PRETTY_FUNCTION__ )) |
6476 | "Use AddTemplateOverloadCandidate for function templates")(static_cast <bool> (!Function->getDescribedFunctionTemplate () && "Use AddTemplateOverloadCandidate for function templates" ) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "clang/lib/Sema/SemaOverload.cpp", 6476, __extension__ __PRETTY_FUNCTION__ )); |
6477 | |
6478 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { |
6479 | if (!isa<CXXConstructorDecl>(Method)) { |
6480 | // If we get here, it's because we're calling a member function |
6481 | // that is named without a member access expression (e.g., |
6482 | // "this->f") that was either written explicitly or created |
6483 | // implicitly. This can happen with a qualified call to a member |
6484 | // function, e.g., X::f(). We use an empty type for the implied |
6485 | // object argument (C++ [over.call.func]p3), and the acting context |
6486 | // is irrelevant. |
6487 | AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), |
6488 | Expr::Classification::makeSimpleLValue(), Args, |
6489 | CandidateSet, SuppressUserConversions, |
6490 | PartialOverloading, EarlyConversions, PO); |
6491 | return; |
6492 | } |
6493 | // We treat a constructor like a non-member function, since its object |
6494 | // argument doesn't participate in overload resolution. |
6495 | } |
6496 | |
6497 | if (!CandidateSet.isNewCandidate(Function, PO)) |
6498 | return; |
6499 | |
6500 | // C++11 [class.copy]p11: [DR1402] |
6501 | // A defaulted move constructor that is defined as deleted is ignored by |
6502 | // overload resolution. |
6503 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); |
6504 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && |
6505 | Constructor->isMoveConstructor()) |
6506 | return; |
6507 | |
6508 | // Overload resolution is always an unevaluated context. |
6509 | EnterExpressionEvaluationContext Unevaluated( |
6510 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6511 | |
6512 | // C++ [over.match.oper]p3: |
6513 | // if no operand has a class type, only those non-member functions in the |
6514 | // lookup set that have a first parameter of type T1 or "reference to |
6515 | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there |
6516 | // is a right operand) a second parameter of type T2 or "reference to |
6517 | // (possibly cv-qualified) T2", when T2 is an enumeration type, are |
6518 | // candidate functions. |
6519 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && |
6520 | !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) |
6521 | return; |
6522 | |
6523 | // Add this candidate |
6524 | OverloadCandidate &Candidate = |
6525 | CandidateSet.addCandidate(Args.size(), EarlyConversions); |
6526 | Candidate.FoundDecl = FoundDecl; |
6527 | Candidate.Function = Function; |
6528 | Candidate.Viable = true; |
6529 | Candidate.RewriteKind = |
6530 | CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); |
6531 | Candidate.IsSurrogate = false; |
6532 | Candidate.IsADLCandidate = IsADLCandidate; |
6533 | Candidate.IgnoreObjectArgument = false; |
6534 | Candidate.ExplicitCallArguments = Args.size(); |
6535 | |
6536 | // Explicit functions are not actually candidates at all if we're not |
6537 | // allowing them in this context, but keep them around so we can point |
6538 | // to them in diagnostics. |
6539 | if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { |
6540 | Candidate.Viable = false; |
6541 | Candidate.FailureKind = ovl_fail_explicit; |
6542 | return; |
6543 | } |
6544 | |
6545 | // Functions with internal linkage are only viable in the same module unit. |
6546 | if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { |
6547 | /// FIXME: Currently, the semantics of linkage in clang is slightly |
6548 | /// different from the semantics in C++ spec. In C++ spec, only names |
6549 | /// have linkage. So that all entities of the same should share one |
6550 | /// linkage. But in clang, different entities of the same could have |
6551 | /// different linkage. |
6552 | NamedDecl *ND = Function; |
6553 | if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) |
6554 | ND = SpecInfo->getTemplate(); |
6555 | |
6556 | if (ND->getFormalLinkage() == Linkage::InternalLinkage) { |
6557 | Candidate.Viable = false; |
6558 | Candidate.FailureKind = ovl_fail_module_mismatched; |
6559 | return; |
6560 | } |
6561 | } |
6562 | |
6563 | if (Function->isMultiVersion() && |
6564 | ((Function->hasAttr<TargetAttr>() && |
6565 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) || |
6566 | (Function->hasAttr<TargetVersionAttr>() && |
6567 | !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
6568 | Candidate.Viable = false; |
6569 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
6570 | return; |
6571 | } |
6572 | |
6573 | if (Constructor) { |
6574 | // C++ [class.copy]p3: |
6575 | // A member function template is never instantiated to perform the copy |
6576 | // of a class object to an object of its class type. |
6577 | QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); |
6578 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && |
6579 | (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || |
6580 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), |
6581 | ClassType))) { |
6582 | Candidate.Viable = false; |
6583 | Candidate.FailureKind = ovl_fail_illegal_constructor; |
6584 | return; |
6585 | } |
6586 | |
6587 | // C++ [over.match.funcs]p8: (proposed DR resolution) |
6588 | // A constructor inherited from class type C that has a first parameter |
6589 | // of type "reference to P" (including such a constructor instantiated |
6590 | // from a template) is excluded from the set of candidate functions when |
6591 | // constructing an object of type cv D if the argument list has exactly |
6592 | // one argument and D is reference-related to P and P is reference-related |
6593 | // to C. |
6594 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); |
6595 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && |
6596 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { |
6597 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); |
6598 | QualType C = Context.getRecordType(Constructor->getParent()); |
6599 | QualType D = Context.getRecordType(Shadow->getParent()); |
6600 | SourceLocation Loc = Args.front()->getExprLoc(); |
6601 | if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && |
6602 | (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { |
6603 | Candidate.Viable = false; |
6604 | Candidate.FailureKind = ovl_fail_inhctor_slice; |
6605 | return; |
6606 | } |
6607 | } |
6608 | |
6609 | // Check that the constructor is capable of constructing an object in the |
6610 | // destination address space. |
6611 | if (!Qualifiers::isAddressSpaceSupersetOf( |
6612 | Constructor->getMethodQualifiers().getAddressSpace(), |
6613 | CandidateSet.getDestAS())) { |
6614 | Candidate.Viable = false; |
6615 | Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; |
6616 | } |
6617 | } |
6618 | |
6619 | unsigned NumParams = Proto->getNumParams(); |
6620 | |
6621 | // (C++ 13.3.2p2): A candidate function having fewer than m |
6622 | // parameters is viable only if it has an ellipsis in its parameter |
6623 | // list (8.3.5). |
6624 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
6625 | !Proto->isVariadic() && |
6626 | shouldEnforceArgLimit(PartialOverloading, Function)) { |
6627 | Candidate.Viable = false; |
6628 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
6629 | return; |
6630 | } |
6631 | |
6632 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
6633 | // is viable only if the (m+1)st parameter has a default argument |
6634 | // (8.3.6). For the purposes of overload resolution, the |
6635 | // parameter list is truncated on the right, so that there are |
6636 | // exactly m parameters. |
6637 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); |
6638 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
6639 | // Not enough arguments. |
6640 | Candidate.Viable = false; |
6641 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
6642 | return; |
6643 | } |
6644 | |
6645 | // (CUDA B.1): Check for invalid calls between targets. |
6646 | if (getLangOpts().CUDA) |
6647 | if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) |
6648 | // Skip the check for callers that are implicit members, because in this |
6649 | // case we may not yet know what the member's target is; the target is |
6650 | // inferred for the member automatically, based on the bases and fields of |
6651 | // the class. |
6652 | if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { |
6653 | Candidate.Viable = false; |
6654 | Candidate.FailureKind = ovl_fail_bad_target; |
6655 | return; |
6656 | } |
6657 | |
6658 | if (Function->getTrailingRequiresClause()) { |
6659 | ConstraintSatisfaction Satisfaction; |
6660 | if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {}, |
6661 | /*ForOverloadResolution*/ true) || |
6662 | !Satisfaction.IsSatisfied) { |
6663 | Candidate.Viable = false; |
6664 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
6665 | return; |
6666 | } |
6667 | } |
6668 | |
6669 | // Determine the implicit conversion sequences for each of the |
6670 | // arguments. |
6671 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
6672 | unsigned ConvIdx = |
6673 | PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; |
6674 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
6675 | // We already formed a conversion sequence for this parameter during |
6676 | // template argument deduction. |
6677 | } else if (ArgIdx < NumParams) { |
6678 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
6679 | // exist for each argument an implicit conversion sequence |
6680 | // (13.3.3.1) that converts that argument to the corresponding |
6681 | // parameter of F. |
6682 | QualType ParamType = Proto->getParamType(ArgIdx); |
6683 | Candidate.Conversions[ConvIdx] = TryCopyInitialization( |
6684 | *this, Args[ArgIdx], ParamType, SuppressUserConversions, |
6685 | /*InOverloadResolution=*/true, |
6686 | /*AllowObjCWritebackConversion=*/ |
6687 | getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); |
6688 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6689 | Candidate.Viable = false; |
6690 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6691 | return; |
6692 | } |
6693 | } else { |
6694 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
6695 | // argument for which there is no corresponding parameter is |
6696 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
6697 | Candidate.Conversions[ConvIdx].setEllipsis(); |
6698 | } |
6699 | } |
6700 | |
6701 | if (EnableIfAttr *FailedAttr = |
6702 | CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { |
6703 | Candidate.Viable = false; |
6704 | Candidate.FailureKind = ovl_fail_enable_if; |
6705 | Candidate.DeductionFailure.Data = FailedAttr; |
6706 | return; |
6707 | } |
6708 | } |
6709 | |
6710 | ObjCMethodDecl * |
6711 | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, |
6712 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { |
6713 | if (Methods.size() <= 1) |
6714 | return nullptr; |
6715 | |
6716 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
6717 | bool Match = true; |
6718 | ObjCMethodDecl *Method = Methods[b]; |
6719 | unsigned NumNamedArgs = Sel.getNumArgs(); |
6720 | // Method might have more arguments than selector indicates. This is due |
6721 | // to addition of c-style arguments in method. |
6722 | if (Method->param_size() > NumNamedArgs) |
6723 | NumNamedArgs = Method->param_size(); |
6724 | if (Args.size() < NumNamedArgs) |
6725 | continue; |
6726 | |
6727 | for (unsigned i = 0; i < NumNamedArgs; i++) { |
6728 | // We can't do any type-checking on a type-dependent argument. |
6729 | if (Args[i]->isTypeDependent()) { |
6730 | Match = false; |
6731 | break; |
6732 | } |
6733 | |
6734 | ParmVarDecl *param = Method->parameters()[i]; |
6735 | Expr *argExpr = Args[i]; |
6736 | assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression" ) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\"" , "clang/lib/Sema/SemaOverload.cpp", 6736, __extension__ __PRETTY_FUNCTION__ )); |
6737 | |
6738 | // Strip the unbridged-cast placeholder expression off unless it's |
6739 | // a consumed argument. |
6740 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && |
6741 | !param->hasAttr<CFConsumedAttr>()) |
6742 | argExpr = stripARCUnbridgedCast(argExpr); |
6743 | |
6744 | // If the parameter is __unknown_anytype, move on to the next method. |
6745 | if (param->getType() == Context.UnknownAnyTy) { |
6746 | Match = false; |
6747 | break; |
6748 | } |
6749 | |
6750 | ImplicitConversionSequence ConversionState |
6751 | = TryCopyInitialization(*this, argExpr, param->getType(), |
6752 | /*SuppressUserConversions*/false, |
6753 | /*InOverloadResolution=*/true, |
6754 | /*AllowObjCWritebackConversion=*/ |
6755 | getLangOpts().ObjCAutoRefCount, |
6756 | /*AllowExplicit*/false); |
6757 | // This function looks for a reasonably-exact match, so we consider |
6758 | // incompatible pointer conversions to be a failure here. |
6759 | if (ConversionState.isBad() || |
6760 | (ConversionState.isStandard() && |
6761 | ConversionState.Standard.Second == |
6762 | ICK_Incompatible_Pointer_Conversion)) { |
6763 | Match = false; |
6764 | break; |
6765 | } |
6766 | } |
6767 | // Promote additional arguments to variadic methods. |
6768 | if (Match && Method->isVariadic()) { |
6769 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { |
6770 | if (Args[i]->isTypeDependent()) { |
6771 | Match = false; |
6772 | break; |
6773 | } |
6774 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
6775 | nullptr); |
6776 | if (Arg.isInvalid()) { |
6777 | Match = false; |
6778 | break; |
6779 | } |
6780 | } |
6781 | } else { |
6782 | // Check for extra arguments to non-variadic methods. |
6783 | if (Args.size() != NumNamedArgs) |
6784 | Match = false; |
6785 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { |
6786 | // Special case when selectors have no argument. In this case, select |
6787 | // one with the most general result type of 'id'. |
6788 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
6789 | QualType ReturnT = Methods[b]->getReturnType(); |
6790 | if (ReturnT->isObjCIdType()) |
6791 | return Methods[b]; |
6792 | } |
6793 | } |
6794 | } |
6795 | |
6796 | if (Match) |
6797 | return Method; |
6798 | } |
6799 | return nullptr; |
6800 | } |
6801 | |
6802 | static bool convertArgsForAvailabilityChecks( |
6803 | Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, |
6804 | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, |
6805 | Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { |
6806 | if (ThisArg) { |
6807 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); |
6808 | assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Shouldn't have `this` for ctors!") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "clang/lib/Sema/SemaOverload.cpp", 6809, __extension__ __PRETTY_FUNCTION__ )) |
6809 | "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Shouldn't have `this` for ctors!") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "clang/lib/Sema/SemaOverload.cpp", 6809, __extension__ __PRETTY_FUNCTION__ )); |
6810 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!" ) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\"" , "clang/lib/Sema/SemaOverload.cpp", 6810, __extension__ __PRETTY_FUNCTION__ )); |
6811 | ExprResult R = S.PerformObjectArgumentInitialization( |
6812 | ThisArg, /*Qualifier=*/nullptr, Method, Method); |
6813 | if (R.isInvalid()) |
6814 | return false; |
6815 | ConvertedThis = R.get(); |
6816 | } else { |
6817 | if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { |
6818 | (void)MD; |
6819 | assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6821, __extension__ __PRETTY_FUNCTION__ )) |
6820 | isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6821, __extension__ __PRETTY_FUNCTION__ )) |
6821 | "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6821, __extension__ __PRETTY_FUNCTION__ )); |
6822 | } |
6823 | ConvertedThis = nullptr; |
6824 | } |
6825 | |
6826 | // Ignore any variadic arguments. Converting them is pointless, since the |
6827 | // user can't refer to them in the function condition. |
6828 | unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); |
6829 | |
6830 | // Convert the arguments. |
6831 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { |
6832 | ExprResult R; |
6833 | R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
6834 | S.Context, Function->getParamDecl(I)), |
6835 | SourceLocation(), Args[I]); |
6836 | |
6837 | if (R.isInvalid()) |
6838 | return false; |
6839 | |
6840 | ConvertedArgs.push_back(R.get()); |
6841 | } |
6842 | |
6843 | if (Trap.hasErrorOccurred()) |
6844 | return false; |
6845 | |
6846 | // Push default arguments if needed. |
6847 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { |
6848 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { |
6849 | ParmVarDecl *P = Function->getParamDecl(i); |
6850 | if (!P->hasDefaultArg()) |
6851 | return false; |
6852 | ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); |
6853 | if (R.isInvalid()) |
6854 | return false; |
6855 | ConvertedArgs.push_back(R.get()); |
6856 | } |
6857 | |
6858 | if (Trap.hasErrorOccurred()) |
6859 | return false; |
6860 | } |
6861 | return true; |
6862 | } |
6863 | |
6864 | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, |
6865 | SourceLocation CallLoc, |
6866 | ArrayRef<Expr *> Args, |
6867 | bool MissingImplicitThis) { |
6868 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); |
6869 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) |
6870 | return nullptr; |
6871 | |
6872 | SFINAETrap Trap(*this); |
6873 | SmallVector<Expr *, 16> ConvertedArgs; |
6874 | // FIXME: We should look into making enable_if late-parsed. |
6875 | Expr *DiscardedThis; |
6876 | if (!convertArgsForAvailabilityChecks( |
6877 | *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, |
6878 | /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) |
6879 | return *EnableIfAttrs.begin(); |
6880 | |
6881 | for (auto *EIA : EnableIfAttrs) { |
6882 | APValue Result; |
6883 | // FIXME: This doesn't consider value-dependent cases, because doing so is |
6884 | // very difficult. Ideally, we should handle them more gracefully. |
6885 | if (EIA->getCond()->isValueDependent() || |
6886 | !EIA->getCond()->EvaluateWithSubstitution( |
6887 | Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) |
6888 | return EIA; |
6889 | |
6890 | if (!Result.isInt() || !Result.getInt().getBoolValue()) |
6891 | return EIA; |
6892 | } |
6893 | return nullptr; |
6894 | } |
6895 | |
6896 | template <typename CheckFn> |
6897 | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, |
6898 | bool ArgDependent, SourceLocation Loc, |
6899 | CheckFn &&IsSuccessful) { |
6900 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; |
6901 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { |
6902 | if (ArgDependent == DIA->getArgDependent()) |
6903 | Attrs.push_back(DIA); |
6904 | } |
6905 | |
6906 | // Common case: No diagnose_if attributes, so we can quit early. |
6907 | if (Attrs.empty()) |
6908 | return false; |
6909 | |
6910 | auto WarningBegin = std::stable_partition( |
6911 | Attrs.begin(), Attrs.end(), |
6912 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); |
6913 | |
6914 | // Note that diagnose_if attributes are late-parsed, so they appear in the |
6915 | // correct order (unlike enable_if attributes). |
6916 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), |
6917 | IsSuccessful); |
6918 | if (ErrAttr != WarningBegin) { |
6919 | const DiagnoseIfAttr *DIA = *ErrAttr; |
6920 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); |
6921 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
6922 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
6923 | return true; |
6924 | } |
6925 | |
6926 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) |
6927 | if (IsSuccessful(DIA)) { |
6928 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); |
6929 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
6930 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
6931 | } |
6932 | |
6933 | return false; |
6934 | } |
6935 | |
6936 | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
6937 | const Expr *ThisArg, |
6938 | ArrayRef<const Expr *> Args, |
6939 | SourceLocation Loc) { |
6940 | return diagnoseDiagnoseIfAttrsWith( |
6941 | *this, Function, /*ArgDependent=*/true, Loc, |
6942 | [&](const DiagnoseIfAttr *DIA) { |
6943 | APValue Result; |
6944 | // It's sane to use the same Args for any redecl of this function, since |
6945 | // EvaluateWithSubstitution only cares about the position of each |
6946 | // argument in the arg list, not the ParmVarDecl* it maps to. |
6947 | if (!DIA->getCond()->EvaluateWithSubstitution( |
6948 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) |
6949 | return false; |
6950 | return Result.isInt() && Result.getInt().getBoolValue(); |
6951 | }); |
6952 | } |
6953 | |
6954 | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
6955 | SourceLocation Loc) { |
6956 | return diagnoseDiagnoseIfAttrsWith( |
6957 | *this, ND, /*ArgDependent=*/false, Loc, |
6958 | [&](const DiagnoseIfAttr *DIA) { |
6959 | bool Result; |
6960 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && |
6961 | Result; |
6962 | }); |
6963 | } |
6964 | |
6965 | /// Add all of the function declarations in the given function set to |
6966 | /// the overload candidate set. |
6967 | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, |
6968 | ArrayRef<Expr *> Args, |
6969 | OverloadCandidateSet &CandidateSet, |
6970 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
6971 | bool SuppressUserConversions, |
6972 | bool PartialOverloading, |
6973 | bool FirstArgumentIsBase) { |
6974 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
6975 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
6976 | ArrayRef<Expr *> FunctionArgs = Args; |
6977 | |
6978 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
6979 | FunctionDecl *FD = |
6980 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
6981 | |
6982 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { |
6983 | QualType ObjectType; |
6984 | Expr::Classification ObjectClassification; |
6985 | if (Args.size() > 0) { |
6986 | if (Expr *E = Args[0]) { |
6987 | // Use the explicit base to restrict the lookup: |
6988 | ObjectType = E->getType(); |
6989 | // Pointers in the object arguments are implicitly dereferenced, so we |
6990 | // always classify them as l-values. |
6991 | if (!ObjectType.isNull() && ObjectType->isPointerType()) |
6992 | ObjectClassification = Expr::Classification::makeSimpleLValue(); |
6993 | else |
6994 | ObjectClassification = E->Classify(Context); |
6995 | } // .. else there is an implicit base. |
6996 | FunctionArgs = Args.slice(1); |
6997 | } |
6998 | if (FunTmpl) { |
6999 | AddMethodTemplateCandidate( |
7000 | FunTmpl, F.getPair(), |
7001 | cast<CXXRecordDecl>(FunTmpl->getDeclContext()), |
7002 | ExplicitTemplateArgs, ObjectType, ObjectClassification, |
7003 | FunctionArgs, CandidateSet, SuppressUserConversions, |
7004 | PartialOverloading); |
7005 | } else { |
7006 | AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), |
7007 | cast<CXXMethodDecl>(FD)->getParent(), ObjectType, |
7008 | ObjectClassification, FunctionArgs, CandidateSet, |
7009 | SuppressUserConversions, PartialOverloading); |
7010 | } |
7011 | } else { |
7012 | // This branch handles both standalone functions and static methods. |
7013 | |
7014 | // Slice the first argument (which is the base) when we access |
7015 | // static method as non-static. |
7016 | if (Args.size() > 0 && |
7017 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && |
7018 | !isa<CXXConstructorDecl>(FD)))) { |
7019 | assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)-> isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()" , "clang/lib/Sema/SemaOverload.cpp", 7019, __extension__ __PRETTY_FUNCTION__ )); |
7020 | FunctionArgs = Args.slice(1); |
7021 | } |
7022 | if (FunTmpl) { |
7023 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), |
7024 | ExplicitTemplateArgs, FunctionArgs, |
7025 | CandidateSet, SuppressUserConversions, |
7026 | PartialOverloading); |
7027 | } else { |
7028 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, |
7029 | SuppressUserConversions, PartialOverloading); |
7030 | } |
7031 | } |
7032 | } |
7033 | } |
7034 | |
7035 | /// AddMethodCandidate - Adds a named decl (which is some kind of |
7036 | /// method) as a method candidate to the given overload set. |
7037 | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, |
7038 | Expr::Classification ObjectClassification, |
7039 | ArrayRef<Expr *> Args, |
7040 | OverloadCandidateSet &CandidateSet, |
7041 | bool SuppressUserConversions, |
7042 | OverloadCandidateParamOrder PO) { |
7043 | NamedDecl *Decl = FoundDecl.getDecl(); |
7044 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); |
7045 | |
7046 | if (isa<UsingShadowDecl>(Decl)) |
7047 | Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); |
7048 | |
7049 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { |
7050 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl ()) && "Expected a member function template") ? void ( 0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "clang/lib/Sema/SemaOverload.cpp", 7051, __extension__ __PRETTY_FUNCTION__ )) |
7051 | "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl ()) && "Expected a member function template") ? void ( 0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "clang/lib/Sema/SemaOverload.cpp", 7051, __extension__ __PRETTY_FUNCTION__ )); |
7052 | AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, |
7053 | /*ExplicitArgs*/ nullptr, ObjectType, |
7054 | ObjectClassification, Args, CandidateSet, |
7055 | SuppressUserConversions, false, PO); |
7056 | } else { |
7057 | AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, |
7058 | ObjectType, ObjectClassification, Args, CandidateSet, |
7059 | SuppressUserConversions, false, std::nullopt, PO); |
7060 | } |
7061 | } |
7062 | |
7063 | /// AddMethodCandidate - Adds the given C++ member function to the set |
7064 | /// of candidate functions, using the given function call arguments |
7065 | /// and the object argument (@c Object). For example, in a call |
7066 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain |
7067 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't |
7068 | /// allow user-defined conversions via constructors or conversion |
7069 | /// operators. |
7070 | void |
7071 | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, |
7072 | CXXRecordDecl *ActingContext, QualType ObjectType, |
7073 | Expr::Classification ObjectClassification, |
7074 | ArrayRef<Expr *> Args, |
7075 | OverloadCandidateSet &CandidateSet, |
7076 | bool SuppressUserConversions, |
7077 | bool PartialOverloading, |
7078 | ConversionSequenceList EarlyConversions, |
7079 | OverloadCandidateParamOrder PO) { |
7080 | const FunctionProtoType *Proto |
7081 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); |
7082 | assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded" ) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\"" , "clang/lib/Sema/SemaOverload.cpp", 7082, __extension__ __PRETTY_FUNCTION__ )); |
7083 | assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Use AddOverloadCandidate for constructors") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "clang/lib/Sema/SemaOverload.cpp", 7084, __extension__ __PRETTY_FUNCTION__ )) |
7084 | "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Use AddOverloadCandidate for constructors") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "clang/lib/Sema/SemaOverload.cpp", 7084, __extension__ __PRETTY_FUNCTION__ )); |
7085 | |
7086 | if (!CandidateSet.isNewCandidate(Method, PO)) |
7087 | return; |
7088 | |
7089 | // C++11 [class.copy]p23: [DR1402] |
7090 | // A defaulted move assignment operator that is defined as deleted is |
7091 | // ignored by overload resolution. |
7092 | if (Method->isDefaulted() && Method->isDeleted() && |
7093 | Method->isMoveAssignmentOperator()) |
7094 | return; |
7095 | |
7096 | // Overload resolution is always an unevaluated context. |
7097 | EnterExpressionEvaluationContext Unevaluated( |
7098 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7099 | |
7100 | // Add this candidate |
7101 | OverloadCandidate &Candidate = |
7102 | CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); |
7103 | Candidate.FoundDecl = FoundDecl; |
7104 | Candidate.Function = Method; |
7105 | Candidate.RewriteKind = |
7106 | CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); |
7107 | Candidate.IsSurrogate = false; |
7108 | Candidate.IgnoreObjectArgument = false; |
7109 | Candidate.ExplicitCallArguments = Args.size(); |
7110 | |
7111 | unsigned NumParams = Proto->getNumParams(); |
7112 | |
7113 | // (C++ 13.3.2p2): A candidate function having fewer than m |
7114 | // parameters is viable only if it has an ellipsis in its parameter |
7115 | // list (8.3.5). |
7116 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
7117 | !Proto->isVariadic() && |
7118 | shouldEnforceArgLimit(PartialOverloading, Method)) { |
7119 | Candidate.Viable = false; |
7120 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
7121 | return; |
7122 | } |
7123 | |
7124 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
7125 | // is viable only if the (m+1)st parameter has a default argument |
7126 | // (8.3.6). For the purposes of overload resolution, the |
7127 | // parameter list is truncated on the right, so that there are |
7128 | // exactly m parameters. |
7129 | unsigned MinRequiredArgs = Method->getMinRequiredArguments(); |
7130 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
7131 | // Not enough arguments. |
7132 | Candidate.Viable = false; |
7133 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
7134 | return; |
7135 | } |
7136 | |
7137 | Candidate.Viable = true; |
7138 | |
7139 | unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7140 | if (ObjectType.isNull()) |
7141 | Candidate.IgnoreObjectArgument = true; |
7142 | else if (Method->isStatic()) { |
7143 | // [over.best.ics.general]p8 |
7144 | // When the parameter is the implicit object parameter of a static member |
7145 | // function, the implicit conversion sequence is a standard conversion |
7146 | // sequence that is neither better nor worse than any other standard |
7147 | // conversion sequence. |
7148 | // |
7149 | // This is a rule that was introduced in C++23 to support static lambdas. We |
7150 | // apply it retroactively because we want to support static lambdas as an |
7151 | // extension and it doesn't hurt previous code. |
7152 | Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); |
7153 | } else { |
7154 | // Determine the implicit conversion sequence for the object |
7155 | // parameter. |
7156 | Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( |
7157 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
7158 | Method, ActingContext); |
7159 | if (Candidate.Conversions[FirstConvIdx].isBad()) { |
7160 | Candidate.Viable = false; |
7161 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7162 | return; |
7163 | } |
7164 | } |
7165 | |
7166 | // (CUDA B.1): Check for invalid calls between targets. |
7167 | if (getLangOpts().CUDA) |
7168 | if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) |
7169 | if (!IsAllowedCUDACall(Caller, Method)) { |
7170 | Candidate.Viable = false; |
7171 | Candidate.FailureKind = ovl_fail_bad_target; |
7172 | return; |
7173 | } |
7174 | |
7175 | if (Method->getTrailingRequiresClause()) { |
7176 | ConstraintSatisfaction Satisfaction; |
7177 | if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, |
7178 | /*ForOverloadResolution*/ true) || |
7179 | !Satisfaction.IsSatisfied) { |
7180 | Candidate.Viable = false; |
7181 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7182 | return; |
7183 | } |
7184 | } |
7185 | |
7186 | // Determine the implicit conversion sequences for each of the |
7187 | // arguments. |
7188 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
7189 | unsigned ConvIdx = |
7190 | PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); |
7191 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
7192 | // We already formed a conversion sequence for this parameter during |
7193 | // template argument deduction. |
7194 | } else if (ArgIdx < NumParams) { |
7195 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
7196 | // exist for each argument an implicit conversion sequence |
7197 | // (13.3.3.1) that converts that argument to the corresponding |
7198 | // parameter of F. |
7199 | QualType ParamType = Proto->getParamType(ArgIdx); |
7200 | Candidate.Conversions[ConvIdx] |
7201 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
7202 | SuppressUserConversions, |
7203 | /*InOverloadResolution=*/true, |
7204 | /*AllowObjCWritebackConversion=*/ |
7205 | getLangOpts().ObjCAutoRefCount); |
7206 | if (Candidate.Conversions[ConvIdx].isBad()) { |
7207 | Candidate.Viable = false; |
7208 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7209 | return; |
7210 | } |
7211 | } else { |
7212 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
7213 | // argument for which there is no corresponding parameter is |
7214 | // considered to "match the ellipsis" (C+ 13.3.3.1.3). |
7215 | Candidate.Conversions[ConvIdx].setEllipsis(); |
7216 | } |
7217 | } |
7218 | |
7219 | if (EnableIfAttr *FailedAttr = |
7220 | CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { |
7221 | Candidate.Viable = false; |
7222 | Candidate.FailureKind = ovl_fail_enable_if; |
7223 | Candidate.DeductionFailure.Data = FailedAttr; |
7224 | return; |
7225 | } |
7226 | |
7227 | if (Method->isMultiVersion() && |
7228 | ((Method->hasAttr<TargetAttr>() && |
7229 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) || |
7230 | (Method->hasAttr<TargetVersionAttr>() && |
7231 | !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
7232 | Candidate.Viable = false; |
7233 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7234 | } |
7235 | } |
7236 | |
7237 | /// Add a C++ member function template as a candidate to the candidate |
7238 | /// set, using template argument deduction to produce an appropriate member |
7239 | /// function template specialization. |
7240 | void Sema::AddMethodTemplateCandidate( |
7241 | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, |
7242 | CXXRecordDecl *ActingContext, |
7243 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, |
7244 | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, |
7245 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7246 | bool PartialOverloading, OverloadCandidateParamOrder PO) { |
7247 | if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) |
7248 | return; |
7249 | |
7250 | // C++ [over.match.funcs]p7: |
7251 | // In each case where a candidate is a function template, candidate |
7252 | // function template specializations are generated using template argument |
7253 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7254 | // candidate functions in the usual way.113) A given name can refer to one |
7255 | // or more function templates and also to a set of overloaded non-template |
7256 | // functions. In such a case, the candidate functions generated from each |
7257 | // function template are combined with the set of non-template candidate |
7258 | // functions. |
7259 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7260 | FunctionDecl *Specialization = nullptr; |
7261 | ConversionSequenceList Conversions; |
7262 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7263 | MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, |
7264 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { |
7265 | return CheckNonDependentConversions( |
7266 | MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, |
7267 | SuppressUserConversions, ActingContext, ObjectType, |
7268 | ObjectClassification, PO); |
7269 | })) { |
7270 | OverloadCandidate &Candidate = |
7271 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
7272 | Candidate.FoundDecl = FoundDecl; |
7273 | Candidate.Function = MethodTmpl->getTemplatedDecl(); |
7274 | Candidate.Viable = false; |
7275 | Candidate.RewriteKind = |
7276 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
7277 | Candidate.IsSurrogate = false; |
7278 | Candidate.IgnoreObjectArgument = |
7279 | cast<CXXMethodDecl>(Candidate.Function)->isStatic() || |
7280 | ObjectType.isNull(); |
7281 | Candidate.ExplicitCallArguments = Args.size(); |
7282 | if (Result == TDK_NonDependentConversionFailure) |
7283 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7284 | else { |
7285 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7286 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7287 | Info); |
7288 | } |
7289 | return; |
7290 | } |
7291 | |
7292 | // Add the function template specialization produced by template argument |
7293 | // deduction as a candidate. |
7294 | assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7294, __extension__ __PRETTY_FUNCTION__ )); |
7295 | assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization ) && "Specialization is not a member function?") ? void (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "clang/lib/Sema/SemaOverload.cpp", 7296, __extension__ __PRETTY_FUNCTION__ )) |
7296 | "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization ) && "Specialization is not a member function?") ? void (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "clang/lib/Sema/SemaOverload.cpp", 7296, __extension__ __PRETTY_FUNCTION__ )); |
7297 | AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, |
7298 | ActingContext, ObjectType, ObjectClassification, Args, |
7299 | CandidateSet, SuppressUserConversions, PartialOverloading, |
7300 | Conversions, PO); |
7301 | } |
7302 | |
7303 | /// Determine whether a given function template has a simple explicit specifier |
7304 | /// or a non-value-dependent explicit-specification that evaluates to true. |
7305 | static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { |
7306 | return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); |
7307 | } |
7308 | |
7309 | /// Add a C++ function template specialization as a candidate |
7310 | /// in the candidate set, using template argument deduction to produce |
7311 | /// an appropriate function template specialization. |
7312 | void Sema::AddTemplateOverloadCandidate( |
7313 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
7314 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
7315 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7316 | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, |
7317 | OverloadCandidateParamOrder PO) { |
7318 | if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) |
7319 | return; |
7320 | |
7321 | // If the function template has a non-dependent explicit specification, |
7322 | // exclude it now if appropriate; we are not permitted to perform deduction |
7323 | // and substitution in this case. |
7324 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { |
7325 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7326 | Candidate.FoundDecl = FoundDecl; |
7327 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7328 | Candidate.Viable = false; |
7329 | Candidate.FailureKind = ovl_fail_explicit; |
7330 | return; |
7331 | } |
7332 | |
7333 | // C++ [over.match.funcs]p7: |
7334 | // In each case where a candidate is a function template, candidate |
7335 | // function template specializations are generated using template argument |
7336 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7337 | // candidate functions in the usual way.113) A given name can refer to one |
7338 | // or more function templates and also to a set of overloaded non-template |
7339 | // functions. In such a case, the candidate functions generated from each |
7340 | // function template are combined with the set of non-template candidate |
7341 | // functions. |
7342 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7343 | FunctionDecl *Specialization = nullptr; |
7344 | ConversionSequenceList Conversions; |
7345 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7346 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, |
7347 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { |
7348 | return CheckNonDependentConversions( |
7349 | FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, |
7350 | SuppressUserConversions, nullptr, QualType(), {}, PO); |
7351 | })) { |
7352 | OverloadCandidate &Candidate = |
7353 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
7354 | Candidate.FoundDecl = FoundDecl; |
7355 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7356 | Candidate.Viable = false; |
7357 | Candidate.RewriteKind = |
7358 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
7359 | Candidate.IsSurrogate = false; |
7360 | Candidate.IsADLCandidate = IsADLCandidate; |
7361 | // Ignore the object argument if there is one, since we don't have an object |
7362 | // type. |
7363 | Candidate.IgnoreObjectArgument = |
7364 | isa<CXXMethodDecl>(Candidate.Function) && |
7365 | !isa<CXXConstructorDecl>(Candidate.Function); |
7366 | Candidate.ExplicitCallArguments = Args.size(); |
7367 | if (Result == TDK_NonDependentConversionFailure) |
7368 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7369 | else { |
7370 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7371 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7372 | Info); |
7373 | } |
7374 | return; |
7375 | } |
7376 | |
7377 | // Add the function template specialization produced by template argument |
7378 | // deduction as a candidate. |
7379 | assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7379, __extension__ __PRETTY_FUNCTION__ )); |
7380 | AddOverloadCandidate( |
7381 | Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, |
7382 | PartialOverloading, AllowExplicit, |
7383 | /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); |
7384 | } |
7385 | |
7386 | /// Check that implicit conversion sequences can be formed for each argument |
7387 | /// whose corresponding parameter has a non-dependent type, per DR1391's |
7388 | /// [temp.deduct.call]p10. |
7389 | bool Sema::CheckNonDependentConversions( |
7390 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, |
7391 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, |
7392 | ConversionSequenceList &Conversions, bool SuppressUserConversions, |
7393 | CXXRecordDecl *ActingContext, QualType ObjectType, |
7394 | Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { |
7395 | // FIXME: The cases in which we allow explicit conversions for constructor |
7396 | // arguments never consider calling a constructor template. It's not clear |
7397 | // that is correct. |
7398 | const bool AllowExplicit = false; |
7399 | |
7400 | auto *FD = FunctionTemplate->getTemplatedDecl(); |
7401 | auto *Method = dyn_cast<CXXMethodDecl>(FD); |
7402 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); |
7403 | unsigned ThisConversions = HasThisConversion ? 1 : 0; |
7404 | |
7405 | Conversions = |
7406 | CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); |
7407 | |
7408 | // Overload resolution is always an unevaluated context. |
7409 | EnterExpressionEvaluationContext Unevaluated( |
7410 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7411 | |
7412 | // For a method call, check the 'this' conversion here too. DR1391 doesn't |
7413 | // require that, but this check should never result in a hard error, and |
7414 | // overload resolution is permitted to sidestep instantiations. |
7415 | if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && |
7416 | !ObjectType.isNull()) { |
7417 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7418 | Conversions[ConvIdx] = TryObjectArgumentInitialization( |
7419 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
7420 | Method, ActingContext); |
7421 | if (Conversions[ConvIdx].isBad()) |
7422 | return true; |
7423 | } |
7424 | |
7425 | for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; |
7426 | ++I) { |
7427 | QualType ParamType = ParamTypes[I]; |
7428 | if (!ParamType->isDependentType()) { |
7429 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed |
7430 | ? 0 |
7431 | : (ThisConversions + I); |
7432 | Conversions[ConvIdx] |
7433 | = TryCopyInitialization(*this, Args[I], ParamType, |
7434 | SuppressUserConversions, |
7435 | /*InOverloadResolution=*/true, |
7436 | /*AllowObjCWritebackConversion=*/ |
7437 | getLangOpts().ObjCAutoRefCount, |
7438 | AllowExplicit); |
7439 | if (Conversions[ConvIdx].isBad()) |
7440 | return true; |
7441 | } |
7442 | } |
7443 | |
7444 | return false; |
7445 | } |
7446 | |
7447 | /// Determine whether this is an allowable conversion from the result |
7448 | /// of an explicit conversion operator to the expected type, per C++ |
7449 | /// [over.match.conv]p1 and [over.match.ref]p1. |
7450 | /// |
7451 | /// \param ConvType The return type of the conversion function. |
7452 | /// |
7453 | /// \param ToType The type we are converting to. |
7454 | /// |
7455 | /// \param AllowObjCPointerConversion Allow a conversion from one |
7456 | /// Objective-C pointer to another. |
7457 | /// |
7458 | /// \returns true if the conversion is allowable, false otherwise. |
7459 | static bool isAllowableExplicitConversion(Sema &S, |
7460 | QualType ConvType, QualType ToType, |
7461 | bool AllowObjCPointerConversion) { |
7462 | QualType ToNonRefType = ToType.getNonReferenceType(); |
7463 | |
7464 | // Easy case: the types are the same. |
7465 | if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) |
7466 | return true; |
7467 | |
7468 | // Allow qualification conversions. |
7469 | bool ObjCLifetimeConversion; |
7470 | if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, |
7471 | ObjCLifetimeConversion)) |
7472 | return true; |
7473 | |
7474 | // If we're not allowed to consider Objective-C pointer conversions, |
7475 | // we're done. |
7476 | if (!AllowObjCPointerConversion) |
7477 | return false; |
7478 | |
7479 | // Is this an Objective-C pointer conversion? |
7480 | bool IncompatibleObjC = false; |
7481 | QualType ConvertedType; |
7482 | return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, |
7483 | IncompatibleObjC); |
7484 | } |
7485 | |
7486 | /// AddConversionCandidate - Add a C++ conversion function as a |
7487 | /// candidate in the candidate set (C++ [over.match.conv], |
7488 | /// C++ [over.match.copy]). From is the expression we're converting from, |
7489 | /// and ToType is the type that we're eventually trying to convert to |
7490 | /// (which may or may not be the same type as the type that the |
7491 | /// conversion function produces). |
7492 | void Sema::AddConversionCandidate( |
7493 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
7494 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
7495 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7496 | bool AllowExplicit, bool AllowResultConversion) { |
7497 | assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate () && "Conversion function templates use AddTemplateConversionCandidate" ) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "clang/lib/Sema/SemaOverload.cpp", 7498, __extension__ __PRETTY_FUNCTION__ )) |
7498 | "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate () && "Conversion function templates use AddTemplateConversionCandidate" ) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "clang/lib/Sema/SemaOverload.cpp", 7498, __extension__ __PRETTY_FUNCTION__ )); |
7499 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); |
7500 | if (!CandidateSet.isNewCandidate(Conversion)) |
7501 | return; |
7502 | |
7503 | // If the conversion function has an undeduced return type, trigger its |
7504 | // deduction now. |
7505 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { |
7506 | if (DeduceReturnType(Conversion, From->getExprLoc())) |
7507 | return; |
7508 | ConvType = Conversion->getConversionType().getNonReferenceType(); |
7509 | } |
7510 | |
7511 | // If we don't allow any conversion of the result type, ignore conversion |
7512 | // functions that don't convert to exactly (possibly cv-qualified) T. |
7513 | if (!AllowResultConversion && |
7514 | !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) |
7515 | return; |
7516 | |
7517 | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion |
7518 | // operator is only a candidate if its return type is the target type or |
7519 | // can be converted to the target type with a qualification conversion. |
7520 | // |
7521 | // FIXME: Include such functions in the candidate list and explain why we |
7522 | // can't select them. |
7523 | if (Conversion->isExplicit() && |
7524 | !isAllowableExplicitConversion(*this, ConvType, ToType, |
7525 | AllowObjCConversionOnExplicit)) |
7526 | return; |
7527 | |
7528 | // Overload resolution is always an unevaluated context. |
7529 | EnterExpressionEvaluationContext Unevaluated( |
7530 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7531 | |
7532 | // Add this candidate |
7533 | OverloadCandidate &Candidate = CandidateSet.addCandidate(1); |
7534 | Candidate.FoundDecl = FoundDecl; |
7535 | Candidate.Function = Conversion; |
7536 | Candidate.IsSurrogate = false; |
7537 | Candidate.IgnoreObjectArgument = false; |
7538 | Candidate.FinalConversion.setAsIdentityConversion(); |
7539 | Candidate.FinalConversion.setFromType(ConvType); |
7540 | Candidate.FinalConversion.setAllToTypes(ToType); |
7541 | Candidate.Viable = true; |
7542 | Candidate.ExplicitCallArguments = 1; |
7543 | |
7544 | // Explicit functions are not actually candidates at all if we're not |
7545 | // allowing them in this context, but keep them around so we can point |
7546 | // to them in diagnostics. |
7547 | if (!AllowExplicit && Conversion->isExplicit()) { |
7548 | Candidate.Viable = false; |
7549 | Candidate.FailureKind = ovl_fail_explicit; |
7550 | return; |
7551 | } |
7552 | |
7553 | // C++ [over.match.funcs]p4: |
7554 | // For conversion functions, the function is considered to be a member of |
7555 | // the class of the implicit implied object argument for the purpose of |
7556 | // defining the type of the implicit object parameter. |
7557 | // |
7558 | // Determine the implicit conversion sequence for the implicit |
7559 | // object parameter. |
7560 | QualType ImplicitParamType = From->getType(); |
7561 | if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) |
7562 | ImplicitParamType = FromPtrType->getPointeeType(); |
7563 | CXXRecordDecl *ConversionContext |
7564 | = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); |
7565 | |
7566 | Candidate.Conversions[0] = TryObjectArgumentInitialization( |
7567 | *this, CandidateSet.getLocation(), From->getType(), |
7568 | From->Classify(Context), Conversion, ConversionContext); |
7569 | |
7570 | if (Candidate.Conversions[0].isBad()) { |
7571 | Candidate.Viable = false; |
7572 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7573 | return; |
7574 | } |
7575 | |
7576 | if (Conversion->getTrailingRequiresClause()) { |
7577 | ConstraintSatisfaction Satisfaction; |
7578 | if (CheckFunctionConstraints(Conversion, Satisfaction) || |
7579 | !Satisfaction.IsSatisfied) { |
7580 | Candidate.Viable = false; |
7581 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7582 | return; |
7583 | } |
7584 | } |
7585 | |
7586 | // We won't go through a user-defined type conversion function to convert a |
7587 | // derived to base as such conversions are given Conversion Rank. They only |
7588 | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] |
7589 | QualType FromCanon |
7590 | = Context.getCanonicalType(From->getType().getUnqualifiedType()); |
7591 | QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); |
7592 | if (FromCanon == ToCanon || |
7593 | IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { |
7594 | Candidate.Viable = false; |
7595 | Candidate.FailureKind = ovl_fail_trivial_conversion; |
7596 | return; |
7597 | } |
7598 | |
7599 | // To determine what the conversion from the result of calling the |
7600 | // conversion function to the type we're eventually trying to |
7601 | // convert to (ToType), we need to synthesize a call to the |
7602 | // conversion function and attempt copy initialization from it. This |
7603 | // makes sure that we get the right semantics with respect to |
7604 | // lvalues/rvalues and the type. Fortunately, we can allocate this |
7605 | // call on the stack and we don't need its arguments to be |
7606 | // well-formed. |
7607 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), |
7608 | VK_LValue, From->getBeginLoc()); |
7609 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, |
7610 | Context.getPointerType(Conversion->getType()), |
7611 | CK_FunctionToPointerDecay, &ConversionRef, |
7612 | VK_PRValue, FPOptionsOverride()); |
7613 | |
7614 | QualType ConversionType = Conversion->getConversionType(); |
7615 | if (!isCompleteType(From->getBeginLoc(), ConversionType)) { |
7616 | Candidate.Viable = false; |
7617 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7618 | return; |
7619 | } |
7620 | |
7621 | ExprValueKind VK = Expr::getValueKindForType(ConversionType); |
7622 | |
7623 | // Note that it is safe to allocate CallExpr on the stack here because |
7624 | // there are 0 arguments (i.e., nothing is allocated using ASTContext's |
7625 | // allocator). |
7626 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); |
7627 | |
7628 | alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
7629 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( |
7630 | Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); |
7631 | |
7632 | ImplicitConversionSequence ICS = |
7633 | TryCopyInitialization(*this, TheTemporaryCall, ToType, |
7634 | /*SuppressUserConversions=*/true, |
7635 | /*InOverloadResolution=*/false, |
7636 | /*AllowObjCWritebackConversion=*/false); |
7637 | |
7638 | switch (ICS.getKind()) { |
7639 | case ImplicitConversionSequence::StandardConversion: |
7640 | Candidate.FinalConversion = ICS.Standard; |
7641 | |
7642 | // C++ [over.ics.user]p3: |
7643 | // If the user-defined conversion is specified by a specialization of a |
7644 | // conversion function template, the second standard conversion sequence |
7645 | // shall have exact match rank. |
7646 | if (Conversion->getPrimaryTemplate() && |
7647 | GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { |
7648 | Candidate.Viable = false; |
7649 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; |
7650 | return; |
7651 | } |
7652 | |
7653 | // C++0x [dcl.init.ref]p5: |
7654 | // In the second case, if the reference is an rvalue reference and |
7655 | // the second standard conversion sequence of the user-defined |
7656 | // conversion sequence includes an lvalue-to-rvalue conversion, the |
7657 | // program is ill-formed. |
7658 | if (ToType->isRValueReferenceType() && |
7659 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
7660 | Candidate.Viable = false; |
7661 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7662 | return; |
7663 | } |
7664 | break; |
7665 | |
7666 | case ImplicitConversionSequence::BadConversion: |
7667 | Candidate.Viable = false; |
7668 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7669 | return; |
7670 | |
7671 | default: |
7672 | llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "clang/lib/Sema/SemaOverload.cpp", 7673) |
7673 | "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "clang/lib/Sema/SemaOverload.cpp", 7673); |
7674 | } |
7675 | |
7676 | if (EnableIfAttr *FailedAttr = |
7677 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
7678 | Candidate.Viable = false; |
7679 | Candidate.FailureKind = ovl_fail_enable_if; |
7680 | Candidate.DeductionFailure.Data = FailedAttr; |
7681 | return; |
7682 | } |
7683 | |
7684 | if (Conversion->isMultiVersion() && |
7685 | ((Conversion->hasAttr<TargetAttr>() && |
7686 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) || |
7687 | (Conversion->hasAttr<TargetVersionAttr>() && |
7688 | !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
7689 | Candidate.Viable = false; |
7690 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7691 | } |
7692 | } |
7693 | |
7694 | /// Adds a conversion function template specialization |
7695 | /// candidate to the overload set, using template argument deduction |
7696 | /// to deduce the template arguments of the conversion function |
7697 | /// template from the type that we are converting to (C++ |
7698 | /// [temp.deduct.conv]). |
7699 | void Sema::AddTemplateConversionCandidate( |
7700 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
7701 | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, |
7702 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7703 | bool AllowExplicit, bool AllowResultConversion) { |
7704 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate ->getTemplatedDecl()) && "Only conversion function templates permitted here" ) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "clang/lib/Sema/SemaOverload.cpp", 7705, __extension__ __PRETTY_FUNCTION__ )) |
7705 | "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate ->getTemplatedDecl()) && "Only conversion function templates permitted here" ) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "clang/lib/Sema/SemaOverload.cpp", 7705, __extension__ __PRETTY_FUNCTION__ )); |
7706 | |
7707 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) |
7708 | return; |
7709 | |
7710 | // If the function template has a non-dependent explicit specification, |
7711 | // exclude it now if appropriate; we are not permitted to perform deduction |
7712 | // and substitution in this case. |
7713 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { |
7714 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7715 | Candidate.FoundDecl = FoundDecl; |
7716 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7717 | Candidate.Viable = false; |
7718 | Candidate.FailureKind = ovl_fail_explicit; |
7719 | return; |
7720 | } |
7721 | |
7722 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7723 | CXXConversionDecl *Specialization = nullptr; |
7724 | if (TemplateDeductionResult Result |
7725 | = DeduceTemplateArguments(FunctionTemplate, ToType, |
7726 | Specialization, Info)) { |
7727 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7728 | Candidate.FoundDecl = FoundDecl; |
7729 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7730 | Candidate.Viable = false; |
7731 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7732 | Candidate.IsSurrogate = false; |
7733 | Candidate.IgnoreObjectArgument = false; |
7734 | Candidate.ExplicitCallArguments = 1; |
7735 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7736 | Info); |
7737 | return; |
7738 | } |
7739 | |
7740 | // Add the conversion function template specialization produced by |
7741 | // template argument deduction as a candidate. |
7742 | assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7742, __extension__ __PRETTY_FUNCTION__ )); |
7743 | AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, |
7744 | CandidateSet, AllowObjCConversionOnExplicit, |
7745 | AllowExplicit, AllowResultConversion); |
7746 | } |
7747 | |
7748 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that |
7749 | /// converts the given @c Object to a function pointer via the |
7750 | /// conversion function @c Conversion, and then attempts to call it |
7751 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is |
7752 | /// the type of function that we'll eventually be calling. |
7753 | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, |
7754 | DeclAccessPair FoundDecl, |
7755 | CXXRecordDecl *ActingContext, |
7756 | const FunctionProtoType *Proto, |
7757 | Expr *Object, |
7758 | ArrayRef<Expr *> Args, |
7759 | OverloadCandidateSet& CandidateSet) { |
7760 | if (!CandidateSet.isNewCandidate(Conversion)) |
7761 | return; |
7762 | |
7763 | // Overload resolution is always an unevaluated context. |
7764 | EnterExpressionEvaluationContext Unevaluated( |
7765 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7766 | |
7767 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); |
7768 | Candidate.FoundDecl = FoundDecl; |
7769 | Candidate.Function = nullptr; |
7770 | Candidate.Surrogate = Conversion; |
7771 | Candidate.Viable = true; |
7772 | Candidate.IsSurrogate = true; |
7773 | Candidate.IgnoreObjectArgument = false; |
7774 | Candidate.ExplicitCallArguments = Args.size(); |
7775 | |
7776 | // Determine the implicit conversion sequence for the implicit |
7777 | // object parameter. |
7778 | ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( |
7779 | *this, CandidateSet.getLocation(), Object->getType(), |
7780 | Object->Classify(Context), Conversion, ActingContext); |
7781 | if (ObjectInit.isBad()) { |
7782 | Candidate.Viable = false; |
7783 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7784 | Candidate.Conversions[0] = ObjectInit; |
7785 | return; |
7786 | } |
7787 | |
7788 | // The first conversion is actually a user-defined conversion whose |
7789 | // first conversion is ObjectInit's standard conversion (which is |
7790 | // effectively a reference binding). Record it as such. |
7791 | Candidate.Conversions[0].setUserDefined(); |
7792 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; |
7793 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; |
7794 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; |
7795 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; |
7796 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; |
7797 | Candidate.Conversions[0].UserDefined.After |
7798 | = Candidate.Conversions[0].UserDefined.Before; |
7799 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); |
7800 | |
7801 | // Find the |
7802 | unsigned NumParams = Proto->getNumParams(); |
7803 | |
7804 | // (C++ 13.3.2p2): A candidate function having fewer than m |
7805 | // parameters is viable only if it has an ellipsis in its parameter |
7806 | // list (8.3.5). |
7807 | if (Args.size() > NumParams && !Proto->isVariadic()) { |
7808 | Candidate.Viable = false; |
7809 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
7810 | return; |
7811 | } |
7812 | |
7813 | // Function types don't have any default arguments, so just check if |
7814 | // we have enough arguments. |
7815 | if (Args.size() < NumParams) { |
7816 | // Not enough arguments. |
7817 | Candidate.Viable = false; |
7818 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
7819 | return; |
7820 | } |
7821 | |
7822 | // Determine the implicit conversion sequences for each of the |
7823 | // arguments. |
7824 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
7825 | if (ArgIdx < NumParams) { |
7826 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
7827 | // exist for each argument an implicit conversion sequence |
7828 | // (13.3.3.1) that converts that argument to the corresponding |
7829 | // parameter of F. |
7830 | QualType ParamType = Proto->getParamType(ArgIdx); |
7831 | Candidate.Conversions[ArgIdx + 1] |
7832 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
7833 | /*SuppressUserConversions=*/false, |
7834 | /*InOverloadResolution=*/false, |
7835 | /*AllowObjCWritebackConversion=*/ |
7836 | getLangOpts().ObjCAutoRefCount); |
7837 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { |
7838 | Candidate.Viable = false; |
7839 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7840 | return; |
7841 | } |
7842 | } else { |
7843 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
7844 | // argument for which there is no corresponding parameter is |
7845 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
7846 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); |
7847 | } |
7848 | } |
7849 | |
7850 | if (EnableIfAttr *FailedAttr = |
7851 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
7852 | Candidate.Viable = false; |
7853 | Candidate.FailureKind = ovl_fail_enable_if; |
7854 | Candidate.DeductionFailure.Data = FailedAttr; |
7855 | return; |
7856 | } |
7857 | } |
7858 | |
7859 | /// Add all of the non-member operator function declarations in the given |
7860 | /// function set to the overload candidate set. |
7861 | void Sema::AddNonMemberOperatorCandidates( |
7862 | const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, |
7863 | OverloadCandidateSet &CandidateSet, |
7864 | TemplateArgumentListInfo *ExplicitTemplateArgs) { |
7865 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
7866 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
7867 | ArrayRef<Expr *> FunctionArgs = Args; |
7868 | |
7869 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
7870 | FunctionDecl *FD = |
7871 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
7872 | |
7873 | // Don't consider rewritten functions if we're not rewriting. |
7874 | if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) |
7875 | continue; |
7876 | |
7877 | assert(!isa<CXXMethodDecl>(FD) &&(static_cast <bool> (!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function") ? void (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "clang/lib/Sema/SemaOverload.cpp", 7878, __extension__ __PRETTY_FUNCTION__ )) |
7878 | "unqualified operator lookup found a member function")(static_cast <bool> (!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function") ? void (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "clang/lib/Sema/SemaOverload.cpp", 7878, __extension__ __PRETTY_FUNCTION__ )); |
7879 | |
7880 | if (FunTmpl) { |
7881 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, |
7882 | FunctionArgs, CandidateSet); |
7883 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) |
7884 | AddTemplateOverloadCandidate( |
7885 | FunTmpl, F.getPair(), ExplicitTemplateArgs, |
7886 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, |
7887 | true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); |
7888 | } else { |
7889 | if (ExplicitTemplateArgs) |
7890 | continue; |
7891 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); |
7892 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) |
7893 | AddOverloadCandidate( |
7894 | FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, |
7895 | false, false, true, false, ADLCallKind::NotADL, std::nullopt, |
7896 | OverloadCandidateParamOrder::Reversed); |
7897 | } |
7898 | } |
7899 | } |
7900 | |
7901 | /// Add overload candidates for overloaded operators that are |
7902 | /// member functions. |
7903 | /// |
7904 | /// Add the overloaded operator candidates that are member functions |
7905 | /// for the operator Op that was used in an operator expression such |
7906 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and |
7907 | /// CandidateSet will store the added overload candidates. (C++ |
7908 | /// [over.match.oper]). |
7909 | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
7910 | SourceLocation OpLoc, |
7911 | ArrayRef<Expr *> Args, |
7912 | OverloadCandidateSet &CandidateSet, |
7913 | OverloadCandidateParamOrder PO) { |
7914 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
7915 | |
7916 | // C++ [over.match.oper]p3: |
7917 | // For a unary operator @ with an operand of a type whose |
7918 | // cv-unqualified version is T1, and for a binary operator @ with |
7919 | // a left operand of a type whose cv-unqualified version is T1 and |
7920 | // a right operand of a type whose cv-unqualified version is T2, |
7921 | // three sets of candidate functions, designated member |
7922 | // candidates, non-member candidates and built-in candidates, are |
7923 | // constructed as follows: |
7924 | QualType T1 = Args[0]->getType(); |
7925 | |
7926 | // -- If T1 is a complete class type or a class currently being |
7927 | // defined, the set of member candidates is the result of the |
7928 | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, |
7929 | // the set of member candidates is empty. |
7930 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { |
7931 | // Complete the type if it can be completed. |
7932 | if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) |
7933 | return; |
7934 | // If the type is neither complete nor being defined, bail out now. |
7935 | if (!T1Rec->getDecl()->getDefinition()) |
7936 | return; |
7937 | |
7938 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); |
7939 | LookupQualifiedName(Operators, T1Rec->getDecl()); |
7940 | Operators.suppressDiagnostics(); |
7941 | |
7942 | for (LookupResult::iterator Oper = Operators.begin(), |
7943 | OperEnd = Operators.end(); |
7944 | Oper != OperEnd; ++Oper) { |
7945 | if (Oper->getAsFunction() && |
7946 | PO == OverloadCandidateParamOrder::Reversed && |
7947 | !CandidateSet.getRewriteInfo().shouldAddReversed( |
7948 | *this, {Args[1], Args[0]}, Oper->getAsFunction())) |
7949 | continue; |
7950 | AddMethodCandidate(Oper.getPair(), Args[0]->getType(), |
7951 | Args[0]->Classify(Context), Args.slice(1), |
7952 | CandidateSet, /*SuppressUserConversion=*/false, PO); |
7953 | } |
7954 | } |
7955 | } |
7956 | |
7957 | /// AddBuiltinCandidate - Add a candidate for a built-in |
7958 | /// operator. ResultTy and ParamTys are the result and parameter types |
7959 | /// of the built-in candidate, respectively. Args and NumArgs are the |
7960 | /// arguments being passed to the candidate. IsAssignmentOperator |
7961 | /// should be true when this built-in candidate is an assignment |
7962 | /// operator. NumContextualBoolArguments is the number of arguments |
7963 | /// (at the beginning of the argument list) that will be contextually |
7964 | /// converted to bool. |
7965 | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
7966 | OverloadCandidateSet& CandidateSet, |
7967 | bool IsAssignmentOperator, |
7968 | unsigned NumContextualBoolArguments) { |
7969 | // Overload resolution is always an unevaluated context. |
7970 | EnterExpressionEvaluationContext Unevaluated( |
7971 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7972 | |
7973 | // Add this candidate |
7974 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); |
7975 | Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); |
7976 | Candidate.Function = nullptr; |
7977 | Candidate.IsSurrogate = false; |
7978 | Candidate.IgnoreObjectArgument = false; |
7979 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); |
7980 | |
7981 | // Determine the implicit conversion sequences for each of the |
7982 | // arguments. |
7983 | Candidate.Viable = true; |
7984 | Candidate.ExplicitCallArguments = Args.size(); |
7985 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
7986 | // C++ [over.match.oper]p4: |
7987 | // For the built-in assignment operators, conversions of the |
7988 | // left operand are restricted as follows: |
7989 | // -- no temporaries are introduced to hold the left operand, and |
7990 | // -- no user-defined conversions are applied to the left |
7991 | // operand to achieve a type match with the left-most |
7992 | // parameter of a built-in candidate. |
7993 | // |
7994 | // We block these conversions by turning off user-defined |
7995 | // conversions, since that is the only way that initialization of |
7996 | // a reference to a non-class type can occur from something that |
7997 | // is not of the same type. |
7998 | if (ArgIdx < NumContextualBoolArguments) { |
7999 | assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "clang/lib/Sema/SemaOverload.cpp", 8000, __extension__ __PRETTY_FUNCTION__ )) |
8000 | "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "clang/lib/Sema/SemaOverload.cpp", 8000, __extension__ __PRETTY_FUNCTION__ )); |
8001 | Candidate.Conversions[ArgIdx] |
8002 | = TryContextuallyConvertToBool(*this, Args[ArgIdx]); |
8003 | } else { |
8004 | Candidate.Conversions[ArgIdx] |
8005 | = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], |
8006 | ArgIdx == 0 && IsAssignmentOperator, |
8007 | /*InOverloadResolution=*/false, |
8008 | /*AllowObjCWritebackConversion=*/ |
8009 | getLangOpts().ObjCAutoRefCount); |
8010 | } |
8011 | if (Candidate.Conversions[ArgIdx].isBad()) { |
8012 | Candidate.Viable = false; |
8013 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8014 | break; |
8015 | } |
8016 | } |
8017 | } |
8018 | |
8019 | namespace { |
8020 | |
8021 | /// BuiltinCandidateTypeSet - A set of types that will be used for the |
8022 | /// candidate operator functions for built-in operators (C++ |
8023 | /// [over.built]). The types are separated into pointer types and |
8024 | /// enumeration types. |
8025 | class BuiltinCandidateTypeSet { |
8026 | /// TypeSet - A set of types. |
8027 | typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, |
8028 | llvm::SmallPtrSet<QualType, 8>> TypeSet; |
8029 | |
8030 | /// PointerTypes - The set of pointer types that will be used in the |
8031 | /// built-in candidates. |
8032 | TypeSet PointerTypes; |
8033 | |
8034 | /// MemberPointerTypes - The set of member pointer types that will be |
8035 | /// used in the built-in candidates. |
8036 | TypeSet MemberPointerTypes; |
8037 | |
8038 | /// EnumerationTypes - The set of enumeration types that will be |
8039 | /// used in the built-in candidates. |
8040 | TypeSet EnumerationTypes; |
8041 | |
8042 | /// The set of vector types that will be used in the built-in |
8043 | /// candidates. |
8044 | TypeSet VectorTypes; |
8045 | |
8046 | /// The set of matrix types that will be used in the built-in |
8047 | /// candidates. |
8048 | TypeSet MatrixTypes; |
8049 | |
8050 | /// A flag indicating non-record types are viable candidates |
8051 | bool HasNonRecordTypes; |
8052 | |
8053 | /// A flag indicating whether either arithmetic or enumeration types |
8054 | /// were present in the candidate set. |
8055 | bool HasArithmeticOrEnumeralTypes; |
8056 | |
8057 | /// A flag indicating whether the nullptr type was present in the |
8058 | /// candidate set. |
8059 | bool HasNullPtrType; |
8060 | |
8061 | /// Sema - The semantic analysis instance where we are building the |
8062 | /// candidate type set. |
8063 | Sema &SemaRef; |
8064 | |
8065 | /// Context - The AST context in which we will build the type sets. |
8066 | ASTContext &Context; |
8067 | |
8068 | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8069 | const Qualifiers &VisibleQuals); |
8070 | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); |
8071 | |
8072 | public: |
8073 | /// iterator - Iterates through the types that are part of the set. |
8074 | typedef TypeSet::iterator iterator; |
8075 | |
8076 | BuiltinCandidateTypeSet(Sema &SemaRef) |
8077 | : HasNonRecordTypes(false), |
8078 | HasArithmeticOrEnumeralTypes(false), |
8079 | HasNullPtrType(false), |
8080 | SemaRef(SemaRef), |
8081 | Context(SemaRef.Context) { } |
8082 | |
8083 | void AddTypesConvertedFrom(QualType Ty, |
8084 | SourceLocation Loc, |
8085 | bool AllowUserConversions, |
8086 | bool AllowExplicitConversions, |
8087 | const Qualifiers &VisibleTypeConversionsQuals); |
8088 | |
8089 | llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } |
8090 | llvm::iterator_range<iterator> member_pointer_types() { |
8091 | return MemberPointerTypes; |
8092 | } |
8093 | llvm::iterator_range<iterator> enumeration_types() { |
8094 | return EnumerationTypes; |
8095 | } |
8096 | llvm::iterator_range<iterator> vector_types() { return VectorTypes; } |
8097 | llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } |
8098 | |
8099 | bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } |
8100 | bool hasNonRecordTypes() { return HasNonRecordTypes; } |
8101 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } |
8102 | bool hasNullPtrType() const { return HasNullPtrType; } |
8103 | }; |
8104 | |
8105 | } // end anonymous namespace |
8106 | |
8107 | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to |
8108 | /// the set of pointer types along with any more-qualified variants of |
8109 | /// that type. For example, if @p Ty is "int const *", this routine |
8110 | /// will add "int const *", "int const volatile *", "int const |
8111 | /// restrict *", and "int const volatile restrict *" to the set of |
8112 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8113 | /// false otherwise. |
8114 | /// |
8115 | /// FIXME: what to do about extended qualifiers? |
8116 | bool |
8117 | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8118 | const Qualifiers &VisibleQuals) { |
8119 | |
8120 | // Insert this type. |
8121 | if (!PointerTypes.insert(Ty)) |
8122 | return false; |
8123 | |
8124 | QualType PointeeTy; |
8125 | const PointerType *PointerTy = Ty->getAs<PointerType>(); |
8126 | bool buildObjCPtr = false; |
8127 | if (!PointerTy) { |
8128 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); |
8129 | PointeeTy = PTy->getPointeeType(); |
8130 | buildObjCPtr = true; |
8131 | } else { |
8132 | PointeeTy = PointerTy->getPointeeType(); |
8133 | } |
8134 | |
8135 | // Don't add qualified variants of arrays. For one, they're not allowed |
8136 | // (the qualifier would sink to the element type), and for another, the |
8137 | // only overload situation where it matters is subscript or pointer +- int, |
8138 | // and those shouldn't have qualifier variants anyway. |
8139 | if (PointeeTy->isArrayType()) |
8140 | return true; |
8141 | |
8142 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8143 | bool hasVolatile = VisibleQuals.hasVolatile(); |
8144 | bool hasRestrict = VisibleQuals.hasRestrict(); |
8145 | |
8146 | // Iterate through all strict supersets of BaseCVR. |
8147 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8148 | if ((CVR | BaseCVR) != CVR) continue; |
8149 | // Skip over volatile if no volatile found anywhere in the types. |
8150 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; |
8151 | |
8152 | // Skip over restrict if no restrict found anywhere in the types, or if |
8153 | // the type cannot be restrict-qualified. |
8154 | if ((CVR & Qualifiers::Restrict) && |
8155 | (!hasRestrict || |
8156 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) |
8157 | continue; |
8158 | |
8159 | // Build qualified pointee type. |
8160 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
8161 | |
8162 | // Build qualified pointer type. |
8163 | QualType QPointerTy; |
8164 | if (!buildObjCPtr) |
8165 | QPointerTy = Context.getPointerType(QPointeeTy); |
8166 | else |
8167 | QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); |
8168 | |
8169 | // Insert qualified pointer type. |
8170 | PointerTypes.insert(QPointerTy); |
8171 | } |
8172 | |
8173 | return true; |
8174 | } |
8175 | |
8176 | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty |
8177 | /// to the set of pointer types along with any more-qualified variants of |
8178 | /// that type. For example, if @p Ty is "int const *", this routine |
8179 | /// will add "int const *", "int const volatile *", "int const |
8180 | /// restrict *", and "int const volatile restrict *" to the set of |
8181 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8182 | /// false otherwise. |
8183 | /// |
8184 | /// FIXME: what to do about extended qualifiers? |
8185 | bool |
8186 | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( |
8187 | QualType Ty) { |
8188 | // Insert this type. |
8189 | if (!MemberPointerTypes.insert(Ty)) |
8190 | return false; |
8191 | |
8192 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); |
8193 | assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!" ) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\"" , "clang/lib/Sema/SemaOverload.cpp", 8193, __extension__ __PRETTY_FUNCTION__ )); |
8194 | |
8195 | QualType PointeeTy = PointerTy->getPointeeType(); |
8196 | // Don't add qualified variants of arrays. For one, they're not allowed |
8197 | // (the qualifier would sink to the element type), and for another, the |
8198 | // only overload situation where it matters is subscript or pointer +- int, |
8199 | // and those shouldn't have qualifier variants anyway. |
8200 | if (PointeeTy->isArrayType()) |
8201 | return true; |
8202 | const Type *ClassTy = PointerTy->getClass(); |
8203 | |
8204 | // Iterate through all strict supersets of the pointee type's CVR |
8205 | // qualifiers. |
8206 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8207 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8208 | if ((CVR | BaseCVR) != CVR) continue; |
8209 | |
8210 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
8211 | MemberPointerTypes.insert( |
8212 | Context.getMemberPointerType(QPointeeTy, ClassTy)); |
8213 | } |
8214 | |
8215 | return true; |
8216 | } |
8217 | |
8218 | /// AddTypesConvertedFrom - Add each of the types to which the type @p |
8219 | /// Ty can be implicit converted to the given set of @p Types. We're |
8220 | /// primarily interested in pointer types and enumeration types. We also |
8221 | /// take member pointer types, for the conditional operator. |
8222 | /// AllowUserConversions is true if we should look at the conversion |
8223 | /// functions of a class type, and AllowExplicitConversions if we |
8224 | /// should also include the explicit conversion functions of a class |
8225 | /// type. |
8226 | void |
8227 | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, |
8228 | SourceLocation Loc, |
8229 | bool AllowUserConversions, |
8230 | bool AllowExplicitConversions, |
8231 | const Qualifiers &VisibleQuals) { |
8232 | // Only deal with canonical types. |
8233 | Ty = Context.getCanonicalType(Ty); |
8234 | |
8235 | // Look through reference types; they aren't part of the type of an |
8236 | // expression for the purposes of conversions. |
8237 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) |
8238 | Ty = RefTy->getPointeeType(); |
8239 | |
8240 | // If we're dealing with an array type, decay to the pointer. |
8241 | if (Ty->isArrayType()) |
8242 | Ty = SemaRef.Context.getArrayDecayedType(Ty); |
8243 | |
8244 | // Otherwise, we don't care about qualifiers on the type. |
8245 | Ty = Ty.getLocalUnqualifiedType(); |
8246 | |
8247 | // Flag if we ever add a non-record type. |
8248 | const RecordType *TyRec = Ty->getAs<RecordType>(); |
8249 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; |
8250 | |
8251 | // Flag if we encounter an arithmetic type. |
8252 | HasArithmeticOrEnumeralTypes = |
8253 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); |
8254 | |
8255 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) |
8256 | PointerTypes.insert(Ty); |
8257 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { |
8258 | // Insert our type, and its more-qualified variants, into the set |
8259 | // of types. |
8260 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) |
8261 | return; |
8262 | } else if (Ty->isMemberPointerType()) { |
8263 | // Member pointers are far easier, since the pointee can't be converted. |
8264 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) |
8265 | return; |
8266 | } else if (Ty->isEnumeralType()) { |
8267 | HasArithmeticOrEnumeralTypes = true; |
8268 | EnumerationTypes.insert(Ty); |
8269 | } else if (Ty->isVectorType()) { |
8270 | // We treat vector types as arithmetic types in many contexts as an |
8271 | // extension. |
8272 | HasArithmeticOrEnumeralTypes = true; |
8273 | VectorTypes.insert(Ty); |
8274 | } else if (Ty->isMatrixType()) { |
8275 | // Similar to vector types, we treat vector types as arithmetic types in |
8276 | // many contexts as an extension. |
8277 | HasArithmeticOrEnumeralTypes = true; |
8278 | MatrixTypes.insert(Ty); |
8279 | } else if (Ty->isNullPtrType()) { |
8280 | HasNullPtrType = true; |
8281 | } else if (AllowUserConversions && TyRec) { |
8282 | // No conversion functions in incomplete types. |
8283 | if (!SemaRef.isCompleteType(Loc, Ty)) |
8284 | return; |
8285 | |
8286 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
8287 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8288 | if (isa<UsingShadowDecl>(D)) |
8289 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
8290 | |
8291 | // Skip conversion function templates; they don't tell us anything |
8292 | // about which builtin types we can convert to. |
8293 | if (isa<FunctionTemplateDecl>(D)) |
8294 | continue; |
8295 | |
8296 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
8297 | if (AllowExplicitConversions || !Conv->isExplicit()) { |
8298 | AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, |
8299 | VisibleQuals); |
8300 | } |
8301 | } |
8302 | } |
8303 | } |
8304 | /// Helper function for adjusting address spaces for the pointer or reference |
8305 | /// operands of builtin operators depending on the argument. |
8306 | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, |
8307 | Expr *Arg) { |
8308 | return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); |
8309 | } |
8310 | |
8311 | /// Helper function for AddBuiltinOperatorCandidates() that adds |
8312 | /// the volatile- and non-volatile-qualified assignment operators for the |
8313 | /// given type to the candidate set. |
8314 | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, |
8315 | QualType T, |
8316 | ArrayRef<Expr *> Args, |
8317 | OverloadCandidateSet &CandidateSet) { |
8318 | QualType ParamTypes[2]; |
8319 | |
8320 | // T& operator=(T&, T) |
8321 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8322 | AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); |
8323 | ParamTypes[1] = T; |
8324 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8325 | /*IsAssignmentOperator=*/true); |
8326 | |
8327 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { |
8328 | // volatile T& operator=(volatile T&, T) |
8329 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8330 | AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), |
8331 | Args[0])); |
8332 | ParamTypes[1] = T; |
8333 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8334 | /*IsAssignmentOperator=*/true); |
8335 | } |
8336 | } |
8337 | |
8338 | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, |
8339 | /// if any, found in visible type conversion functions found in ArgExpr's type. |
8340 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { |
8341 | Qualifiers VRQuals; |
8342 | const RecordType *TyRec; |
8343 | if (const MemberPointerType *RHSMPType = |
8344 | ArgExpr->getType()->getAs<MemberPointerType>()) |
8345 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); |
8346 | else |
8347 | TyRec = ArgExpr->getType()->getAs<RecordType>(); |
8348 | if (!TyRec) { |
8349 | // Just to be safe, assume the worst case. |
8350 | VRQuals.addVolatile(); |
8351 | VRQuals.addRestrict(); |
8352 | return VRQuals; |
8353 | } |
8354 | |
8355 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
8356 | if (!ClassDecl->hasDefinition()) |
8357 | return VRQuals; |
8358 | |
8359 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8360 | if (isa<UsingShadowDecl>(D)) |
8361 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
8362 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { |
8363 | QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); |
8364 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) |
8365 | CanTy = ResTypeRef->getPointeeType(); |
8366 | // Need to go down the pointer/mempointer chain and add qualifiers |
8367 | // as see them. |
8368 | bool done = false; |
8369 | while (!done) { |
8370 | if (CanTy.isRestrictQualified()) |
8371 | VRQuals.addRestrict(); |
8372 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) |
8373 | CanTy = ResTypePtr->getPointeeType(); |
8374 | else if (const MemberPointerType *ResTypeMPtr = |
8375 | CanTy->getAs<MemberPointerType>()) |
8376 | CanTy = ResTypeMPtr->getPointeeType(); |
8377 | else |
8378 | done = true; |
8379 | if (CanTy.isVolatileQualified()) |
8380 | VRQuals.addVolatile(); |
8381 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) |
8382 | return VRQuals; |
8383 | } |
8384 | } |
8385 | } |
8386 | return VRQuals; |
8387 | } |
8388 | |
8389 | // Note: We're currently only handling qualifiers that are meaningful for the |
8390 | // LHS of compound assignment overloading. |
8391 | static void forAllQualifierCombinationsImpl( |
8392 | QualifiersAndAtomic Available, QualifiersAndAtomic Applied, |
8393 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8394 | // _Atomic |
8395 | if (Available.hasAtomic()) { |
8396 | Available.removeAtomic(); |
8397 | forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); |
8398 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8399 | return; |
8400 | } |
8401 | |
8402 | // volatile |
8403 | if (Available.hasVolatile()) { |
8404 | Available.removeVolatile(); |
8405 | assert(!Applied.hasVolatile())(static_cast <bool> (!Applied.hasVolatile()) ? void (0) : __assert_fail ("!Applied.hasVolatile()", "clang/lib/Sema/SemaOverload.cpp" , 8405, __extension__ __PRETTY_FUNCTION__)); |
8406 | forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), |
8407 | Callback); |
8408 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8409 | return; |
8410 | } |
8411 | |
8412 | Callback(Applied); |
8413 | } |
8414 | |
8415 | static void forAllQualifierCombinations( |
8416 | QualifiersAndAtomic Quals, |
8417 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8418 | return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), |
8419 | Callback); |
8420 | } |
8421 | |
8422 | static QualType makeQualifiedLValueReferenceType(QualType Base, |
8423 | QualifiersAndAtomic Quals, |
8424 | Sema &S) { |
8425 | if (Quals.hasAtomic()) |
8426 | Base = S.Context.getAtomicType(Base); |
8427 | if (Quals.hasVolatile()) |
8428 | Base = S.Context.getVolatileType(Base); |
8429 | return S.Context.getLValueReferenceType(Base); |
8430 | } |
8431 | |
8432 | namespace { |
8433 | |
8434 | /// Helper class to manage the addition of builtin operator overload |
8435 | /// candidates. It provides shared state and utility methods used throughout |
8436 | /// the process, as well as a helper method to add each group of builtin |
8437 | /// operator overloads from the standard to a candidate set. |
8438 | class BuiltinOperatorOverloadBuilder { |
8439 | // Common instance state available to all overload candidate addition methods. |
8440 | Sema &S; |
8441 | ArrayRef<Expr *> Args; |
8442 | QualifiersAndAtomic VisibleTypeConversionsQuals; |
8443 | bool HasArithmeticOrEnumeralCandidateType; |
8444 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; |
8445 | OverloadCandidateSet &CandidateSet; |
8446 | |
8447 | static constexpr int ArithmeticTypesCap = 24; |
8448 | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; |
8449 | |
8450 | // Define some indices used to iterate over the arithmetic types in |
8451 | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic |
8452 | // types are that preserved by promotion (C++ [over.built]p2). |
8453 | unsigned FirstIntegralType, |
8454 | LastIntegralType; |
8455 | unsigned FirstPromotedIntegralType, |
8456 | LastPromotedIntegralType; |
8457 | unsigned FirstPromotedArithmeticType, |
8458 | LastPromotedArithmeticType; |
8459 | unsigned NumArithmeticTypes; |
8460 | |
8461 | void InitArithmeticTypes() { |
8462 | // Start of promoted types. |
8463 | FirstPromotedArithmeticType = 0; |
8464 | ArithmeticTypes.push_back(S.Context.FloatTy); |
8465 | ArithmeticTypes.push_back(S.Context.DoubleTy); |
8466 | ArithmeticTypes.push_back(S.Context.LongDoubleTy); |
8467 | if (S.Context.getTargetInfo().hasFloat128Type()) |
8468 | ArithmeticTypes.push_back(S.Context.Float128Ty); |
8469 | if (S.Context.getTargetInfo().hasIbm128Type()) |
8470 | ArithmeticTypes.push_back(S.Context.Ibm128Ty); |
8471 | |
8472 | // Start of integral types. |
8473 | FirstIntegralType = ArithmeticTypes.size(); |
8474 | FirstPromotedIntegralType = ArithmeticTypes.size(); |
8475 | ArithmeticTypes.push_back(S.Context.IntTy); |
8476 | ArithmeticTypes.push_back(S.Context.LongTy); |
8477 | ArithmeticTypes.push_back(S.Context.LongLongTy); |
8478 | if (S.Context.getTargetInfo().hasInt128Type() || |
8479 | (S.Context.getAuxTargetInfo() && |
8480 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8481 | ArithmeticTypes.push_back(S.Context.Int128Ty); |
8482 | ArithmeticTypes.push_back(S.Context.UnsignedIntTy); |
8483 | ArithmeticTypes.push_back(S.Context.UnsignedLongTy); |
8484 | ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); |
8485 | if (S.Context.getTargetInfo().hasInt128Type() || |
8486 | (S.Context.getAuxTargetInfo() && |
8487 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8488 | ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); |
8489 | LastPromotedIntegralType = ArithmeticTypes.size(); |
8490 | LastPromotedArithmeticType = ArithmeticTypes.size(); |
8491 | // End of promoted types. |
8492 | |
8493 | ArithmeticTypes.push_back(S.Context.BoolTy); |
8494 | ArithmeticTypes.push_back(S.Context.CharTy); |
8495 | ArithmeticTypes.push_back(S.Context.WCharTy); |
8496 | if (S.Context.getLangOpts().Char8) |
8497 | ArithmeticTypes.push_back(S.Context.Char8Ty); |
8498 | ArithmeticTypes.push_back(S.Context.Char16Ty); |
8499 | ArithmeticTypes.push_back(S.Context.Char32Ty); |
8500 | ArithmeticTypes.push_back(S.Context.SignedCharTy); |
8501 | ArithmeticTypes.push_back(S.Context.ShortTy); |
8502 | ArithmeticTypes.push_back(S.Context.UnsignedCharTy); |
8503 | ArithmeticTypes.push_back(S.Context.UnsignedShortTy); |
8504 | LastIntegralType = ArithmeticTypes.size(); |
8505 | NumArithmeticTypes = ArithmeticTypes.size(); |
8506 | // End of integral types. |
8507 | // FIXME: What about complex? What about half? |
8508 | |
8509 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "clang/lib/Sema/SemaOverload.cpp", 8510, __extension__ __PRETTY_FUNCTION__ )) |
8510 | "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "clang/lib/Sema/SemaOverload.cpp", 8510, __extension__ __PRETTY_FUNCTION__ )); |
8511 | } |
8512 | |
8513 | /// Helper method to factor out the common pattern of adding overloads |
8514 | /// for '++' and '--' builtin operators. |
8515 | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, |
8516 | bool HasVolatile, |
8517 | bool HasRestrict) { |
8518 | QualType ParamTypes[2] = { |
8519 | S.Context.getLValueReferenceType(CandidateTy), |
8520 | S.Context.IntTy |
8521 | }; |
8522 | |
8523 | // Non-volatile version. |
8524 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8525 | |
8526 | // Use a heuristic to reduce number of builtin candidates in the set: |
8527 | // add volatile version only if there are conversions to a volatile type. |
8528 | if (HasVolatile) { |
8529 | ParamTypes[0] = |
8530 | S.Context.getLValueReferenceType( |
8531 | S.Context.getVolatileType(CandidateTy)); |
8532 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8533 | } |
8534 | |
8535 | // Add restrict version only if there are conversions to a restrict type |
8536 | // and our candidate type is a non-restrict-qualified pointer. |
8537 | if (HasRestrict && CandidateTy->isAnyPointerType() && |
8538 | !CandidateTy.isRestrictQualified()) { |
8539 | ParamTypes[0] |
8540 | = S.Context.getLValueReferenceType( |
8541 | S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); |
8542 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8543 | |
8544 | if (HasVolatile) { |
8545 | ParamTypes[0] |
8546 | = S.Context.getLValueReferenceType( |
8547 | S.Context.getCVRQualifiedType(CandidateTy, |
8548 | (Qualifiers::Volatile | |
8549 | Qualifiers::Restrict))); |
8550 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8551 | } |
8552 | } |
8553 | |
8554 | } |
8555 | |
8556 | /// Helper to add an overload candidate for a binary builtin with types \p L |
8557 | /// and \p R. |
8558 | void AddCandidate(QualType L, QualType R) { |
8559 | QualType LandR[2] = {L, R}; |
8560 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8561 | } |
8562 | |
8563 | public: |
8564 | BuiltinOperatorOverloadBuilder( |
8565 | Sema &S, ArrayRef<Expr *> Args, |
8566 | QualifiersAndAtomic VisibleTypeConversionsQuals, |
8567 | bool HasArithmeticOrEnumeralCandidateType, |
8568 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, |
8569 | OverloadCandidateSet &CandidateSet) |
8570 | : S(S), Args(Args), |
8571 | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), |
8572 | HasArithmeticOrEnumeralCandidateType( |
8573 | HasArithmeticOrEnumeralCandidateType), |
8574 | CandidateTypes(CandidateTypes), |
8575 | CandidateSet(CandidateSet) { |
8576 | |
8577 | InitArithmeticTypes(); |
8578 | } |
8579 | |
8580 | // Increment is deprecated for bool since C++17. |
8581 | // |
8582 | // C++ [over.built]p3: |
8583 | // |
8584 | // For every pair (T, VQ), where T is an arithmetic type other |
8585 | // than bool, and VQ is either volatile or empty, there exist |
8586 | // candidate operator functions of the form |
8587 | // |
8588 | // VQ T& operator++(VQ T&); |
8589 | // T operator++(VQ T&, int); |
8590 | // |
8591 | // C++ [over.built]p4: |
8592 | // |
8593 | // For every pair (T, VQ), where T is an arithmetic type other |
8594 | // than bool, and VQ is either volatile or empty, there exist |
8595 | // candidate operator functions of the form |
8596 | // |
8597 | // VQ T& operator--(VQ T&); |
8598 | // T operator--(VQ T&, int); |
8599 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { |
8600 | if (!HasArithmeticOrEnumeralCandidateType) |
8601 | return; |
8602 | |
8603 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { |
8604 | const auto TypeOfT = ArithmeticTypes[Arith]; |
8605 | if (TypeOfT == S.Context.BoolTy) { |
8606 | if (Op == OO_MinusMinus) |
8607 | continue; |
8608 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) |
8609 | continue; |
8610 | } |
8611 | addPlusPlusMinusMinusStyleOverloads( |
8612 | TypeOfT, |
8613 | VisibleTypeConversionsQuals.hasVolatile(), |
8614 | VisibleTypeConversionsQuals.hasRestrict()); |
8615 | } |
8616 | } |
8617 | |
8618 | // C++ [over.built]p5: |
8619 | // |
8620 | // For every pair (T, VQ), where T is a cv-qualified or |
8621 | // cv-unqualified object type, and VQ is either volatile or |
8622 | // empty, there exist candidate operator functions of the form |
8623 | // |
8624 | // T*VQ& operator++(T*VQ&); |
8625 | // T*VQ& operator--(T*VQ&); |
8626 | // T* operator++(T*VQ&, int); |
8627 | // T* operator--(T*VQ&, int); |
8628 | void addPlusPlusMinusMinusPointerOverloads() { |
8629 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
8630 | // Skip pointer types that aren't pointers to object types. |
8631 | if (!PtrTy->getPointeeType()->isObjectType()) |
8632 | continue; |
8633 | |
8634 | addPlusPlusMinusMinusStyleOverloads( |
8635 | PtrTy, |
8636 | (!PtrTy.isVolatileQualified() && |
8637 | VisibleTypeConversionsQuals.hasVolatile()), |
8638 | (!PtrTy.isRestrictQualified() && |
8639 | VisibleTypeConversionsQuals.hasRestrict())); |
8640 | } |
8641 | } |
8642 | |
8643 | // C++ [over.built]p6: |
8644 | // For every cv-qualified or cv-unqualified object type T, there |
8645 | // exist candidate operator functions of the form |
8646 | // |
8647 | // T& operator*(T*); |
8648 | // |
8649 | // C++ [over.built]p7: |
8650 | // For every function type T that does not have cv-qualifiers or a |
8651 | // ref-qualifier, there exist candidate operator functions of the form |
8652 | // T& operator*(T*); |
8653 | void addUnaryStarPointerOverloads() { |
8654 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) { |
8655 | QualType PointeeTy = ParamTy->getPointeeType(); |
8656 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) |
8657 | continue; |
8658 | |
8659 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) |
8660 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) |
8661 | continue; |
8662 | |
8663 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
8664 | } |
8665 | } |
8666 | |
8667 | // C++ [over.built]p9: |
8668 | // For every promoted arithmetic type T, there exist candidate |
8669 | // operator functions of the form |
8670 | // |
8671 | // T operator+(T); |
8672 | // T operator-(T); |
8673 | void addUnaryPlusOrMinusArithmeticOverloads() { |
8674 | if (!HasArithmeticOrEnumeralCandidateType) |
8675 | return; |
8676 | |
8677 | for (unsigned Arith = FirstPromotedArithmeticType; |
8678 | Arith < LastPromotedArithmeticType; ++Arith) { |
8679 | QualType ArithTy = ArithmeticTypes[Arith]; |
8680 | S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); |
8681 | } |
8682 | |
8683 | // Extension: We also add these operators for vector types. |
8684 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
8685 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
8686 | } |
8687 | |
8688 | // C++ [over.built]p8: |
8689 | // For every type T, there exist candidate operator functions of |
8690 | // the form |
8691 | // |
8692 | // T* operator+(T*); |
8693 | void addUnaryPlusPointerOverloads() { |
8694 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) |
8695 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
8696 | } |
8697 | |
8698 | // C++ [over.built]p10: |
8699 | // For every promoted integral type T, there exist candidate |
8700 | // operator functions of the form |
8701 | // |
8702 | // T operator~(T); |
8703 | void addUnaryTildePromotedIntegralOverloads() { |
8704 | if (!HasArithmeticOrEnumeralCandidateType) |
8705 | return; |
8706 | |
8707 | for (unsigned Int = FirstPromotedIntegralType; |
8708 | Int < LastPromotedIntegralType; ++Int) { |
8709 | QualType IntTy = ArithmeticTypes[Int]; |
8710 | S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); |
8711 | } |
8712 | |
8713 | // Extension: We also add this operator for vector types. |
8714 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
8715 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
8716 | } |
8717 | |
8718 | // C++ [over.match.oper]p16: |
8719 | // For every pointer to member type T or type std::nullptr_t, there |
8720 | // exist candidate operator functions of the form |
8721 | // |
8722 | // bool operator==(T,T); |
8723 | // bool operator!=(T,T); |
8724 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { |
8725 | /// Set of (canonical) types that we've already handled. |
8726 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8727 | |
8728 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8729 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
8730 | // Don't add the same builtin candidate twice. |
8731 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
8732 | continue; |
8733 | |
8734 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
8735 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8736 | } |
8737 | |
8738 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { |
8739 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); |
8740 | if (AddedTypes.insert(NullPtrTy).second) { |
8741 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; |
8742 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8743 | } |
8744 | } |
8745 | } |
8746 | } |
8747 | |
8748 | // C++ [over.built]p15: |
8749 | // |
8750 | // For every T, where T is an enumeration type or a pointer type, |
8751 | // there exist candidate operator functions of the form |
8752 | // |
8753 | // bool operator<(T, T); |
8754 | // bool operator>(T, T); |
8755 | // bool operator<=(T, T); |
8756 | // bool operator>=(T, T); |
8757 | // bool operator==(T, T); |
8758 | // bool operator!=(T, T); |
8759 | // R operator<=>(T, T) |
8760 | void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { |
8761 | // C++ [over.match.oper]p3: |
8762 | // [...]the built-in candidates include all of the candidate operator |
8763 | // functions defined in 13.6 that, compared to the given operator, [...] |
8764 | // do not have the same parameter-type-list as any non-template non-member |
8765 | // candidate. |
8766 | // |
8767 | // Note that in practice, this only affects enumeration types because there |
8768 | // aren't any built-in candidates of record type, and a user-defined operator |
8769 | // must have an operand of record or enumeration type. Also, the only other |
8770 | // overloaded operator with enumeration arguments, operator=, |
8771 | // cannot be overloaded for enumeration types, so this is the only place |
8772 | // where we must suppress candidates like this. |
8773 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > |
8774 | UserDefinedBinaryOperators; |
8775 | |
8776 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8777 | if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { |
8778 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), |
8779 | CEnd = CandidateSet.end(); |
8780 | C != CEnd; ++C) { |
8781 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) |
8782 | continue; |
8783 | |
8784 | if (C->Function->isFunctionTemplateSpecialization()) |
8785 | continue; |
8786 | |
8787 | // We interpret "same parameter-type-list" as applying to the |
8788 | // "synthesized candidate, with the order of the two parameters |
8789 | // reversed", not to the original function. |
8790 | bool Reversed = C->isReversed(); |
8791 | QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) |
8792 | ->getType() |
8793 | .getUnqualifiedType(); |
8794 | QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) |
8795 | ->getType() |
8796 | .getUnqualifiedType(); |
8797 | |
8798 | // Skip if either parameter isn't of enumeral type. |
8799 | if (!FirstParamType->isEnumeralType() || |
8800 | !SecondParamType->isEnumeralType()) |
8801 | continue; |
8802 | |
8803 | // Add this operator to the set of known user-defined operators. |
8804 | UserDefinedBinaryOperators.insert( |
8805 | std::make_pair(S.Context.getCanonicalType(FirstParamType), |
8806 | S.Context.getCanonicalType(SecondParamType))); |
8807 | } |
8808 | } |
8809 | } |
8810 | |
8811 | /// Set of (canonical) types that we've already handled. |
8812 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8813 | |
8814 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8815 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
8816 | // Don't add the same builtin candidate twice. |
8817 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
8818 | continue; |
8819 | if (IsSpaceship && PtrTy->isFunctionPointerType()) |
8820 | continue; |
8821 | |
8822 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
8823 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8824 | } |
8825 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
8826 | CanQualType CanonType = S.Context.getCanonicalType(EnumTy); |
8827 | |
8828 | // Don't add the same builtin candidate twice, or if a user defined |
8829 | // candidate exists. |
8830 | if (!AddedTypes.insert(CanonType).second || |
8831 | UserDefinedBinaryOperators.count(std::make_pair(CanonType, |
8832 | CanonType))) |
8833 | continue; |
8834 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
8835 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8836 | } |
8837 | } |
8838 | } |
8839 | |
8840 | // C++ [over.built]p13: |
8841 | // |
8842 | // For every cv-qualified or cv-unqualified object type T |
8843 | // there exist candidate operator functions of the form |
8844 | // |
8845 | // T* operator+(T*, ptrdiff_t); |
8846 | // T& operator[](T*, ptrdiff_t); [BELOW] |
8847 | // T* operator-(T*, ptrdiff_t); |
8848 | // T* operator+(ptrdiff_t, T*); |
8849 | // T& operator[](ptrdiff_t, T*); [BELOW] |
8850 | // |
8851 | // C++ [over.built]p14: |
8852 | // |
8853 | // For every T, where T is a pointer to object type, there |
8854 | // exist candidate operator functions of the form |
8855 | // |
8856 | // ptrdiff_t operator-(T, T); |
8857 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { |
8858 | /// Set of (canonical) types that we've already handled. |
8859 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8860 | |
8861 | for (int Arg = 0; Arg < 2; ++Arg) { |
8862 | QualType AsymmetricParamTypes[2] = { |
8863 | S.Context.getPointerDiffType(), |
8864 | S.Context.getPointerDiffType(), |
8865 | }; |
8866 | for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { |
8867 | QualType PointeeTy = PtrTy->getPointeeType(); |
8868 | if (!PointeeTy->isObjectType()) |
8869 | continue; |
8870 | |
8871 | AsymmetricParamTypes[Arg] = PtrTy; |
8872 | if (Arg == 0 || Op == OO_Plus) { |
8873 | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) |
8874 | // T* operator+(ptrdiff_t, T*); |
8875 | S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); |
8876 | } |
8877 | if (Op == OO_Minus) { |
8878 | // ptrdiff_t operator-(T, T); |
8879 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
8880 | continue; |
8881 | |
8882 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
8883 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8884 | } |
8885 | } |
8886 | } |
8887 | } |
8888 | |
8889 | // C++ [over.built]p12: |
8890 | // |
8891 | // For every pair of promoted arithmetic types L and R, there |
8892 | // exist candidate operator functions of the form |
8893 | // |
8894 | // LR operator*(L, R); |
8895 | // LR operator/(L, R); |
8896 | // LR operator+(L, R); |
8897 | // LR operator-(L, R); |
8898 | // bool operator<(L, R); |
8899 | // bool operator>(L, R); |
8900 | // bool operator<=(L, R); |
8901 | // bool operator>=(L, R); |
8902 | // bool operator==(L, R); |
8903 | // bool operator!=(L, R); |
8904 | // |
8905 | // where LR is the result of the usual arithmetic conversions |
8906 | // between types L and R. |
8907 | // |
8908 | // C++ [over.built]p24: |
8909 | // |
8910 | // For every pair of promoted arithmetic types L and R, there exist |
8911 | // candidate operator functions of the form |
8912 | // |
8913 | // LR operator?(bool, L, R); |
8914 | // |
8915 | // where LR is the result of the usual arithmetic conversions |
8916 | // between types L and R. |
8917 | // Our candidates ignore the first parameter. |
8918 | void addGenericBinaryArithmeticOverloads() { |
8919 | if (!HasArithmeticOrEnumeralCandidateType) |
8920 | return; |
8921 | |
8922 | for (unsigned Left = FirstPromotedArithmeticType; |
8923 | Left < LastPromotedArithmeticType; ++Left) { |
8924 | for (unsigned Right = FirstPromotedArithmeticType; |
8925 | Right < LastPromotedArithmeticType; ++Right) { |
8926 | QualType LandR[2] = { ArithmeticTypes[Left], |
8927 | ArithmeticTypes[Right] }; |
8928 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8929 | } |
8930 | } |
8931 | |
8932 | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the |
8933 | // conditional operator for vector types. |
8934 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
8935 | for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { |
8936 | QualType LandR[2] = {Vec1Ty, Vec2Ty}; |
8937 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8938 | } |
8939 | } |
8940 | |
8941 | /// Add binary operator overloads for each candidate matrix type M1, M2: |
8942 | /// * (M1, M1) -> M1 |
8943 | /// * (M1, M1.getElementType()) -> M1 |
8944 | /// * (M2.getElementType(), M2) -> M2 |
8945 | /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. |
8946 | void addMatrixBinaryArithmeticOverloads() { |
8947 | if (!HasArithmeticOrEnumeralCandidateType) |
8948 | return; |
8949 | |
8950 | for (QualType M1 : CandidateTypes[0].matrix_types()) { |
8951 | AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); |
8952 | AddCandidate(M1, M1); |
8953 | } |
8954 | |
8955 | for (QualType M2 : CandidateTypes[1].matrix_types()) { |
8956 | AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); |
8957 | if (!CandidateTypes[0].containsMatrixType(M2)) |
8958 | AddCandidate(M2, M2); |
8959 | } |
8960 | } |
8961 | |
8962 | // C++2a [over.built]p14: |
8963 | // |
8964 | // For every integral type T there exists a candidate operator function |
8965 | // of the form |
8966 | // |
8967 | // std::strong_ordering operator<=>(T, T) |
8968 | // |
8969 | // C++2a [over.built]p15: |
8970 | // |
8971 | // For every pair of floating-point types L and R, there exists a candidate |
8972 | // operator function of the form |
8973 | // |
8974 | // std::partial_ordering operator<=>(L, R); |
8975 | // |
8976 | // FIXME: The current specification for integral types doesn't play nice with |
8977 | // the direction of p0946r0, which allows mixed integral and unscoped-enum |
8978 | // comparisons. Under the current spec this can lead to ambiguity during |
8979 | // overload resolution. For example: |
8980 | // |
8981 | // enum A : int {a}; |
8982 | // auto x = (a <=> (long)42); |
8983 | // |
8984 | // error: call is ambiguous for arguments 'A' and 'long'. |
8985 | // note: candidate operator<=>(int, int) |
8986 | // note: candidate operator<=>(long, long) |
8987 | // |
8988 | // To avoid this error, this function deviates from the specification and adds |
8989 | // the mixed overloads `operator<=>(L, R)` where L and R are promoted |
8990 | // arithmetic types (the same as the generic relational overloads). |
8991 | // |
8992 | // For now this function acts as a placeholder. |
8993 | void addThreeWayArithmeticOverloads() { |
8994 | addGenericBinaryArithmeticOverloads(); |
8995 | } |
8996 | |
8997 | // C++ [over.built]p17: |
8998 | // |
8999 | // For every pair of promoted integral types L and R, there |
9000 | // exist candidate operator functions of the form |
9001 | // |
9002 | // LR operator%(L, R); |
9003 | // LR operator&(L, R); |
9004 | // LR operator^(L, R); |
9005 | // LR operator|(L, R); |
9006 | // L operator<<(L, R); |
9007 | // L operator>>(L, R); |
9008 | // |
9009 | // where LR is the result of the usual arithmetic conversions |
9010 | // between types L and R. |
9011 | void addBinaryBitwiseArithmeticOverloads() { |
9012 | if (!HasArithmeticOrEnumeralCandidateType) |
9013 | return; |
9014 | |
9015 | for (unsigned Left = FirstPromotedIntegralType; |
9016 | Left < LastPromotedIntegralType; ++Left) { |
9017 | for (unsigned Right = FirstPromotedIntegralType; |
9018 | Right < LastPromotedIntegralType; ++Right) { |
9019 | QualType LandR[2] = { ArithmeticTypes[Left], |
9020 | ArithmeticTypes[Right] }; |
9021 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
9022 | } |
9023 | } |
9024 | } |
9025 | |
9026 | // C++ [over.built]p20: |
9027 | // |
9028 | // For every pair (T, VQ), where T is an enumeration or |
9029 | // pointer to member type and VQ is either volatile or |
9030 | // empty, there exist candidate operator functions of the form |
9031 | // |
9032 | // VQ T& operator=(VQ T&, T); |
9033 | void addAssignmentMemberPointerOrEnumeralOverloads() { |
9034 | /// Set of (canonical) types that we've already handled. |
9035 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9036 | |
9037 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9038 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9039 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) |
9040 | continue; |
9041 | |
9042 | AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); |
9043 | } |
9044 | |
9045 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9046 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
9047 | continue; |
9048 | |
9049 | AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); |
9050 | } |
9051 | } |
9052 | } |
9053 | |
9054 | // C++ [over.built]p19: |
9055 | // |
9056 | // For every pair (T, VQ), where T is any type and VQ is either |
9057 | // volatile or empty, there exist candidate operator functions |
9058 | // of the form |
9059 | // |
9060 | // T*VQ& operator=(T*VQ&, T*); |
9061 | // |
9062 | // C++ [over.built]p21: |
9063 | // |
9064 | // For every pair (T, VQ), where T is a cv-qualified or |
9065 | // cv-unqualified object type and VQ is either volatile or |
9066 | // empty, there exist candidate operator functions of the form |
9067 | // |
9068 | // T*VQ& operator+=(T*VQ&, ptrdiff_t); |
9069 | // T*VQ& operator-=(T*VQ&, ptrdiff_t); |
9070 | void addAssignmentPointerOverloads(bool isEqualOp) { |
9071 | /// Set of (canonical) types that we've already handled. |
9072 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9073 | |
9074 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9075 | // If this is operator=, keep track of the builtin candidates we added. |
9076 | if (isEqualOp) |
9077 | AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); |
9078 | else if (!PtrTy->getPointeeType()->isObjectType()) |
9079 | continue; |
9080 | |
9081 | // non-volatile version |
9082 | QualType ParamTypes[2] = { |
9083 | S.Context.getLValueReferenceType(PtrTy), |
9084 | isEqualOp ? PtrTy : S.Context.getPointerDiffType(), |
9085 | }; |
9086 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9087 | /*IsAssignmentOperator=*/ isEqualOp); |
9088 | |
9089 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9090 | VisibleTypeConversionsQuals.hasVolatile(); |
9091 | if (NeedVolatile) { |
9092 | // volatile version |
9093 | ParamTypes[0] = |
9094 | S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); |
9095 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9096 | /*IsAssignmentOperator=*/isEqualOp); |
9097 | } |
9098 | |
9099 | if (!PtrTy.isRestrictQualified() && |
9100 | VisibleTypeConversionsQuals.hasRestrict()) { |
9101 | // restrict version |
9102 | ParamTypes[0] = |
9103 | S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); |
9104 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9105 | /*IsAssignmentOperator=*/isEqualOp); |
9106 | |
9107 | if (NeedVolatile) { |
9108 | // volatile restrict version |
9109 | ParamTypes[0] = |
9110 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( |
9111 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); |
9112 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9113 | /*IsAssignmentOperator=*/isEqualOp); |
9114 | } |
9115 | } |
9116 | } |
9117 | |
9118 | if (isEqualOp) { |
9119 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9120 | // Make sure we don't add the same candidate twice. |
9121 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9122 | continue; |
9123 | |
9124 | QualType ParamTypes[2] = { |
9125 | S.Context.getLValueReferenceType(PtrTy), |
9126 | PtrTy, |
9127 | }; |
9128 | |
9129 | // non-volatile version |
9130 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9131 | /*IsAssignmentOperator=*/true); |
9132 | |
9133 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9134 | VisibleTypeConversionsQuals.hasVolatile(); |
9135 | if (NeedVolatile) { |
9136 | // volatile version |
9137 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9138 | S.Context.getVolatileType(PtrTy)); |
9139 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9140 | /*IsAssignmentOperator=*/true); |
9141 | } |
9142 | |
9143 | if (!PtrTy.isRestrictQualified() && |
9144 | VisibleTypeConversionsQuals.hasRestrict()) { |
9145 | // restrict version |
9146 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9147 | S.Context.getRestrictType(PtrTy)); |
9148 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9149 | /*IsAssignmentOperator=*/true); |
9150 | |
9151 | if (NeedVolatile) { |
9152 | // volatile restrict version |
9153 | ParamTypes[0] = |
9154 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( |
9155 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); |
9156 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9157 | /*IsAssignmentOperator=*/true); |
9158 | } |
9159 | } |
9160 | } |
9161 | } |
9162 | } |
9163 | |
9164 | // C++ [over.built]p18: |
9165 | // |
9166 | // For every triple (L, VQ, R), where L is an arithmetic type, |
9167 | // VQ is either volatile or empty, and R is a promoted |
9168 | // arithmetic type, there exist candidate operator functions of |
9169 | // the form |
9170 | // |
9171 | // VQ L& operator=(VQ L&, R); |
9172 | // VQ L& operator*=(VQ L&, R); |
9173 | // VQ L& operator/=(VQ L&, R); |
9174 | // VQ L& operator+=(VQ L&, R); |
9175 | // VQ L& operator-=(VQ L&, R); |
9176 | void addAssignmentArithmeticOverloads(bool isEqualOp) { |
9177 | if (!HasArithmeticOrEnumeralCandidateType) |
9178 | return; |
9179 | |
9180 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { |
9181 | for (unsigned Right = FirstPromotedArithmeticType; |
9182 | Right < LastPromotedArithmeticType; ++Right) { |
9183 | QualType ParamTypes[2]; |
9184 | ParamTypes[1] = ArithmeticTypes[Right]; |
9185 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9186 | S, ArithmeticTypes[Left], Args[0]); |
9187 | |
9188 | forAllQualifierCombinations( |
9189 | VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { |
9190 | ParamTypes[0] = |
9191 | makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); |
9192 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9193 | /*IsAssignmentOperator=*/isEqualOp); |
9194 | }); |
9195 | } |
9196 | } |
9197 | |
9198 | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. |
9199 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
9200 | for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { |
9201 | QualType ParamTypes[2]; |
9202 | ParamTypes[1] = Vec2Ty; |
9203 | // Add this built-in operator as a candidate (VQ is empty). |
9204 | ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); |
9205 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9206 | /*IsAssignmentOperator=*/isEqualOp); |
9207 | |
9208 | // Add this built-in operator as a candidate (VQ is 'volatile'). |
9209 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
9210 | ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); |
9211 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); |
9212 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9213 | /*IsAssignmentOperator=*/isEqualOp); |
9214 | } |
9215 | } |
9216 | } |
9217 | |
9218 | // C++ [over.built]p22: |
9219 | // |
9220 | // For every triple (L, VQ, R), where L is an integral type, VQ |
9221 | // is either volatile or empty, and R is a promoted integral |
9222 | // type, there exist candidate operator functions of the form |
9223 | // |
9224 | // VQ L& operator%=(VQ L&, R); |
9225 | // VQ L& operator<<=(VQ L&, R); |
9226 | // VQ L& operator>>=(VQ L&, R); |
9227 | // VQ L& operator&=(VQ L&, R); |
9228 | // VQ L& operator^=(VQ L&, R); |
9229 | // VQ L& operator|=(VQ L&, R); |
9230 | void addAssignmentIntegralOverloads() { |
9231 | if (!HasArithmeticOrEnumeralCandidateType) |
9232 | return; |
9233 | |
9234 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { |
9235 | for (unsigned Right = FirstPromotedIntegralType; |
9236 | Right < LastPromotedIntegralType; ++Right) { |
9237 | QualType ParamTypes[2]; |
9238 | ParamTypes[1] = ArithmeticTypes[Right]; |
9239 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9240 | S, ArithmeticTypes[Left], Args[0]); |
9241 | |
9242 | forAllQualifierCombinations( |
9243 | VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { |
9244 | ParamTypes[0] = |
9245 | makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); |
9246 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9247 | }); |
9248 | } |
9249 | } |
9250 | } |
9251 | |
9252 | // C++ [over.operator]p23: |
9253 | // |
9254 | // There also exist candidate operator functions of the form |
9255 | // |
9256 | // bool operator!(bool); |
9257 | // bool operator&&(bool, bool); |
9258 | // bool operator||(bool, bool); |
9259 | void addExclaimOverload() { |
9260 | QualType ParamTy = S.Context.BoolTy; |
9261 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, |
9262 | /*IsAssignmentOperator=*/false, |
9263 | /*NumContextualBoolArguments=*/1); |
9264 | } |
9265 | void addAmpAmpOrPipePipeOverload() { |
9266 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; |
9267 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9268 | /*IsAssignmentOperator=*/false, |
9269 | /*NumContextualBoolArguments=*/2); |
9270 | } |
9271 | |
9272 | // C++ [over.built]p13: |
9273 | // |
9274 | // For every cv-qualified or cv-unqualified object type T there |
9275 | // exist candidate operator functions of the form |
9276 | // |
9277 | // T* operator+(T*, ptrdiff_t); [ABOVE] |
9278 | // T& operator[](T*, ptrdiff_t); |
9279 | // T* operator-(T*, ptrdiff_t); [ABOVE] |
9280 | // T* operator+(ptrdiff_t, T*); [ABOVE] |
9281 | // T& operator[](ptrdiff_t, T*); |
9282 | void addSubscriptOverloads() { |
9283 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9284 | QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; |
9285 | QualType PointeeType = PtrTy->getPointeeType(); |
9286 | if (!PointeeType->isObjectType()) |
9287 | continue; |
9288 | |
9289 | // T& operator[](T*, ptrdiff_t) |
9290 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9291 | } |
9292 | |
9293 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9294 | QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; |
9295 | QualType PointeeType = PtrTy->getPointeeType(); |
9296 | if (!PointeeType->isObjectType()) |
9297 | continue; |
9298 | |
9299 | // T& operator[](ptrdiff_t, T*) |
9300 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9301 | } |
9302 | } |
9303 | |
9304 | // C++ [over.built]p11: |
9305 | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, |
9306 | // C1 is the same type as C2 or is a derived class of C2, T is an object |
9307 | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, |
9308 | // there exist candidate operator functions of the form |
9309 | // |
9310 | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); |
9311 | // |
9312 | // where CV12 is the union of CV1 and CV2. |
9313 | void addArrowStarOverloads() { |
9314 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9315 | QualType C1Ty = PtrTy; |
9316 | QualType C1; |
9317 | QualifierCollector Q1; |
9318 | C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); |
9319 | if (!isa<RecordType>(C1)) |
9320 | continue; |
9321 | // heuristic to reduce number of builtin candidates in the set. |
9322 | // Add volatile/restrict version only if there are conversions to a |
9323 | // volatile/restrict type. |
9324 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) |
9325 | continue; |
9326 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) |
9327 | continue; |
9328 | for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { |
9329 | const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); |
9330 | QualType C2 = QualType(mptr->getClass(), 0); |
9331 | C2 = C2.getUnqualifiedType(); |
9332 | if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) |
9333 | break; |
9334 | QualType ParamTypes[2] = {PtrTy, MemPtrTy}; |
9335 | // build CV12 T& |
9336 | QualType T = mptr->getPointeeType(); |
9337 | if (!VisibleTypeConversionsQuals.hasVolatile() && |
9338 | T.isVolatileQualified()) |
9339 | continue; |
9340 | if (!VisibleTypeConversionsQuals.hasRestrict() && |
9341 | T.isRestrictQualified()) |
9342 | continue; |
9343 | T = Q1.apply(S.Context, T); |
9344 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9345 | } |
9346 | } |
9347 | } |
9348 | |
9349 | // Note that we don't consider the first argument, since it has been |
9350 | // contextually converted to bool long ago. The candidates below are |
9351 | // therefore added as binary. |
9352 | // |
9353 | // C++ [over.built]p25: |
9354 | // For every type T, where T is a pointer, pointer-to-member, or scoped |
9355 | // enumeration type, there exist candidate operator functions of the form |
9356 | // |
9357 | // T operator?(bool, T, T); |
9358 | // |
9359 | void addConditionalOperatorOverloads() { |
9360 | /// Set of (canonical) types that we've already handled. |
9361 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9362 | |
9363 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9364 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
9365 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9366 | continue; |
9367 | |
9368 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9369 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9370 | } |
9371 | |
9372 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9373 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
9374 | continue; |
9375 | |
9376 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
9377 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9378 | } |
9379 | |
9380 | if (S.getLangOpts().CPlusPlus11) { |
9381 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9382 | if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) |
9383 | continue; |
9384 | |
9385 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) |
9386 | continue; |
9387 | |
9388 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
9389 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9390 | } |
9391 | } |
9392 | } |
9393 | } |
9394 | }; |
9395 | |
9396 | } // end anonymous namespace |
9397 | |
9398 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in |
9399 | /// operator overloads to the candidate set (C++ [over.built]), based |
9400 | /// on the operator @p Op and the arguments given. For example, if the |
9401 | /// operator is a binary '+', this routine might add "int |
9402 | /// operator+(int, int)" to cover integer addition. |
9403 | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
9404 | SourceLocation OpLoc, |
9405 | ArrayRef<Expr *> Args, |
9406 | OverloadCandidateSet &CandidateSet) { |
9407 | // Find all of the types that the arguments can convert to, but only |
9408 | // if the operator we're looking at has built-in operator candidates |
9409 | // that make use of these types. Also record whether we encounter non-record |
9410 | // candidate types or either arithmetic or enumeral candidate types. |
9411 | QualifiersAndAtomic VisibleTypeConversionsQuals; |
9412 | VisibleTypeConversionsQuals.addConst(); |
9413 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9414 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); |
9415 | if (Args[ArgIdx]->getType()->isAtomicType()) |
9416 | VisibleTypeConversionsQuals.addAtomic(); |
9417 | } |
9418 | |
9419 | bool HasNonRecordCandidateType = false; |
9420 | bool HasArithmeticOrEnumeralCandidateType = false; |
9421 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; |
9422 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9423 | CandidateTypes.emplace_back(*this); |
9424 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), |
9425 | OpLoc, |
9426 | true, |
9427 | (Op == OO_Exclaim || |
9428 | Op == OO_AmpAmp || |
9429 | Op == OO_PipePipe), |
9430 | VisibleTypeConversionsQuals); |
9431 | HasNonRecordCandidateType = HasNonRecordCandidateType || |
9432 | CandidateTypes[ArgIdx].hasNonRecordTypes(); |
9433 | HasArithmeticOrEnumeralCandidateType = |
9434 | HasArithmeticOrEnumeralCandidateType || |
9435 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); |
9436 | } |
9437 | |
9438 | // Exit early when no non-record types have been added to the candidate set |
9439 | // for any of the arguments to the operator. |
9440 | // |
9441 | // We can't exit early for !, ||, or &&, since there we have always have |
9442 | // 'bool' overloads. |
9443 | if (!HasNonRecordCandidateType && |
9444 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) |
9445 | return; |
9446 | |
9447 | // Setup an object to manage the common state for building overloads. |
9448 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, |
9449 | VisibleTypeConversionsQuals, |
9450 | HasArithmeticOrEnumeralCandidateType, |
9451 | CandidateTypes, CandidateSet); |
9452 | |
9453 | // Dispatch over the operation to add in only those overloads which apply. |
9454 | switch (Op) { |
9455 | case OO_None: |
9456 | case NUM_OVERLOADED_OPERATORS: |
9457 | llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator" , "clang/lib/Sema/SemaOverload.cpp", 9457); |
9458 | |
9459 | case OO_New: |
9460 | case OO_Delete: |
9461 | case OO_Array_New: |
9462 | case OO_Array_Delete: |
9463 | case OO_Call: |
9464 | llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "clang/lib/Sema/SemaOverload.cpp", 9465) |
9465 | "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "clang/lib/Sema/SemaOverload.cpp", 9465); |
9466 | |
9467 | case OO_Comma: |
9468 | case OO_Arrow: |
9469 | case OO_Coawait: |
9470 | // C++ [over.match.oper]p3: |
9471 | // -- For the operator ',', the unary operator '&', the |
9472 | // operator '->', or the operator 'co_await', the |
9473 | // built-in candidates set is empty. |
9474 | break; |
9475 | |
9476 | case OO_Plus: // '+' is either unary or binary |
9477 | if (Args.size() == 1) |
9478 | OpBuilder.addUnaryPlusPointerOverloads(); |
9479 | [[fallthrough]]; |
9480 | |
9481 | case OO_Minus: // '-' is either unary or binary |
9482 | if (Args.size() == 1) { |
9483 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); |
9484 | } else { |
9485 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); |
9486 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9487 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9488 | } |
9489 | break; |
9490 | |
9491 | case OO_Star: // '*' is either unary or binary |
9492 | if (Args.size() == 1) |
9493 | OpBuilder.addUnaryStarPointerOverloads(); |
9494 | else { |
9495 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9496 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9497 | } |
9498 | break; |
9499 | |
9500 | case OO_Slash: |
9501 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9502 | break; |
9503 | |
9504 | case OO_PlusPlus: |
9505 | case OO_MinusMinus: |
9506 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); |
9507 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); |
9508 | break; |
9509 | |
9510 | case OO_EqualEqual: |
9511 | case OO_ExclaimEqual: |
9512 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); |
9513 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9514 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9515 | break; |
9516 | |
9517 | case OO_Less: |
9518 | case OO_Greater: |
9519 | case OO_LessEqual: |
9520 | case OO_GreaterEqual: |
9521 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9522 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9523 | break; |
9524 | |
9525 | case OO_Spaceship: |
9526 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); |
9527 | OpBuilder.addThreeWayArithmeticOverloads(); |
9528 | break; |
9529 | |
9530 | case OO_Percent: |
9531 | case OO_Caret: |
9532 | case OO_Pipe: |
9533 | case OO_LessLess: |
9534 | case OO_GreaterGreater: |
9535 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9536 | break; |
9537 | |
9538 | case OO_Amp: // '&' is either unary or binary |
9539 | if (Args.size() == 1) |
9540 | // C++ [over.match.oper]p3: |
9541 | // -- For the operator ',', the unary operator '&', or the |
9542 | // operator '->', the built-in candidates set is empty. |
9543 | break; |
9544 | |
9545 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9546 | break; |
9547 | |
9548 | case OO_Tilde: |
9549 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); |
9550 | break; |
9551 | |
9552 | case OO_Equal: |
9553 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); |
9554 | [[fallthrough]]; |
9555 | |
9556 | case OO_PlusEqual: |
9557 | case OO_MinusEqual: |
9558 | OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); |
9559 | [[fallthrough]]; |
9560 | |
9561 | case OO_StarEqual: |
9562 | case OO_SlashEqual: |
9563 | OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); |
9564 | break; |
9565 | |
9566 | case OO_PercentEqual: |
9567 | case OO_LessLessEqual: |
9568 | case OO_GreaterGreaterEqual: |
9569 | case OO_AmpEqual: |
9570 | case OO_CaretEqual: |
9571 | case OO_PipeEqual: |
9572 | OpBuilder.addAssignmentIntegralOverloads(); |
9573 | break; |
9574 | |
9575 | case OO_Exclaim: |
9576 | OpBuilder.addExclaimOverload(); |
9577 | break; |
9578 | |
9579 | case OO_AmpAmp: |
9580 | case OO_PipePipe: |
9581 | OpBuilder.addAmpAmpOrPipePipeOverload(); |
9582 | break; |
9583 | |
9584 | case OO_Subscript: |
9585 | if (Args.size() == 2) |
9586 | OpBuilder.addSubscriptOverloads(); |
9587 | break; |
9588 | |
9589 | case OO_ArrowStar: |
9590 | OpBuilder.addArrowStarOverloads(); |
9591 | break; |
9592 | |
9593 | case OO_Conditional: |
9594 | OpBuilder.addConditionalOperatorOverloads(); |
9595 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9596 | break; |
9597 | } |
9598 | } |
9599 | |
9600 | /// Add function candidates found via argument-dependent lookup |
9601 | /// to the set of overloading candidates. |
9602 | /// |
9603 | /// This routine performs argument-dependent name lookup based on the |
9604 | /// given function name (which may also be an operator name) and adds |
9605 | /// all of the overload candidates found by ADL to the overload |
9606 | /// candidate set (C++ [basic.lookup.argdep]). |
9607 | void |
9608 | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, |
9609 | SourceLocation Loc, |
9610 | ArrayRef<Expr *> Args, |
9611 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
9612 | OverloadCandidateSet& CandidateSet, |
9613 | bool PartialOverloading) { |
9614 | ADLResult Fns; |
9615 | |
9616 | // FIXME: This approach for uniquing ADL results (and removing |
9617 | // redundant candidates from the set) relies on pointer-equality, |
9618 | // which means we need to key off the canonical decl. However, |
9619 | // always going back to the canonical decl might not get us the |
9620 | // right set of default arguments. What default arguments are |
9621 | // we supposed to consider on ADL candidates, anyway? |
9622 | |
9623 | // FIXME: Pass in the explicit template arguments? |
9624 | ArgumentDependentLookup(Name, Loc, Args, Fns); |
9625 | |
9626 | // Erase all of the candidates we already knew about. |
9627 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), |
9628 | CandEnd = CandidateSet.end(); |
9629 | Cand != CandEnd; ++Cand) |
9630 | if (Cand->Function) { |
9631 | Fns.erase(Cand->Function); |
9632 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) |
9633 | Fns.erase(FunTmpl); |
9634 | } |
9635 | |
9636 | // For each of the ADL candidates we found, add it to the overload |
9637 | // set. |
9638 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { |
9639 | DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); |
9640 | |
9641 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { |
9642 | if (ExplicitTemplateArgs) |
9643 | continue; |
9644 | |
9645 | AddOverloadCandidate( |
9646 | FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, |
9647 | PartialOverloading, /*AllowExplicit=*/true, |
9648 | /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); |
9649 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { |
9650 | AddOverloadCandidate( |
9651 | FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, |
9652 | /*SuppressUserConversions=*/false, PartialOverloading, |
9653 | /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, |
9654 | ADLCallKind::UsesADL, std::nullopt, |
9655 | OverloadCandidateParamOrder::Reversed); |
9656 | } |
9657 | } else { |
9658 | auto *FTD = cast<FunctionTemplateDecl>(*I); |
9659 | AddTemplateOverloadCandidate( |
9660 | FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, |
9661 | /*SuppressUserConversions=*/false, PartialOverloading, |
9662 | /*AllowExplicit=*/true, ADLCallKind::UsesADL); |
9663 | if (CandidateSet.getRewriteInfo().shouldAddReversed( |
9664 | *this, Args, FTD->getTemplatedDecl())) { |
9665 | AddTemplateOverloadCandidate( |
9666 | FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, |
9667 | CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, |
9668 | /*AllowExplicit=*/true, ADLCallKind::UsesADL, |
9669 | OverloadCandidateParamOrder::Reversed); |
9670 | } |
9671 | } |
9672 | } |
9673 | } |
9674 | |
9675 | namespace { |
9676 | enum class Comparison { Equal, Better, Worse }; |
9677 | } |
9678 | |
9679 | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of |
9680 | /// overload resolution. |
9681 | /// |
9682 | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff |
9683 | /// Cand1's first N enable_if attributes have precisely the same conditions as |
9684 | /// Cand2's first N enable_if attributes (where N = the number of enable_if |
9685 | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. |
9686 | /// |
9687 | /// Note that you can have a pair of candidates such that Cand1's enable_if |
9688 | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are |
9689 | /// worse than Cand1's. |
9690 | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, |
9691 | const FunctionDecl *Cand2) { |
9692 | // Common case: One (or both) decls don't have enable_if attrs. |
9693 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); |
9694 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); |
9695 | if (!Cand1Attr || !Cand2Attr) { |
9696 | if (Cand1Attr == Cand2Attr) |
9697 | return Comparison::Equal; |
9698 | return Cand1Attr ? Comparison::Better : Comparison::Worse; |
9699 | } |
9700 | |
9701 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); |
9702 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); |
9703 | |
9704 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; |
9705 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { |
9706 | std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); |
9707 | std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); |
9708 | |
9709 | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 |
9710 | // has fewer enable_if attributes than Cand2, and vice versa. |
9711 | if (!Cand1A) |
9712 | return Comparison::Worse; |
9713 | if (!Cand2A) |
9714 | return Comparison::Better; |
9715 | |
9716 | Cand1ID.clear(); |
9717 | Cand2ID.clear(); |
9718 | |
9719 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); |
9720 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); |
9721 | if (Cand1ID != Cand2ID) |
9722 | return Comparison::Worse; |
9723 | } |
9724 | |
9725 | return Comparison::Equal; |
9726 | } |
9727 | |
9728 | static Comparison |
9729 | isBetterMultiversionCandidate(const OverloadCandidate &Cand1, |
9730 | const OverloadCandidate &Cand2) { |
9731 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || |
9732 | !Cand2.Function->isMultiVersion()) |
9733 | return Comparison::Equal; |
9734 | |
9735 | // If both are invalid, they are equal. If one of them is invalid, the other |
9736 | // is better. |
9737 | if (Cand1.Function->isInvalidDecl()) { |
9738 | if (Cand2.Function->isInvalidDecl()) |
9739 | return Comparison::Equal; |
9740 | return Comparison::Worse; |
9741 | } |
9742 | if (Cand2.Function->isInvalidDecl()) |
9743 | return Comparison::Better; |
9744 | |
9745 | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer |
9746 | // cpu_dispatch, else arbitrarily based on the identifiers. |
9747 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); |
9748 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); |
9749 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); |
9750 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); |
9751 | |
9752 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) |
9753 | return Comparison::Equal; |
9754 | |
9755 | if (Cand1CPUDisp && !Cand2CPUDisp) |
9756 | return Comparison::Better; |
9757 | if (Cand2CPUDisp && !Cand1CPUDisp) |
9758 | return Comparison::Worse; |
9759 | |
9760 | if (Cand1CPUSpec && Cand2CPUSpec) { |
9761 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) |
9762 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() |
9763 | ? Comparison::Better |
9764 | : Comparison::Worse; |
9765 | |
9766 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> |
9767 | FirstDiff = std::mismatch( |
9768 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), |
9769 | Cand2CPUSpec->cpus_begin(), |
9770 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { |
9771 | return LHS->getName() == RHS->getName(); |
9772 | }); |
9773 | |
9774 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9776, __extension__ __PRETTY_FUNCTION__ )) |
9775 | "Two different cpu-specific versions should not have the same "(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9776, __extension__ __PRETTY_FUNCTION__ )) |
9776 | "identifier list, otherwise they'd be the same decl!")(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9776, __extension__ __PRETTY_FUNCTION__ )); |
9777 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() |
9778 | ? Comparison::Better |
9779 | : Comparison::Worse; |
9780 | } |
9781 | llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch" , "clang/lib/Sema/SemaOverload.cpp", 9781); |
9782 | } |
9783 | |
9784 | /// Compute the type of the implicit object parameter for the given function, |
9785 | /// if any. Returns std::nullopt if there is no implicit object parameter, and a |
9786 | /// null QualType if there is a 'matches anything' implicit object parameter. |
9787 | static std::optional<QualType> |
9788 | getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { |
9789 | if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) |
9790 | return std::nullopt; |
9791 | |
9792 | auto *M = cast<CXXMethodDecl>(F); |
9793 | // Static member functions' object parameters match all types. |
9794 | if (M->isStatic()) |
9795 | return QualType(); |
9796 | |
9797 | QualType T = M->getThisObjectType(); |
9798 | if (M->getRefQualifier() == RQ_RValue) |
9799 | return Context.getRValueReferenceType(T); |
9800 | return Context.getLValueReferenceType(T); |
9801 | } |
9802 | |
9803 | static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, |
9804 | const FunctionDecl *F2, unsigned NumParams) { |
9805 | if (declaresSameEntity(F1, F2)) |
9806 | return true; |
9807 | |
9808 | auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { |
9809 | if (First) { |
9810 | if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) |
9811 | return *T; |
9812 | } |
9813 | assert(I < F->getNumParams())(static_cast <bool> (I < F->getNumParams()) ? void (0) : __assert_fail ("I < F->getNumParams()", "clang/lib/Sema/SemaOverload.cpp" , 9813, __extension__ __PRETTY_FUNCTION__)); |
9814 | return F->getParamDecl(I++)->getType(); |
9815 | }; |
9816 | |
9817 | unsigned I1 = 0, I2 = 0; |
9818 | for (unsigned I = 0; I != NumParams; ++I) { |
9819 | QualType T1 = NextParam(F1, I1, I == 0); |
9820 | QualType T2 = NextParam(F2, I2, I == 0); |
9821 | assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types")(static_cast <bool> (!T1.isNull() && !T2.isNull () && "Unexpected null param types") ? void (0) : __assert_fail ("!T1.isNull() && !T2.isNull() && \"Unexpected null param types\"" , "clang/lib/Sema/SemaOverload.cpp", 9821, __extension__ __PRETTY_FUNCTION__ )); |
9822 | if (!Context.hasSameUnqualifiedType(T1, T2)) |
9823 | return false; |
9824 | } |
9825 | return true; |
9826 | } |
9827 | |
9828 | /// We're allowed to use constraints partial ordering only if the candidates |
9829 | /// have the same parameter types: |
9830 | /// [over.match.best]p2.6 |
9831 | /// F1 and F2 are non-template functions with the same parameter-type-lists, |
9832 | /// and F1 is more constrained than F2 [...] |
9833 | static bool sameFunctionParameterTypeLists(Sema &S, |
9834 | const OverloadCandidate &Cand1, |
9835 | const OverloadCandidate &Cand2) { |
9836 | if (Cand1.Function && Cand2.Function) { |
9837 | auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); |
9838 | auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); |
9839 | if (PT1->getNumParams() == PT2->getNumParams() && |
9840 | PT1->isVariadic() == PT2->isVariadic() && |
9841 | S.FunctionParamTypesAreEqual(PT1, PT2, nullptr, |
9842 | Cand1.isReversed() ^ Cand2.isReversed())) |
9843 | return true; |
9844 | } |
9845 | return false; |
9846 | } |
9847 | |
9848 | /// isBetterOverloadCandidate - Determines whether the first overload |
9849 | /// candidate is a better candidate than the second (C++ 13.3.3p1). |
9850 | bool clang::isBetterOverloadCandidate( |
9851 | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, |
9852 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { |
9853 | // Define viable functions to be better candidates than non-viable |
9854 | // functions. |
9855 | if (!Cand2.Viable) |
9856 | return Cand1.Viable; |
9857 | else if (!Cand1.Viable) |
9858 | return false; |
9859 | |
9860 | // [CUDA] A function with 'never' preference is marked not viable, therefore |
9861 | // is never shown up here. The worst preference shown up here is 'wrong side', |
9862 | // e.g. an H function called by a HD function in device compilation. This is |
9863 | // valid AST as long as the HD function is not emitted, e.g. it is an inline |
9864 | // function which is called only by an H function. A deferred diagnostic will |
9865 | // be triggered if it is emitted. However a wrong-sided function is still |
9866 | // a viable candidate here. |
9867 | // |
9868 | // If Cand1 can be emitted and Cand2 cannot be emitted in the current |
9869 | // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 |
9870 | // can be emitted, Cand1 is not better than Cand2. This rule should have |
9871 | // precedence over other rules. |
9872 | // |
9873 | // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then |
9874 | // other rules should be used to determine which is better. This is because |
9875 | // host/device based overloading resolution is mostly for determining |
9876 | // viability of a function. If two functions are both viable, other factors |
9877 | // should take precedence in preference, e.g. the standard-defined preferences |
9878 | // like argument conversion ranks or enable_if partial-ordering. The |
9879 | // preference for pass-object-size parameters is probably most similar to a |
9880 | // type-based-overloading decision and so should take priority. |
9881 | // |
9882 | // If other rules cannot determine which is better, CUDA preference will be |
9883 | // used again to determine which is better. |
9884 | // |
9885 | // TODO: Currently IdentifyCUDAPreference does not return correct values |
9886 | // for functions called in global variable initializers due to missing |
9887 | // correct context about device/host. Therefore we can only enforce this |
9888 | // rule when there is a caller. We should enforce this rule for functions |
9889 | // in global variable initializers once proper context is added. |
9890 | // |
9891 | // TODO: We can only enable the hostness based overloading resolution when |
9892 | // -fgpu-exclude-wrong-side-overloads is on since this requires deferring |
9893 | // overloading resolution diagnostics. |
9894 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && |
9895 | S.getLangOpts().GPUExcludeWrongSideOverloads) { |
9896 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { |
9897 | bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); |
9898 | bool IsCand1ImplicitHD = |
9899 | Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); |
9900 | bool IsCand2ImplicitHD = |
9901 | Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); |
9902 | auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); |
9903 | auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); |
9904 | assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)(static_cast <bool> (P1 != Sema::CFP_Never && P2 != Sema::CFP_Never) ? void (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never" , "clang/lib/Sema/SemaOverload.cpp", 9904, __extension__ __PRETTY_FUNCTION__ )); |
9905 | // The implicit HD function may be a function in a system header which |
9906 | // is forced by pragma. In device compilation, if we prefer HD candidates |
9907 | // over wrong-sided candidates, overloading resolution may change, which |
9908 | // may result in non-deferrable diagnostics. As a workaround, we let |
9909 | // implicit HD candidates take equal preference as wrong-sided candidates. |
9910 | // This will preserve the overloading resolution. |
9911 | // TODO: We still need special handling of implicit HD functions since |
9912 | // they may incur other diagnostics to be deferred. We should make all |
9913 | // host/device related diagnostics deferrable and remove special handling |
9914 | // of implicit HD functions. |
9915 | auto EmitThreshold = |
9916 | (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && |
9917 | (IsCand1ImplicitHD || IsCand2ImplicitHD)) |
9918 | ? Sema::CFP_Never |
9919 | : Sema::CFP_WrongSide; |
9920 | auto Cand1Emittable = P1 > EmitThreshold; |
9921 | auto Cand2Emittable = P2 > EmitThreshold; |
9922 | if (Cand1Emittable && !Cand2Emittable) |
9923 | return true; |
9924 | if (!Cand1Emittable && Cand2Emittable) |
9925 | return false; |
9926 | } |
9927 | } |
9928 | |
9929 | // C++ [over.match.best]p1: (Changed in C++23) |
9930 | // |
9931 | // -- if F is a static member function, ICS1(F) is defined such |
9932 | // that ICS1(F) is neither better nor worse than ICS1(G) for |
9933 | // any function G, and, symmetrically, ICS1(G) is neither |
9934 | // better nor worse than ICS1(F). |
9935 | unsigned StartArg = 0; |
9936 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) |
9937 | StartArg = 1; |
9938 | |
9939 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { |
9940 | // We don't allow incompatible pointer conversions in C++. |
9941 | if (!S.getLangOpts().CPlusPlus) |
9942 | return ICS.isStandard() && |
9943 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; |
9944 | |
9945 | // The only ill-formed conversion we allow in C++ is the string literal to |
9946 | // char* conversion, which is only considered ill-formed after C++11. |
9947 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
9948 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); |
9949 | }; |
9950 | |
9951 | // Define functions that don't require ill-formed conversions for a given |
9952 | // argument to be better candidates than functions that do. |
9953 | unsigned NumArgs = Cand1.Conversions.size(); |
9954 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast <bool> (Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch") ? void (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\"" , "clang/lib/Sema/SemaOverload.cpp", 9954, __extension__ __PRETTY_FUNCTION__ )); |
9955 | bool HasBetterConversion = false; |
9956 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
9957 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); |
9958 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); |
9959 | if (Cand1Bad != Cand2Bad) { |
9960 | if (Cand1Bad) |
9961 | return false; |
9962 | HasBetterConversion = true; |
9963 | } |
9964 | } |
9965 | |
9966 | if (HasBetterConversion) |
9967 | return true; |
9968 | |
9969 | // C++ [over.match.best]p1: |
9970 | // A viable function F1 is defined to be a better function than another |
9971 | // viable function F2 if for all arguments i, ICSi(F1) is not a worse |
9972 | // conversion sequence than ICSi(F2), and then... |
9973 | bool HasWorseConversion = false; |
9974 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
9975 | switch (CompareImplicitConversionSequences(S, Loc, |
9976 | Cand1.Conversions[ArgIdx], |
9977 | Cand2.Conversions[ArgIdx])) { |
9978 | case ImplicitConversionSequence::Better: |
9979 | // Cand1 has a better conversion sequence. |
9980 | HasBetterConversion = true; |
9981 | break; |
9982 | |
9983 | case ImplicitConversionSequence::Worse: |
9984 | if (Cand1.Function && Cand2.Function && |
9985 | Cand1.isReversed() != Cand2.isReversed() && |
9986 | haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, |
9987 | NumArgs)) { |
9988 | // Work around large-scale breakage caused by considering reversed |
9989 | // forms of operator== in C++20: |
9990 | // |
9991 | // When comparing a function against a reversed function with the same |
9992 | // parameter types, if we have a better conversion for one argument and |
9993 | // a worse conversion for the other, the implicit conversion sequences |
9994 | // are treated as being equally good. |
9995 | // |
9996 | // This prevents a comparison function from being considered ambiguous |
9997 | // with a reversed form that is written in the same way. |
9998 | // |
9999 | // We diagnose this as an extension from CreateOverloadedBinOp. |
10000 | HasWorseConversion = true; |
10001 | break; |
10002 | } |
10003 | |
10004 | // Cand1 can't be better than Cand2. |
10005 | return false; |
10006 | |
10007 | case ImplicitConversionSequence::Indistinguishable: |
10008 | // Do nothing. |
10009 | break; |
10010 | } |
10011 | } |
10012 | |
10013 | // -- for some argument j, ICSj(F1) is a better conversion sequence than |
10014 | // ICSj(F2), or, if not that, |
10015 | if (HasBetterConversion && !HasWorseConversion) |
10016 | return true; |
10017 | |
10018 | // -- the context is an initialization by user-defined conversion |
10019 | // (see 8.5, 13.3.1.5) and the standard conversion sequence |
10020 | // from the return type of F1 to the destination type (i.e., |
10021 | // the type of the entity being initialized) is a better |
10022 | // conversion sequence than the standard conversion sequence |
10023 | // from the return type of F2 to the destination type. |
10024 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && |
10025 | Cand1.Function && Cand2.Function && |
10026 | isa<CXXConversionDecl>(Cand1.Function) && |
10027 | isa<CXXConversionDecl>(Cand2.Function)) { |
10028 | // First check whether we prefer one of the conversion functions over the |
10029 | // other. This only distinguishes the results in non-standard, extension |
10030 | // cases such as the conversion from a lambda closure type to a function |
10031 | // pointer or block. |
10032 | ImplicitConversionSequence::CompareKind Result = |
10033 | compareConversionFunctions(S, Cand1.Function, Cand2.Function); |
10034 | if (Result == ImplicitConversionSequence::Indistinguishable) |
10035 | Result = CompareStandardConversionSequences(S, Loc, |
10036 | Cand1.FinalConversion, |
10037 | Cand2.FinalConversion); |
10038 | |
10039 | if (Result != ImplicitConversionSequence::Indistinguishable) |
10040 | return Result == ImplicitConversionSequence::Better; |
10041 | |
10042 | // FIXME: Compare kind of reference binding if conversion functions |
10043 | // convert to a reference type used in direct reference binding, per |
10044 | // C++14 [over.match.best]p1 section 2 bullet 3. |
10045 | } |
10046 | |
10047 | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, |
10048 | // as combined with the resolution to CWG issue 243. |
10049 | // |
10050 | // When the context is initialization by constructor ([over.match.ctor] or |
10051 | // either phase of [over.match.list]), a constructor is preferred over |
10052 | // a conversion function. |
10053 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && |
10054 | Cand1.Function && Cand2.Function && |
10055 | isa<CXXConstructorDecl>(Cand1.Function) != |
10056 | isa<CXXConstructorDecl>(Cand2.Function)) |
10057 | return isa<CXXConstructorDecl>(Cand1.Function); |
10058 | |
10059 | // -- F1 is a non-template function and F2 is a function template |
10060 | // specialization, or, if not that, |
10061 | bool Cand1IsSpecialization = Cand1.Function && |
10062 | Cand1.Function->getPrimaryTemplate(); |
10063 | bool Cand2IsSpecialization = Cand2.Function && |
10064 | Cand2.Function->getPrimaryTemplate(); |
10065 | if (Cand1IsSpecialization != Cand2IsSpecialization) |
10066 | return Cand2IsSpecialization; |
10067 | |
10068 | // -- F1 and F2 are function template specializations, and the function |
10069 | // template for F1 is more specialized than the template for F2 |
10070 | // according to the partial ordering rules described in 14.5.5.2, or, |
10071 | // if not that, |
10072 | if (Cand1IsSpecialization && Cand2IsSpecialization) { |
10073 | if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( |
10074 | Cand1.Function->getPrimaryTemplate(), |
10075 | Cand2.Function->getPrimaryTemplate(), Loc, |
10076 | isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion |
10077 | : TPOC_Call, |
10078 | Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, |
10079 | Cand1.isReversed() ^ Cand2.isReversed())) |
10080 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); |
10081 | } |
10082 | |
10083 | // -— F1 and F2 are non-template functions with the same |
10084 | // parameter-type-lists, and F1 is more constrained than F2 [...], |
10085 | if (!Cand1IsSpecialization && !Cand2IsSpecialization && |
10086 | sameFunctionParameterTypeLists(S, Cand1, Cand2)) { |
10087 | FunctionDecl *Function1 = Cand1.Function; |
10088 | FunctionDecl *Function2 = Cand2.Function; |
10089 | if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction()) |
10090 | Function1 = MF; |
10091 | if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction()) |
10092 | Function2 = MF; |
10093 | |
10094 | const Expr *RC1 = Function1->getTrailingRequiresClause(); |
10095 | const Expr *RC2 = Function2->getTrailingRequiresClause(); |
10096 | if (RC1 && RC2) { |
10097 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
10098 | if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2, |
10099 | AtLeastAsConstrained1) || |
10100 | S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1, |
10101 | AtLeastAsConstrained2)) |
10102 | return false; |
10103 | if (AtLeastAsConstrained1 != AtLeastAsConstrained2) |
10104 | return AtLeastAsConstrained1; |
10105 | } else if (RC1 || RC2) { |
10106 | return RC1 != nullptr; |
10107 | } |
10108 | } |
10109 | |
10110 | // -- F1 is a constructor for a class D, F2 is a constructor for a base |
10111 | // class B of D, and for all arguments the corresponding parameters of |
10112 | // F1 and F2 have the same type. |
10113 | // FIXME: Implement the "all parameters have the same type" check. |
10114 | bool Cand1IsInherited = |
10115 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); |
10116 | bool Cand2IsInherited = |
10117 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); |
10118 | if (Cand1IsInherited != Cand2IsInherited) |
10119 | return Cand2IsInherited; |
10120 | else if (Cand1IsInherited) { |
10121 | assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail ("Cand2IsInherited", "clang/lib/Sema/SemaOverload.cpp", 10121 , __extension__ __PRETTY_FUNCTION__)); |
10122 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); |
10123 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); |
10124 | if (Cand1Class->isDerivedFrom(Cand2Class)) |
10125 | return true; |
10126 | if (Cand2Class->isDerivedFrom(Cand1Class)) |
10127 | return false; |
10128 | // Inherited from sibling base classes: still ambiguous. |
10129 | } |
10130 | |
10131 | // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not |
10132 | // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate |
10133 | // with reversed order of parameters and F1 is not |
10134 | // |
10135 | // We rank reversed + different operator as worse than just reversed, but |
10136 | // that comparison can never happen, because we only consider reversing for |
10137 | // the maximally-rewritten operator (== or <=>). |
10138 | if (Cand1.RewriteKind != Cand2.RewriteKind) |
10139 | return Cand1.RewriteKind < Cand2.RewriteKind; |
10140 | |
10141 | // Check C++17 tie-breakers for deduction guides. |
10142 | { |
10143 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); |
10144 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); |
10145 | if (Guide1 && Guide2) { |
10146 | // -- F1 is generated from a deduction-guide and F2 is not |
10147 | if (Guide1->isImplicit() != Guide2->isImplicit()) |
10148 | return Guide2->isImplicit(); |
10149 | |
10150 | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not |
10151 | if (Guide1->isCopyDeductionCandidate()) |
10152 | return true; |
10153 | } |
10154 | } |
10155 | |
10156 | // Check for enable_if value-based overload resolution. |
10157 | if (Cand1.Function && Cand2.Function) { |
10158 | Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); |
10159 | if (Cmp != Comparison::Equal) |
10160 | return Cmp == Comparison::Better; |
10161 | } |
10162 | |
10163 | bool HasPS1 = Cand1.Function != nullptr && |
10164 | functionHasPassObjectSizeParams(Cand1.Function); |
10165 | bool HasPS2 = Cand2.Function != nullptr && |
10166 | functionHasPassObjectSizeParams(Cand2.Function); |
10167 | if (HasPS1 != HasPS2 && HasPS1) |
10168 | return true; |
10169 | |
10170 | auto MV = isBetterMultiversionCandidate(Cand1, Cand2); |
10171 | if (MV == Comparison::Better) |
10172 | return true; |
10173 | if (MV == Comparison::Worse) |
10174 | return false; |
10175 | |
10176 | // If other rules cannot determine which is better, CUDA preference is used |
10177 | // to determine which is better. |
10178 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { |
10179 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10180 | return S.IdentifyCUDAPreference(Caller, Cand1.Function) > |
10181 | S.IdentifyCUDAPreference(Caller, Cand2.Function); |
10182 | } |
10183 | |
10184 | // General member function overloading is handled above, so this only handles |
10185 | // constructors with address spaces. |
10186 | // This only handles address spaces since C++ has no other |
10187 | // qualifier that can be used with constructors. |
10188 | const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); |
10189 | const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); |
10190 | if (CD1 && CD2) { |
10191 | LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); |
10192 | LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); |
10193 | if (AS1 != AS2) { |
10194 | if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) |
10195 | return true; |
10196 | if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) |
10197 | return false; |
10198 | } |
10199 | } |
10200 | |
10201 | return false; |
10202 | } |
10203 | |
10204 | /// Determine whether two declarations are "equivalent" for the purposes of |
10205 | /// name lookup and overload resolution. This applies when the same internal/no |
10206 | /// linkage entity is defined by two modules (probably by textually including |
10207 | /// the same header). In such a case, we don't consider the declarations to |
10208 | /// declare the same entity, but we also don't want lookups with both |
10209 | /// declarations visible to be ambiguous in some cases (this happens when using |
10210 | /// a modularized libstdc++). |
10211 | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
10212 | const NamedDecl *B) { |
10213 | auto *VA = dyn_cast_or_null<ValueDecl>(A); |
10214 | auto *VB = dyn_cast_or_null<ValueDecl>(B); |
10215 | if (!VA || !VB) |
10216 | return false; |
10217 | |
10218 | // The declarations must be declaring the same name as an internal linkage |
10219 | // entity in different modules. |
10220 | if (!VA->getDeclContext()->getRedeclContext()->Equals( |
10221 | VB->getDeclContext()->getRedeclContext()) || |
10222 | getOwningModule(VA) == getOwningModule(VB) || |
10223 | VA->isExternallyVisible() || VB->isExternallyVisible()) |
10224 | return false; |
10225 | |
10226 | // Check that the declarations appear to be equivalent. |
10227 | // |
10228 | // FIXME: Checking the type isn't really enough to resolve the ambiguity. |
10229 | // For constants and functions, we should check the initializer or body is |
10230 | // the same. For non-constant variables, we shouldn't allow it at all. |
10231 | if (Context.hasSameType(VA->getType(), VB->getType())) |
10232 | return true; |
10233 | |
10234 | // Enum constants within unnamed enumerations will have different types, but |
10235 | // may still be similar enough to be interchangeable for our purposes. |
10236 | if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { |
10237 | if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { |
10238 | // Only handle anonymous enums. If the enumerations were named and |
10239 | // equivalent, they would have been merged to the same type. |
10240 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); |
10241 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); |
10242 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || |
10243 | !Context.hasSameType(EnumA->getIntegerType(), |
10244 | EnumB->getIntegerType())) |
10245 | return false; |
10246 | // Allow this only if the value is the same for both enumerators. |
10247 | return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); |
10248 | } |
10249 | } |
10250 | |
10251 | // Nothing else is sufficiently similar. |
10252 | return false; |
10253 | } |
10254 | |
10255 | void Sema::diagnoseEquivalentInternalLinkageDeclarations( |
10256 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { |
10257 | assert(D && "Unknown declaration")(static_cast <bool> (D && "Unknown declaration" ) ? void (0) : __assert_fail ("D && \"Unknown declaration\"" , "clang/lib/Sema/SemaOverload.cpp", 10257, __extension__ __PRETTY_FUNCTION__ )); |
10258 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; |
10259 | |
10260 | Module *M = getOwningModule(D); |
10261 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10262 | << !M << (M ? M->getFullModuleName() : ""); |
10263 | |
10264 | for (auto *E : Equiv) { |
10265 | Module *M = getOwningModule(E); |
10266 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10267 | << !M << (M ? M->getFullModuleName() : ""); |
10268 | } |
10269 | } |
10270 | |
10271 | bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { |
10272 | return FailureKind == ovl_fail_bad_deduction && |
10273 | DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied && |
10274 | static_cast<CNSInfo *>(DeductionFailure.Data) |
10275 | ->Satisfaction.ContainsErrors; |
10276 | } |
10277 | |
10278 | /// Computes the best viable function (C++ 13.3.3) |
10279 | /// within an overload candidate set. |
10280 | /// |
10281 | /// \param Loc The location of the function name (or operator symbol) for |
10282 | /// which overload resolution occurs. |
10283 | /// |
10284 | /// \param Best If overload resolution was successful or found a deleted |
10285 | /// function, \p Best points to the candidate function found. |
10286 | /// |
10287 | /// \returns The result of overload resolution. |
10288 | OverloadingResult |
10289 | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, |
10290 | iterator &Best) { |
10291 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; |
10292 | std::transform(begin(), end(), std::back_inserter(Candidates), |
10293 | [](OverloadCandidate &Cand) { return &Cand; }); |
10294 | |
10295 | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but |
10296 | // are accepted by both clang and NVCC. However, during a particular |
10297 | // compilation mode only one call variant is viable. We need to |
10298 | // exclude non-viable overload candidates from consideration based |
10299 | // only on their host/device attributes. Specifically, if one |
10300 | // candidate call is WrongSide and the other is SameSide, we ignore |
10301 | // the WrongSide candidate. |
10302 | // We only need to remove wrong-sided candidates here if |
10303 | // -fgpu-exclude-wrong-side-overloads is off. When |
10304 | // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared |
10305 | // uniformly in isBetterOverloadCandidate. |
10306 | if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { |
10307 | const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10308 | bool ContainsSameSideCandidate = |
10309 | llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { |
10310 | // Check viable function only. |
10311 | return Cand->Viable && Cand->Function && |
10312 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
10313 | Sema::CFP_SameSide; |
10314 | }); |
10315 | if (ContainsSameSideCandidate) { |
10316 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { |
10317 | // Check viable function only to avoid unnecessary data copying/moving. |
10318 | return Cand->Viable && Cand->Function && |
10319 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
10320 | Sema::CFP_WrongSide; |
10321 | }; |
10322 | llvm::erase_if(Candidates, IsWrongSideCandidate); |
10323 | } |
10324 | } |
10325 | |
10326 | // Find the best viable function. |
10327 | Best = end(); |
10328 | for (auto *Cand : Candidates) { |
10329 | Cand->Best = false; |
10330 | if (Cand->Viable) { |
10331 | if (Best == end() || |
10332 | isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) |
10333 | Best = Cand; |
10334 | } else if (Cand->NotValidBecauseConstraintExprHasError()) { |
10335 | // This candidate has constraint that we were unable to evaluate because |
10336 | // it referenced an expression that contained an error. Rather than fall |
10337 | // back onto a potentially unintended candidate (made worse by |
10338 | // subsuming constraints), treat this as 'no viable candidate'. |
10339 | Best = end(); |
10340 | return OR_No_Viable_Function; |
10341 | } |
10342 | } |
10343 | |
10344 | // If we didn't find any viable functions, abort. |
10345 | if (Best == end()) |
10346 | return OR_No_Viable_Function; |
10347 | |
10348 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; |
10349 | |
10350 | llvm::SmallVector<OverloadCandidate*, 4> PendingBest; |
10351 | PendingBest.push_back(&*Best); |
10352 | Best->Best = true; |
10353 | |
10354 | // Make sure that this function is better than every other viable |
10355 | // function. If not, we have an ambiguity. |
10356 | while (!PendingBest.empty()) { |
10357 | auto *Curr = PendingBest.pop_back_val(); |
10358 | for (auto *Cand : Candidates) { |
10359 | if (Cand->Viable && !Cand->Best && |
10360 | !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { |
10361 | PendingBest.push_back(Cand); |
10362 | Cand->Best = true; |
10363 | |
10364 | if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, |
10365 | Curr->Function)) |
10366 | EquivalentCands.push_back(Cand->Function); |
10367 | else |
10368 | Best = end(); |
10369 | } |
10370 | } |
10371 | } |
10372 | |
10373 | // If we found more than one best candidate, this is ambiguous. |
10374 | if (Best == end()) |
10375 | return OR_Ambiguous; |
10376 | |
10377 | // Best is the best viable function. |
10378 | if (Best->Function && Best->Function->isDeleted()) |
10379 | return OR_Deleted; |
10380 | |
10381 | if (!EquivalentCands.empty()) |
10382 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, |
10383 | EquivalentCands); |
10384 | |
10385 | return OR_Success; |
10386 | } |
10387 | |
10388 | namespace { |
10389 | |
10390 | enum OverloadCandidateKind { |
10391 | oc_function, |
10392 | oc_method, |
10393 | oc_reversed_binary_operator, |
10394 | oc_constructor, |
10395 | oc_implicit_default_constructor, |
10396 | oc_implicit_copy_constructor, |
10397 | oc_implicit_move_constructor, |
10398 | oc_implicit_copy_assignment, |
10399 | oc_implicit_move_assignment, |
10400 | oc_implicit_equality_comparison, |
10401 | oc_inherited_constructor |
10402 | }; |
10403 | |
10404 | enum OverloadCandidateSelect { |
10405 | ocs_non_template, |
10406 | ocs_template, |
10407 | ocs_described_template, |
10408 | }; |
10409 | |
10410 | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> |
10411 | ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, |
10412 | const FunctionDecl *Fn, |
10413 | OverloadCandidateRewriteKind CRK, |
10414 | std::string &Description) { |
10415 | |
10416 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); |
10417 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { |
10418 | isTemplate = true; |
10419 | Description = S.getTemplateArgumentBindingsText( |
10420 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); |
10421 | } |
10422 | |
10423 | OverloadCandidateSelect Select = [&]() { |
10424 | if (!Description.empty()) |
10425 | return ocs_described_template; |
10426 | return isTemplate ? ocs_template : ocs_non_template; |
10427 | }(); |
10428 | |
10429 | OverloadCandidateKind Kind = [&]() { |
10430 | if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) |
10431 | return oc_implicit_equality_comparison; |
10432 | |
10433 | if (CRK & CRK_Reversed) |
10434 | return oc_reversed_binary_operator; |
10435 | |
10436 | if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { |
10437 | if (!Ctor->isImplicit()) { |
10438 | if (isa<ConstructorUsingShadowDecl>(Found)) |
10439 | return oc_inherited_constructor; |
10440 | else |
10441 | return oc_constructor; |
10442 | } |
10443 | |
10444 | if (Ctor->isDefaultConstructor()) |
10445 | return oc_implicit_default_constructor; |
10446 | |
10447 | if (Ctor->isMoveConstructor()) |
10448 | return oc_implicit_move_constructor; |
10449 | |
10450 | assert(Ctor->isCopyConstructor() &&(static_cast <bool> (Ctor->isCopyConstructor() && "unexpected sort of implicit constructor") ? void (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "clang/lib/Sema/SemaOverload.cpp", 10451, __extension__ __PRETTY_FUNCTION__ )) |
10451 | "unexpected sort of implicit constructor")(static_cast <bool> (Ctor->isCopyConstructor() && "unexpected sort of implicit constructor") ? void (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "clang/lib/Sema/SemaOverload.cpp", 10451, __extension__ __PRETTY_FUNCTION__ )); |
10452 | return oc_implicit_copy_constructor; |
10453 | } |
10454 | |
10455 | if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) { |
10456 | // This actually gets spelled 'candidate function' for now, but |
10457 | // it doesn't hurt to split it out. |
10458 | if (!Meth->isImplicit()) |
10459 | return oc_method; |
10460 | |
10461 | if (Meth->isMoveAssignmentOperator()) |
10462 | return oc_implicit_move_assignment; |
10463 | |
10464 | if (Meth->isCopyAssignmentOperator()) |
10465 | return oc_implicit_copy_assignment; |
10466 | |
10467 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast <bool> (isa<CXXConversionDecl>(Meth) && "expected conversion") ? void (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\"" , "clang/lib/Sema/SemaOverload.cpp", 10467, __extension__ __PRETTY_FUNCTION__ )); |
10468 | return oc_method; |
10469 | } |
10470 | |
10471 | return oc_function; |
10472 | }(); |
10473 | |
10474 | return std::make_pair(Kind, Select); |
10475 | } |
10476 | |
10477 | void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { |
10478 | // FIXME: It'd be nice to only emit a note once per using-decl per overload |
10479 | // set. |
10480 | if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) |
10481 | S.Diag(FoundDecl->getLocation(), |
10482 | diag::note_ovl_candidate_inherited_constructor) |
10483 | << Shadow->getNominatedBaseClass(); |
10484 | } |
10485 | |
10486 | } // end anonymous namespace |
10487 | |
10488 | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, |
10489 | const FunctionDecl *FD) { |
10490 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { |
10491 | bool AlwaysTrue; |
10492 | if (EnableIf->getCond()->isValueDependent() || |
10493 | !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) |
10494 | return false; |
10495 | if (!AlwaysTrue) |
10496 | return false; |
10497 | } |
10498 | return true; |
10499 | } |
10500 | |
10501 | /// Returns true if we can take the address of the function. |
10502 | /// |
10503 | /// \param Complain - If true, we'll emit a diagnostic |
10504 | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are |
10505 | /// we in overload resolution? |
10506 | /// \param Loc - The location of the statement we're complaining about. Ignored |
10507 | /// if we're not complaining, or if we're in overload resolution. |
10508 | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, |
10509 | bool Complain, |
10510 | bool InOverloadResolution, |
10511 | SourceLocation Loc) { |
10512 | if (!isFunctionAlwaysEnabled(S.Context, FD)) { |
10513 | if (Complain) { |
10514 | if (InOverloadResolution) |
10515 | S.Diag(FD->getBeginLoc(), |
10516 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); |
10517 | else |
10518 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; |
10519 | } |
10520 | return false; |
10521 | } |
10522 | |
10523 | if (FD->getTrailingRequiresClause()) { |
10524 | ConstraintSatisfaction Satisfaction; |
10525 | if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) |
10526 | return false; |
10527 | if (!Satisfaction.IsSatisfied) { |
10528 | if (Complain) { |
10529 | if (InOverloadResolution) { |
10530 | SmallString<128> TemplateArgString; |
10531 | if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { |
10532 | TemplateArgString += " "; |
10533 | TemplateArgString += S.getTemplateArgumentBindingsText( |
10534 | FunTmpl->getTemplateParameters(), |
10535 | *FD->getTemplateSpecializationArgs()); |
10536 | } |
10537 | |
10538 | S.Diag(FD->getBeginLoc(), |
10539 | diag::note_ovl_candidate_unsatisfied_constraints) |
10540 | << TemplateArgString; |
10541 | } else |
10542 | S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) |
10543 | << FD; |
10544 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
10545 | } |
10546 | return false; |
10547 | } |
10548 | } |
10549 | |
10550 | auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { |
10551 | return P->hasAttr<PassObjectSizeAttr>(); |
10552 | }); |
10553 | if (I == FD->param_end()) |
10554 | return true; |
10555 | |
10556 | if (Complain) { |
10557 | // Add one to ParamNo because it's user-facing |
10558 | unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; |
10559 | if (InOverloadResolution) |
10560 | S.Diag(FD->getLocation(), |
10561 | diag::note_ovl_candidate_has_pass_object_size_params) |
10562 | << ParamNo; |
10563 | else |
10564 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) |
10565 | << FD << ParamNo; |
10566 | } |
10567 | return false; |
10568 | } |
10569 | |
10570 | static bool checkAddressOfCandidateIsAvailable(Sema &S, |
10571 | const FunctionDecl *FD) { |
10572 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, |
10573 | /*InOverloadResolution=*/true, |
10574 | /*Loc=*/SourceLocation()); |
10575 | } |
10576 | |
10577 | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
10578 | bool Complain, |
10579 | SourceLocation Loc) { |
10580 | return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, |
10581 | /*InOverloadResolution=*/false, |
10582 | Loc); |
10583 | } |
10584 | |
10585 | // Don't print candidates other than the one that matches the calling |
10586 | // convention of the call operator, since that is guaranteed to exist. |
10587 | static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { |
10588 | const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); |
10589 | |
10590 | if (!ConvD) |
10591 | return false; |
10592 | const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); |
10593 | if (!RD->isLambda()) |
10594 | return false; |
10595 | |
10596 | CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); |
10597 | CallingConv CallOpCC = |
10598 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
10599 | QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); |
10600 | CallingConv ConvToCC = |
10601 | ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); |
10602 | |
10603 | return ConvToCC != CallOpCC; |
10604 | } |
10605 | |
10606 | // Notes the location of an overload candidate. |
10607 | void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, |
10608 | OverloadCandidateRewriteKind RewriteKind, |
10609 | QualType DestType, bool TakingAddress) { |
10610 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) |
10611 | return; |
10612 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && |
10613 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) |
10614 | return; |
10615 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && |
10616 | !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) |
10617 | return; |
10618 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
10619 | return; |
10620 | |
10621 | std::string FnDesc; |
10622 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = |
10623 | ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); |
10624 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) |
10625 | << (unsigned)KSPair.first << (unsigned)KSPair.second |
10626 | << Fn << FnDesc; |
10627 | |
10628 | HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); |
10629 | Diag(Fn->getLocation(), PD); |
10630 | MaybeEmitInheritedConstructorNote(*this, Found); |
10631 | } |
10632 | |
10633 | static void |
10634 | MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { |
10635 | // Perhaps the ambiguity was caused by two atomic constraints that are |
10636 | // 'identical' but not equivalent: |
10637 | // |
10638 | // void foo() requires (sizeof(T) > 4) { } // #1 |
10639 | // void foo() requires (sizeof(T) > 4) && T::value { } // #2 |
10640 | // |
10641 | // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause |
10642 | // #2 to subsume #1, but these constraint are not considered equivalent |
10643 | // according to the subsumption rules because they are not the same |
10644 | // source-level construct. This behavior is quite confusing and we should try |
10645 | // to help the user figure out what happened. |
10646 | |
10647 | SmallVector<const Expr *, 3> FirstAC, SecondAC; |
10648 | FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; |
10649 | for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
10650 | if (!I->Function) |
10651 | continue; |
10652 | SmallVector<const Expr *, 3> AC; |
10653 | if (auto *Template = I->Function->getPrimaryTemplate()) |
10654 | Template->getAssociatedConstraints(AC); |
10655 | else |
10656 | I->Function->getAssociatedConstraints(AC); |
10657 | if (AC.empty()) |
10658 | continue; |
10659 | if (FirstCand == nullptr) { |
10660 | FirstCand = I->Function; |
10661 | FirstAC = AC; |
10662 | } else if (SecondCand == nullptr) { |
10663 | SecondCand = I->Function; |
10664 | SecondAC = AC; |
10665 | } else { |
10666 | // We have more than one pair of constrained functions - this check is |
10667 | // expensive and we'd rather not try to diagnose it. |
10668 | return; |
10669 | } |
10670 | } |
10671 | if (!SecondCand) |
10672 | return; |
10673 | // The diagnostic can only happen if there are associated constraints on |
10674 | // both sides (there needs to be some identical atomic constraint). |
10675 | if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, |
10676 | SecondCand, SecondAC)) |
10677 | // Just show the user one diagnostic, they'll probably figure it out |
10678 | // from here. |
10679 | return; |
10680 | } |
10681 | |
10682 | // Notes the location of all overload candidates designated through |
10683 | // OverloadedExpr |
10684 | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, |
10685 | bool TakingAddress) { |
10686 | assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast <bool> (OverloadedExpr->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 10686, __extension__ __PRETTY_FUNCTION__ )); |
10687 | |
10688 | OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); |
10689 | OverloadExpr *OvlExpr = Ovl.Expression; |
10690 | |
10691 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
10692 | IEnd = OvlExpr->decls_end(); |
10693 | I != IEnd; ++I) { |
10694 | if (FunctionTemplateDecl *FunTmpl = |
10695 | dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { |
10696 | NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, |
10697 | TakingAddress); |
10698 | } else if (FunctionDecl *Fun |
10699 | = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { |
10700 | NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); |
10701 | } |
10702 | } |
10703 | } |
10704 | |
10705 | /// Diagnoses an ambiguous conversion. The partial diagnostic is the |
10706 | /// "lead" diagnostic; it will be given two arguments, the source and |
10707 | /// target types of the conversion. |
10708 | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( |
10709 | Sema &S, |
10710 | SourceLocation CaretLoc, |
10711 | const PartialDiagnostic &PDiag) const { |
10712 | S.Diag(CaretLoc, PDiag) |
10713 | << Ambiguous.getFromType() << Ambiguous.getToType(); |
10714 | unsigned CandsShown = 0; |
10715 | AmbiguousConversionSequence::const_iterator I, E; |
10716 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { |
10717 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) |
10718 | break; |
10719 | ++CandsShown; |
10720 | S.NoteOverloadCandidate(I->first, I->second); |
10721 | } |
10722 | S.Diags.overloadCandidatesShown(CandsShown); |
10723 | if (I != E) |
10724 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); |
10725 | } |
10726 | |
10727 | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, |
10728 | unsigned I, bool TakingCandidateAddress) { |
10729 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; |
10730 | assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail ("Conv.isBad()", "clang/lib/Sema/SemaOverload.cpp", 10730, __extension__ __PRETTY_FUNCTION__)); |
10731 | assert(Cand->Function && "for now, candidate must be a function")(static_cast <bool> (Cand->Function && "for now, candidate must be a function" ) ? void (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\"" , "clang/lib/Sema/SemaOverload.cpp", 10731, __extension__ __PRETTY_FUNCTION__ )); |
10732 | FunctionDecl *Fn = Cand->Function; |
10733 | |
10734 | // There's a conversion slot for the object argument if this is a |
10735 | // non-constructor method. Note that 'I' corresponds the |
10736 | // conversion-slot index. |
10737 | bool isObjectArgument = false; |
10738 | if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { |
10739 | if (I == 0) |
10740 | isObjectArgument = true; |
10741 | else |
10742 | I--; |
10743 | } |
10744 | |
10745 | std::string FnDesc; |
10746 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
10747 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), |
10748 | FnDesc); |
10749 | |
10750 | Expr *FromExpr = Conv.Bad.FromExpr; |
10751 | QualType FromTy = Conv.Bad.getFromType(); |
10752 | QualType ToTy = Conv.Bad.getToType(); |
10753 | |
10754 | if (FromTy == S.Context.OverloadTy) { |
10755 | assert(FromExpr && "overload set argument came from implicit argument?")(static_cast <bool> (FromExpr && "overload set argument came from implicit argument?" ) ? void (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\"" , "clang/lib/Sema/SemaOverload.cpp", 10755, __extension__ __PRETTY_FUNCTION__ )); |
10756 | Expr *E = FromExpr->IgnoreParens(); |
10757 | if (isa<UnaryOperator>(E)) |
10758 | E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); |
10759 | DeclarationName Name = cast<OverloadExpr>(E)->getName(); |
10760 | |
10761 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) |
10762 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10763 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy |
10764 | << Name << I + 1; |
10765 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10766 | return; |
10767 | } |
10768 | |
10769 | // Do some hand-waving analysis to see if the non-viability is due |
10770 | // to a qualifier mismatch. |
10771 | CanQualType CFromTy = S.Context.getCanonicalType(FromTy); |
10772 | CanQualType CToTy = S.Context.getCanonicalType(ToTy); |
10773 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) |
10774 | CToTy = RT->getPointeeType(); |
10775 | else { |
10776 | // TODO: detect and diagnose the full richness of const mismatches. |
10777 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) |
10778 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { |
10779 | CFromTy = FromPT->getPointeeType(); |
10780 | CToTy = ToPT->getPointeeType(); |
10781 | } |
10782 | } |
10783 | |
10784 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && |
10785 | !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { |
10786 | Qualifiers FromQs = CFromTy.getQualifiers(); |
10787 | Qualifiers ToQs = CToTy.getQualifiers(); |
10788 | |
10789 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { |
10790 | if (isObjectArgument) |
10791 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) |
10792 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10793 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10794 | << FromQs.getAddressSpace() << ToQs.getAddressSpace(); |
10795 | else |
10796 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) |
10797 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10798 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10799 | << FromQs.getAddressSpace() << ToQs.getAddressSpace() |
10800 | << ToTy->isReferenceType() << I + 1; |
10801 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10802 | return; |
10803 | } |
10804 | |
10805 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
10806 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) |
10807 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10808 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10809 | << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() |
10810 | << (unsigned)isObjectArgument << I + 1; |
10811 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10812 | return; |
10813 | } |
10814 | |
10815 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { |
10816 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) |
10817 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10818 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10819 | << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() |
10820 | << (unsigned)isObjectArgument << I + 1; |
10821 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10822 | return; |
10823 | } |
10824 | |
10825 | if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { |
10826 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) |
10827 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10828 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10829 | << FromQs.hasUnaligned() << I + 1; |
10830 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10831 | return; |
10832 | } |
10833 | |
10834 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
10835 | assert(CVR && "expected qualifiers mismatch")(static_cast <bool> (CVR && "expected qualifiers mismatch" ) ? void (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\"" , "clang/lib/Sema/SemaOverload.cpp", 10835, __extension__ __PRETTY_FUNCTION__ )); |
10836 | |
10837 | if (isObjectArgument) { |
10838 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) |
10839 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10840 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10841 | << (CVR - 1); |
10842 | } else { |
10843 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) |
10844 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10845 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10846 | << (CVR - 1) << I + 1; |
10847 | } |
10848 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10849 | return; |
10850 | } |
10851 | |
10852 | if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || |
10853 | Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { |
10854 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) |
10855 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10856 | << (unsigned)isObjectArgument << I + 1 |
10857 | << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) |
10858 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); |
10859 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10860 | return; |
10861 | } |
10862 | |
10863 | // Special diagnostic for failure to convert an initializer list, since |
10864 | // telling the user that it has type void is not useful. |
10865 | if (FromExpr && isa<InitListExpr>(FromExpr)) { |
10866 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) |
10867 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10868 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10869 | << ToTy << (unsigned)isObjectArgument << I + 1 |
10870 | << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 |
10871 | : Conv.Bad.Kind == BadConversionSequence::too_many_initializers |
10872 | ? 2 |
10873 | : 0); |
10874 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10875 | return; |
10876 | } |
10877 | |
10878 | // Diagnose references or pointers to incomplete types differently, |
10879 | // since it's far from impossible that the incompleteness triggered |
10880 | // the failure. |
10881 | QualType TempFromTy = FromTy.getNonReferenceType(); |
10882 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) |
10883 | TempFromTy = PTy->getPointeeType(); |
10884 | if (TempFromTy->isIncompleteType()) { |
10885 | // Emit the generic diagnostic and, optionally, add the hints to it. |
10886 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) |
10887 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10888 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10889 | << ToTy << (unsigned)isObjectArgument << I + 1 |
10890 | << (unsigned)(Cand->Fix.Kind); |
10891 | |
10892 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10893 | return; |
10894 | } |
10895 | |
10896 | // Diagnose base -> derived pointer conversions. |
10897 | unsigned BaseToDerivedConversion = 0; |
10898 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { |
10899 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { |
10900 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
10901 | FromPtrTy->getPointeeType()) && |
10902 | !FromPtrTy->getPointeeType()->isIncompleteType() && |
10903 | !ToPtrTy->getPointeeType()->isIncompleteType() && |
10904 | S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), |
10905 | FromPtrTy->getPointeeType())) |
10906 | BaseToDerivedConversion = 1; |
10907 | } |
10908 | } else if (const ObjCObjectPointerType *FromPtrTy |
10909 | = FromTy->getAs<ObjCObjectPointerType>()) { |
10910 | if (const ObjCObjectPointerType *ToPtrTy |
10911 | = ToTy->getAs<ObjCObjectPointerType>()) |
10912 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) |
10913 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) |
10914 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
10915 | FromPtrTy->getPointeeType()) && |
10916 | FromIface->isSuperClassOf(ToIface)) |
10917 | BaseToDerivedConversion = 2; |
10918 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { |
10919 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && |
10920 | !FromTy->isIncompleteType() && |
10921 | !ToRefTy->getPointeeType()->isIncompleteType() && |
10922 | S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { |
10923 | BaseToDerivedConversion = 3; |
10924 | } |
10925 | } |
10926 | |
10927 | if (BaseToDerivedConversion) { |
10928 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) |
10929 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10930 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10931 | << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; |
10932 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10933 | return; |
10934 | } |
10935 | |
10936 | if (isa<ObjCObjectPointerType>(CFromTy) && |
10937 | isa<PointerType>(CToTy)) { |
10938 | Qualifiers FromQs = CFromTy.getQualifiers(); |
10939 | Qualifiers ToQs = CToTy.getQualifiers(); |
10940 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
10941 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) |
10942 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10943 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10944 | << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; |
10945 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10946 | return; |
10947 | } |
10948 | } |
10949 | |
10950 | if (TakingCandidateAddress && |
10951 | !checkAddressOfCandidateIsAvailable(S, Cand->Function)) |
10952 | return; |
10953 | |
10954 | // Emit the generic diagnostic and, optionally, add the hints to it. |
10955 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); |
10956 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10957 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10958 | << ToTy << (unsigned)isObjectArgument << I + 1 |
10959 | << (unsigned)(Cand->Fix.Kind); |
10960 | |
10961 | // Check that location of Fn is not in system header. |
10962 | if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) { |
10963 | // If we can fix the conversion, suggest the FixIts. |
10964 | for (const FixItHint &HI : Cand->Fix.Hints) |
10965 | FDiag << HI; |
10966 | } |
10967 | |
10968 | S.Diag(Fn->getLocation(), FDiag); |
10969 | |
10970 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10971 | } |
10972 | |
10973 | /// Additional arity mismatch diagnosis specific to a function overload |
10974 | /// candidates. This is not covered by the more general DiagnoseArityMismatch() |
10975 | /// over a candidate in any candidate set. |
10976 | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, |
10977 | unsigned NumArgs) { |
10978 | FunctionDecl *Fn = Cand->Function; |
10979 | unsigned MinParams = Fn->getMinRequiredArguments(); |
10980 | |
10981 | // With invalid overloaded operators, it's possible that we think we |
10982 | // have an arity mismatch when in fact it looks like we have the |
10983 | // right number of arguments, because only overloaded operators have |
10984 | // the weird behavior of overloading member and non-member functions. |
10985 | // Just don't report anything. |
10986 | if (Fn->isInvalidDecl() && |
10987 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) |
10988 | return true; |
10989 | |
10990 | if (NumArgs < MinParams) { |
10991 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10993, __extension__ __PRETTY_FUNCTION__ )) |
10992 | (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10993, __extension__ __PRETTY_FUNCTION__ )) |
10993 | Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10993, __extension__ __PRETTY_FUNCTION__ )); |
10994 | } else { |
10995 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10997, __extension__ __PRETTY_FUNCTION__ )) |
10996 | (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10997, __extension__ __PRETTY_FUNCTION__ )) |
10997 | Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10997, __extension__ __PRETTY_FUNCTION__ )); |
10998 | } |
10999 | |
11000 | return false; |
11001 | } |
11002 | |
11003 | /// General arity mismatch diagnosis over a candidate in a candidate set. |
11004 | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, |
11005 | unsigned NumFormalArgs) { |
11006 | assert(isa<FunctionDecl>(D) &&(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 11009, __extension__ __PRETTY_FUNCTION__ )) |
11007 | "The templated declaration should at least be a function"(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 11009, __extension__ __PRETTY_FUNCTION__ )) |
11008 | " when diagnosing bad template argument deduction due to too many"(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 11009, __extension__ __PRETTY_FUNCTION__ )) |
11009 | " or too few arguments")(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 11009, __extension__ __PRETTY_FUNCTION__ )); |
11010 | |
11011 | FunctionDecl *Fn = cast<FunctionDecl>(D); |
11012 | |
11013 | // TODO: treat calls to a missing default constructor as a special case |
11014 | const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); |
11015 | unsigned MinParams = Fn->getMinRequiredArguments(); |
11016 | |
11017 | // at least / at most / exactly |
11018 | unsigned mode, modeCount; |
11019 | if (NumFormalArgs < MinParams) { |
11020 | if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || |
11021 | FnTy->isTemplateVariadic()) |
11022 | mode = 0; // "at least" |
11023 | else |
11024 | mode = 2; // "exactly" |
11025 | modeCount = MinParams; |
11026 | } else { |
11027 | if (MinParams != FnTy->getNumParams()) |
11028 | mode = 1; // "at most" |
11029 | else |
11030 | mode = 2; // "exactly" |
11031 | modeCount = FnTy->getNumParams(); |
11032 | } |
11033 | |
11034 | std::string Description; |
11035 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11036 | ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); |
11037 | |
11038 | if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) |
11039 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) |
11040 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11041 | << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; |
11042 | else |
11043 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) |
11044 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11045 | << Description << mode << modeCount << NumFormalArgs; |
11046 | |
11047 | MaybeEmitInheritedConstructorNote(S, Found); |
11048 | } |
11049 | |
11050 | /// Arity mismatch diagnosis specific to a function overload candidate. |
11051 | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, |
11052 | unsigned NumFormalArgs) { |
11053 | if (!CheckArityMismatch(S, Cand, NumFormalArgs)) |
11054 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); |
11055 | } |
11056 | |
11057 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { |
11058 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) |
11059 | return TD; |
11060 | llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp" , 11061) |
11061 | " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp" , 11061); |
11062 | } |
11063 | |
11064 | /// Diagnose a failed template-argument deduction. |
11065 | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, |
11066 | DeductionFailureInfo &DeductionFailure, |
11067 | unsigned NumArgs, |
11068 | bool TakingCandidateAddress) { |
11069 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); |
11070 | NamedDecl *ParamD; |
11071 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || |
11072 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || |
11073 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); |
11074 | switch (DeductionFailure.Result) { |
11075 | case Sema::TDK_Success: |
11076 | llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction" , "clang/lib/Sema/SemaOverload.cpp", 11076); |
11077 | |
11078 | case Sema::TDK_Incomplete: { |
11079 | assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 11079, __extension__ __PRETTY_FUNCTION__ )); |
11080 | S.Diag(Templated->getLocation(), |
11081 | diag::note_ovl_candidate_incomplete_deduction) |
11082 | << ParamD->getDeclName(); |
11083 | MaybeEmitInheritedConstructorNote(S, Found); |
11084 | return; |
11085 | } |
11086 | |
11087 | case Sema::TDK_IncompletePack: { |
11088 | assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 11088, __extension__ __PRETTY_FUNCTION__ )); |
11089 | S.Diag(Templated->getLocation(), |
11090 | diag::note_ovl_candidate_incomplete_deduction_pack) |
11091 | << ParamD->getDeclName() |
11092 | << (DeductionFailure.getFirstArg()->pack_size() + 1) |
11093 | << *DeductionFailure.getFirstArg(); |
11094 | MaybeEmitInheritedConstructorNote(S, Found); |
11095 | return; |
11096 | } |
11097 | |
11098 | case Sema::TDK_Underqualified: { |
11099 | assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast <bool> (ParamD && "no parameter found for bad qualifiers deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 11099, __extension__ __PRETTY_FUNCTION__ )); |
11100 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); |
11101 | |
11102 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); |
11103 | |
11104 | // Param will have been canonicalized, but it should just be a |
11105 | // qualified version of ParamD, so move the qualifiers to that. |
11106 | QualifierCollector Qs; |
11107 | Qs.strip(Param); |
11108 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); |
11109 | assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast <bool> (S.Context.hasSameType(Param, NonCanonParam )) ? void (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)" , "clang/lib/Sema/SemaOverload.cpp", 11109, __extension__ __PRETTY_FUNCTION__ )); |
11110 | |
11111 | // Arg has also been canonicalized, but there's nothing we can do |
11112 | // about that. It also doesn't matter as much, because it won't |
11113 | // have any template parameters in it (because deduction isn't |
11114 | // done on dependent types). |
11115 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); |
11116 | |
11117 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) |
11118 | << ParamD->getDeclName() << Arg << NonCanonParam; |
11119 | MaybeEmitInheritedConstructorNote(S, Found); |
11120 | return; |
11121 | } |
11122 | |
11123 | case Sema::TDK_Inconsistent: { |
11124 | assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast <bool> (ParamD && "no parameter found for inconsistent deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 11124, __extension__ __PRETTY_FUNCTION__ )); |
11125 | int which = 0; |
11126 | if (isa<TemplateTypeParmDecl>(ParamD)) |
11127 | which = 0; |
11128 | else if (isa<NonTypeTemplateParmDecl>(ParamD)) { |
11129 | // Deduction might have failed because we deduced arguments of two |
11130 | // different types for a non-type template parameter. |
11131 | // FIXME: Use a different TDK value for this. |
11132 | QualType T1 = |
11133 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); |
11134 | QualType T2 = |
11135 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); |
11136 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { |
11137 | S.Diag(Templated->getLocation(), |
11138 | diag::note_ovl_candidate_inconsistent_deduction_types) |
11139 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 |
11140 | << *DeductionFailure.getSecondArg() << T2; |
11141 | MaybeEmitInheritedConstructorNote(S, Found); |
11142 | return; |
11143 | } |
11144 | |
11145 | which = 1; |
11146 | } else { |
11147 | which = 2; |
11148 | } |
11149 | |
11150 | // Tweak the diagnostic if the problem is that we deduced packs of |
11151 | // different arities. We'll print the actual packs anyway in case that |
11152 | // includes additional useful information. |
11153 | if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && |
11154 | DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && |
11155 | DeductionFailure.getFirstArg()->pack_size() != |
11156 | DeductionFailure.getSecondArg()->pack_size()) { |
11157 | which = 3; |
11158 | } |
11159 | |
11160 | S.Diag(Templated->getLocation(), |
11161 | diag::note_ovl_candidate_inconsistent_deduction) |
11162 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() |
11163 | << *DeductionFailure.getSecondArg(); |
11164 | MaybeEmitInheritedConstructorNote(S, Found); |
11165 | return; |
11166 | } |
11167 | |
11168 | case Sema::TDK_InvalidExplicitArguments: |
11169 | assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast <bool> (ParamD && "no parameter found for invalid explicit arguments" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 11169, __extension__ __PRETTY_FUNCTION__ )); |
11170 | if (ParamD->getDeclName()) |
11171 | S.Diag(Templated->getLocation(), |
11172 | diag::note_ovl_candidate_explicit_arg_mismatch_named) |
11173 | << ParamD->getDeclName(); |
11174 | else { |
11175 | int index = 0; |
11176 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) |
11177 | index = TTP->getIndex(); |
11178 | else if (NonTypeTemplateParmDecl *NTTP |
11179 | = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) |
11180 | index = NTTP->getIndex(); |
11181 | else |
11182 | index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); |
11183 | S.Diag(Templated->getLocation(), |
11184 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) |
11185 | << (index + 1); |
11186 | } |
11187 | MaybeEmitInheritedConstructorNote(S, Found); |
11188 | return; |
11189 | |
11190 | case Sema::TDK_ConstraintsNotSatisfied: { |
11191 | // Format the template argument list into the argument string. |
11192 | SmallString<128> TemplateArgString; |
11193 | TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); |
11194 | TemplateArgString = " "; |
11195 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11196 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11197 | if (TemplateArgString.size() == 1) |
11198 | TemplateArgString.clear(); |
11199 | S.Diag(Templated->getLocation(), |
11200 | diag::note_ovl_candidate_unsatisfied_constraints) |
11201 | << TemplateArgString; |
11202 | |
11203 | S.DiagnoseUnsatisfiedConstraint( |
11204 | static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); |
11205 | return; |
11206 | } |
11207 | case Sema::TDK_TooManyArguments: |
11208 | case Sema::TDK_TooFewArguments: |
11209 | DiagnoseArityMismatch(S, Found, Templated, NumArgs); |
11210 | return; |
11211 | |
11212 | case Sema::TDK_InstantiationDepth: |
11213 | S.Diag(Templated->getLocation(), |
11214 | diag::note_ovl_candidate_instantiation_depth); |
11215 | MaybeEmitInheritedConstructorNote(S, Found); |
11216 | return; |
11217 | |
11218 | case Sema::TDK_SubstitutionFailure: { |
11219 | // Format the template argument list into the argument string. |
11220 | SmallString<128> TemplateArgString; |
11221 | if (TemplateArgumentList *Args = |
11222 | DeductionFailure.getTemplateArgumentList()) { |
11223 | TemplateArgString = " "; |
11224 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11225 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11226 | if (TemplateArgString.size() == 1) |
11227 | TemplateArgString.clear(); |
11228 | } |
11229 | |
11230 | // If this candidate was disabled by enable_if, say so. |
11231 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); |
11232 | if (PDiag && PDiag->second.getDiagID() == |
11233 | diag::err_typename_nested_not_found_enable_if) { |
11234 | // FIXME: Use the source range of the condition, and the fully-qualified |
11235 | // name of the enable_if template. These are both present in PDiag. |
11236 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) |
11237 | << "'enable_if'" << TemplateArgString; |
11238 | return; |
11239 | } |
11240 | |
11241 | // We found a specific requirement that disabled the enable_if. |
11242 | if (PDiag && PDiag->second.getDiagID() == |
11243 | diag::err_typename_nested_not_found_requirement) { |
11244 | S.Diag(Templated->getLocation(), |
11245 | diag::note_ovl_candidate_disabled_by_requirement) |
11246 | << PDiag->second.getStringArg(0) << TemplateArgString; |
11247 | return; |
11248 | } |
11249 | |
11250 | // Format the SFINAE diagnostic into the argument string. |
11251 | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s |
11252 | // formatted message in another diagnostic. |
11253 | SmallString<128> SFINAEArgString; |
11254 | SourceRange R; |
11255 | if (PDiag) { |
11256 | SFINAEArgString = ": "; |
11257 | R = SourceRange(PDiag->first, PDiag->first); |
11258 | PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); |
11259 | } |
11260 | |
11261 | S.Diag(Templated->getLocation(), |
11262 | diag::note_ovl_candidate_substitution_failure) |
11263 | << TemplateArgString << SFINAEArgString << R; |
11264 | MaybeEmitInheritedConstructorNote(S, Found); |
11265 | return; |
11266 | } |
11267 | |
11268 | case Sema::TDK_DeducedMismatch: |
11269 | case Sema::TDK_DeducedMismatchNested: { |
11270 | // Format the template argument list into the argument string. |
11271 | SmallString<128> TemplateArgString; |
11272 | if (TemplateArgumentList *Args = |
11273 | DeductionFailure.getTemplateArgumentList()) { |
11274 | TemplateArgString = " "; |
11275 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11276 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11277 | if (TemplateArgString.size() == 1) |
11278 | TemplateArgString.clear(); |
11279 | } |
11280 | |
11281 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) |
11282 | << (*DeductionFailure.getCallArgIndex() + 1) |
11283 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() |
11284 | << TemplateArgString |
11285 | << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); |
11286 | break; |
11287 | } |
11288 | |
11289 | case Sema::TDK_NonDeducedMismatch: { |
11290 | // FIXME: Provide a source location to indicate what we couldn't match. |
11291 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); |
11292 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); |
11293 | if (FirstTA.getKind() == TemplateArgument::Template && |
11294 | SecondTA.getKind() == TemplateArgument::Template) { |
11295 | TemplateName FirstTN = FirstTA.getAsTemplate(); |
11296 | TemplateName SecondTN = SecondTA.getAsTemplate(); |
11297 | if (FirstTN.getKind() == TemplateName::Template && |
11298 | SecondTN.getKind() == TemplateName::Template) { |
11299 | if (FirstTN.getAsTemplateDecl()->getName() == |
11300 | SecondTN.getAsTemplateDecl()->getName()) { |
11301 | // FIXME: This fixes a bad diagnostic where both templates are named |
11302 | // the same. This particular case is a bit difficult since: |
11303 | // 1) It is passed as a string to the diagnostic printer. |
11304 | // 2) The diagnostic printer only attempts to find a better |
11305 | // name for types, not decls. |
11306 | // Ideally, this should folded into the diagnostic printer. |
11307 | S.Diag(Templated->getLocation(), |
11308 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) |
11309 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); |
11310 | return; |
11311 | } |
11312 | } |
11313 | } |
11314 | |
11315 | if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && |
11316 | !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) |
11317 | return; |
11318 | |
11319 | // FIXME: For generic lambda parameters, check if the function is a lambda |
11320 | // call operator, and if so, emit a prettier and more informative |
11321 | // diagnostic that mentions 'auto' and lambda in addition to |
11322 | // (or instead of?) the canonical template type parameters. |
11323 | S.Diag(Templated->getLocation(), |
11324 | diag::note_ovl_candidate_non_deduced_mismatch) |
11325 | << FirstTA << SecondTA; |
11326 | return; |
11327 | } |
11328 | // TODO: diagnose these individually, then kill off |
11329 | // note_ovl_candidate_bad_deduction, which is uselessly vague. |
11330 | case Sema::TDK_MiscellaneousDeductionFailure: |
11331 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); |
11332 | MaybeEmitInheritedConstructorNote(S, Found); |
11333 | return; |
11334 | case Sema::TDK_CUDATargetMismatch: |
11335 | S.Diag(Templated->getLocation(), |
11336 | diag::note_cuda_ovl_candidate_target_mismatch); |
11337 | return; |
11338 | } |
11339 | } |
11340 | |
11341 | /// Diagnose a failed template-argument deduction, for function calls. |
11342 | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, |
11343 | unsigned NumArgs, |
11344 | bool TakingCandidateAddress) { |
11345 | unsigned TDK = Cand->DeductionFailure.Result; |
11346 | if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { |
11347 | if (CheckArityMismatch(S, Cand, NumArgs)) |
11348 | return; |
11349 | } |
11350 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern |
11351 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); |
11352 | } |
11353 | |
11354 | /// CUDA: diagnose an invalid call across targets. |
11355 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { |
11356 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
11357 | FunctionDecl *Callee = Cand->Function; |
11358 | |
11359 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), |
11360 | CalleeTarget = S.IdentifyCUDATarget(Callee); |
11361 | |
11362 | std::string FnDesc; |
11363 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11364 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, |
11365 | Cand->getRewriteKind(), FnDesc); |
11366 | |
11367 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) |
11368 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11369 | << FnDesc /* Ignored */ |
11370 | << CalleeTarget << CallerTarget; |
11371 | |
11372 | // This could be an implicit constructor for which we could not infer the |
11373 | // target due to a collsion. Diagnose that case. |
11374 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); |
11375 | if (Meth != nullptr && Meth->isImplicit()) { |
11376 | CXXRecordDecl *ParentClass = Meth->getParent(); |
11377 | Sema::CXXSpecialMember CSM; |
11378 | |
11379 | switch (FnKindPair.first) { |
11380 | default: |
11381 | return; |
11382 | case oc_implicit_default_constructor: |
11383 | CSM = Sema::CXXDefaultConstructor; |
11384 | break; |
11385 | case oc_implicit_copy_constructor: |
11386 | CSM = Sema::CXXCopyConstructor; |
11387 | break; |
11388 | case oc_implicit_move_constructor: |
11389 | CSM = Sema::CXXMoveConstructor; |
11390 | break; |
11391 | case oc_implicit_copy_assignment: |
11392 | CSM = Sema::CXXCopyAssignment; |
11393 | break; |
11394 | case oc_implicit_move_assignment: |
11395 | CSM = Sema::CXXMoveAssignment; |
11396 | break; |
11397 | }; |
11398 | |
11399 | bool ConstRHS = false; |
11400 | if (Meth->getNumParams()) { |
11401 | if (const ReferenceType *RT = |
11402 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { |
11403 | ConstRHS = RT->getPointeeType().isConstQualified(); |
11404 | } |
11405 | } |
11406 | |
11407 | S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, |
11408 | /* ConstRHS */ ConstRHS, |
11409 | /* Diagnose */ true); |
11410 | } |
11411 | } |
11412 | |
11413 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { |
11414 | FunctionDecl *Callee = Cand->Function; |
11415 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); |
11416 | |
11417 | S.Diag(Callee->getLocation(), |
11418 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
11419 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
11420 | } |
11421 | |
11422 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { |
11423 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); |
11424 | assert(ES.isExplicit() && "not an explicit candidate")(static_cast <bool> (ES.isExplicit() && "not an explicit candidate" ) ? void (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 11424, __extension__ __PRETTY_FUNCTION__ )); |
11425 | |
11426 | unsigned Kind; |
11427 | switch (Cand->Function->getDeclKind()) { |
11428 | case Decl::Kind::CXXConstructor: |
11429 | Kind = 0; |
11430 | break; |
11431 | case Decl::Kind::CXXConversion: |
11432 | Kind = 1; |
11433 | break; |
11434 | case Decl::Kind::CXXDeductionGuide: |
11435 | Kind = Cand->Function->isImplicit() ? 0 : 2; |
11436 | break; |
11437 | default: |
11438 | llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "clang/lib/Sema/SemaOverload.cpp" , 11438); |
11439 | } |
11440 | |
11441 | // Note the location of the first (in-class) declaration; a redeclaration |
11442 | // (particularly an out-of-class definition) will typically lack the |
11443 | // 'explicit' specifier. |
11444 | // FIXME: This is probably a good thing to do for all 'candidate' notes. |
11445 | FunctionDecl *First = Cand->Function->getFirstDecl(); |
11446 | if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) |
11447 | First = Pattern->getFirstDecl(); |
11448 | |
11449 | S.Diag(First->getLocation(), |
11450 | diag::note_ovl_candidate_explicit) |
11451 | << Kind << (ES.getExpr() ? 1 : 0) |
11452 | << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); |
11453 | } |
11454 | |
11455 | /// Generates a 'note' diagnostic for an overload candidate. We've |
11456 | /// already generated a primary error at the call site. |
11457 | /// |
11458 | /// It really does need to be a single diagnostic with its caret |
11459 | /// pointed at the candidate declaration. Yes, this creates some |
11460 | /// major challenges of technical writing. Yes, this makes pointing |
11461 | /// out problems with specific arguments quite awkward. It's still |
11462 | /// better than generating twenty screens of text for every failed |
11463 | /// overload. |
11464 | /// |
11465 | /// It would be great to be able to express per-candidate problems |
11466 | /// more richly for those diagnostic clients that cared, but we'd |
11467 | /// still have to be just as careful with the default diagnostics. |
11468 | /// \param CtorDestAS Addr space of object being constructed (for ctor |
11469 | /// candidates only). |
11470 | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, |
11471 | unsigned NumArgs, |
11472 | bool TakingCandidateAddress, |
11473 | LangAS CtorDestAS = LangAS::Default) { |
11474 | FunctionDecl *Fn = Cand->Function; |
11475 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
11476 | return; |
11477 | |
11478 | // There is no physical candidate declaration to point to for OpenCL builtins. |
11479 | // Except for failed conversions, the notes are identical for each candidate, |
11480 | // so do not generate such notes. |
11481 | if (S.getLangOpts().OpenCL && Fn->isImplicit() && |
11482 | Cand->FailureKind != ovl_fail_bad_conversion) |
11483 | return; |
11484 | |
11485 | // Note deleted candidates, but only if they're viable. |
11486 | if (Cand->Viable) { |
11487 | if (Fn->isDeleted()) { |
11488 | std::string FnDesc; |
11489 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11490 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, |
11491 | Cand->getRewriteKind(), FnDesc); |
11492 | |
11493 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) |
11494 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11495 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); |
11496 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11497 | return; |
11498 | } |
11499 | |
11500 | // We don't really have anything else to say about viable candidates. |
11501 | S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11502 | return; |
11503 | } |
11504 | |
11505 | switch (Cand->FailureKind) { |
11506 | case ovl_fail_too_many_arguments: |
11507 | case ovl_fail_too_few_arguments: |
11508 | return DiagnoseArityMismatch(S, Cand, NumArgs); |
11509 | |
11510 | case ovl_fail_bad_deduction: |
11511 | return DiagnoseBadDeduction(S, Cand, NumArgs, |
11512 | TakingCandidateAddress); |
11513 | |
11514 | case ovl_fail_illegal_constructor: { |
11515 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) |
11516 | << (Fn->getPrimaryTemplate() ? 1 : 0); |
11517 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11518 | return; |
11519 | } |
11520 | |
11521 | case ovl_fail_object_addrspace_mismatch: { |
11522 | Qualifiers QualsForPrinting; |
11523 | QualsForPrinting.setAddressSpace(CtorDestAS); |
11524 | S.Diag(Fn->getLocation(), |
11525 | diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) |
11526 | << QualsForPrinting; |
11527 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11528 | return; |
11529 | } |
11530 | |
11531 | case ovl_fail_trivial_conversion: |
11532 | case ovl_fail_bad_final_conversion: |
11533 | case ovl_fail_final_conversion_not_exact: |
11534 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11535 | |
11536 | case ovl_fail_bad_conversion: { |
11537 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); |
11538 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) |
11539 | if (Cand->Conversions[I].isBad()) |
11540 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); |
11541 | |
11542 | // FIXME: this currently happens when we're called from SemaInit |
11543 | // when user-conversion overload fails. Figure out how to handle |
11544 | // those conditions and diagnose them well. |
11545 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11546 | } |
11547 | |
11548 | case ovl_fail_bad_target: |
11549 | return DiagnoseBadTarget(S, Cand); |
11550 | |
11551 | case ovl_fail_enable_if: |
11552 | return DiagnoseFailedEnableIfAttr(S, Cand); |
11553 | |
11554 | case ovl_fail_explicit: |
11555 | return DiagnoseFailedExplicitSpec(S, Cand); |
11556 | |
11557 | case ovl_fail_inhctor_slice: |
11558 | // It's generally not interesting to note copy/move constructors here. |
11559 | if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) |
11560 | return; |
11561 | S.Diag(Fn->getLocation(), |
11562 | diag::note_ovl_candidate_inherited_constructor_slice) |
11563 | << (Fn->getPrimaryTemplate() ? 1 : 0) |
11564 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); |
11565 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11566 | return; |
11567 | |
11568 | case ovl_fail_addr_not_available: { |
11569 | bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); |
11570 | (void)Available; |
11571 | assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail ("!Available", "clang/lib/Sema/SemaOverload.cpp", 11571, __extension__ __PRETTY_FUNCTION__)); |
11572 | break; |
11573 | } |
11574 | case ovl_non_default_multiversion_function: |
11575 | // Do nothing, these should simply be ignored. |
11576 | break; |
11577 | |
11578 | case ovl_fail_constraints_not_satisfied: { |
11579 | std::string FnDesc; |
11580 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11581 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, |
11582 | Cand->getRewriteKind(), FnDesc); |
11583 | |
11584 | S.Diag(Fn->getLocation(), |
11585 | diag::note_ovl_candidate_constraints_not_satisfied) |
11586 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11587 | << FnDesc /* Ignored */; |
11588 | ConstraintSatisfaction Satisfaction; |
11589 | if (S.CheckFunctionConstraints(Fn, Satisfaction)) |
11590 | break; |
11591 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
11592 | } |
11593 | } |
11594 | } |
11595 | |
11596 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { |
11597 | if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) |
11598 | return; |
11599 | |
11600 | // Desugar the type of the surrogate down to a function type, |
11601 | // retaining as many typedefs as possible while still showing |
11602 | // the function type (and, therefore, its parameter types). |
11603 | QualType FnType = Cand->Surrogate->getConversionType(); |
11604 | bool isLValueReference = false; |
11605 | bool isRValueReference = false; |
11606 | bool isPointer = false; |
11607 | if (const LValueReferenceType *FnTypeRef = |
11608 | FnType->getAs<LValueReferenceType>()) { |
11609 | FnType = FnTypeRef->getPointeeType(); |
11610 | isLValueReference = true; |
11611 | } else if (const RValueReferenceType *FnTypeRef = |
11612 | FnType->getAs<RValueReferenceType>()) { |
11613 | FnType = FnTypeRef->getPointeeType(); |
11614 | isRValueReference = true; |
11615 | } |
11616 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { |
11617 | FnType = FnTypePtr->getPointeeType(); |
11618 | isPointer = true; |
11619 | } |
11620 | // Desugar down to a function type. |
11621 | FnType = QualType(FnType->getAs<FunctionType>(), 0); |
11622 | // Reconstruct the pointer/reference as appropriate. |
11623 | if (isPointer) FnType = S.Context.getPointerType(FnType); |
11624 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); |
11625 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); |
11626 | |
11627 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) |
11628 | << FnType; |
11629 | } |
11630 | |
11631 | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, |
11632 | SourceLocation OpLoc, |
11633 | OverloadCandidate *Cand) { |
11634 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast <bool> (Cand->Conversions.size() <= 2 && "builtin operator is not binary") ? void (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\"" , "clang/lib/Sema/SemaOverload.cpp", 11634, __extension__ __PRETTY_FUNCTION__ )); |
11635 | std::string TypeStr("operator"); |
11636 | TypeStr += Opc; |
11637 | TypeStr += "("; |
11638 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); |
11639 | if (Cand->Conversions.size() == 1) { |
11640 | TypeStr += ")"; |
11641 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
11642 | } else { |
11643 | TypeStr += ", "; |
11644 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); |
11645 | TypeStr += ")"; |
11646 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
11647 | } |
11648 | } |
11649 | |
11650 | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, |
11651 | OverloadCandidate *Cand) { |
11652 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { |
11653 | if (ICS.isBad()) break; // all meaningless after first invalid |
11654 | if (!ICS.isAmbiguous()) continue; |
11655 | |
11656 | ICS.DiagnoseAmbiguousConversion( |
11657 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); |
11658 | } |
11659 | } |
11660 | |
11661 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { |
11662 | if (Cand->Function) |
11663 | return Cand->Function->getLocation(); |
11664 | if (Cand->IsSurrogate) |
11665 | return Cand->Surrogate->getLocation(); |
11666 | return SourceLocation(); |
11667 | } |
11668 | |
11669 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { |
11670 | switch ((Sema::TemplateDeductionResult)DFI.Result) { |
11671 | case Sema::TDK_Success: |
11672 | case Sema::TDK_NonDependentConversionFailure: |
11673 | case Sema::TDK_AlreadyDiagnosed: |
11674 | llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction" , "clang/lib/Sema/SemaOverload.cpp", 11674); |
11675 | |
11676 | case Sema::TDK_Invalid: |
11677 | case Sema::TDK_Incomplete: |
11678 | case Sema::TDK_IncompletePack: |
11679 | return 1; |
11680 | |
11681 | case Sema::TDK_Underqualified: |
11682 | case Sema::TDK_Inconsistent: |
11683 | return 2; |
11684 | |
11685 | case Sema::TDK_SubstitutionFailure: |
11686 | case Sema::TDK_DeducedMismatch: |
11687 | case Sema::TDK_ConstraintsNotSatisfied: |
11688 | case Sema::TDK_DeducedMismatchNested: |
11689 | case Sema::TDK_NonDeducedMismatch: |
11690 | case Sema::TDK_MiscellaneousDeductionFailure: |
11691 | case Sema::TDK_CUDATargetMismatch: |
11692 | return 3; |
11693 | |
11694 | case Sema::TDK_InstantiationDepth: |
11695 | return 4; |
11696 | |
11697 | case Sema::TDK_InvalidExplicitArguments: |
11698 | return 5; |
11699 | |
11700 | case Sema::TDK_TooManyArguments: |
11701 | case Sema::TDK_TooFewArguments: |
11702 | return 6; |
11703 | } |
11704 | llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result" , "clang/lib/Sema/SemaOverload.cpp", 11704); |
11705 | } |
11706 | |
11707 | namespace { |
11708 | struct CompareOverloadCandidatesForDisplay { |
11709 | Sema &S; |
11710 | SourceLocation Loc; |
11711 | size_t NumArgs; |
11712 | OverloadCandidateSet::CandidateSetKind CSK; |
11713 | |
11714 | CompareOverloadCandidatesForDisplay( |
11715 | Sema &S, SourceLocation Loc, size_t NArgs, |
11716 | OverloadCandidateSet::CandidateSetKind CSK) |
11717 | : S(S), NumArgs(NArgs), CSK(CSK) {} |
11718 | |
11719 | OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { |
11720 | // If there are too many or too few arguments, that's the high-order bit we |
11721 | // want to sort by, even if the immediate failure kind was something else. |
11722 | if (C->FailureKind == ovl_fail_too_many_arguments || |
11723 | C->FailureKind == ovl_fail_too_few_arguments) |
11724 | return static_cast<OverloadFailureKind>(C->FailureKind); |
11725 | |
11726 | if (C->Function) { |
11727 | if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) |
11728 | return ovl_fail_too_many_arguments; |
11729 | if (NumArgs < C->Function->getMinRequiredArguments()) |
11730 | return ovl_fail_too_few_arguments; |
11731 | } |
11732 | |
11733 | return static_cast<OverloadFailureKind>(C->FailureKind); |
11734 | } |
11735 | |
11736 | bool operator()(const OverloadCandidate *L, |
11737 | const OverloadCandidate *R) { |
11738 | // Fast-path this check. |
11739 | if (L == R) return false; |
11740 | |
11741 | // Order first by viability. |
11742 | if (L->Viable) { |
11743 | if (!R->Viable) return true; |
11744 | |
11745 | // TODO: introduce a tri-valued comparison for overload |
11746 | // candidates. Would be more worthwhile if we had a sort |
11747 | // that could exploit it. |
11748 | if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) |
11749 | return true; |
11750 | if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) |
11751 | return false; |
11752 | } else if (R->Viable) |
11753 | return false; |
11754 | |
11755 | assert(L->Viable == R->Viable)(static_cast <bool> (L->Viable == R->Viable) ? void (0) : __assert_fail ("L->Viable == R->Viable", "clang/lib/Sema/SemaOverload.cpp" , 11755, __extension__ __PRETTY_FUNCTION__)); |
11756 | |
11757 | // Criteria by which we can sort non-viable candidates: |
11758 | if (!L->Viable) { |
11759 | OverloadFailureKind LFailureKind = EffectiveFailureKind(L); |
11760 | OverloadFailureKind RFailureKind = EffectiveFailureKind(R); |
11761 | |
11762 | // 1. Arity mismatches come after other candidates. |
11763 | if (LFailureKind == ovl_fail_too_many_arguments || |
11764 | LFailureKind == ovl_fail_too_few_arguments) { |
11765 | if (RFailureKind == ovl_fail_too_many_arguments || |
11766 | RFailureKind == ovl_fail_too_few_arguments) { |
11767 | int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); |
11768 | int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); |
11769 | if (LDist == RDist) { |
11770 | if (LFailureKind == RFailureKind) |
11771 | // Sort non-surrogates before surrogates. |
11772 | return !L->IsSurrogate && R->IsSurrogate; |
11773 | // Sort candidates requiring fewer parameters than there were |
11774 | // arguments given after candidates requiring more parameters |
11775 | // than there were arguments given. |
11776 | return LFailureKind == ovl_fail_too_many_arguments; |
11777 | } |
11778 | return LDist < RDist; |
11779 | } |
11780 | return false; |
11781 | } |
11782 | if (RFailureKind == ovl_fail_too_many_arguments || |
11783 | RFailureKind == ovl_fail_too_few_arguments) |
11784 | return true; |
11785 | |
11786 | // 2. Bad conversions come first and are ordered by the number |
11787 | // of bad conversions and quality of good conversions. |
11788 | if (LFailureKind == ovl_fail_bad_conversion) { |
11789 | if (RFailureKind != ovl_fail_bad_conversion) |
11790 | return true; |
11791 | |
11792 | // The conversion that can be fixed with a smaller number of changes, |
11793 | // comes first. |
11794 | unsigned numLFixes = L->Fix.NumConversionsFixed; |
11795 | unsigned numRFixes = R->Fix.NumConversionsFixed; |
11796 | numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; |
11797 | numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; |
11798 | if (numLFixes != numRFixes) { |
11799 | return numLFixes < numRFixes; |
11800 | } |
11801 | |
11802 | // If there's any ordering between the defined conversions... |
11803 | // FIXME: this might not be transitive. |
11804 | assert(L->Conversions.size() == R->Conversions.size())(static_cast <bool> (L->Conversions.size() == R-> Conversions.size()) ? void (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()" , "clang/lib/Sema/SemaOverload.cpp", 11804, __extension__ __PRETTY_FUNCTION__ )); |
11805 | |
11806 | int leftBetter = 0; |
11807 | unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); |
11808 | for (unsigned E = L->Conversions.size(); I != E; ++I) { |
11809 | switch (CompareImplicitConversionSequences(S, Loc, |
11810 | L->Conversions[I], |
11811 | R->Conversions[I])) { |
11812 | case ImplicitConversionSequence::Better: |
11813 | leftBetter++; |
11814 | break; |
11815 | |
11816 | case ImplicitConversionSequence::Worse: |
11817 | leftBetter--; |
11818 | break; |
11819 | |
11820 | case ImplicitConversionSequence::Indistinguishable: |
11821 | break; |
11822 | } |
11823 | } |
11824 | if (leftBetter > 0) return true; |
11825 | if (leftBetter < 0) return false; |
11826 | |
11827 | } else if (RFailureKind == ovl_fail_bad_conversion) |
11828 | return false; |
11829 | |
11830 | if (LFailureKind == ovl_fail_bad_deduction) { |
11831 | if (RFailureKind != ovl_fail_bad_deduction) |
11832 | return true; |
11833 | |
11834 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
11835 | return RankDeductionFailure(L->DeductionFailure) |
11836 | < RankDeductionFailure(R->DeductionFailure); |
11837 | } else if (RFailureKind == ovl_fail_bad_deduction) |
11838 | return false; |
11839 | |
11840 | // TODO: others? |
11841 | } |
11842 | |
11843 | // Sort everything else by location. |
11844 | SourceLocation LLoc = GetLocationForCandidate(L); |
11845 | SourceLocation RLoc = GetLocationForCandidate(R); |
11846 | |
11847 | // Put candidates without locations (e.g. builtins) at the end. |
11848 | if (LLoc.isInvalid()) return false; |
11849 | if (RLoc.isInvalid()) return true; |
11850 | |
11851 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
11852 | } |
11853 | }; |
11854 | } |
11855 | |
11856 | /// CompleteNonViableCandidate - Normally, overload resolution only |
11857 | /// computes up to the first bad conversion. Produces the FixIt set if |
11858 | /// possible. |
11859 | static void |
11860 | CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, |
11861 | ArrayRef<Expr *> Args, |
11862 | OverloadCandidateSet::CandidateSetKind CSK) { |
11863 | assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail ("!Cand->Viable", "clang/lib/Sema/SemaOverload.cpp", 11863 , __extension__ __PRETTY_FUNCTION__)); |
11864 | |
11865 | // Don't do anything on failures other than bad conversion. |
11866 | if (Cand->FailureKind != ovl_fail_bad_conversion) |
11867 | return; |
11868 | |
11869 | // We only want the FixIts if all the arguments can be corrected. |
11870 | bool Unfixable = false; |
11871 | // Use a implicit copy initialization to check conversion fixes. |
11872 | Cand->Fix.setConversionChecker(TryCopyInitialization); |
11873 | |
11874 | // Attempt to fix the bad conversion. |
11875 | unsigned ConvCount = Cand->Conversions.size(); |
11876 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; |
11877 | ++ConvIdx) { |
11878 | assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast <bool> (ConvIdx != ConvCount && "no bad conversion in candidate" ) ? void (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 11878, __extension__ __PRETTY_FUNCTION__ )); |
11879 | if (Cand->Conversions[ConvIdx].isInitialized() && |
11880 | Cand->Conversions[ConvIdx].isBad()) { |
11881 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
11882 | break; |
11883 | } |
11884 | } |
11885 | |
11886 | // FIXME: this should probably be preserved from the overload |
11887 | // operation somehow. |
11888 | bool SuppressUserConversions = false; |
11889 | |
11890 | unsigned ConvIdx = 0; |
11891 | unsigned ArgIdx = 0; |
11892 | ArrayRef<QualType> ParamTypes; |
11893 | bool Reversed = Cand->isReversed(); |
11894 | |
11895 | if (Cand->IsSurrogate) { |
11896 | QualType ConvType |
11897 | = Cand->Surrogate->getConversionType().getNonReferenceType(); |
11898 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
11899 | ConvType = ConvPtrType->getPointeeType(); |
11900 | ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); |
11901 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
11902 | ConvIdx = 1; |
11903 | } else if (Cand->Function) { |
11904 | ParamTypes = |
11905 | Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); |
11906 | if (isa<CXXMethodDecl>(Cand->Function) && |
11907 | !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { |
11908 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
11909 | ConvIdx = 1; |
11910 | if (CSK == OverloadCandidateSet::CSK_Operator && |
11911 | Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && |
11912 | Cand->Function->getDeclName().getCXXOverloadedOperator() != |
11913 | OO_Subscript) |
11914 | // Argument 0 is 'this', which doesn't have a corresponding parameter. |
11915 | ArgIdx = 1; |
11916 | } |
11917 | } else { |
11918 | // Builtin operator. |
11919 | assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail ("ConvCount <= 3", "clang/lib/Sema/SemaOverload.cpp", 11919 , __extension__ __PRETTY_FUNCTION__)); |
11920 | ParamTypes = Cand->BuiltinParamTypes; |
11921 | } |
11922 | |
11923 | // Fill in the rest of the conversions. |
11924 | for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; |
11925 | ConvIdx != ConvCount; |
11926 | ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { |
11927 | assert(ArgIdx < Args.size() && "no argument for this arg conversion")(static_cast <bool> (ArgIdx < Args.size() && "no argument for this arg conversion") ? void (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\"" , "clang/lib/Sema/SemaOverload.cpp", 11927, __extension__ __PRETTY_FUNCTION__ )); |
11928 | if (Cand->Conversions[ConvIdx].isInitialized()) { |
11929 | // We've already checked this conversion. |
11930 | } else if (ParamIdx < ParamTypes.size()) { |
11931 | if (ParamTypes[ParamIdx]->isDependentType()) |
11932 | Cand->Conversions[ConvIdx].setAsIdentityConversion( |
11933 | Args[ArgIdx]->getType()); |
11934 | else { |
11935 | Cand->Conversions[ConvIdx] = |
11936 | TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], |
11937 | SuppressUserConversions, |
11938 | /*InOverloadResolution=*/true, |
11939 | /*AllowObjCWritebackConversion=*/ |
11940 | S.getLangOpts().ObjCAutoRefCount); |
11941 | // Store the FixIt in the candidate if it exists. |
11942 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) |
11943 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
11944 | } |
11945 | } else |
11946 | Cand->Conversions[ConvIdx].setEllipsis(); |
11947 | } |
11948 | } |
11949 | |
11950 | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( |
11951 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
11952 | SourceLocation OpLoc, |
11953 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
11954 | // Sort the candidates by viability and position. Sorting directly would |
11955 | // be prohibitive, so we make a set of pointers and sort those. |
11956 | SmallVector<OverloadCandidate*, 32> Cands; |
11957 | if (OCD == OCD_AllCandidates) Cands.reserve(size()); |
11958 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
11959 | if (!Filter(*Cand)) |
11960 | continue; |
11961 | switch (OCD) { |
11962 | case OCD_AllCandidates: |
11963 | if (!Cand->Viable) { |
11964 | if (!Cand->Function && !Cand->IsSurrogate) { |
11965 | // This a non-viable builtin candidate. We do not, in general, |
11966 | // want to list every possible builtin candidate. |
11967 | continue; |
11968 | } |
11969 | CompleteNonViableCandidate(S, Cand, Args, Kind); |
11970 | } |
11971 | break; |
11972 | |
11973 | case OCD_ViableCandidates: |
11974 | if (!Cand->Viable) |
11975 | continue; |
11976 | break; |
11977 | |
11978 | case OCD_AmbiguousCandidates: |
11979 | if (!Cand->Best) |
11980 | continue; |
11981 | break; |
11982 | } |
11983 | |
11984 | Cands.push_back(Cand); |
11985 | } |
11986 | |
11987 | llvm::stable_sort( |
11988 | Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); |
11989 | |
11990 | return Cands; |
11991 | } |
11992 | |
11993 | bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, |
11994 | SourceLocation OpLoc) { |
11995 | bool DeferHint = false; |
11996 | if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { |
11997 | // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or |
11998 | // host device candidates. |
11999 | auto WrongSidedCands = |
12000 | CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { |
12001 | return (Cand.Viable == false && |
12002 | Cand.FailureKind == ovl_fail_bad_target) || |
12003 | (Cand.Function && |
12004 | Cand.Function->template hasAttr<CUDAHostAttr>() && |
12005 | Cand.Function->template hasAttr<CUDADeviceAttr>()); |
12006 | }); |
12007 | DeferHint = !WrongSidedCands.empty(); |
12008 | } |
12009 | return DeferHint; |
12010 | } |
12011 | |
12012 | /// When overload resolution fails, prints diagnostic messages containing the |
12013 | /// candidates in the candidate set. |
12014 | void OverloadCandidateSet::NoteCandidates( |
12015 | PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, |
12016 | ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, |
12017 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
12018 | |
12019 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); |
12020 | |
12021 | S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); |
12022 | |
12023 | NoteCandidates(S, Args, Cands, Opc, OpLoc); |
12024 | |
12025 | if (OCD == OCD_AmbiguousCandidates) |
12026 | MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); |
12027 | } |
12028 | |
12029 | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, |
12030 | ArrayRef<OverloadCandidate *> Cands, |
12031 | StringRef Opc, SourceLocation OpLoc) { |
12032 | bool ReportedAmbiguousConversions = false; |
12033 | |
12034 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12035 | unsigned CandsShown = 0; |
12036 | auto I = Cands.begin(), E = Cands.end(); |
12037 | for (; I != E; ++I) { |
12038 | OverloadCandidate *Cand = *I; |
12039 | |
12040 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && |
12041 | ShowOverloads == Ovl_Best) { |
12042 | break; |
12043 | } |
12044 | ++CandsShown; |
12045 | |
12046 | if (Cand->Function) |
12047 | NoteFunctionCandidate(S, Cand, Args.size(), |
12048 | /*TakingCandidateAddress=*/false, DestAS); |
12049 | else if (Cand->IsSurrogate) |
12050 | NoteSurrogateCandidate(S, Cand); |
12051 | else { |
12052 | assert(Cand->Viable &&(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 12053, __extension__ __PRETTY_FUNCTION__ )) |
12053 | "Non-viable built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 12053, __extension__ __PRETTY_FUNCTION__ )); |
12054 | // Generally we only see ambiguities including viable builtin |
12055 | // operators if overload resolution got screwed up by an |
12056 | // ambiguous user-defined conversion. |
12057 | // |
12058 | // FIXME: It's quite possible for different conversions to see |
12059 | // different ambiguities, though. |
12060 | if (!ReportedAmbiguousConversions) { |
12061 | NoteAmbiguousUserConversions(S, OpLoc, Cand); |
12062 | ReportedAmbiguousConversions = true; |
12063 | } |
12064 | |
12065 | // If this is a viable builtin, print it. |
12066 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); |
12067 | } |
12068 | } |
12069 | |
12070 | // Inform S.Diags that we've shown an overload set with N elements. This may |
12071 | // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). |
12072 | S.Diags.overloadCandidatesShown(CandsShown); |
12073 | |
12074 | if (I != E) |
12075 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates, |
12076 | shouldDeferDiags(S, Args, OpLoc)) |
12077 | << int(E - I); |
12078 | } |
12079 | |
12080 | static SourceLocation |
12081 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { |
12082 | return Cand->Specialization ? Cand->Specialization->getLocation() |
12083 | : SourceLocation(); |
12084 | } |
12085 | |
12086 | namespace { |
12087 | struct CompareTemplateSpecCandidatesForDisplay { |
12088 | Sema &S; |
12089 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} |
12090 | |
12091 | bool operator()(const TemplateSpecCandidate *L, |
12092 | const TemplateSpecCandidate *R) { |
12093 | // Fast-path this check. |
12094 | if (L == R) |
12095 | return false; |
12096 | |
12097 | // Assuming that both candidates are not matches... |
12098 | |
12099 | // Sort by the ranking of deduction failures. |
12100 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
12101 | return RankDeductionFailure(L->DeductionFailure) < |
12102 | RankDeductionFailure(R->DeductionFailure); |
12103 | |
12104 | // Sort everything else by location. |
12105 | SourceLocation LLoc = GetLocationForCandidate(L); |
12106 | SourceLocation RLoc = GetLocationForCandidate(R); |
12107 | |
12108 | // Put candidates without locations (e.g. builtins) at the end. |
12109 | if (LLoc.isInvalid()) |
12110 | return false; |
12111 | if (RLoc.isInvalid()) |
12112 | return true; |
12113 | |
12114 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
12115 | } |
12116 | }; |
12117 | } |
12118 | |
12119 | /// Diagnose a template argument deduction failure. |
12120 | /// We are treating these failures as overload failures due to bad |
12121 | /// deductions. |
12122 | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, |
12123 | bool ForTakingAddress) { |
12124 | DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern |
12125 | DeductionFailure, /*NumArgs=*/0, ForTakingAddress); |
12126 | } |
12127 | |
12128 | void TemplateSpecCandidateSet::destroyCandidates() { |
12129 | for (iterator i = begin(), e = end(); i != e; ++i) { |
12130 | i->DeductionFailure.Destroy(); |
12131 | } |
12132 | } |
12133 | |
12134 | void TemplateSpecCandidateSet::clear() { |
12135 | destroyCandidates(); |
12136 | Candidates.clear(); |
12137 | } |
12138 | |
12139 | /// NoteCandidates - When no template specialization match is found, prints |
12140 | /// diagnostic messages containing the non-matching specializations that form |
12141 | /// the candidate set. |
12142 | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with |
12143 | /// OCD == OCD_AllCandidates and Cand->Viable == false. |
12144 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { |
12145 | // Sort the candidates by position (assuming no candidate is a match). |
12146 | // Sorting directly would be prohibitive, so we make a set of pointers |
12147 | // and sort those. |
12148 | SmallVector<TemplateSpecCandidate *, 32> Cands; |
12149 | Cands.reserve(size()); |
12150 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
12151 | if (Cand->Specialization) |
12152 | Cands.push_back(Cand); |
12153 | // Otherwise, this is a non-matching builtin candidate. We do not, |
12154 | // in general, want to list every possible builtin candidate. |
12155 | } |
12156 | |
12157 | llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); |
12158 | |
12159 | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() |
12160 | // for generalization purposes (?). |
12161 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12162 | |
12163 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; |
12164 | unsigned CandsShown = 0; |
12165 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
12166 | TemplateSpecCandidate *Cand = *I; |
12167 | |
12168 | // Set an arbitrary limit on the number of candidates we'll spam |
12169 | // the user with. FIXME: This limit should depend on details of the |
12170 | // candidate list. |
12171 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) |
12172 | break; |
12173 | ++CandsShown; |
12174 | |
12175 | assert(Cand->Specialization &&(static_cast <bool> (Cand->Specialization && "Non-matching built-in candidates are not added to Cands.") ? void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 12176, __extension__ __PRETTY_FUNCTION__ )) |
12176 | "Non-matching built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Specialization && "Non-matching built-in candidates are not added to Cands.") ? void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 12176, __extension__ __PRETTY_FUNCTION__ )); |
12177 | Cand->NoteDeductionFailure(S, ForTakingAddress); |
12178 | } |
12179 | |
12180 | if (I != E) |
12181 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); |
12182 | } |
12183 | |
12184 | // [PossiblyAFunctionType] --> [Return] |
12185 | // NonFunctionType --> NonFunctionType |
12186 | // R (A) --> R(A) |
12187 | // R (*)(A) --> R (A) |
12188 | // R (&)(A) --> R (A) |
12189 | // R (S::*)(A) --> R (A) |
12190 | QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { |
12191 | QualType Ret = PossiblyAFunctionType; |
12192 | if (const PointerType *ToTypePtr = |
12193 | PossiblyAFunctionType->getAs<PointerType>()) |
12194 | Ret = ToTypePtr->getPointeeType(); |
12195 | else if (const ReferenceType *ToTypeRef = |
12196 | PossiblyAFunctionType->getAs<ReferenceType>()) |
12197 | Ret = ToTypeRef->getPointeeType(); |
12198 | else if (const MemberPointerType *MemTypePtr = |
12199 | PossiblyAFunctionType->getAs<MemberPointerType>()) |
12200 | Ret = MemTypePtr->getPointeeType(); |
12201 | Ret = |
12202 | Context.getCanonicalType(Ret).getUnqualifiedType(); |
12203 | return Ret; |
12204 | } |
12205 | |
12206 | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, |
12207 | bool Complain = true) { |
12208 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
12209 | S.DeduceReturnType(FD, Loc, Complain)) |
12210 | return true; |
12211 | |
12212 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
12213 | if (S.getLangOpts().CPlusPlus17 && |
12214 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && |
12215 | !S.ResolveExceptionSpec(Loc, FPT)) |
12216 | return true; |
12217 | |
12218 | return false; |
12219 | } |
12220 | |
12221 | namespace { |
12222 | // A helper class to help with address of function resolution |
12223 | // - allows us to avoid passing around all those ugly parameters |
12224 | class AddressOfFunctionResolver { |
12225 | Sema& S; |
12226 | Expr* SourceExpr; |
12227 | const QualType& TargetType; |
12228 | QualType TargetFunctionType; // Extracted function type from target type |
12229 | |
12230 | bool Complain; |
12231 | //DeclAccessPair& ResultFunctionAccessPair; |
12232 | ASTContext& Context; |
12233 | |
12234 | bool TargetTypeIsNonStaticMemberFunction; |
12235 | bool FoundNonTemplateFunction; |
12236 | bool StaticMemberFunctionFromBoundPointer; |
12237 | bool HasComplained; |
12238 | |
12239 | OverloadExpr::FindResult OvlExprInfo; |
12240 | OverloadExpr *OvlExpr; |
12241 | TemplateArgumentListInfo OvlExplicitTemplateArgs; |
12242 | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; |
12243 | TemplateSpecCandidateSet FailedCandidates; |
12244 | |
12245 | public: |
12246 | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, |
12247 | const QualType &TargetType, bool Complain) |
12248 | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), |
12249 | Complain(Complain), Context(S.getASTContext()), |
12250 | TargetTypeIsNonStaticMemberFunction( |
12251 | !!TargetType->getAs<MemberPointerType>()), |
12252 | FoundNonTemplateFunction(false), |
12253 | StaticMemberFunctionFromBoundPointer(false), |
12254 | HasComplained(false), |
12255 | OvlExprInfo(OverloadExpr::find(SourceExpr)), |
12256 | OvlExpr(OvlExprInfo.Expression), |
12257 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { |
12258 | ExtractUnqualifiedFunctionTypeFromTargetType(); |
12259 | |
12260 | if (TargetFunctionType->isFunctionType()) { |
12261 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) |
12262 | if (!UME->isImplicitAccess() && |
12263 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) |
12264 | StaticMemberFunctionFromBoundPointer = true; |
12265 | } else if (OvlExpr->hasExplicitTemplateArgs()) { |
12266 | DeclAccessPair dap; |
12267 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( |
12268 | OvlExpr, false, &dap)) { |
12269 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) |
12270 | if (!Method->isStatic()) { |
12271 | // If the target type is a non-function type and the function found |
12272 | // is a non-static member function, pretend as if that was the |
12273 | // target, it's the only possible type to end up with. |
12274 | TargetTypeIsNonStaticMemberFunction = true; |
12275 | |
12276 | // And skip adding the function if its not in the proper form. |
12277 | // We'll diagnose this due to an empty set of functions. |
12278 | if (!OvlExprInfo.HasFormOfMemberPointer) |
12279 | return; |
12280 | } |
12281 | |
12282 | Matches.push_back(std::make_pair(dap, Fn)); |
12283 | } |
12284 | return; |
12285 | } |
12286 | |
12287 | if (OvlExpr->hasExplicitTemplateArgs()) |
12288 | OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); |
12289 | |
12290 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { |
12291 | // C++ [over.over]p4: |
12292 | // If more than one function is selected, [...] |
12293 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { |
12294 | if (FoundNonTemplateFunction) |
12295 | EliminateAllTemplateMatches(); |
12296 | else |
12297 | EliminateAllExceptMostSpecializedTemplate(); |
12298 | } |
12299 | } |
12300 | |
12301 | if (S.getLangOpts().CUDA && Matches.size() > 1) |
12302 | EliminateSuboptimalCudaMatches(); |
12303 | } |
12304 | |
12305 | bool hasComplained() const { return HasComplained; } |
12306 | |
12307 | private: |
12308 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { |
12309 | QualType Discard; |
12310 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || |
12311 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); |
12312 | } |
12313 | |
12314 | /// \return true if A is considered a better overload candidate for the |
12315 | /// desired type than B. |
12316 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { |
12317 | // If A doesn't have exactly the correct type, we don't want to classify it |
12318 | // as "better" than anything else. This way, the user is required to |
12319 | // disambiguate for us if there are multiple candidates and no exact match. |
12320 | return candidateHasExactlyCorrectType(A) && |
12321 | (!candidateHasExactlyCorrectType(B) || |
12322 | compareEnableIfAttrs(S, A, B) == Comparison::Better); |
12323 | } |
12324 | |
12325 | /// \return true if we were able to eliminate all but one overload candidate, |
12326 | /// false otherwise. |
12327 | bool eliminiateSuboptimalOverloadCandidates() { |
12328 | // Same algorithm as overload resolution -- one pass to pick the "best", |
12329 | // another pass to be sure that nothing is better than the best. |
12330 | auto Best = Matches.begin(); |
12331 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) |
12332 | if (isBetterCandidate(I->second, Best->second)) |
12333 | Best = I; |
12334 | |
12335 | const FunctionDecl *BestFn = Best->second; |
12336 | auto IsBestOrInferiorToBest = [this, BestFn]( |
12337 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { |
12338 | return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); |
12339 | }; |
12340 | |
12341 | // Note: We explicitly leave Matches unmodified if there isn't a clear best |
12342 | // option, so we can potentially give the user a better error |
12343 | if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) |
12344 | return false; |
12345 | Matches[0] = *Best; |
12346 | Matches.resize(1); |
12347 | return true; |
12348 | } |
12349 | |
12350 | bool isTargetTypeAFunction() const { |
12351 | return TargetFunctionType->isFunctionType(); |
12352 | } |
12353 | |
12354 | // [ToType] [Return] |
12355 | |
12356 | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false |
12357 | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false |
12358 | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true |
12359 | void inline ExtractUnqualifiedFunctionTypeFromTargetType() { |
12360 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); |
12361 | } |
12362 | |
12363 | // return true if any matching specializations were found |
12364 | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, |
12365 | const DeclAccessPair& CurAccessFunPair) { |
12366 | if (CXXMethodDecl *Method |
12367 | = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { |
12368 | // Skip non-static function templates when converting to pointer, and |
12369 | // static when converting to member pointer. |
12370 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) |
12371 | return false; |
12372 | } |
12373 | else if (TargetTypeIsNonStaticMemberFunction) |
12374 | return false; |
12375 | |
12376 | // C++ [over.over]p2: |
12377 | // If the name is a function template, template argument deduction is |
12378 | // done (14.8.2.2), and if the argument deduction succeeds, the |
12379 | // resulting template argument list is used to generate a single |
12380 | // function template specialization, which is added to the set of |
12381 | // overloaded functions considered. |
12382 | FunctionDecl *Specialization = nullptr; |
12383 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
12384 | if (Sema::TemplateDeductionResult Result |
12385 | = S.DeduceTemplateArguments(FunctionTemplate, |
12386 | &OvlExplicitTemplateArgs, |
12387 | TargetFunctionType, Specialization, |
12388 | Info, /*IsAddressOfFunction*/true)) { |
12389 | // Make a note of the failed deduction for diagnostics. |
12390 | FailedCandidates.addCandidate() |
12391 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), |
12392 | MakeDeductionFailureInfo(Context, Result, Info)); |
12393 | return false; |
12394 | } |
12395 | |
12396 | // Template argument deduction ensures that we have an exact match or |
12397 | // compatible pointer-to-function arguments that would be adjusted by ICS. |
12398 | // This function template specicalization works. |
12399 | assert(S.isSameOrCompatibleFunctionType((static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12401, __extension__ __PRETTY_FUNCTION__ )) |
12400 | Context.getCanonicalType(Specialization->getType()),(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12401, __extension__ __PRETTY_FUNCTION__ )) |
12401 | Context.getCanonicalType(TargetFunctionType)))(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12401, __extension__ __PRETTY_FUNCTION__ )); |
12402 | |
12403 | if (!S.checkAddressOfFunctionIsAvailable(Specialization)) |
12404 | return false; |
12405 | |
12406 | Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); |
12407 | return true; |
12408 | } |
12409 | |
12410 | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, |
12411 | const DeclAccessPair& CurAccessFunPair) { |
12412 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
12413 | // Skip non-static functions when converting to pointer, and static |
12414 | // when converting to member pointer. |
12415 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) |
12416 | return false; |
12417 | } |
12418 | else if (TargetTypeIsNonStaticMemberFunction) |
12419 | return false; |
12420 | |
12421 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { |
12422 | if (S.getLangOpts().CUDA) |
12423 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) |
12424 | if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) |
12425 | return false; |
12426 | if (FunDecl->isMultiVersion()) { |
12427 | const auto *TA = FunDecl->getAttr<TargetAttr>(); |
12428 | if (TA && !TA->isDefaultVersion()) |
12429 | return false; |
12430 | const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); |
12431 | if (TVA && !TVA->isDefaultVersion()) |
12432 | return false; |
12433 | } |
12434 | |
12435 | // If any candidate has a placeholder return type, trigger its deduction |
12436 | // now. |
12437 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), |
12438 | Complain)) { |
12439 | HasComplained |= Complain; |
12440 | return false; |
12441 | } |
12442 | |
12443 | if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) |
12444 | return false; |
12445 | |
12446 | // If we're in C, we need to support types that aren't exactly identical. |
12447 | if (!S.getLangOpts().CPlusPlus || |
12448 | candidateHasExactlyCorrectType(FunDecl)) { |
12449 | Matches.push_back(std::make_pair( |
12450 | CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); |
12451 | FoundNonTemplateFunction = true; |
12452 | return true; |
12453 | } |
12454 | } |
12455 | |
12456 | return false; |
12457 | } |
12458 | |
12459 | bool FindAllFunctionsThatMatchTargetTypeExactly() { |
12460 | bool Ret = false; |
12461 | |
12462 | // If the overload expression doesn't have the form of a pointer to |
12463 | // member, don't try to convert it to a pointer-to-member type. |
12464 | if (IsInvalidFormOfPointerToMemberFunction()) |
12465 | return false; |
12466 | |
12467 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
12468 | E = OvlExpr->decls_end(); |
12469 | I != E; ++I) { |
12470 | // Look through any using declarations to find the underlying function. |
12471 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); |
12472 | |
12473 | // C++ [over.over]p3: |
12474 | // Non-member functions and static member functions match |
12475 | // targets of type "pointer-to-function" or "reference-to-function." |
12476 | // Nonstatic member functions match targets of |
12477 | // type "pointer-to-member-function." |
12478 | // Note that according to DR 247, the containing class does not matter. |
12479 | if (FunctionTemplateDecl *FunctionTemplate |
12480 | = dyn_cast<FunctionTemplateDecl>(Fn)) { |
12481 | if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) |
12482 | Ret = true; |
12483 | } |
12484 | // If we have explicit template arguments supplied, skip non-templates. |
12485 | else if (!OvlExpr->hasExplicitTemplateArgs() && |
12486 | AddMatchingNonTemplateFunction(Fn, I.getPair())) |
12487 | Ret = true; |
12488 | } |
12489 | assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0) : __assert_fail ("Ret || Matches.empty()", "clang/lib/Sema/SemaOverload.cpp" , 12489, __extension__ __PRETTY_FUNCTION__)); |
12490 | return Ret; |
12491 | } |
12492 | |
12493 | void EliminateAllExceptMostSpecializedTemplate() { |
12494 | // [...] and any given function template specialization F1 is |
12495 | // eliminated if the set contains a second function template |
12496 | // specialization whose function template is more specialized |
12497 | // than the function template of F1 according to the partial |
12498 | // ordering rules of 14.5.5.2. |
12499 | |
12500 | // The algorithm specified above is quadratic. We instead use a |
12501 | // two-pass algorithm (similar to the one used to identify the |
12502 | // best viable function in an overload set) that identifies the |
12503 | // best function template (if it exists). |
12504 | |
12505 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! |
12506 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) |
12507 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); |
12508 | |
12509 | // TODO: It looks like FailedCandidates does not serve much purpose |
12510 | // here, since the no_viable diagnostic has index 0. |
12511 | UnresolvedSetIterator Result = S.getMostSpecialized( |
12512 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, |
12513 | SourceExpr->getBeginLoc(), S.PDiag(), |
12514 | S.PDiag(diag::err_addr_ovl_ambiguous) |
12515 | << Matches[0].second->getDeclName(), |
12516 | S.PDiag(diag::note_ovl_candidate) |
12517 | << (unsigned)oc_function << (unsigned)ocs_described_template, |
12518 | Complain, TargetFunctionType); |
12519 | |
12520 | if (Result != MatchesCopy.end()) { |
12521 | // Make it the first and only element |
12522 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; |
12523 | Matches[0].second = cast<FunctionDecl>(*Result); |
12524 | Matches.resize(1); |
12525 | } else |
12526 | HasComplained |= Complain; |
12527 | } |
12528 | |
12529 | void EliminateAllTemplateMatches() { |
12530 | // [...] any function template specializations in the set are |
12531 | // eliminated if the set also contains a non-template function, [...] |
12532 | for (unsigned I = 0, N = Matches.size(); I != N; ) { |
12533 | if (Matches[I].second->getPrimaryTemplate() == nullptr) |
12534 | ++I; |
12535 | else { |
12536 | Matches[I] = Matches[--N]; |
12537 | Matches.resize(N); |
12538 | } |
12539 | } |
12540 | } |
12541 | |
12542 | void EliminateSuboptimalCudaMatches() { |
12543 | S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), |
12544 | Matches); |
12545 | } |
12546 | |
12547 | public: |
12548 | void ComplainNoMatchesFound() const { |
12549 | assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail ("Matches.empty()", "clang/lib/Sema/SemaOverload.cpp", 12549 , __extension__ __PRETTY_FUNCTION__)); |
12550 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) |
12551 | << OvlExpr->getName() << TargetFunctionType |
12552 | << OvlExpr->getSourceRange(); |
12553 | if (FailedCandidates.empty()) |
12554 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
12555 | /*TakingAddress=*/true); |
12556 | else { |
12557 | // We have some deduction failure messages. Use them to diagnose |
12558 | // the function templates, and diagnose the non-template candidates |
12559 | // normally. |
12560 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
12561 | IEnd = OvlExpr->decls_end(); |
12562 | I != IEnd; ++I) |
12563 | if (FunctionDecl *Fun = |
12564 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) |
12565 | if (!functionHasPassObjectSizeParams(Fun)) |
12566 | S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, |
12567 | /*TakingAddress=*/true); |
12568 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); |
12569 | } |
12570 | } |
12571 | |
12572 | bool IsInvalidFormOfPointerToMemberFunction() const { |
12573 | return TargetTypeIsNonStaticMemberFunction && |
12574 | !OvlExprInfo.HasFormOfMemberPointer; |
12575 | } |
12576 | |
12577 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { |
12578 | // TODO: Should we condition this on whether any functions might |
12579 | // have matched, or is it more appropriate to do that in callers? |
12580 | // TODO: a fixit wouldn't hurt. |
12581 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) |
12582 | << TargetType << OvlExpr->getSourceRange(); |
12583 | } |
12584 | |
12585 | bool IsStaticMemberFunctionFromBoundPointer() const { |
12586 | return StaticMemberFunctionFromBoundPointer; |
12587 | } |
12588 | |
12589 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { |
12590 | S.Diag(OvlExpr->getBeginLoc(), |
12591 | diag::err_invalid_form_pointer_member_function) |
12592 | << OvlExpr->getSourceRange(); |
12593 | } |
12594 | |
12595 | void ComplainOfInvalidConversion() const { |
12596 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) |
12597 | << OvlExpr->getName() << TargetType; |
12598 | } |
12599 | |
12600 | void ComplainMultipleMatchesFound() const { |
12601 | assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) : __assert_fail ("Matches.size() > 1", "clang/lib/Sema/SemaOverload.cpp" , 12601, __extension__ __PRETTY_FUNCTION__)); |
12602 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) |
12603 | << OvlExpr->getName() << OvlExpr->getSourceRange(); |
12604 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
12605 | /*TakingAddress=*/true); |
12606 | } |
12607 | |
12608 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } |
12609 | |
12610 | int getNumMatches() const { return Matches.size(); } |
12611 | |
12612 | FunctionDecl* getMatchingFunctionDecl() const { |
12613 | if (Matches.size() != 1) return nullptr; |
12614 | return Matches[0].second; |
12615 | } |
12616 | |
12617 | const DeclAccessPair* getMatchingFunctionAccessPair() const { |
12618 | if (Matches.size() != 1) return nullptr; |
12619 | return &Matches[0].first; |
12620 | } |
12621 | }; |
12622 | } |
12623 | |
12624 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of |
12625 | /// an overloaded function (C++ [over.over]), where @p From is an |
12626 | /// expression with overloaded function type and @p ToType is the type |
12627 | /// we're trying to resolve to. For example: |
12628 | /// |
12629 | /// @code |
12630 | /// int f(double); |
12631 | /// int f(int); |
12632 | /// |
12633 | /// int (*pfd)(double) = f; // selects f(double) |
12634 | /// @endcode |
12635 | /// |
12636 | /// This routine returns the resulting FunctionDecl if it could be |
12637 | /// resolved, and NULL otherwise. When @p Complain is true, this |
12638 | /// routine will emit diagnostics if there is an error. |
12639 | FunctionDecl * |
12640 | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
12641 | QualType TargetType, |
12642 | bool Complain, |
12643 | DeclAccessPair &FoundResult, |
12644 | bool *pHadMultipleCandidates) { |
12645 | assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast <bool> (AddressOfExpr->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 12645, __extension__ __PRETTY_FUNCTION__ )); |
12646 | |
12647 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, |
12648 | Complain); |
12649 | int NumMatches = Resolver.getNumMatches(); |
12650 | FunctionDecl *Fn = nullptr; |
12651 | bool ShouldComplain = Complain && !Resolver.hasComplained(); |
12652 | if (NumMatches == 0 && ShouldComplain) { |
12653 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) |
12654 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); |
12655 | else |
12656 | Resolver.ComplainNoMatchesFound(); |
12657 | } |
12658 | else if (NumMatches > 1 && ShouldComplain) |
12659 | Resolver.ComplainMultipleMatchesFound(); |
12660 | else if (NumMatches == 1) { |
12661 | Fn = Resolver.getMatchingFunctionDecl(); |
12662 | assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn" , "clang/lib/Sema/SemaOverload.cpp", 12662, __extension__ __PRETTY_FUNCTION__ )); |
12663 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
12664 | ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); |
12665 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); |
12666 | if (Complain) { |
12667 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) |
12668 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); |
12669 | else |
12670 | CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); |
12671 | } |
12672 | } |
12673 | |
12674 | if (pHadMultipleCandidates) |
12675 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); |
12676 | return Fn; |
12677 | } |
12678 | |
12679 | /// Given an expression that refers to an overloaded function, try to |
12680 | /// resolve that function to a single function that can have its address taken. |
12681 | /// This will modify `Pair` iff it returns non-null. |
12682 | /// |
12683 | /// This routine can only succeed if from all of the candidates in the overload |
12684 | /// set for SrcExpr that can have their addresses taken, there is one candidate |
12685 | /// that is more constrained than the rest. |
12686 | FunctionDecl * |
12687 | Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { |
12688 | OverloadExpr::FindResult R = OverloadExpr::find(E); |
12689 | OverloadExpr *Ovl = R.Expression; |
12690 | bool IsResultAmbiguous = false; |
12691 | FunctionDecl *Result = nullptr; |
12692 | DeclAccessPair DAP; |
12693 | SmallVector<FunctionDecl *, 2> AmbiguousDecls; |
12694 | |
12695 | auto CheckMoreConstrained = [&](FunctionDecl *FD1, |
12696 | FunctionDecl *FD2) -> std::optional<bool> { |
12697 | if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) |
12698 | FD1 = MF; |
12699 | if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) |
12700 | FD2 = MF; |
12701 | SmallVector<const Expr *, 1> AC1, AC2; |
12702 | FD1->getAssociatedConstraints(AC1); |
12703 | FD2->getAssociatedConstraints(AC2); |
12704 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
12705 | if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) |
12706 | return std::nullopt; |
12707 | if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) |
12708 | return std::nullopt; |
12709 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
12710 | return std::nullopt; |
12711 | return AtLeastAsConstrained1; |
12712 | }; |
12713 | |
12714 | // Don't use the AddressOfResolver because we're specifically looking for |
12715 | // cases where we have one overload candidate that lacks |
12716 | // enable_if/pass_object_size/... |
12717 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { |
12718 | auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); |
12719 | if (!FD) |
12720 | return nullptr; |
12721 | |
12722 | if (!checkAddressOfFunctionIsAvailable(FD)) |
12723 | continue; |
12724 | |
12725 | // We have more than one result - see if it is more constrained than the |
12726 | // previous one. |
12727 | if (Result) { |
12728 | std::optional<bool> MoreConstrainedThanPrevious = |
12729 | CheckMoreConstrained(FD, Result); |
12730 | if (!MoreConstrainedThanPrevious) { |
12731 | IsResultAmbiguous = true; |
12732 | AmbiguousDecls.push_back(FD); |
12733 | continue; |
12734 | } |
12735 | if (!*MoreConstrainedThanPrevious) |
12736 | continue; |
12737 | // FD is more constrained - replace Result with it. |
12738 | } |
12739 | IsResultAmbiguous = false; |
12740 | DAP = I.getPair(); |
12741 | Result = FD; |
12742 | } |
12743 | |
12744 | if (IsResultAmbiguous) |
12745 | return nullptr; |
12746 | |
12747 | if (Result) { |
12748 | SmallVector<const Expr *, 1> ResultAC; |
12749 | // We skipped over some ambiguous declarations which might be ambiguous with |
12750 | // the selected result. |
12751 | for (FunctionDecl *Skipped : AmbiguousDecls) |
12752 | if (!CheckMoreConstrained(Skipped, Result)) |
12753 | return nullptr; |
12754 | Pair = DAP; |
12755 | } |
12756 | return Result; |
12757 | } |
12758 | |
12759 | /// Given an overloaded function, tries to turn it into a non-overloaded |
12760 | /// function reference using resolveAddressOfSingleOverloadCandidate. This |
12761 | /// will perform access checks, diagnose the use of the resultant decl, and, if |
12762 | /// requested, potentially perform a function-to-pointer decay. |
12763 | /// |
12764 | /// Returns false if resolveAddressOfSingleOverloadCandidate fails. |
12765 | /// Otherwise, returns true. This may emit diagnostics and return true. |
12766 | bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( |
12767 | ExprResult &SrcExpr, bool DoFunctionPointerConversion) { |
12768 | Expr *E = SrcExpr.get(); |
12769 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast <bool> (E->getType() == Context.OverloadTy && "SrcExpr must be an overload") ? void (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\"" , "clang/lib/Sema/SemaOverload.cpp", 12769, __extension__ __PRETTY_FUNCTION__ )); |
12770 | |
12771 | DeclAccessPair DAP; |
12772 | FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); |
12773 | if (!Found || Found->isCPUDispatchMultiVersion() || |
12774 | Found->isCPUSpecificMultiVersion()) |
12775 | return false; |
12776 | |
12777 | // Emitting multiple diagnostics for a function that is both inaccessible and |
12778 | // unavailable is consistent with our behavior elsewhere. So, always check |
12779 | // for both. |
12780 | DiagnoseUseOfDecl(Found, E->getExprLoc()); |
12781 | CheckAddressOfMemberAccess(E, DAP); |
12782 | Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); |
12783 | if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) |
12784 | SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); |
12785 | else |
12786 | SrcExpr = Fixed; |
12787 | return true; |
12788 | } |
12789 | |
12790 | /// Given an expression that refers to an overloaded function, try to |
12791 | /// resolve that overloaded function expression down to a single function. |
12792 | /// |
12793 | /// This routine can only resolve template-ids that refer to a single function |
12794 | /// template, where that template-id refers to a single template whose template |
12795 | /// arguments are either provided by the template-id or have defaults, |
12796 | /// as described in C++0x [temp.arg.explicit]p3. |
12797 | /// |
12798 | /// If no template-ids are found, no diagnostics are emitted and NULL is |
12799 | /// returned. |
12800 | FunctionDecl * |
12801 | Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, |
12802 | bool Complain, |
12803 | DeclAccessPair *FoundResult) { |
12804 | // C++ [over.over]p1: |
12805 | // [...] [Note: any redundant set of parentheses surrounding the |
12806 | // overloaded function name is ignored (5.1). ] |
12807 | // C++ [over.over]p1: |
12808 | // [...] The overloaded function name can be preceded by the & |
12809 | // operator. |
12810 | |
12811 | // If we didn't actually find any template-ids, we're done. |
12812 | if (!ovl->hasExplicitTemplateArgs()) |
12813 | return nullptr; |
12814 | |
12815 | TemplateArgumentListInfo ExplicitTemplateArgs; |
12816 | ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); |
12817 | TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); |
12818 | |
12819 | // Look through all of the overloaded functions, searching for one |
12820 | // whose type matches exactly. |
12821 | FunctionDecl *Matched = nullptr; |
12822 | for (UnresolvedSetIterator I = ovl->decls_begin(), |
12823 | E = ovl->decls_end(); I != E; ++I) { |
12824 | // C++0x [temp.arg.explicit]p3: |
12825 | // [...] In contexts where deduction is done and fails, or in contexts |
12826 | // where deduction is not done, if a template argument list is |
12827 | // specified and it, along with any default template arguments, |
12828 | // identifies a single function template specialization, then the |
12829 | // template-id is an lvalue for the function template specialization. |
12830 | FunctionTemplateDecl *FunctionTemplate |
12831 | = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); |
12832 | |
12833 | // C++ [over.over]p2: |
12834 | // If the name is a function template, template argument deduction is |
12835 | // done (14.8.2.2), and if the argument deduction succeeds, the |
12836 | // resulting template argument list is used to generate a single |
12837 | // function template specialization, which is added to the set of |
12838 | // overloaded functions considered. |
12839 | FunctionDecl *Specialization = nullptr; |
12840 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
12841 | if (TemplateDeductionResult Result |
12842 | = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, |
12843 | Specialization, Info, |
12844 | /*IsAddressOfFunction*/true)) { |
12845 | // Make a note of the failed deduction for diagnostics. |
12846 | // TODO: Actually use the failed-deduction info? |
12847 | FailedCandidates.addCandidate() |
12848 | .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), |
12849 | MakeDeductionFailureInfo(Context, Result, Info)); |
12850 | continue; |
12851 | } |
12852 | |
12853 | assert(Specialization && "no specialization and no error?")(static_cast <bool> (Specialization && "no specialization and no error?" ) ? void (0) : __assert_fail ("Specialization && \"no specialization and no error?\"" , "clang/lib/Sema/SemaOverload.cpp", 12853, __extension__ __PRETTY_FUNCTION__ )); |
12854 | |
12855 | // Multiple matches; we can't resolve to a single declaration. |
12856 | if (Matched) { |
12857 | if (Complain) { |
12858 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) |
12859 | << ovl->getName(); |
12860 | NoteAllOverloadCandidates(ovl); |
12861 | } |
12862 | return nullptr; |
12863 | } |
12864 | |
12865 | Matched = Specialization; |
12866 | if (FoundResult) *FoundResult = I.getPair(); |
12867 | } |
12868 | |
12869 | if (Matched && |
12870 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) |
12871 | return nullptr; |
12872 | |
12873 | return Matched; |
12874 | } |
12875 | |
12876 | // Resolve and fix an overloaded expression that can be resolved |
12877 | // because it identifies a single function template specialization. |
12878 | // |
12879 | // Last three arguments should only be supplied if Complain = true |
12880 | // |
12881 | // Return true if it was logically possible to so resolve the |
12882 | // expression, regardless of whether or not it succeeded. Always |
12883 | // returns true if 'complain' is set. |
12884 | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( |
12885 | ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, |
12886 | SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, |
12887 | unsigned DiagIDForComplaining) { |
12888 | assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast <bool> (SrcExpr.get()->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 12888, __extension__ __PRETTY_FUNCTION__ )); |
12889 | |
12890 | OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); |
12891 | |
12892 | DeclAccessPair found; |
12893 | ExprResult SingleFunctionExpression; |
12894 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( |
12895 | ovl.Expression, /*complain*/ false, &found)) { |
12896 | if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { |
12897 | SrcExpr = ExprError(); |
12898 | return true; |
12899 | } |
12900 | |
12901 | // It is only correct to resolve to an instance method if we're |
12902 | // resolving a form that's permitted to be a pointer to member. |
12903 | // Otherwise we'll end up making a bound member expression, which |
12904 | // is illegal in all the contexts we resolve like this. |
12905 | if (!ovl.HasFormOfMemberPointer && |
12906 | isa<CXXMethodDecl>(fn) && |
12907 | cast<CXXMethodDecl>(fn)->isInstance()) { |
12908 | if (!complain) return false; |
12909 | |
12910 | Diag(ovl.Expression->getExprLoc(), |
12911 | diag::err_bound_member_function) |
12912 | << 0 << ovl.Expression->getSourceRange(); |
12913 | |
12914 | // TODO: I believe we only end up here if there's a mix of |
12915 | // static and non-static candidates (otherwise the expression |
12916 | // would have 'bound member' type, not 'overload' type). |
12917 | // Ideally we would note which candidate was chosen and why |
12918 | // the static candidates were rejected. |
12919 | SrcExpr = ExprError(); |
12920 | return true; |
12921 | } |
12922 | |
12923 | // Fix the expression to refer to 'fn'. |
12924 | SingleFunctionExpression = |
12925 | FixOverloadedFunctionReference(SrcExpr.get(), found, fn); |
12926 | |
12927 | // If desired, do function-to-pointer decay. |
12928 | if (doFunctionPointerConversion) { |
12929 | SingleFunctionExpression = |
12930 | DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); |
12931 | if (SingleFunctionExpression.isInvalid()) { |
12932 | SrcExpr = ExprError(); |
12933 | return true; |
12934 | } |
12935 | } |
12936 | } |
12937 | |
12938 | if (!SingleFunctionExpression.isUsable()) { |
12939 | if (complain) { |
12940 | Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) |
12941 | << ovl.Expression->getName() |
12942 | << DestTypeForComplaining |
12943 | << OpRangeForComplaining |
12944 | << ovl.Expression->getQualifierLoc().getSourceRange(); |
12945 | NoteAllOverloadCandidates(SrcExpr.get()); |
12946 | |
12947 | SrcExpr = ExprError(); |
12948 | return true; |
12949 | } |
12950 | |
12951 | return false; |
12952 | } |
12953 | |
12954 | SrcExpr = SingleFunctionExpression; |
12955 | return true; |
12956 | } |
12957 | |
12958 | /// Add a single candidate to the overload set. |
12959 | static void AddOverloadedCallCandidate(Sema &S, |
12960 | DeclAccessPair FoundDecl, |
12961 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
12962 | ArrayRef<Expr *> Args, |
12963 | OverloadCandidateSet &CandidateSet, |
12964 | bool PartialOverloading, |
12965 | bool KnownValid) { |
12966 | NamedDecl *Callee = FoundDecl.getDecl(); |
12967 | if (isa<UsingShadowDecl>(Callee)) |
12968 | Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); |
12969 | |
12970 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { |
12971 | if (ExplicitTemplateArgs) { |
12972 | assert(!KnownValid && "Explicit template arguments?")(static_cast <bool> (!KnownValid && "Explicit template arguments?" ) ? void (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\"" , "clang/lib/Sema/SemaOverload.cpp", 12972, __extension__ __PRETTY_FUNCTION__ )); |
12973 | return; |
12974 | } |
12975 | // Prevent ill-formed function decls to be added as overload candidates. |
12976 | if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) |
12977 | return; |
12978 | |
12979 | S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, |
12980 | /*SuppressUserConversions=*/false, |
12981 | PartialOverloading); |
12982 | return; |
12983 | } |
12984 | |
12985 | if (FunctionTemplateDecl *FuncTemplate |
12986 | = dyn_cast<FunctionTemplateDecl>(Callee)) { |
12987 | S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, |
12988 | ExplicitTemplateArgs, Args, CandidateSet, |
12989 | /*SuppressUserConversions=*/false, |
12990 | PartialOverloading); |
12991 | return; |
12992 | } |
12993 | |
12994 | assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast <bool> (!KnownValid && "unhandled case in overloaded call candidate" ) ? void (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 12994, __extension__ __PRETTY_FUNCTION__ )); |
12995 | } |
12996 | |
12997 | /// Add the overload candidates named by callee and/or found by argument |
12998 | /// dependent lookup to the given overload set. |
12999 | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
13000 | ArrayRef<Expr *> Args, |
13001 | OverloadCandidateSet &CandidateSet, |
13002 | bool PartialOverloading) { |
13003 | |
13004 | #ifndef NDEBUG |
13005 | // Verify that ArgumentDependentLookup is consistent with the rules |
13006 | // in C++0x [basic.lookup.argdep]p3: |
13007 | // |
13008 | // Let X be the lookup set produced by unqualified lookup (3.4.1) |
13009 | // and let Y be the lookup set produced by argument dependent |
13010 | // lookup (defined as follows). If X contains |
13011 | // |
13012 | // -- a declaration of a class member, or |
13013 | // |
13014 | // -- a block-scope function declaration that is not a |
13015 | // using-declaration, or |
13016 | // |
13017 | // -- a declaration that is neither a function or a function |
13018 | // template |
13019 | // |
13020 | // then Y is empty. |
13021 | |
13022 | if (ULE->requiresADL()) { |
13023 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13024 | E = ULE->decls_end(); I != E; ++I) { |
13025 | assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord ()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()" , "clang/lib/Sema/SemaOverload.cpp", 13025, __extension__ __PRETTY_FUNCTION__ )); |
13026 | assert(isa<UsingShadowDecl>(*I) ||(static_cast <bool> (isa<UsingShadowDecl>(*I) || ! (*I)->getDeclContext()->isFunctionOrMethod()) ? void (0 ) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "clang/lib/Sema/SemaOverload.cpp", 13027, __extension__ __PRETTY_FUNCTION__ )) |
13027 | !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast <bool> (isa<UsingShadowDecl>(*I) || ! (*I)->getDeclContext()->isFunctionOrMethod()) ? void (0 ) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "clang/lib/Sema/SemaOverload.cpp", 13027, __extension__ __PRETTY_FUNCTION__ )); |
13028 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate ()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()" , "clang/lib/Sema/SemaOverload.cpp", 13028, __extension__ __PRETTY_FUNCTION__ )); |
13029 | } |
13030 | } |
13031 | #endif |
13032 | |
13033 | // It would be nice to avoid this copy. |
13034 | TemplateArgumentListInfo TABuffer; |
13035 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13036 | if (ULE->hasExplicitTemplateArgs()) { |
13037 | ULE->copyTemplateArgumentsInto(TABuffer); |
13038 | ExplicitTemplateArgs = &TABuffer; |
13039 | } |
13040 | |
13041 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13042 | E = ULE->decls_end(); I != E; ++I) |
13043 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, |
13044 | CandidateSet, PartialOverloading, |
13045 | /*KnownValid*/ true); |
13046 | |
13047 | if (ULE->requiresADL()) |
13048 | AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), |
13049 | Args, ExplicitTemplateArgs, |
13050 | CandidateSet, PartialOverloading); |
13051 | } |
13052 | |
13053 | /// Add the call candidates from the given set of lookup results to the given |
13054 | /// overload set. Non-function lookup results are ignored. |
13055 | void Sema::AddOverloadedCallCandidates( |
13056 | LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, |
13057 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { |
13058 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) |
13059 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, |
13060 | CandidateSet, false, /*KnownValid*/ false); |
13061 | } |
13062 | |
13063 | /// Determine whether a declaration with the specified name could be moved into |
13064 | /// a different namespace. |
13065 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { |
13066 | switch (Name.getCXXOverloadedOperator()) { |
13067 | case OO_New: case OO_Array_New: |
13068 | case OO_Delete: case OO_Array_Delete: |
13069 | return false; |
13070 | |
13071 | default: |
13072 | return true; |
13073 | } |
13074 | } |
13075 | |
13076 | /// Attempt to recover from an ill-formed use of a non-dependent name in a |
13077 | /// template, where the non-dependent name was declared after the template |
13078 | /// was defined. This is common in code written for a compilers which do not |
13079 | /// correctly implement two-stage name lookup. |
13080 | /// |
13081 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13082 | static bool DiagnoseTwoPhaseLookup( |
13083 | Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, |
13084 | LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, |
13085 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
13086 | CXXRecordDecl **FoundInClass = nullptr) { |
13087 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) |
13088 | return false; |
13089 | |
13090 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { |
13091 | if (DC->isTransparentContext()) |
13092 | continue; |
13093 | |
13094 | SemaRef.LookupQualifiedName(R, DC); |
13095 | |
13096 | if (!R.empty()) { |
13097 | R.suppressDiagnostics(); |
13098 | |
13099 | OverloadCandidateSet Candidates(FnLoc, CSK); |
13100 | SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, |
13101 | Candidates); |
13102 | |
13103 | OverloadCandidateSet::iterator Best; |
13104 | OverloadingResult OR = |
13105 | Candidates.BestViableFunction(SemaRef, FnLoc, Best); |
13106 | |
13107 | if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { |
13108 | // We either found non-function declarations or a best viable function |
13109 | // at class scope. A class-scope lookup result disables ADL. Don't |
13110 | // look past this, but let the caller know that we found something that |
13111 | // either is, or might be, usable in this class. |
13112 | if (FoundInClass) { |
13113 | *FoundInClass = RD; |
13114 | if (OR == OR_Success) { |
13115 | R.clear(); |
13116 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); |
13117 | R.resolveKind(); |
13118 | } |
13119 | } |
13120 | return false; |
13121 | } |
13122 | |
13123 | if (OR != OR_Success) { |
13124 | // There wasn't a unique best function or function template. |
13125 | return false; |
13126 | } |
13127 | |
13128 | // Find the namespaces where ADL would have looked, and suggest |
13129 | // declaring the function there instead. |
13130 | Sema::AssociatedNamespaceSet AssociatedNamespaces; |
13131 | Sema::AssociatedClassSet AssociatedClasses; |
13132 | SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, |
13133 | AssociatedNamespaces, |
13134 | AssociatedClasses); |
13135 | Sema::AssociatedNamespaceSet SuggestedNamespaces; |
13136 | if (canBeDeclaredInNamespace(R.getLookupName())) { |
13137 | DeclContext *Std = SemaRef.getStdNamespace(); |
13138 | for (Sema::AssociatedNamespaceSet::iterator |
13139 | it = AssociatedNamespaces.begin(), |
13140 | end = AssociatedNamespaces.end(); it != end; ++it) { |
13141 | // Never suggest declaring a function within namespace 'std'. |
13142 | if (Std && Std->Encloses(*it)) |
13143 | continue; |
13144 | |
13145 | // Never suggest declaring a function within a namespace with a |
13146 | // reserved name, like __gnu_cxx. |
13147 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); |
13148 | if (NS && |
13149 | NS->getQualifiedNameAsString().find("__") != std::string::npos) |
13150 | continue; |
13151 | |
13152 | SuggestedNamespaces.insert(*it); |
13153 | } |
13154 | } |
13155 | |
13156 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) |
13157 | << R.getLookupName(); |
13158 | if (SuggestedNamespaces.empty()) { |
13159 | SemaRef.Diag(Best->Function->getLocation(), |
13160 | diag::note_not_found_by_two_phase_lookup) |
13161 | << R.getLookupName() << 0; |
13162 | } else if (SuggestedNamespaces.size() == 1) { |
13163 | SemaRef.Diag(Best->Function->getLocation(), |
13164 | diag::note_not_found_by_two_phase_lookup) |
13165 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); |
13166 | } else { |
13167 | // FIXME: It would be useful to list the associated namespaces here, |
13168 | // but the diagnostics infrastructure doesn't provide a way to produce |
13169 | // a localized representation of a list of items. |
13170 | SemaRef.Diag(Best->Function->getLocation(), |
13171 | diag::note_not_found_by_two_phase_lookup) |
13172 | << R.getLookupName() << 2; |
13173 | } |
13174 | |
13175 | // Try to recover by calling this function. |
13176 | return true; |
13177 | } |
13178 | |
13179 | R.clear(); |
13180 | } |
13181 | |
13182 | return false; |
13183 | } |
13184 | |
13185 | /// Attempt to recover from ill-formed use of a non-dependent operator in a |
13186 | /// template, where the non-dependent operator was declared after the template |
13187 | /// was defined. |
13188 | /// |
13189 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13190 | static bool |
13191 | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, |
13192 | SourceLocation OpLoc, |
13193 | ArrayRef<Expr *> Args) { |
13194 | DeclarationName OpName = |
13195 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); |
13196 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); |
13197 | return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, |
13198 | OverloadCandidateSet::CSK_Operator, |
13199 | /*ExplicitTemplateArgs=*/nullptr, Args); |
13200 | } |
13201 | |
13202 | namespace { |
13203 | class BuildRecoveryCallExprRAII { |
13204 | Sema &SemaRef; |
13205 | Sema::SatisfactionStackResetRAII SatStack; |
13206 | |
13207 | public: |
13208 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { |
13209 | assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr == false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false" , "clang/lib/Sema/SemaOverload.cpp", 13209, __extension__ __PRETTY_FUNCTION__ )); |
13210 | SemaRef.IsBuildingRecoveryCallExpr = true; |
13211 | } |
13212 | |
13213 | ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } |
13214 | }; |
13215 | } |
13216 | |
13217 | /// Attempts to recover from a call where no functions were found. |
13218 | /// |
13219 | /// This function will do one of three things: |
13220 | /// * Diagnose, recover, and return a recovery expression. |
13221 | /// * Diagnose, fail to recover, and return ExprError(). |
13222 | /// * Do not diagnose, do not recover, and return ExprResult(). The caller is |
13223 | /// expected to diagnose as appropriate. |
13224 | static ExprResult |
13225 | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13226 | UnresolvedLookupExpr *ULE, |
13227 | SourceLocation LParenLoc, |
13228 | MutableArrayRef<Expr *> Args, |
13229 | SourceLocation RParenLoc, |
13230 | bool EmptyLookup, bool AllowTypoCorrection) { |
13231 | // Do not try to recover if it is already building a recovery call. |
13232 | // This stops infinite loops for template instantiations like |
13233 | // |
13234 | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} |
13235 | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} |
13236 | if (SemaRef.IsBuildingRecoveryCallExpr) |
13237 | return ExprResult(); |
13238 | BuildRecoveryCallExprRAII RCE(SemaRef); |
13239 | |
13240 | CXXScopeSpec SS; |
13241 | SS.Adopt(ULE->getQualifierLoc()); |
13242 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); |
13243 | |
13244 | TemplateArgumentListInfo TABuffer; |
13245 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13246 | if (ULE->hasExplicitTemplateArgs()) { |
13247 | ULE->copyTemplateArgumentsInto(TABuffer); |
13248 | ExplicitTemplateArgs = &TABuffer; |
13249 | } |
13250 | |
13251 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), |
13252 | Sema::LookupOrdinaryName); |
13253 | CXXRecordDecl *FoundInClass = nullptr; |
13254 | if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, |
13255 | OverloadCandidateSet::CSK_Normal, |
13256 | ExplicitTemplateArgs, Args, &FoundInClass)) { |
13257 | // OK, diagnosed a two-phase lookup issue. |
13258 | } else if (EmptyLookup) { |
13259 | // Try to recover from an empty lookup with typo correction. |
13260 | R.clear(); |
13261 | NoTypoCorrectionCCC NoTypoValidator{}; |
13262 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), |
13263 | ExplicitTemplateArgs != nullptr, |
13264 | dyn_cast<MemberExpr>(Fn)); |
13265 | CorrectionCandidateCallback &Validator = |
13266 | AllowTypoCorrection |
13267 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) |
13268 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); |
13269 | if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, |
13270 | Args)) |
13271 | return ExprError(); |
13272 | } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { |
13273 | // We found a usable declaration of the name in a dependent base of some |
13274 | // enclosing class. |
13275 | // FIXME: We should also explain why the candidates found by name lookup |
13276 | // were not viable. |
13277 | if (SemaRef.DiagnoseDependentMemberLookup(R)) |
13278 | return ExprError(); |
13279 | } else { |
13280 | // We had viable candidates and couldn't recover; let the caller diagnose |
13281 | // this. |
13282 | return ExprResult(); |
13283 | } |
13284 | |
13285 | // If we get here, we should have issued a diagnostic and formed a recovery |
13286 | // lookup result. |
13287 | assert(!R.empty() && "lookup results empty despite recovery")(static_cast <bool> (!R.empty() && "lookup results empty despite recovery" ) ? void (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\"" , "clang/lib/Sema/SemaOverload.cpp", 13287, __extension__ __PRETTY_FUNCTION__ )); |
13288 | |
13289 | // If recovery created an ambiguity, just bail out. |
13290 | if (R.isAmbiguous()) { |
13291 | R.suppressDiagnostics(); |
13292 | return ExprError(); |
13293 | } |
13294 | |
13295 | // Build an implicit member call if appropriate. Just drop the |
13296 | // casts and such from the call, we don't really care. |
13297 | ExprResult NewFn = ExprError(); |
13298 | if ((*R.begin())->isCXXClassMember()) |
13299 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, |
13300 | ExplicitTemplateArgs, S); |
13301 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) |
13302 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, |
13303 | ExplicitTemplateArgs); |
13304 | else |
13305 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); |
13306 | |
13307 | if (NewFn.isInvalid()) |
13308 | return ExprError(); |
13309 | |
13310 | // This shouldn't cause an infinite loop because we're giving it |
13311 | // an expression with viable lookup results, which should never |
13312 | // end up here. |
13313 | return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, |
13314 | MultiExprArg(Args.data(), Args.size()), |
13315 | RParenLoc); |
13316 | } |
13317 | |
13318 | /// Constructs and populates an OverloadedCandidateSet from |
13319 | /// the given function. |
13320 | /// \returns true when an the ExprResult output parameter has been set. |
13321 | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, |
13322 | UnresolvedLookupExpr *ULE, |
13323 | MultiExprArg Args, |
13324 | SourceLocation RParenLoc, |
13325 | OverloadCandidateSet *CandidateSet, |
13326 | ExprResult *Result) { |
13327 | #ifndef NDEBUG |
13328 | if (ULE->requiresADL()) { |
13329 | // To do ADL, we must have found an unqualified name. |
13330 | assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast <bool> (!ULE->getQualifier() && "qualified name with ADL") ? void (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\"" , "clang/lib/Sema/SemaOverload.cpp", 13330, __extension__ __PRETTY_FUNCTION__ )); |
13331 | |
13332 | // We don't perform ADL for implicit declarations of builtins. |
13333 | // Verify that this was correctly set up. |
13334 | FunctionDecl *F; |
13335 | if (ULE->decls_begin() != ULE->decls_end() && |
13336 | ULE->decls_begin() + 1 == ULE->decls_end() && |
13337 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && |
13338 | F->getBuiltinID() && F->isImplicit()) |
13339 | llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin" , "clang/lib/Sema/SemaOverload.cpp", 13339); |
13340 | |
13341 | // We don't perform ADL in C. |
13342 | assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast <bool> (getLangOpts().CPlusPlus && "ADL enabled in C") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\"" , "clang/lib/Sema/SemaOverload.cpp", 13342, __extension__ __PRETTY_FUNCTION__ )); |
13343 | } |
13344 | #endif |
13345 | |
13346 | UnbridgedCastsSet UnbridgedCasts; |
13347 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { |
13348 | *Result = ExprError(); |
13349 | return true; |
13350 | } |
13351 | |
13352 | // Add the functions denoted by the callee to the set of candidate |
13353 | // functions, including those from argument-dependent lookup. |
13354 | AddOverloadedCallCandidates(ULE, Args, *CandidateSet); |
13355 | |
13356 | if (getLangOpts().MSVCCompat && |
13357 | CurContext->isDependentContext() && !isSFINAEContext() && |
13358 | (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { |
13359 | |
13360 | OverloadCandidateSet::iterator Best; |
13361 | if (CandidateSet->empty() || |
13362 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == |
13363 | OR_No_Viable_Function) { |
13364 | // In Microsoft mode, if we are inside a template class member function |
13365 | // then create a type dependent CallExpr. The goal is to postpone name |
13366 | // lookup to instantiation time to be able to search into type dependent |
13367 | // base classes. |
13368 | CallExpr *CE = |
13369 | CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, |
13370 | RParenLoc, CurFPFeatureOverrides()); |
13371 | CE->markDependentForPostponedNameLookup(); |
13372 | *Result = CE; |
13373 | return true; |
13374 | } |
13375 | } |
13376 | |
13377 | if (CandidateSet->empty()) |
13378 | return false; |
13379 | |
13380 | UnbridgedCasts.restore(); |
13381 | return false; |
13382 | } |
13383 | |
13384 | // Guess at what the return type for an unresolvable overload should be. |
13385 | static QualType chooseRecoveryType(OverloadCandidateSet &CS, |
13386 | OverloadCandidateSet::iterator *Best) { |
13387 | std::optional<QualType> Result; |
13388 | // Adjust Type after seeing a candidate. |
13389 | auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { |
13390 | if (!Candidate.Function) |
13391 | return; |
13392 | if (Candidate.Function->isInvalidDecl()) |
13393 | return; |
13394 | QualType T = Candidate.Function->getReturnType(); |
13395 | if (T.isNull()) |
13396 | return; |
13397 | if (!Result) |
13398 | Result = T; |
13399 | else if (Result != T) |
13400 | Result = QualType(); |
13401 | }; |
13402 | |
13403 | // Look for an unambiguous type from a progressively larger subset. |
13404 | // e.g. if types disagree, but all *viable* overloads return int, choose int. |
13405 | // |
13406 | // First, consider only the best candidate. |
13407 | if (Best && *Best != CS.end()) |
13408 | ConsiderCandidate(**Best); |
13409 | // Next, consider only viable candidates. |
13410 | if (!Result) |
13411 | for (const auto &C : CS) |
13412 | if (C.Viable) |
13413 | ConsiderCandidate(C); |
13414 | // Finally, consider all candidates. |
13415 | if (!Result) |
13416 | for (const auto &C : CS) |
13417 | ConsiderCandidate(C); |
13418 | |
13419 | if (!Result) |
13420 | return QualType(); |
13421 | auto Value = *Result; |
13422 | if (Value.isNull() || Value->isUndeducedType()) |
13423 | return QualType(); |
13424 | return Value; |
13425 | } |
13426 | |
13427 | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns |
13428 | /// the completed call expression. If overload resolution fails, emits |
13429 | /// diagnostics and returns ExprError() |
13430 | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13431 | UnresolvedLookupExpr *ULE, |
13432 | SourceLocation LParenLoc, |
13433 | MultiExprArg Args, |
13434 | SourceLocation RParenLoc, |
13435 | Expr *ExecConfig, |
13436 | OverloadCandidateSet *CandidateSet, |
13437 | OverloadCandidateSet::iterator *Best, |
13438 | OverloadingResult OverloadResult, |
13439 | bool AllowTypoCorrection) { |
13440 | switch (OverloadResult) { |
13441 | case OR_Success: { |
13442 | FunctionDecl *FDecl = (*Best)->Function; |
13443 | SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); |
13444 | if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) |
13445 | return ExprError(); |
13446 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
13447 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, |
13448 | ExecConfig, /*IsExecConfig=*/false, |
13449 | (*Best)->IsADLCandidate); |
13450 | } |
13451 | |
13452 | case OR_No_Viable_Function: { |
13453 | // Try to recover by looking for viable functions which the user might |
13454 | // have meant to call. |
13455 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, |
13456 | Args, RParenLoc, |
13457 | CandidateSet->empty(), |
13458 | AllowTypoCorrection); |
13459 | if (Recovery.isInvalid() || Recovery.isUsable()) |
13460 | return Recovery; |
13461 | |
13462 | // If the user passes in a function that we can't take the address of, we |
13463 | // generally end up emitting really bad error messages. Here, we attempt to |
13464 | // emit better ones. |
13465 | for (const Expr *Arg : Args) { |
13466 | if (!Arg->getType()->isFunctionType()) |
13467 | continue; |
13468 | if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { |
13469 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); |
13470 | if (FD && |
13471 | !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, |
13472 | Arg->getExprLoc())) |
13473 | return ExprError(); |
13474 | } |
13475 | } |
13476 | |
13477 | CandidateSet->NoteCandidates( |
13478 | PartialDiagnosticAt( |
13479 | Fn->getBeginLoc(), |
13480 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) |
13481 | << ULE->getName() << Fn->getSourceRange()), |
13482 | SemaRef, OCD_AllCandidates, Args); |
13483 | break; |
13484 | } |
13485 | |
13486 | case OR_Ambiguous: |
13487 | CandidateSet->NoteCandidates( |
13488 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13489 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) |
13490 | << ULE->getName() << Fn->getSourceRange()), |
13491 | SemaRef, OCD_AmbiguousCandidates, Args); |
13492 | break; |
13493 | |
13494 | case OR_Deleted: { |
13495 | CandidateSet->NoteCandidates( |
13496 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13497 | SemaRef.PDiag(diag::err_ovl_deleted_call) |
13498 | << ULE->getName() << Fn->getSourceRange()), |
13499 | SemaRef, OCD_AllCandidates, Args); |
13500 | |
13501 | // We emitted an error for the unavailable/deleted function call but keep |
13502 | // the call in the AST. |
13503 | FunctionDecl *FDecl = (*Best)->Function; |
13504 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
13505 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, |
13506 | ExecConfig, /*IsExecConfig=*/false, |
13507 | (*Best)->IsADLCandidate); |
13508 | } |
13509 | } |
13510 | |
13511 | // Overload resolution failed, try to recover. |
13512 | SmallVector<Expr *, 8> SubExprs = {Fn}; |
13513 | SubExprs.append(Args.begin(), Args.end()); |
13514 | return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, |
13515 | chooseRecoveryType(*CandidateSet, Best)); |
13516 | } |
13517 | |
13518 | static void markUnaddressableCandidatesUnviable(Sema &S, |
13519 | OverloadCandidateSet &CS) { |
13520 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { |
13521 | if (I->Viable && |
13522 | !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { |
13523 | I->Viable = false; |
13524 | I->FailureKind = ovl_fail_addr_not_available; |
13525 | } |
13526 | } |
13527 | } |
13528 | |
13529 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn |
13530 | /// (which eventually refers to the declaration Func) and the call |
13531 | /// arguments Args/NumArgs, attempt to resolve the function call down |
13532 | /// to a specific function. If overload resolution succeeds, returns |
13533 | /// the call expression produced by overload resolution. |
13534 | /// Otherwise, emits diagnostics and returns ExprError. |
13535 | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
13536 | UnresolvedLookupExpr *ULE, |
13537 | SourceLocation LParenLoc, |
13538 | MultiExprArg Args, |
13539 | SourceLocation RParenLoc, |
13540 | Expr *ExecConfig, |
13541 | bool AllowTypoCorrection, |
13542 | bool CalleesAddressIsTaken) { |
13543 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), |
13544 | OverloadCandidateSet::CSK_Normal); |
13545 | ExprResult result; |
13546 | |
13547 | if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, |
13548 | &result)) |
13549 | return result; |
13550 | |
13551 | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that |
13552 | // functions that aren't addressible are considered unviable. |
13553 | if (CalleesAddressIsTaken) |
13554 | markUnaddressableCandidatesUnviable(*this, CandidateSet); |
13555 | |
13556 | OverloadCandidateSet::iterator Best; |
13557 | OverloadingResult OverloadResult = |
13558 | CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); |
13559 | |
13560 | return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, |
13561 | ExecConfig, &CandidateSet, &Best, |
13562 | OverloadResult, AllowTypoCorrection); |
13563 | } |
13564 | |
13565 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { |
13566 | return Functions.size() > 1 || |
13567 | (Functions.size() == 1 && |
13568 | isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); |
13569 | } |
13570 | |
13571 | ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, |
13572 | NestedNameSpecifierLoc NNSLoc, |
13573 | DeclarationNameInfo DNI, |
13574 | const UnresolvedSetImpl &Fns, |
13575 | bool PerformADL) { |
13576 | return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, |
13577 | PerformADL, IsOverloaded(Fns), |
13578 | Fns.begin(), Fns.end()); |
13579 | } |
13580 | |
13581 | /// Create a unary operation that may resolve to an overloaded |
13582 | /// operator. |
13583 | /// |
13584 | /// \param OpLoc The location of the operator itself (e.g., '*'). |
13585 | /// |
13586 | /// \param Opc The UnaryOperatorKind that describes this operator. |
13587 | /// |
13588 | /// \param Fns The set of non-member functions that will be |
13589 | /// considered by overload resolution. The caller needs to build this |
13590 | /// set based on the context using, e.g., |
13591 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
13592 | /// set should not contain any member functions; those will be added |
13593 | /// by CreateOverloadedUnaryOp(). |
13594 | /// |
13595 | /// \param Input The input argument. |
13596 | ExprResult |
13597 | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
13598 | const UnresolvedSetImpl &Fns, |
13599 | Expr *Input, bool PerformADL) { |
13600 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); |
13601 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast <bool> (Op != OO_None && "Invalid opcode for overloaded unary operator" ) ? void (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\"" , "clang/lib/Sema/SemaOverload.cpp", 13601, __extension__ __PRETTY_FUNCTION__ )); |
13602 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
13603 | // TODO: provide better source location info. |
13604 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
13605 | |
13606 | if (checkPlaceholderForOverload(*this, Input)) |
13607 | return ExprError(); |
13608 | |
13609 | Expr *Args[2] = { Input, nullptr }; |
13610 | unsigned NumArgs = 1; |
13611 | |
13612 | // For post-increment and post-decrement, add the implicit '0' as |
13613 | // the second argument, so that we know this is a post-increment or |
13614 | // post-decrement. |
13615 | if (Opc == UO_PostInc || Opc == UO_PostDec) { |
13616 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
13617 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, |
13618 | SourceLocation()); |
13619 | NumArgs = 2; |
13620 | } |
13621 | |
13622 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); |
13623 | |
13624 | if (Input->isTypeDependent()) { |
13625 | if (Fns.empty()) |
13626 | return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, |
13627 | VK_PRValue, OK_Ordinary, OpLoc, false, |
13628 | CurFPFeatureOverrides()); |
13629 | |
13630 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
13631 | ExprResult Fn = CreateUnresolvedLookupExpr( |
13632 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); |
13633 | if (Fn.isInvalid()) |
13634 | return ExprError(); |
13635 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, |
13636 | Context.DependentTy, VK_PRValue, OpLoc, |
13637 | CurFPFeatureOverrides()); |
13638 | } |
13639 | |
13640 | // Build an empty overload set. |
13641 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); |
13642 | |
13643 | // Add the candidates from the given function set. |
13644 | AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); |
13645 | |
13646 | // Add operator candidates that are member functions. |
13647 | AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
13648 | |
13649 | // Add candidates from ADL. |
13650 | if (PerformADL) { |
13651 | AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, |
13652 | /*ExplicitTemplateArgs*/nullptr, |
13653 | CandidateSet); |
13654 | } |
13655 | |
13656 | // Add builtin operator candidates. |
13657 | AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
13658 | |
13659 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
13660 | |
13661 | // Perform overload resolution. |
13662 | OverloadCandidateSet::iterator Best; |
13663 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
13664 | case OR_Success: { |
13665 | // We found a built-in operator or an overloaded operator. |
13666 | FunctionDecl *FnDecl = Best->Function; |
13667 | |
13668 | if (FnDecl) { |
13669 | Expr *Base = nullptr; |
13670 | // We matched an overloaded operator. Build a call to that |
13671 | // operator. |
13672 | |
13673 | // Convert the arguments. |
13674 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
13675 | CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); |
13676 | |
13677 | ExprResult InputRes = |
13678 | PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, |
13679 | Best->FoundDecl, Method); |
13680 | if (InputRes.isInvalid()) |
13681 | return ExprError(); |
13682 | Base = Input = InputRes.get(); |
13683 | } else { |
13684 | // Convert the arguments. |
13685 | ExprResult InputInit |
13686 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( |
13687 | Context, |
13688 | FnDecl->getParamDecl(0)), |
13689 | SourceLocation(), |
13690 | Input); |
13691 | if (InputInit.isInvalid()) |
13692 | return ExprError(); |
13693 | Input = InputInit.get(); |
13694 | } |
13695 | |
13696 | // Build the actual expression node. |
13697 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, |
13698 | Base, HadMultipleCandidates, |
13699 | OpLoc); |
13700 | if (FnExpr.isInvalid()) |
13701 | return ExprError(); |
13702 | |
13703 | // Determine the result type. |
13704 | QualType ResultTy = FnDecl->getReturnType(); |
13705 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
13706 | ResultTy = ResultTy.getNonLValueExprType(Context); |
13707 | |
13708 | Args[0] = Input; |
13709 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
13710 | Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, |
13711 | CurFPFeatureOverrides(), Best->IsADLCandidate); |
13712 | |
13713 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) |
13714 | return ExprError(); |
13715 | |
13716 | if (CheckFunctionCall(FnDecl, TheCall, |
13717 | FnDecl->getType()->castAs<FunctionProtoType>())) |
13718 | return ExprError(); |
13719 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); |
13720 | } else { |
13721 | // We matched a built-in operator. Convert the arguments, then |
13722 | // break out so that we will build the appropriate built-in |
13723 | // operator node. |
13724 | ExprResult InputRes = PerformImplicitConversion( |
13725 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, |
13726 | CCK_ForBuiltinOverloadedOp); |
13727 | if (InputRes.isInvalid()) |
13728 | return ExprError(); |
13729 | Input = InputRes.get(); |
13730 | break; |
13731 | } |
13732 | } |
13733 | |
13734 | case OR_No_Viable_Function: |
13735 | // This is an erroneous use of an operator which can be overloaded by |
13736 | // a non-member function. Check for non-member operators which were |
13737 | // defined too late to be candidates. |
13738 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) |
13739 | // FIXME: Recover by calling the found function. |
13740 | return ExprError(); |
13741 | |
13742 | // No viable function; fall through to handling this as a |
13743 | // built-in operator, which will produce an error message for us. |
13744 | break; |
13745 | |
13746 | case OR_Ambiguous: |
13747 | CandidateSet.NoteCandidates( |
13748 | PartialDiagnosticAt(OpLoc, |
13749 | PDiag(diag::err_ovl_ambiguous_oper_unary) |
13750 | << UnaryOperator::getOpcodeStr(Opc) |
13751 | << Input->getType() << Input->getSourceRange()), |
13752 | *this, OCD_AmbiguousCandidates, ArgsArray, |
13753 | UnaryOperator::getOpcodeStr(Opc), OpLoc); |
13754 | return ExprError(); |
13755 | |
13756 | case OR_Deleted: |
13757 | CandidateSet.NoteCandidates( |
13758 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
13759 | << UnaryOperator::getOpcodeStr(Opc) |
13760 | << Input->getSourceRange()), |
13761 | *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), |
13762 | OpLoc); |
13763 | return ExprError(); |
13764 | } |
13765 | |
13766 | // Either we found no viable overloaded operator or we matched a |
13767 | // built-in operator. In either case, fall through to trying to |
13768 | // build a built-in operation. |
13769 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
13770 | } |
13771 | |
13772 | /// Perform lookup for an overloaded binary operator. |
13773 | void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, |
13774 | OverloadedOperatorKind Op, |
13775 | const UnresolvedSetImpl &Fns, |
13776 | ArrayRef<Expr *> Args, bool PerformADL) { |
13777 | SourceLocation OpLoc = CandidateSet.getLocation(); |
13778 | |
13779 | OverloadedOperatorKind ExtraOp = |
13780 | CandidateSet.getRewriteInfo().AllowRewrittenCandidates |
13781 | ? getRewrittenOverloadedOperator(Op) |
13782 | : OO_None; |
13783 | |
13784 | // Add the candidates from the given function set. This also adds the |
13785 | // rewritten candidates using these functions if necessary. |
13786 | AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); |
13787 | |
13788 | // Add operator candidates that are member functions. |
13789 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
13790 | if (CandidateSet.getRewriteInfo().allowsReversed(Op)) |
13791 | AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, |
13792 | OverloadCandidateParamOrder::Reversed); |
13793 | |
13794 | // In C++20, also add any rewritten member candidates. |
13795 | if (ExtraOp) { |
13796 | AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); |
13797 | if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) |
13798 | AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, |
13799 | CandidateSet, |
13800 | OverloadCandidateParamOrder::Reversed); |
13801 | } |
13802 | |
13803 | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not |
13804 | // performed for an assignment operator (nor for operator[] nor operator->, |
13805 | // which don't get here). |
13806 | if (Op != OO_Equal && PerformADL) { |
13807 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
13808 | AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, |
13809 | /*ExplicitTemplateArgs*/ nullptr, |
13810 | CandidateSet); |
13811 | if (ExtraOp) { |
13812 | DeclarationName ExtraOpName = |
13813 | Context.DeclarationNames.getCXXOperatorName(ExtraOp); |
13814 | AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, |
13815 | /*ExplicitTemplateArgs*/ nullptr, |
13816 | CandidateSet); |
13817 | } |
13818 | } |
13819 | |
13820 | // Add builtin operator candidates. |
13821 | // |
13822 | // FIXME: We don't add any rewritten candidates here. This is strictly |
13823 | // incorrect; a builtin candidate could be hidden by a non-viable candidate, |
13824 | // resulting in our selecting a rewritten builtin candidate. For example: |
13825 | // |
13826 | // enum class E { e }; |
13827 | // bool operator!=(E, E) requires false; |
13828 | // bool k = E::e != E::e; |
13829 | // |
13830 | // ... should select the rewritten builtin candidate 'operator==(E, E)'. But |
13831 | // it seems unreasonable to consider rewritten builtin candidates. A core |
13832 | // issue has been filed proposing to removed this requirement. |
13833 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
13834 | } |
13835 | |
13836 | /// Create a binary operation that may resolve to an overloaded |
13837 | /// operator. |
13838 | /// |
13839 | /// \param OpLoc The location of the operator itself (e.g., '+'). |
13840 | /// |
13841 | /// \param Opc The BinaryOperatorKind that describes this operator. |
13842 | /// |
13843 | /// \param Fns The set of non-member functions that will be |
13844 | /// considered by overload resolution. The caller needs to build this |
13845 | /// set based on the context using, e.g., |
13846 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
13847 | /// set should not contain any member functions; those will be added |
13848 | /// by CreateOverloadedBinOp(). |
13849 | /// |
13850 | /// \param LHS Left-hand argument. |
13851 | /// \param RHS Right-hand argument. |
13852 | /// \param PerformADL Whether to consider operator candidates found by ADL. |
13853 | /// \param AllowRewrittenCandidates Whether to consider candidates found by |
13854 | /// C++20 operator rewrites. |
13855 | /// \param DefaultedFn If we are synthesizing a defaulted operator function, |
13856 | /// the function in question. Such a function is never a candidate in |
13857 | /// our overload resolution. This also enables synthesizing a three-way |
13858 | /// comparison from < and == as described in C++20 [class.spaceship]p1. |
13859 | ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, |
13860 | BinaryOperatorKind Opc, |
13861 | const UnresolvedSetImpl &Fns, Expr *LHS, |
13862 | Expr *RHS, bool PerformADL, |
13863 | bool AllowRewrittenCandidates, |
13864 | FunctionDecl *DefaultedFn) { |
13865 | Expr *Args[2] = { LHS, RHS }; |
13866 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple |
13867 | |
13868 | if (!getLangOpts().CPlusPlus20) |
13869 | AllowRewrittenCandidates = false; |
13870 | |
13871 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); |
13872 | |
13873 | // If either side is type-dependent, create an appropriate dependent |
13874 | // expression. |
13875 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { |
13876 | if (Fns.empty()) { |
13877 | // If there are no functions to store, just build a dependent |
13878 | // BinaryOperator or CompoundAssignment. |
13879 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
13880 | return CompoundAssignOperator::Create( |
13881 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, |
13882 | OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, |
13883 | Context.DependentTy); |
13884 | return BinaryOperator::Create( |
13885 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, |
13886 | OK_Ordinary, OpLoc, CurFPFeatureOverrides()); |
13887 | } |
13888 | |
13889 | // FIXME: save results of ADL from here? |
13890 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
13891 | // TODO: provide better source location info in DNLoc component. |
13892 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
13893 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
13894 | ExprResult Fn = CreateUnresolvedLookupExpr( |
13895 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); |
13896 | if (Fn.isInvalid()) |
13897 | return ExprError(); |
13898 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, |
13899 | Context.DependentTy, VK_PRValue, OpLoc, |
13900 | CurFPFeatureOverrides()); |
13901 | } |
13902 | |
13903 | // Always do placeholder-like conversions on the RHS. |
13904 | if (checkPlaceholderForOverload(*this, Args[1])) |
13905 | return ExprError(); |
13906 | |
13907 | // Do placeholder-like conversion on the LHS; note that we should |
13908 | // not get here with a PseudoObject LHS. |
13909 | assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (Args[0]->getObjectKind() != OK_ObjCProperty ) ? void (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty" , "clang/lib/Sema/SemaOverload.cpp", 13909, __extension__ __PRETTY_FUNCTION__ )); |
13910 | if (checkPlaceholderForOverload(*this, Args[0])) |
13911 | return ExprError(); |
13912 | |
13913 | // If this is the assignment operator, we only perform overload resolution |
13914 | // if the left-hand side is a class or enumeration type. This is actually |
13915 | // a hack. The standard requires that we do overload resolution between the |
13916 | // various built-in candidates, but as DR507 points out, this can lead to |
13917 | // problems. So we do it this way, which pretty much follows what GCC does. |
13918 | // Note that we go the traditional code path for compound assignment forms. |
13919 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) |
13920 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
13921 | |
13922 | // If this is the .* operator, which is not overloadable, just |
13923 | // create a built-in binary operator. |
13924 | if (Opc == BO_PtrMemD) |
13925 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
13926 | |
13927 | // Build the overload set. |
13928 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, |
13929 | OverloadCandidateSet::OperatorRewriteInfo( |
13930 | Op, OpLoc, AllowRewrittenCandidates)); |
13931 | if (DefaultedFn) |
13932 | CandidateSet.exclude(DefaultedFn); |
13933 | LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); |
13934 | |
13935 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
13936 | |
13937 | // Perform overload resolution. |
13938 | OverloadCandidateSet::iterator Best; |
13939 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
13940 | case OR_Success: { |
13941 | // We found a built-in operator or an overloaded operator. |
13942 | FunctionDecl *FnDecl = Best->Function; |
13943 | |
13944 | bool IsReversed = Best->isReversed(); |
13945 | if (IsReversed) |
13946 | std::swap(Args[0], Args[1]); |
13947 | |
13948 | if (FnDecl) { |
13949 | Expr *Base = nullptr; |
13950 | // We matched an overloaded operator. Build a call to that |
13951 | // operator. |
13952 | |
13953 | OverloadedOperatorKind ChosenOp = |
13954 | FnDecl->getDeclName().getCXXOverloadedOperator(); |
13955 | |
13956 | // C++2a [over.match.oper]p9: |
13957 | // If a rewritten operator== candidate is selected by overload |
13958 | // resolution for an operator@, its return type shall be cv bool |
13959 | if (Best->RewriteKind && ChosenOp == OO_EqualEqual && |
13960 | !FnDecl->getReturnType()->isBooleanType()) { |
13961 | bool IsExtension = |
13962 | FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); |
13963 | Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool |
13964 | : diag::err_ovl_rewrite_equalequal_not_bool) |
13965 | << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) |
13966 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
13967 | Diag(FnDecl->getLocation(), diag::note_declared_at); |
13968 | if (!IsExtension) |
13969 | return ExprError(); |
13970 | } |
13971 | |
13972 | if (AllowRewrittenCandidates && !IsReversed && |
13973 | CandidateSet.getRewriteInfo().isReversible()) { |
13974 | // We could have reversed this operator, but didn't. Check if some |
13975 | // reversed form was a viable candidate, and if so, if it had a |
13976 | // better conversion for either parameter. If so, this call is |
13977 | // formally ambiguous, and allowing it is an extension. |
13978 | llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; |
13979 | for (OverloadCandidate &Cand : CandidateSet) { |
13980 | if (Cand.Viable && Cand.Function && Cand.isReversed() && |
13981 | haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { |
13982 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
13983 | if (CompareImplicitConversionSequences( |
13984 | *this, OpLoc, Cand.Conversions[ArgIdx], |
13985 | Best->Conversions[ArgIdx]) == |
13986 | ImplicitConversionSequence::Better) { |
13987 | AmbiguousWith.push_back(Cand.Function); |
13988 | break; |
13989 | } |
13990 | } |
13991 | } |
13992 | } |
13993 | |
13994 | if (!AmbiguousWith.empty()) { |
13995 | bool AmbiguousWithSelf = |
13996 | AmbiguousWith.size() == 1 && |
13997 | declaresSameEntity(AmbiguousWith.front(), FnDecl); |
13998 | Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) |
13999 | << BinaryOperator::getOpcodeStr(Opc) |
14000 | << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf |
14001 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14002 | if (AmbiguousWithSelf) { |
14003 | Diag(FnDecl->getLocation(), |
14004 | diag::note_ovl_ambiguous_oper_binary_reversed_self); |
14005 | // Mark member== const or provide matching != to disallow reversed |
14006 | // args. Eg. |
14007 | // struct S { bool operator==(const S&); }; |
14008 | // S()==S(); |
14009 | if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) |
14010 | if (Op == OverloadedOperatorKind::OO_EqualEqual && |
14011 | !MD->isConst() && |
14012 | Context.hasSameUnqualifiedType( |
14013 | MD->getThisObjectType(), |
14014 | MD->getParamDecl(0)->getType().getNonReferenceType()) && |
14015 | Context.hasSameUnqualifiedType(MD->getThisObjectType(), |
14016 | Args[0]->getType()) && |
14017 | Context.hasSameUnqualifiedType(MD->getThisObjectType(), |
14018 | Args[1]->getType())) |
14019 | Diag(FnDecl->getLocation(), |
14020 | diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); |
14021 | } else { |
14022 | Diag(FnDecl->getLocation(), |
14023 | diag::note_ovl_ambiguous_oper_binary_selected_candidate); |
14024 | for (auto *F : AmbiguousWith) |
14025 | Diag(F->getLocation(), |
14026 | diag::note_ovl_ambiguous_oper_binary_reversed_candidate); |
14027 | } |
14028 | } |
14029 | } |
14030 | |
14031 | // Convert the arguments. |
14032 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
14033 | // Best->Access is only meaningful for class members. |
14034 | CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); |
14035 | |
14036 | ExprResult Arg1 = |
14037 | PerformCopyInitialization( |
14038 | InitializedEntity::InitializeParameter(Context, |
14039 | FnDecl->getParamDecl(0)), |
14040 | SourceLocation(), Args[1]); |
14041 | if (Arg1.isInvalid()) |
14042 | return ExprError(); |
14043 | |
14044 | ExprResult Arg0 = |
14045 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, |
14046 | Best->FoundDecl, Method); |
14047 | if (Arg0.isInvalid()) |
14048 | return ExprError(); |
14049 | Base = Args[0] = Arg0.getAs<Expr>(); |
14050 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14051 | } else { |
14052 | // Convert the arguments. |
14053 | ExprResult Arg0 = PerformCopyInitialization( |
14054 | InitializedEntity::InitializeParameter(Context, |
14055 | FnDecl->getParamDecl(0)), |
14056 | SourceLocation(), Args[0]); |
14057 | if (Arg0.isInvalid()) |
14058 | return ExprError(); |
14059 | |
14060 | ExprResult Arg1 = |
14061 | PerformCopyInitialization( |
14062 | InitializedEntity::InitializeParameter(Context, |
14063 | FnDecl->getParamDecl(1)), |
14064 | SourceLocation(), Args[1]); |
14065 | if (Arg1.isInvalid()) |
14066 | return ExprError(); |
14067 | Args[0] = LHS = Arg0.getAs<Expr>(); |
Although the value stored to 'LHS' is used in the enclosing expression, the value is never actually read from 'LHS' | |
14068 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14069 | } |
14070 | |
14071 | // Build the actual expression node. |
14072 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, |
14073 | Best->FoundDecl, Base, |
14074 | HadMultipleCandidates, OpLoc); |
14075 | if (FnExpr.isInvalid()) |
14076 | return ExprError(); |
14077 | |
14078 | // Determine the result type. |
14079 | QualType ResultTy = FnDecl->getReturnType(); |
14080 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
14081 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14082 | |
14083 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( |
14084 | Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, |
14085 | CurFPFeatureOverrides(), Best->IsADLCandidate); |
14086 | |
14087 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, |
14088 | FnDecl)) |
14089 | return ExprError(); |
14090 | |
14091 | ArrayRef<const Expr *> ArgsArray(Args, 2); |
14092 | const Expr *ImplicitThis = nullptr; |
14093 | // Cut off the implicit 'this'. |
14094 | if (isa<CXXMethodDecl>(FnDecl)) { |
14095 | ImplicitThis = ArgsArray[0]; |
14096 | ArgsArray = ArgsArray.slice(1); |
14097 | } |
14098 | |
14099 | // Check for a self move. |
14100 | if (Op == OO_Equal) |
14101 | DiagnoseSelfMove(Args[0], Args[1], OpLoc); |
14102 | |
14103 | if (ImplicitThis) { |
14104 | QualType ThisType = Context.getPointerType(ImplicitThis->getType()); |
14105 | QualType ThisTypeFromDecl = Context.getPointerType( |
14106 | cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); |
14107 | |
14108 | CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, |
14109 | ThisTypeFromDecl); |
14110 | } |
14111 | |
14112 | checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, |
14113 | isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), |
14114 | VariadicDoesNotApply); |
14115 | |
14116 | ExprResult R = MaybeBindToTemporary(TheCall); |
14117 | if (R.isInvalid()) |
14118 | return ExprError(); |
14119 | |
14120 | R = CheckForImmediateInvocation(R, FnDecl); |
14121 | if (R.isInvalid()) |
14122 | return ExprError(); |
14123 | |
14124 | // For a rewritten candidate, we've already reversed the arguments |
14125 | // if needed. Perform the rest of the rewrite now. |
14126 | if ((Best->RewriteKind & CRK_DifferentOperator) || |
14127 | (Op == OO_Spaceship && IsReversed)) { |
14128 | if (Op == OO_ExclaimEqual) { |
14129 | assert(ChosenOp == OO_EqualEqual && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_EqualEqual && "unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 14129, __extension__ __PRETTY_FUNCTION__ )); |
14130 | R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); |
14131 | } else { |
14132 | assert(ChosenOp == OO_Spaceship && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_Spaceship && "unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 14132, __extension__ __PRETTY_FUNCTION__ )); |
14133 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
14134 | Expr *ZeroLiteral = |
14135 | IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); |
14136 | |
14137 | Sema::CodeSynthesisContext Ctx; |
14138 | Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; |
14139 | Ctx.Entity = FnDecl; |
14140 | pushCodeSynthesisContext(Ctx); |
14141 | |
14142 | R = CreateOverloadedBinOp( |
14143 | OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), |
14144 | IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, |
14145 | /*AllowRewrittenCandidates=*/false); |
14146 | |
14147 | popCodeSynthesisContext(); |
14148 | } |
14149 | if (R.isInvalid()) |
14150 | return ExprError(); |
14151 | } else { |
14152 | assert(ChosenOp == Op && "unexpected operator name")(static_cast <bool> (ChosenOp == Op && "unexpected operator name" ) ? void (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 14152, __extension__ __PRETTY_FUNCTION__ )); |
14153 | } |
14154 | |
14155 | // Make a note in the AST if we did any rewriting. |
14156 | if (Best->RewriteKind != CRK_None) |
14157 | R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); |
14158 | |
14159 | return R; |
14160 | } else { |
14161 | // We matched a built-in operator. Convert the arguments, then |
14162 | // break out so that we will build the appropriate built-in |
14163 | // operator node. |
14164 | ExprResult ArgsRes0 = PerformImplicitConversion( |
14165 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
14166 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14167 | if (ArgsRes0.isInvalid()) |
14168 | return ExprError(); |
14169 | Args[0] = ArgsRes0.get(); |
14170 | |
14171 | ExprResult ArgsRes1 = PerformImplicitConversion( |
14172 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
14173 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14174 | if (ArgsRes1.isInvalid()) |
14175 | return ExprError(); |
14176 | Args[1] = ArgsRes1.get(); |
14177 | break; |
14178 | } |
14179 | } |
14180 | |
14181 | case OR_No_Viable_Function: { |
14182 | // C++ [over.match.oper]p9: |
14183 | // If the operator is the operator , [...] and there are no |
14184 | // viable functions, then the operator is assumed to be the |
14185 | // built-in operator and interpreted according to clause 5. |
14186 | if (Opc == BO_Comma) |
14187 | break; |
14188 | |
14189 | // When defaulting an 'operator<=>', we can try to synthesize a three-way |
14190 | // compare result using '==' and '<'. |
14191 | if (DefaultedFn && Opc == BO_Cmp) { |
14192 | ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], |
14193 | Args[1], DefaultedFn); |
14194 | if (E.isInvalid() || E.isUsable()) |
14195 | return E; |
14196 | } |
14197 | |
14198 | // For class as left operand for assignment or compound assignment |
14199 | // operator do not fall through to handling in built-in, but report that |
14200 | // no overloaded assignment operator found |
14201 | ExprResult Result = ExprError(); |
14202 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); |
14203 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, |
14204 | Args, OpLoc); |
14205 | DeferDiagsRAII DDR(*this, |
14206 | CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); |
14207 | if (Args[0]->getType()->isRecordType() && |
14208 | Opc >= BO_Assign && Opc <= BO_OrAssign) { |
14209 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
14210 | << BinaryOperator::getOpcodeStr(Opc) |
14211 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14212 | if (Args[0]->getType()->isIncompleteType()) { |
14213 | Diag(OpLoc, diag::note_assign_lhs_incomplete) |
14214 | << Args[0]->getType() |
14215 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14216 | } |
14217 | } else { |
14218 | // This is an erroneous use of an operator which can be overloaded by |
14219 | // a non-member function. Check for non-member operators which were |
14220 | // defined too late to be candidates. |
14221 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) |
14222 | // FIXME: Recover by calling the found function. |
14223 | return ExprError(); |
14224 | |
14225 | // No viable function; try to create a built-in operation, which will |
14226 | // produce an error. Then, show the non-viable candidates. |
14227 | Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14228 | } |
14229 | assert(Result.isInvalid() &&(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "clang/lib/Sema/SemaOverload.cpp", 14230, __extension__ __PRETTY_FUNCTION__ )) |
14230 | "C++ binary operator overloading is missing candidates!")(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "clang/lib/Sema/SemaOverload.cpp", 14230, __extension__ __PRETTY_FUNCTION__ )); |
14231 | CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); |
14232 | return Result; |
14233 | } |
14234 | |
14235 | case OR_Ambiguous: |
14236 | CandidateSet.NoteCandidates( |
14237 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
14238 | << BinaryOperator::getOpcodeStr(Opc) |
14239 | << Args[0]->getType() |
14240 | << Args[1]->getType() |
14241 | << Args[0]->getSourceRange() |
14242 | << Args[1]->getSourceRange()), |
14243 | *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14244 | OpLoc); |
14245 | return ExprError(); |
14246 | |
14247 | case OR_Deleted: |
14248 | if (isImplicitlyDeleted(Best->Function)) { |
14249 | FunctionDecl *DeletedFD = Best->Function; |
14250 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); |
14251 | if (DFK.isSpecialMember()) { |
14252 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) |
14253 | << Args[0]->getType() << DFK.asSpecialMember(); |
14254 | } else { |
14255 | assert(DFK.isComparison())(static_cast <bool> (DFK.isComparison()) ? void (0) : __assert_fail ("DFK.isComparison()", "clang/lib/Sema/SemaOverload.cpp", 14255 , __extension__ __PRETTY_FUNCTION__)); |
14256 | Diag(OpLoc, diag::err_ovl_deleted_comparison) |
14257 | << Args[0]->getType() << DeletedFD; |
14258 | } |
14259 | |
14260 | // The user probably meant to call this special member. Just |
14261 | // explain why it's deleted. |
14262 | NoteDeletedFunction(DeletedFD); |
14263 | return ExprError(); |
14264 | } |
14265 | CandidateSet.NoteCandidates( |
14266 | PartialDiagnosticAt( |
14267 | OpLoc, PDiag(diag::err_ovl_deleted_oper) |
14268 | << getOperatorSpelling(Best->Function->getDeclName() |
14269 | .getCXXOverloadedOperator()) |
14270 | << Args[0]->getSourceRange() |
14271 | << Args[1]->getSourceRange()), |
14272 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14273 | OpLoc); |
14274 | return ExprError(); |
14275 | } |
14276 | |
14277 | // We matched a built-in operator; build it. |
14278 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14279 | } |
14280 | |
14281 | ExprResult Sema::BuildSynthesizedThreeWayComparison( |
14282 | SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, |
14283 | FunctionDecl *DefaultedFn) { |
14284 | const ComparisonCategoryInfo *Info = |
14285 | Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); |
14286 | // If we're not producing a known comparison category type, we can't |
14287 | // synthesize a three-way comparison. Let the caller diagnose this. |
14288 | if (!Info) |
14289 | return ExprResult((Expr*)nullptr); |
14290 | |
14291 | // If we ever want to perform this synthesis more generally, we will need to |
14292 | // apply the temporary materialization conversion to the operands. |
14293 | assert(LHS->isGLValue() && RHS->isGLValue() &&(static_cast <bool> (LHS->isGLValue() && RHS ->isGLValue() && "cannot use prvalue expressions more than once" ) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\"" , "clang/lib/Sema/SemaOverload.cpp", 14294, __extension__ __PRETTY_FUNCTION__ )) |
14294 | "cannot use prvalue expressions more than once")(static_cast <bool> (LHS->isGLValue() && RHS ->isGLValue() && "cannot use prvalue expressions more than once" ) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\"" , "clang/lib/Sema/SemaOverload.cpp", 14294, __extension__ __PRETTY_FUNCTION__ )); |
14295 | Expr *OrigLHS = LHS; |
14296 | Expr *OrigRHS = RHS; |
14297 | |
14298 | // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to |
14299 | // each of them multiple times below. |
14300 | LHS = new (Context) |
14301 | OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), |
14302 | LHS->getObjectKind(), LHS); |
14303 | RHS = new (Context) |
14304 | OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), |
14305 | RHS->getObjectKind(), RHS); |
14306 | |
14307 | ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, |
14308 | DefaultedFn); |
14309 | if (Eq.isInvalid()) |
14310 | return ExprError(); |
14311 | |
14312 | ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, |
14313 | true, DefaultedFn); |
14314 | if (Less.isInvalid()) |
14315 | return ExprError(); |
14316 | |
14317 | ExprResult Greater; |
14318 | if (Info->isPartial()) { |
14319 | Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, |
14320 | DefaultedFn); |
14321 | if (Greater.isInvalid()) |
14322 | return ExprError(); |
14323 | } |
14324 | |
14325 | // Form the list of comparisons we're going to perform. |
14326 | struct Comparison { |
14327 | ExprResult Cmp; |
14328 | ComparisonCategoryResult Result; |
14329 | } Comparisons[4] = |
14330 | { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal |
14331 | : ComparisonCategoryResult::Equivalent}, |
14332 | {Less, ComparisonCategoryResult::Less}, |
14333 | {Greater, ComparisonCategoryResult::Greater}, |
14334 | {ExprResult(), ComparisonCategoryResult::Unordered}, |
14335 | }; |
14336 | |
14337 | int I = Info->isPartial() ? 3 : 2; |
14338 | |
14339 | // Combine the comparisons with suitable conditional expressions. |
14340 | ExprResult Result; |
14341 | for (; I >= 0; --I) { |
14342 | // Build a reference to the comparison category constant. |
14343 | auto *VI = Info->lookupValueInfo(Comparisons[I].Result); |
14344 | // FIXME: Missing a constant for a comparison category. Diagnose this? |
14345 | if (!VI) |
14346 | return ExprResult((Expr*)nullptr); |
14347 | ExprResult ThisResult = |
14348 | BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); |
14349 | if (ThisResult.isInvalid()) |
14350 | return ExprError(); |
14351 | |
14352 | // Build a conditional unless this is the final case. |
14353 | if (Result.get()) { |
14354 | Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), |
14355 | ThisResult.get(), Result.get()); |
14356 | if (Result.isInvalid()) |
14357 | return ExprError(); |
14358 | } else { |
14359 | Result = ThisResult; |
14360 | } |
14361 | } |
14362 | |
14363 | // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to |
14364 | // bind the OpaqueValueExprs before they're (repeatedly) used. |
14365 | Expr *SyntacticForm = BinaryOperator::Create( |
14366 | Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), |
14367 | Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, |
14368 | CurFPFeatureOverrides()); |
14369 | Expr *SemanticForm[] = {LHS, RHS, Result.get()}; |
14370 | return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); |
14371 | } |
14372 | |
14373 | static bool PrepareArgumentsForCallToObjectOfClassType( |
14374 | Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, |
14375 | MultiExprArg Args, SourceLocation LParenLoc) { |
14376 | |
14377 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
14378 | unsigned NumParams = Proto->getNumParams(); |
14379 | unsigned NumArgsSlots = |
14380 | MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); |
14381 | // Build the full argument list for the method call (the implicit object |
14382 | // parameter is placed at the beginning of the list). |
14383 | MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); |
14384 | bool IsError = false; |
14385 | // Initialize the implicit object parameter. |
14386 | // Check the argument types. |
14387 | for (unsigned i = 0; i != NumParams; i++) { |
14388 | Expr *Arg; |
14389 | if (i < Args.size()) { |
14390 | Arg = Args[i]; |
14391 | ExprResult InputInit = |
14392 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
14393 | S.Context, Method->getParamDecl(i)), |
14394 | SourceLocation(), Arg); |
14395 | IsError |= InputInit.isInvalid(); |
14396 | Arg = InputInit.getAs<Expr>(); |
14397 | } else { |
14398 | ExprResult DefArg = |
14399 | S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); |
14400 | if (DefArg.isInvalid()) { |
14401 | IsError = true; |
14402 | break; |
14403 | } |
14404 | Arg = DefArg.getAs<Expr>(); |
14405 | } |
14406 | |
14407 | MethodArgs.push_back(Arg); |
14408 | } |
14409 | return IsError; |
14410 | } |
14411 | |
14412 | ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
14413 | SourceLocation RLoc, |
14414 | Expr *Base, |
14415 | MultiExprArg ArgExpr) { |
14416 | SmallVector<Expr *, 2> Args; |
14417 | Args.push_back(Base); |
14418 | for (auto *e : ArgExpr) { |
14419 | Args.push_back(e); |
14420 | } |
14421 | DeclarationName OpName = |
14422 | Context.DeclarationNames.getCXXOperatorName(OO_Subscript); |
14423 | |
14424 | SourceRange Range = ArgExpr.empty() |
14425 | ? SourceRange{} |
14426 | : SourceRange(ArgExpr.front()->getBeginLoc(), |
14427 | ArgExpr.back()->getEndLoc()); |
14428 | |
14429 | // If either side is type-dependent, create an appropriate dependent |
14430 | // expression. |
14431 | if (Expr::hasAnyTypeDependentArguments(Args)) { |
14432 | |
14433 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
14434 | // CHECKME: no 'operator' keyword? |
14435 | DeclarationNameInfo OpNameInfo(OpName, LLoc); |
14436 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
14437 | ExprResult Fn = CreateUnresolvedLookupExpr( |
14438 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); |
14439 | if (Fn.isInvalid()) |
14440 | return ExprError(); |
14441 | // Can't add any actual overloads yet |
14442 | |
14443 | return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, |
14444 | Context.DependentTy, VK_PRValue, RLoc, |
14445 | CurFPFeatureOverrides()); |
14446 | } |
14447 | |
14448 | // Handle placeholders |
14449 | UnbridgedCastsSet UnbridgedCasts; |
14450 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { |
14451 | return ExprError(); |
14452 | } |
14453 | // Build an empty overload set. |
14454 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); |
14455 | |
14456 | // Subscript can only be overloaded as a member function. |
14457 | |
14458 | // Add operator candidates that are member functions. |
14459 | AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
14460 | |
14461 | // Add builtin operator candidates. |
14462 | if (Args.size() == 2) |
14463 | AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
14464 | |
14465 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14466 | |
14467 | // Perform overload resolution. |
14468 | OverloadCandidateSet::iterator Best; |
14469 | switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { |
14470 | case OR_Success: { |
14471 | // We found a built-in operator or an overloaded operator. |
14472 | FunctionDecl *FnDecl = Best->Function; |
14473 | |
14474 | if (FnDecl) { |
14475 | // We matched an overloaded operator. Build a call to that |
14476 | // operator. |
14477 | |
14478 | CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); |
14479 | |
14480 | // Convert the arguments. |
14481 | CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); |
14482 | SmallVector<Expr *, 2> MethodArgs; |
14483 | |
14484 | // Handle 'this' parameter if the selected function is not static. |
14485 | if (Method->isInstance()) { |
14486 | ExprResult Arg0 = PerformObjectArgumentInitialization( |
14487 | Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
14488 | if (Arg0.isInvalid()) |
14489 | return ExprError(); |
14490 | |
14491 | MethodArgs.push_back(Arg0.get()); |
14492 | } |
14493 | |
14494 | bool IsError = PrepareArgumentsForCallToObjectOfClassType( |
14495 | *this, MethodArgs, Method, ArgExpr, LLoc); |
14496 | if (IsError) |
14497 | return ExprError(); |
14498 | |
14499 | // Build the actual expression node. |
14500 | DeclarationNameInfo OpLocInfo(OpName, LLoc); |
14501 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
14502 | ExprResult FnExpr = CreateFunctionRefExpr( |
14503 | *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, |
14504 | OpLocInfo.getLoc(), OpLocInfo.getInfo()); |
14505 | if (FnExpr.isInvalid()) |
14506 | return ExprError(); |
14507 | |
14508 | // Determine the result type |
14509 | QualType ResultTy = FnDecl->getReturnType(); |
14510 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
14511 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14512 | |
14513 | CallExpr *TheCall; |
14514 | if (Method->isInstance()) |
14515 | TheCall = CXXOperatorCallExpr::Create( |
14516 | Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, |
14517 | RLoc, CurFPFeatureOverrides()); |
14518 | else |
14519 | TheCall = |
14520 | CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK, |
14521 | RLoc, CurFPFeatureOverrides()); |
14522 | |
14523 | if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) |
14524 | return ExprError(); |
14525 | |
14526 | if (CheckFunctionCall(Method, TheCall, |
14527 | Method->getType()->castAs<FunctionProtoType>())) |
14528 | return ExprError(); |
14529 | |
14530 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), |
14531 | FnDecl); |
14532 | } else { |
14533 | // We matched a built-in operator. Convert the arguments, then |
14534 | // break out so that we will build the appropriate built-in |
14535 | // operator node. |
14536 | ExprResult ArgsRes0 = PerformImplicitConversion( |
14537 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
14538 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14539 | if (ArgsRes0.isInvalid()) |
14540 | return ExprError(); |
14541 | Args[0] = ArgsRes0.get(); |
14542 | |
14543 | ExprResult ArgsRes1 = PerformImplicitConversion( |
14544 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
14545 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14546 | if (ArgsRes1.isInvalid()) |
14547 | return ExprError(); |
14548 | Args[1] = ArgsRes1.get(); |
14549 | |
14550 | break; |
14551 | } |
14552 | } |
14553 | |
14554 | case OR_No_Viable_Function: { |
14555 | PartialDiagnostic PD = |
14556 | CandidateSet.empty() |
14557 | ? (PDiag(diag::err_ovl_no_oper) |
14558 | << Args[0]->getType() << /*subscript*/ 0 |
14559 | << Args[0]->getSourceRange() << Range) |
14560 | : (PDiag(diag::err_ovl_no_viable_subscript) |
14561 | << Args[0]->getType() << Args[0]->getSourceRange() << Range); |
14562 | CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, |
14563 | OCD_AllCandidates, ArgExpr, "[]", LLoc); |
14564 | return ExprError(); |
14565 | } |
14566 | |
14567 | case OR_Ambiguous: |
14568 | if (Args.size() == 2) { |
14569 | CandidateSet.NoteCandidates( |
14570 | PartialDiagnosticAt( |
14571 | LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
14572 | << "[]" << Args[0]->getType() << Args[1]->getType() |
14573 | << Args[0]->getSourceRange() << Range), |
14574 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); |
14575 | } else { |
14576 | CandidateSet.NoteCandidates( |
14577 | PartialDiagnosticAt(LLoc, |
14578 | PDiag(diag::err_ovl_ambiguous_subscript_call) |
14579 | << Args[0]->getType() |
14580 | << Args[0]->getSourceRange() << Range), |
14581 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); |
14582 | } |
14583 | return ExprError(); |
14584 | |
14585 | case OR_Deleted: |
14586 | CandidateSet.NoteCandidates( |
14587 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) |
14588 | << "[]" << Args[0]->getSourceRange() |
14589 | << Range), |
14590 | *this, OCD_AllCandidates, Args, "[]", LLoc); |
14591 | return ExprError(); |
14592 | } |
14593 | |
14594 | // We matched a built-in operator; build it. |
14595 | return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); |
14596 | } |
14597 | |
14598 | /// BuildCallToMemberFunction - Build a call to a member |
14599 | /// function. MemExpr is the expression that refers to the member |
14600 | /// function (and includes the object parameter), Args/NumArgs are the |
14601 | /// arguments to the function call (not including the object |
14602 | /// parameter). The caller needs to validate that the member |
14603 | /// expression refers to a non-static member function or an overloaded |
14604 | /// member function. |
14605 | ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, |
14606 | SourceLocation LParenLoc, |
14607 | MultiExprArg Args, |
14608 | SourceLocation RParenLoc, |
14609 | Expr *ExecConfig, bool IsExecConfig, |
14610 | bool AllowRecovery) { |
14611 | assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast <bool> (MemExprE->getType() == Context. BoundMemberTy || MemExprE->getType() == Context.OverloadTy ) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 14612, __extension__ __PRETTY_FUNCTION__ )) |
14612 | MemExprE->getType() == Context.OverloadTy)(static_cast <bool> (MemExprE->getType() == Context. BoundMemberTy || MemExprE->getType() == Context.OverloadTy ) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 14612, __extension__ __PRETTY_FUNCTION__ )); |
14613 | |
14614 | // Dig out the member expression. This holds both the object |
14615 | // argument and the member function we're referring to. |
14616 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); |
14617 | |
14618 | // Determine whether this is a call to a pointer-to-member function. |
14619 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { |
14620 | assert(op->getType() == Context.BoundMemberTy)(static_cast <bool> (op->getType() == Context.BoundMemberTy ) ? void (0) : __assert_fail ("op->getType() == Context.BoundMemberTy" , "clang/lib/Sema/SemaOverload.cpp", 14620, __extension__ __PRETTY_FUNCTION__ )); |
14621 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast <bool> (op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI" , "clang/lib/Sema/SemaOverload.cpp", 14621, __extension__ __PRETTY_FUNCTION__ )); |
14622 | |
14623 | QualType fnType = |
14624 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); |
14625 | |
14626 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); |
14627 | QualType resultType = proto->getCallResultType(Context); |
14628 | ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); |
14629 | |
14630 | // Check that the object type isn't more qualified than the |
14631 | // member function we're calling. |
14632 | Qualifiers funcQuals = proto->getMethodQuals(); |
14633 | |
14634 | QualType objectType = op->getLHS()->getType(); |
14635 | if (op->getOpcode() == BO_PtrMemI) |
14636 | objectType = objectType->castAs<PointerType>()->getPointeeType(); |
14637 | Qualifiers objectQuals = objectType.getQualifiers(); |
14638 | |
14639 | Qualifiers difference = objectQuals - funcQuals; |
14640 | difference.removeObjCGCAttr(); |
14641 | difference.removeAddressSpace(); |
14642 | if (difference) { |
14643 | std::string qualsString = difference.getAsString(); |
14644 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) |
14645 | << fnType.getUnqualifiedType() |
14646 | << qualsString |
14647 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); |
14648 | } |
14649 | |
14650 | CXXMemberCallExpr *call = CXXMemberCallExpr::Create( |
14651 | Context, MemExprE, Args, resultType, valueKind, RParenLoc, |
14652 | CurFPFeatureOverrides(), proto->getNumParams()); |
14653 | |
14654 | if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), |
14655 | call, nullptr)) |
14656 | return ExprError(); |
14657 | |
14658 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) |
14659 | return ExprError(); |
14660 | |
14661 | if (CheckOtherCall(call, proto)) |
14662 | return ExprError(); |
14663 | |
14664 | return MaybeBindToTemporary(call); |
14665 | } |
14666 | |
14667 | // We only try to build a recovery expr at this level if we can preserve |
14668 | // the return type, otherwise we return ExprError() and let the caller |
14669 | // recover. |
14670 | auto BuildRecoveryExpr = [&](QualType Type) { |
14671 | if (!AllowRecovery) |
14672 | return ExprError(); |
14673 | std::vector<Expr *> SubExprs = {MemExprE}; |
14674 | llvm::append_range(SubExprs, Args); |
14675 | return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, |
14676 | Type); |
14677 | }; |
14678 | if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) |
14679 | return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, |
14680 | RParenLoc, CurFPFeatureOverrides()); |
14681 | |
14682 | UnbridgedCastsSet UnbridgedCasts; |
14683 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
14684 | return ExprError(); |
14685 | |
14686 | MemberExpr *MemExpr; |
14687 | CXXMethodDecl *Method = nullptr; |
14688 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); |
14689 | NestedNameSpecifier *Qualifier = nullptr; |
14690 | if (isa<MemberExpr>(NakedMemExpr)) { |
14691 | MemExpr = cast<MemberExpr>(NakedMemExpr); |
14692 | Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); |
14693 | FoundDecl = MemExpr->getFoundDecl(); |
14694 | Qualifier = MemExpr->getQualifier(); |
14695 | UnbridgedCasts.restore(); |
14696 | } else { |
14697 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); |
14698 | Qualifier = UnresExpr->getQualifier(); |
14699 | |
14700 | QualType ObjectType = UnresExpr->getBaseType(); |
14701 | Expr::Classification ObjectClassification |
14702 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() |
14703 | : UnresExpr->getBase()->Classify(Context); |
14704 | |
14705 | // Add overload candidates |
14706 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), |
14707 | OverloadCandidateSet::CSK_Normal); |
14708 | |
14709 | // FIXME: avoid copy. |
14710 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
14711 | if (UnresExpr->hasExplicitTemplateArgs()) { |
14712 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
14713 | TemplateArgs = &TemplateArgsBuffer; |
14714 | } |
14715 | |
14716 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), |
14717 | E = UnresExpr->decls_end(); I != E; ++I) { |
14718 | |
14719 | NamedDecl *Func = *I; |
14720 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); |
14721 | if (isa<UsingShadowDecl>(Func)) |
14722 | Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); |
14723 | |
14724 | |
14725 | // Microsoft supports direct constructor calls. |
14726 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { |
14727 | AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, |
14728 | CandidateSet, |
14729 | /*SuppressUserConversions*/ false); |
14730 | } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { |
14731 | // If explicit template arguments were provided, we can't call a |
14732 | // non-template member function. |
14733 | if (TemplateArgs) |
14734 | continue; |
14735 | |
14736 | AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, |
14737 | ObjectClassification, Args, CandidateSet, |
14738 | /*SuppressUserConversions=*/false); |
14739 | } else { |
14740 | AddMethodTemplateCandidate( |
14741 | cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, |
14742 | TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, |
14743 | /*SuppressUserConversions=*/false); |
14744 | } |
14745 | } |
14746 | |
14747 | DeclarationName DeclName = UnresExpr->getMemberName(); |
14748 | |
14749 | UnbridgedCasts.restore(); |
14750 | |
14751 | OverloadCandidateSet::iterator Best; |
14752 | bool Succeeded = false; |
14753 | switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), |
14754 | Best)) { |
14755 | case OR_Success: |
14756 | Method = cast<CXXMethodDecl>(Best->Function); |
14757 | FoundDecl = Best->FoundDecl; |
14758 | CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); |
14759 | if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc())) |
14760 | break; |
14761 | // If FoundDecl is different from Method (such as if one is a template |
14762 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
14763 | // called on both. |
14764 | // FIXME: This would be more comprehensively addressed by modifying |
14765 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
14766 | // being used. |
14767 | if (Method != FoundDecl.getDecl() && |
14768 | DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc())) |
14769 | break; |
14770 | Succeeded = true; |
14771 | break; |
14772 | |
14773 | case OR_No_Viable_Function: |
14774 | CandidateSet.NoteCandidates( |
14775 | PartialDiagnosticAt( |
14776 | UnresExpr->getMemberLoc(), |
14777 | PDiag(diag::err_ovl_no_viable_member_function_in_call) |
14778 | << DeclName << MemExprE->getSourceRange()), |
14779 | *this, OCD_AllCandidates, Args); |
14780 | break; |
14781 | case OR_Ambiguous: |
14782 | CandidateSet.NoteCandidates( |
14783 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
14784 | PDiag(diag::err_ovl_ambiguous_member_call) |
14785 | << DeclName << MemExprE->getSourceRange()), |
14786 | *this, OCD_AmbiguousCandidates, Args); |
14787 | break; |
14788 | case OR_Deleted: |
14789 | CandidateSet.NoteCandidates( |
14790 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
14791 | PDiag(diag::err_ovl_deleted_member_call) |
14792 | << DeclName << MemExprE->getSourceRange()), |
14793 | *this, OCD_AllCandidates, Args); |
14794 | break; |
14795 | } |
14796 | // Overload resolution fails, try to recover. |
14797 | if (!Succeeded) |
14798 | return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); |
14799 | |
14800 | MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); |
14801 | |
14802 | // If overload resolution picked a static member, build a |
14803 | // non-member call based on that function. |
14804 | if (Method->isStatic()) { |
14805 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, |
14806 | ExecConfig, IsExecConfig); |
14807 | } |
14808 | |
14809 | MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); |
14810 | } |
14811 | |
14812 | QualType ResultType = Method->getReturnType(); |
14813 | ExprValueKind VK = Expr::getValueKindForType(ResultType); |
14814 | ResultType = ResultType.getNonLValueExprType(Context); |
14815 | |
14816 | assert(Method && "Member call to something that isn't a method?")(static_cast <bool> (Method && "Member call to something that isn't a method?" ) ? void (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\"" , "clang/lib/Sema/SemaOverload.cpp", 14816, __extension__ __PRETTY_FUNCTION__ )); |
14817 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
14818 | CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( |
14819 | Context, MemExprE, Args, ResultType, VK, RParenLoc, |
14820 | CurFPFeatureOverrides(), Proto->getNumParams()); |
14821 | |
14822 | // Check for a valid return type. |
14823 | if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), |
14824 | TheCall, Method)) |
14825 | return BuildRecoveryExpr(ResultType); |
14826 | |
14827 | // Convert the object argument (for a non-static member function call). |
14828 | // We only need to do this if there was actually an overload; otherwise |
14829 | // it was done at lookup. |
14830 | if (!Method->isStatic()) { |
14831 | ExprResult ObjectArg = |
14832 | PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, |
14833 | FoundDecl, Method); |
14834 | if (ObjectArg.isInvalid()) |
14835 | return ExprError(); |
14836 | MemExpr->setBase(ObjectArg.get()); |
14837 | } |
14838 | |
14839 | // Convert the rest of the arguments |
14840 | if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, |
14841 | RParenLoc)) |
14842 | return BuildRecoveryExpr(ResultType); |
14843 | |
14844 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
14845 | |
14846 | if (CheckFunctionCall(Method, TheCall, Proto)) |
14847 | return ExprError(); |
14848 | |
14849 | // In the case the method to call was not selected by the overloading |
14850 | // resolution process, we still need to handle the enable_if attribute. Do |
14851 | // that here, so it will not hide previous -- and more relevant -- errors. |
14852 | if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { |
14853 | if (const EnableIfAttr *Attr = |
14854 | CheckEnableIf(Method, LParenLoc, Args, true)) { |
14855 | Diag(MemE->getMemberLoc(), |
14856 | diag::err_ovl_no_viable_member_function_in_call) |
14857 | << Method << Method->getSourceRange(); |
14858 | Diag(Method->getLocation(), |
14859 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
14860 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
14861 | return ExprError(); |
14862 | } |
14863 | } |
14864 | |
14865 | if ((isa<CXXConstructorDecl>(CurContext) || |
14866 | isa<CXXDestructorDecl>(CurContext)) && |
14867 | TheCall->getMethodDecl()->isPure()) { |
14868 | const CXXMethodDecl *MD = TheCall->getMethodDecl(); |
14869 | |
14870 | if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && |
14871 | MemExpr->performsVirtualDispatch(getLangOpts())) { |
14872 | Diag(MemExpr->getBeginLoc(), |
14873 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) |
14874 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) |
14875 | << MD->getParent(); |
14876 | |
14877 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); |
14878 | if (getLangOpts().AppleKext) |
14879 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) |
14880 | << MD->getParent() << MD->getDeclName(); |
14881 | } |
14882 | } |
14883 | |
14884 | if (CXXDestructorDecl *DD = |
14885 | dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { |
14886 | // a->A::f() doesn't go through the vtable, except in AppleKext mode. |
14887 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; |
14888 | CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, |
14889 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, |
14890 | MemExpr->getMemberLoc()); |
14891 | } |
14892 | |
14893 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), |
14894 | TheCall->getMethodDecl()); |
14895 | } |
14896 | |
14897 | /// BuildCallToObjectOfClassType - Build a call to an object of class |
14898 | /// type (C++ [over.call.object]), which can end up invoking an |
14899 | /// overloaded function call operator (@c operator()) or performing a |
14900 | /// user-defined conversion on the object argument. |
14901 | ExprResult |
14902 | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, |
14903 | SourceLocation LParenLoc, |
14904 | MultiExprArg Args, |
14905 | SourceLocation RParenLoc) { |
14906 | if (checkPlaceholderForOverload(*this, Obj)) |
14907 | return ExprError(); |
14908 | ExprResult Object = Obj; |
14909 | |
14910 | UnbridgedCastsSet UnbridgedCasts; |
14911 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
14912 | return ExprError(); |
14913 | |
14914 | assert(Object.get()->getType()->isRecordType() &&(static_cast <bool> (Object.get()->getType()->isRecordType () && "Requires object type argument") ? void (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "clang/lib/Sema/SemaOverload.cpp", 14915, __extension__ __PRETTY_FUNCTION__ )) |
14915 | "Requires object type argument")(static_cast <bool> (Object.get()->getType()->isRecordType () && "Requires object type argument") ? void (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "clang/lib/Sema/SemaOverload.cpp", 14915, __extension__ __PRETTY_FUNCTION__ )); |
14916 | |
14917 | // C++ [over.call.object]p1: |
14918 | // If the primary-expression E in the function call syntax |
14919 | // evaluates to a class object of type "cv T", then the set of |
14920 | // candidate functions includes at least the function call |
14921 | // operators of T. The function call operators of T are obtained by |
14922 | // ordinary lookup of the name operator() in the context of |
14923 | // (E).operator(). |
14924 | OverloadCandidateSet CandidateSet(LParenLoc, |
14925 | OverloadCandidateSet::CSK_Operator); |
14926 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); |
14927 | |
14928 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), |
14929 | diag::err_incomplete_object_call, Object.get())) |
14930 | return true; |
14931 | |
14932 | const auto *Record = Object.get()->getType()->castAs<RecordType>(); |
14933 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); |
14934 | LookupQualifiedName(R, Record->getDecl()); |
14935 | R.suppressDiagnostics(); |
14936 | |
14937 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
14938 | Oper != OperEnd; ++Oper) { |
14939 | AddMethodCandidate(Oper.getPair(), Object.get()->getType(), |
14940 | Object.get()->Classify(Context), Args, CandidateSet, |
14941 | /*SuppressUserConversion=*/false); |
14942 | } |
14943 | |
14944 | // C++ [over.call.object]p2: |
14945 | // In addition, for each (non-explicit in C++0x) conversion function |
14946 | // declared in T of the form |
14947 | // |
14948 | // operator conversion-type-id () cv-qualifier; |
14949 | // |
14950 | // where cv-qualifier is the same cv-qualification as, or a |
14951 | // greater cv-qualification than, cv, and where conversion-type-id |
14952 | // denotes the type "pointer to function of (P1,...,Pn) returning |
14953 | // R", or the type "reference to pointer to function of |
14954 | // (P1,...,Pn) returning R", or the type "reference to function |
14955 | // of (P1,...,Pn) returning R", a surrogate call function [...] |
14956 | // is also considered as a candidate function. Similarly, |
14957 | // surrogate call functions are added to the set of candidate |
14958 | // functions for each conversion function declared in an |
14959 | // accessible base class provided the function is not hidden |
14960 | // within T by another intervening declaration. |
14961 | const auto &Conversions = |
14962 | cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); |
14963 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
14964 | NamedDecl *D = *I; |
14965 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
14966 | if (isa<UsingShadowDecl>(D)) |
14967 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
14968 | |
14969 | // Skip over templated conversion functions; they aren't |
14970 | // surrogates. |
14971 | if (isa<FunctionTemplateDecl>(D)) |
14972 | continue; |
14973 | |
14974 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
14975 | if (!Conv->isExplicit()) { |
14976 | // Strip the reference type (if any) and then the pointer type (if |
14977 | // any) to get down to what might be a function type. |
14978 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); |
14979 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
14980 | ConvType = ConvPtrType->getPointeeType(); |
14981 | |
14982 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) |
14983 | { |
14984 | AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, |
14985 | Object.get(), Args, CandidateSet); |
14986 | } |
14987 | } |
14988 | } |
14989 | |
14990 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14991 | |
14992 | // Perform overload resolution. |
14993 | OverloadCandidateSet::iterator Best; |
14994 | switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), |
14995 | Best)) { |
14996 | case OR_Success: |
14997 | // Overload resolution succeeded; we'll build the appropriate call |
14998 | // below. |
14999 | break; |
15000 | |
15001 | case OR_No_Viable_Function: { |
15002 | PartialDiagnostic PD = |
15003 | CandidateSet.empty() |
15004 | ? (PDiag(diag::err_ovl_no_oper) |
15005 | << Object.get()->getType() << /*call*/ 1 |
15006 | << Object.get()->getSourceRange()) |
15007 | : (PDiag(diag::err_ovl_no_viable_object_call) |
15008 | << Object.get()->getType() << Object.get()->getSourceRange()); |
15009 | CandidateSet.NoteCandidates( |
15010 | PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, |
15011 | OCD_AllCandidates, Args); |
15012 | break; |
15013 | } |
15014 | case OR_Ambiguous: |
15015 | CandidateSet.NoteCandidates( |
15016 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15017 | PDiag(diag::err_ovl_ambiguous_object_call) |
15018 | << Object.get()->getType() |
15019 | << Object.get()->getSourceRange()), |
15020 | *this, OCD_AmbiguousCandidates, Args); |
15021 | break; |
15022 | |
15023 | case OR_Deleted: |
15024 | CandidateSet.NoteCandidates( |
15025 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15026 | PDiag(diag::err_ovl_deleted_object_call) |
15027 | << Object.get()->getType() |
15028 | << Object.get()->getSourceRange()), |
15029 | *this, OCD_AllCandidates, Args); |
15030 | break; |
15031 | } |
15032 | |
15033 | if (Best == CandidateSet.end()) |
15034 | return true; |
15035 | |
15036 | UnbridgedCasts.restore(); |
15037 | |
15038 | if (Best->Function == nullptr) { |
15039 | // Since there is no function declaration, this is one of the |
15040 | // surrogate candidates. Dig out the conversion function. |
15041 | CXXConversionDecl *Conv |
15042 | = cast<CXXConversionDecl>( |
15043 | Best->Conversions[0].UserDefined.ConversionFunction); |
15044 | |
15045 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, |
15046 | Best->FoundDecl); |
15047 | if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) |
15048 | return ExprError(); |
15049 | assert(Conv == Best->FoundDecl.getDecl() &&(static_cast <bool> (Conv == Best->FoundDecl.getDecl () && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "clang/lib/Sema/SemaOverload.cpp", 15050, __extension__ __PRETTY_FUNCTION__ )) |
15050 | "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast <bool> (Conv == Best->FoundDecl.getDecl () && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "clang/lib/Sema/SemaOverload.cpp", 15050, __extension__ __PRETTY_FUNCTION__ )); |
15051 | // We selected one of the surrogate functions that converts the |
15052 | // object parameter to a function pointer. Perform the conversion |
15053 | // on the object argument, then let BuildCallExpr finish the job. |
15054 | |
15055 | // Create an implicit member expr to refer to the conversion operator. |
15056 | // and then call it. |
15057 | ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, |
15058 | Conv, HadMultipleCandidates); |
15059 | if (Call.isInvalid()) |
15060 | return ExprError(); |
15061 | // Record usage of conversion in an implicit cast. |
15062 | Call = ImplicitCastExpr::Create( |
15063 | Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), |
15064 | nullptr, VK_PRValue, CurFPFeatureOverrides()); |
15065 | |
15066 | return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); |
15067 | } |
15068 | |
15069 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); |
15070 | |
15071 | // We found an overloaded operator(). Build a CXXOperatorCallExpr |
15072 | // that calls this method, using Object for the implicit object |
15073 | // parameter and passing along the remaining arguments. |
15074 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
15075 | |
15076 | // An error diagnostic has already been printed when parsing the declaration. |
15077 | if (Method->isInvalidDecl()) |
15078 | return ExprError(); |
15079 | |
15080 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
15081 | unsigned NumParams = Proto->getNumParams(); |
15082 | |
15083 | DeclarationNameInfo OpLocInfo( |
15084 | Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); |
15085 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); |
15086 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15087 | Obj, HadMultipleCandidates, |
15088 | OpLocInfo.getLoc(), |
15089 | OpLocInfo.getInfo()); |
15090 | if (NewFn.isInvalid()) |
15091 | return true; |
15092 | |
15093 | SmallVector<Expr *, 8> MethodArgs; |
15094 | MethodArgs.reserve(NumParams + 1); |
15095 | |
15096 | bool IsError = false; |
15097 | |
15098 | // Initialize the implicit object parameter if needed. |
15099 | // Since C++23, this could also be a call to a static call operator |
15100 | // which we emit as a regular CallExpr. |
15101 | if (Method->isInstance()) { |
15102 | ExprResult ObjRes = PerformObjectArgumentInitialization( |
15103 | Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
15104 | if (ObjRes.isInvalid()) |
15105 | IsError = true; |
15106 | else |
15107 | Object = ObjRes; |
15108 | MethodArgs.push_back(Object.get()); |
15109 | } |
15110 | |
15111 | IsError |= PrepareArgumentsForCallToObjectOfClassType( |
15112 | *this, MethodArgs, Method, Args, LParenLoc); |
15113 | |
15114 | // If this is a variadic call, handle args passed through "...". |
15115 | if (Proto->isVariadic()) { |
15116 | // Promote the arguments (C99 6.5.2.2p7). |
15117 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { |
15118 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
15119 | nullptr); |
15120 | IsError |= Arg.isInvalid(); |
15121 | MethodArgs.push_back(Arg.get()); |
15122 | } |
15123 | } |
15124 | |
15125 | if (IsError) |
15126 | return true; |
15127 | |
15128 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
15129 | |
15130 | // Once we've built TheCall, all of the expressions are properly owned. |
15131 | QualType ResultTy = Method->getReturnType(); |
15132 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15133 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15134 | |
15135 | CallExpr *TheCall; |
15136 | if (Method->isInstance()) |
15137 | TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), |
15138 | MethodArgs, ResultTy, VK, RParenLoc, |
15139 | CurFPFeatureOverrides()); |
15140 | else |
15141 | TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK, |
15142 | RParenLoc, CurFPFeatureOverrides()); |
15143 | |
15144 | if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) |
15145 | return true; |
15146 | |
15147 | if (CheckFunctionCall(Method, TheCall, Proto)) |
15148 | return true; |
15149 | |
15150 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15151 | } |
15152 | |
15153 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> |
15154 | /// (if one exists), where @c Base is an expression of class type and |
15155 | /// @c Member is the name of the member we're trying to find. |
15156 | ExprResult |
15157 | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, |
15158 | bool *NoArrowOperatorFound) { |
15159 | assert(Base->getType()->isRecordType() &&(static_cast <bool> (Base->getType()->isRecordType () && "left-hand side must have class type") ? void ( 0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "clang/lib/Sema/SemaOverload.cpp", 15160, __extension__ __PRETTY_FUNCTION__ )) |
15160 | "left-hand side must have class type")(static_cast <bool> (Base->getType()->isRecordType () && "left-hand side must have class type") ? void ( 0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "clang/lib/Sema/SemaOverload.cpp", 15160, __extension__ __PRETTY_FUNCTION__ )); |
15161 | |
15162 | if (checkPlaceholderForOverload(*this, Base)) |
15163 | return ExprError(); |
15164 | |
15165 | SourceLocation Loc = Base->getExprLoc(); |
15166 | |
15167 | // C++ [over.ref]p1: |
15168 | // |
15169 | // [...] An expression x->m is interpreted as (x.operator->())->m |
15170 | // for a class object x of type T if T::operator->() exists and if |
15171 | // the operator is selected as the best match function by the |
15172 | // overload resolution mechanism (13.3). |
15173 | DeclarationName OpName = |
15174 | Context.DeclarationNames.getCXXOperatorName(OO_Arrow); |
15175 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); |
15176 | |
15177 | if (RequireCompleteType(Loc, Base->getType(), |
15178 | diag::err_typecheck_incomplete_tag, Base)) |
15179 | return ExprError(); |
15180 | |
15181 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); |
15182 | LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); |
15183 | R.suppressDiagnostics(); |
15184 | |
15185 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
15186 | Oper != OperEnd; ++Oper) { |
15187 | AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), |
15188 | std::nullopt, CandidateSet, |
15189 | /*SuppressUserConversion=*/false); |
15190 | } |
15191 | |
15192 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15193 | |
15194 | // Perform overload resolution. |
15195 | OverloadCandidateSet::iterator Best; |
15196 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
15197 | case OR_Success: |
15198 | // Overload resolution succeeded; we'll build the call below. |
15199 | break; |
15200 | |
15201 | case OR_No_Viable_Function: { |
15202 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); |
15203 | if (CandidateSet.empty()) { |
15204 | QualType BaseType = Base->getType(); |
15205 | if (NoArrowOperatorFound) { |
15206 | // Report this specific error to the caller instead of emitting a |
15207 | // diagnostic, as requested. |
15208 | *NoArrowOperatorFound = true; |
15209 | return ExprError(); |
15210 | } |
15211 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
15212 | << BaseType << Base->getSourceRange(); |
15213 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { |
15214 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) |
15215 | << FixItHint::CreateReplacement(OpLoc, "."); |
15216 | } |
15217 | } else |
15218 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
15219 | << "operator->" << Base->getSourceRange(); |
15220 | CandidateSet.NoteCandidates(*this, Base, Cands); |
15221 | return ExprError(); |
15222 | } |
15223 | case OR_Ambiguous: |
15224 | CandidateSet.NoteCandidates( |
15225 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) |
15226 | << "->" << Base->getType() |
15227 | << Base->getSourceRange()), |
15228 | *this, OCD_AmbiguousCandidates, Base); |
15229 | return ExprError(); |
15230 | |
15231 | case OR_Deleted: |
15232 | CandidateSet.NoteCandidates( |
15233 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
15234 | << "->" << Base->getSourceRange()), |
15235 | *this, OCD_AllCandidates, Base); |
15236 | return ExprError(); |
15237 | } |
15238 | |
15239 | CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); |
15240 | |
15241 | // Convert the object parameter. |
15242 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
15243 | ExprResult BaseResult = |
15244 | PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, |
15245 | Best->FoundDecl, Method); |
15246 | if (BaseResult.isInvalid()) |
15247 | return ExprError(); |
15248 | Base = BaseResult.get(); |
15249 | |
15250 | // Build the operator call. |
15251 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15252 | Base, HadMultipleCandidates, OpLoc); |
15253 | if (FnExpr.isInvalid()) |
15254 | return ExprError(); |
15255 | |
15256 | QualType ResultTy = Method->getReturnType(); |
15257 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15258 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15259 | CXXOperatorCallExpr *TheCall = |
15260 | CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, |
15261 | ResultTy, VK, OpLoc, CurFPFeatureOverrides()); |
15262 | |
15263 | if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) |
15264 | return ExprError(); |
15265 | |
15266 | if (CheckFunctionCall(Method, TheCall, |
15267 | Method->getType()->castAs<FunctionProtoType>())) |
15268 | return ExprError(); |
15269 | |
15270 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15271 | } |
15272 | |
15273 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to |
15274 | /// a literal operator described by the provided lookup results. |
15275 | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, |
15276 | DeclarationNameInfo &SuffixInfo, |
15277 | ArrayRef<Expr*> Args, |
15278 | SourceLocation LitEndLoc, |
15279 | TemplateArgumentListInfo *TemplateArgs) { |
15280 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); |
15281 | |
15282 | OverloadCandidateSet CandidateSet(UDSuffixLoc, |
15283 | OverloadCandidateSet::CSK_Normal); |
15284 | AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, |
15285 | TemplateArgs); |
15286 | |
15287 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15288 | |
15289 | // Perform overload resolution. This will usually be trivial, but might need |
15290 | // to perform substitutions for a literal operator template. |
15291 | OverloadCandidateSet::iterator Best; |
15292 | switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { |
15293 | case OR_Success: |
15294 | case OR_Deleted: |
15295 | break; |
15296 | |
15297 | case OR_No_Viable_Function: |
15298 | CandidateSet.NoteCandidates( |
15299 | PartialDiagnosticAt(UDSuffixLoc, |
15300 | PDiag(diag::err_ovl_no_viable_function_in_call) |
15301 | << R.getLookupName()), |
15302 | *this, OCD_AllCandidates, Args); |
15303 | return ExprError(); |
15304 | |
15305 | case OR_Ambiguous: |
15306 | CandidateSet.NoteCandidates( |
15307 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) |
15308 | << R.getLookupName()), |
15309 | *this, OCD_AmbiguousCandidates, Args); |
15310 | return ExprError(); |
15311 | } |
15312 | |
15313 | FunctionDecl *FD = Best->Function; |
15314 | ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, |
15315 | nullptr, HadMultipleCandidates, |
15316 | SuffixInfo.getLoc(), |
15317 | SuffixInfo.getInfo()); |
15318 | if (Fn.isInvalid()) |
15319 | return true; |
15320 | |
15321 | // Check the argument types. This should almost always be a no-op, except |
15322 | // that array-to-pointer decay is applied to string literals. |
15323 | Expr *ConvArgs[2]; |
15324 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
15325 | ExprResult InputInit = PerformCopyInitialization( |
15326 | InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), |
15327 | SourceLocation(), Args[ArgIdx]); |
15328 | if (InputInit.isInvalid()) |
15329 | return true; |
15330 | ConvArgs[ArgIdx] = InputInit.get(); |
15331 | } |
15332 | |
15333 | QualType ResultTy = FD->getReturnType(); |
15334 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15335 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15336 | |
15337 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( |
15338 | Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK, |
15339 | LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); |
15340 | |
15341 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) |
15342 | return ExprError(); |
15343 | |
15344 | if (CheckFunctionCall(FD, UDL, nullptr)) |
15345 | return ExprError(); |
15346 | |
15347 | return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); |
15348 | } |
15349 | |
15350 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the |
15351 | /// given LookupResult is non-empty, it is assumed to describe a member which |
15352 | /// will be invoked. Otherwise, the function will be found via argument |
15353 | /// dependent lookup. |
15354 | /// CallExpr is set to a valid expression and FRS_Success returned on success, |
15355 | /// otherwise CallExpr is set to ExprError() and some non-success value |
15356 | /// is returned. |
15357 | Sema::ForRangeStatus |
15358 | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, |
15359 | SourceLocation RangeLoc, |
15360 | const DeclarationNameInfo &NameInfo, |
15361 | LookupResult &MemberLookup, |
15362 | OverloadCandidateSet *CandidateSet, |
15363 | Expr *Range, ExprResult *CallExpr) { |
15364 | Scope *S = nullptr; |
15365 | |
15366 | CandidateSet->clear(OverloadCandidateSet::CSK_Normal); |
15367 | if (!MemberLookup.empty()) { |
15368 | ExprResult MemberRef = |
15369 | BuildMemberReferenceExpr(Range, Range->getType(), Loc, |
15370 | /*IsPtr=*/false, CXXScopeSpec(), |
15371 | /*TemplateKWLoc=*/SourceLocation(), |
15372 | /*FirstQualifierInScope=*/nullptr, |
15373 | MemberLookup, |
15374 | /*TemplateArgs=*/nullptr, S); |
15375 | if (MemberRef.isInvalid()) { |
15376 | *CallExpr = ExprError(); |
15377 | return FRS_DiagnosticIssued; |
15378 | } |
15379 | *CallExpr = |
15380 | BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr); |
15381 | if (CallExpr->isInvalid()) { |
15382 | *CallExpr = ExprError(); |
15383 | return FRS_DiagnosticIssued; |
15384 | } |
15385 | } else { |
15386 | ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, |
15387 | NestedNameSpecifierLoc(), |
15388 | NameInfo, UnresolvedSet<0>()); |
15389 | if (FnR.isInvalid()) |
15390 | return FRS_DiagnosticIssued; |
15391 | UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); |
15392 | |
15393 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, |
15394 | CandidateSet, CallExpr); |
15395 | if (CandidateSet->empty() || CandidateSetError) { |
15396 | *CallExpr = ExprError(); |
15397 | return FRS_NoViableFunction; |
15398 | } |
15399 | OverloadCandidateSet::iterator Best; |
15400 | OverloadingResult OverloadResult = |
15401 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); |
15402 | |
15403 | if (OverloadResult == OR_No_Viable_Function) { |
15404 | *CallExpr = ExprError(); |
15405 | return FRS_NoViableFunction; |
15406 | } |
15407 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, |
15408 | Loc, nullptr, CandidateSet, &Best, |
15409 | OverloadResult, |
15410 | /*AllowTypoCorrection=*/false); |
15411 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { |
15412 | *CallExpr = ExprError(); |
15413 | return FRS_DiagnosticIssued; |
15414 | } |
15415 | } |
15416 | return FRS_Success; |
15417 | } |
15418 | |
15419 | |
15420 | /// FixOverloadedFunctionReference - E is an expression that refers to |
15421 | /// a C++ overloaded function (possibly with some parentheses and |
15422 | /// perhaps a '&' around it). We have resolved the overloaded function |
15423 | /// to the function declaration Fn, so patch up the expression E to |
15424 | /// refer (possibly indirectly) to Fn. Returns the new expr. |
15425 | Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, |
15426 | FunctionDecl *Fn) { |
15427 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { |
15428 | Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), |
15429 | Found, Fn); |
15430 | if (SubExpr == PE->getSubExpr()) |
15431 | return PE; |
15432 | |
15433 | return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); |
15434 | } |
15435 | |
15436 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { |
15437 | Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), |
15438 | Found, Fn); |
15439 | assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15441, __extension__ __PRETTY_FUNCTION__ )) |
15440 | SubExpr->getType()) &&(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15441, __extension__ __PRETTY_FUNCTION__ )) |
15441 | "Implicit cast type cannot be determined from overload")(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15441, __extension__ __PRETTY_FUNCTION__ )); |
15442 | assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast <bool> (ICE->path_empty() && "fixing up hierarchy conversion?" ) ? void (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\"" , "clang/lib/Sema/SemaOverload.cpp", 15442, __extension__ __PRETTY_FUNCTION__ )); |
15443 | if (SubExpr == ICE->getSubExpr()) |
15444 | return ICE; |
15445 | |
15446 | return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), |
15447 | SubExpr, nullptr, ICE->getValueKind(), |
15448 | CurFPFeatureOverrides()); |
15449 | } |
15450 | |
15451 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { |
15452 | if (!GSE->isResultDependent()) { |
15453 | Expr *SubExpr = |
15454 | FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); |
15455 | if (SubExpr == GSE->getResultExpr()) |
15456 | return GSE; |
15457 | |
15458 | // Replace the resulting type information before rebuilding the generic |
15459 | // selection expression. |
15460 | ArrayRef<Expr *> A = GSE->getAssocExprs(); |
15461 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); |
15462 | unsigned ResultIdx = GSE->getResultIndex(); |
15463 | AssocExprs[ResultIdx] = SubExpr; |
15464 | |
15465 | return GenericSelectionExpr::Create( |
15466 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), |
15467 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
15468 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
15469 | ResultIdx); |
15470 | } |
15471 | // Rather than fall through to the unreachable, return the original generic |
15472 | // selection expression. |
15473 | return GSE; |
15474 | } |
15475 | |
15476 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { |
15477 | assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function") ? void (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "clang/lib/Sema/SemaOverload.cpp", 15478, __extension__ __PRETTY_FUNCTION__ )) |
15478 | "Can only take the address of an overloaded function")(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function") ? void (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "clang/lib/Sema/SemaOverload.cpp", 15478, __extension__ __PRETTY_FUNCTION__ )); |
15479 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
15480 | if (Method->isStatic()) { |
15481 | // Do nothing: static member functions aren't any different |
15482 | // from non-member functions. |
15483 | } else { |
15484 | // Fix the subexpression, which really has to be an |
15485 | // UnresolvedLookupExpr holding an overloaded member function |
15486 | // or template. |
15487 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), |
15488 | Found, Fn); |
15489 | if (SubExpr == UnOp->getSubExpr()) |
15490 | return UnOp; |
15491 | |
15492 | assert(isa<DeclRefExpr>(SubExpr)(static_cast <bool> (isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref") ? void (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "clang/lib/Sema/SemaOverload.cpp", 15493, __extension__ __PRETTY_FUNCTION__ )) |
15493 | && "fixed to something other than a decl ref")(static_cast <bool> (isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref") ? void (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "clang/lib/Sema/SemaOverload.cpp", 15493, __extension__ __PRETTY_FUNCTION__ )); |
15494 | assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast <bool> (cast<DeclRefExpr>(SubExpr)-> getQualifier() && "fixed to a member ref with no nested name qualifier" ) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "clang/lib/Sema/SemaOverload.cpp", 15495, __extension__ __PRETTY_FUNCTION__ )) |
15495 | && "fixed to a member ref with no nested name qualifier")(static_cast <bool> (cast<DeclRefExpr>(SubExpr)-> getQualifier() && "fixed to a member ref with no nested name qualifier" ) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "clang/lib/Sema/SemaOverload.cpp", 15495, __extension__ __PRETTY_FUNCTION__ )); |
15496 | |
15497 | // We have taken the address of a pointer to member |
15498 | // function. Perform the computation here so that we get the |
15499 | // appropriate pointer to member type. |
15500 | QualType ClassType |
15501 | = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); |
15502 | QualType MemPtrType |
15503 | = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); |
15504 | // Under the MS ABI, lock down the inheritance model now. |
15505 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
15506 | (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); |
15507 | |
15508 | return UnaryOperator::Create( |
15509 | Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, |
15510 | UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); |
15511 | } |
15512 | } |
15513 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), |
15514 | Found, Fn); |
15515 | if (SubExpr == UnOp->getSubExpr()) |
15516 | return UnOp; |
15517 | |
15518 | // FIXME: This can't currently fail, but in principle it could. |
15519 | return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr) |
15520 | .get(); |
15521 | } |
15522 | |
15523 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { |
15524 | // FIXME: avoid copy. |
15525 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
15526 | if (ULE->hasExplicitTemplateArgs()) { |
15527 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); |
15528 | TemplateArgs = &TemplateArgsBuffer; |
15529 | } |
15530 | |
15531 | QualType Type = Fn->getType(); |
15532 | ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; |
15533 | |
15534 | // FIXME: Duplicated from BuildDeclarationNameExpr. |
15535 | if (unsigned BID = Fn->getBuiltinID()) { |
15536 | if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { |
15537 | Type = Context.BuiltinFnTy; |
15538 | ValueKind = VK_PRValue; |
15539 | } |
15540 | } |
15541 | |
15542 | DeclRefExpr *DRE = BuildDeclRefExpr( |
15543 | Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), |
15544 | Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); |
15545 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); |
15546 | return DRE; |
15547 | } |
15548 | |
15549 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { |
15550 | // FIXME: avoid copy. |
15551 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
15552 | if (MemExpr->hasExplicitTemplateArgs()) { |
15553 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
15554 | TemplateArgs = &TemplateArgsBuffer; |
15555 | } |
15556 | |
15557 | Expr *Base; |
15558 | |
15559 | // If we're filling in a static method where we used to have an |
15560 | // implicit member access, rewrite to a simple decl ref. |
15561 | if (MemExpr->isImplicitAccess()) { |
15562 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
15563 | DeclRefExpr *DRE = BuildDeclRefExpr( |
15564 | Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), |
15565 | MemExpr->getQualifierLoc(), Found.getDecl(), |
15566 | MemExpr->getTemplateKeywordLoc(), TemplateArgs); |
15567 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); |
15568 | return DRE; |
15569 | } else { |
15570 | SourceLocation Loc = MemExpr->getMemberLoc(); |
15571 | if (MemExpr->getQualifier()) |
15572 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); |
15573 | Base = |
15574 | BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); |
15575 | } |
15576 | } else |
15577 | Base = MemExpr->getBase(); |
15578 | |
15579 | ExprValueKind valueKind; |
15580 | QualType type; |
15581 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
15582 | valueKind = VK_LValue; |
15583 | type = Fn->getType(); |
15584 | } else { |
15585 | valueKind = VK_PRValue; |
15586 | type = Context.BoundMemberTy; |
15587 | } |
15588 | |
15589 | return BuildMemberExpr( |
15590 | Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), |
15591 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, |
15592 | /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), |
15593 | type, valueKind, OK_Ordinary, TemplateArgs); |
15594 | } |
15595 | |
15596 | llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function" , "clang/lib/Sema/SemaOverload.cpp", 15596); |
15597 | } |
15598 | |
15599 | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, |
15600 | DeclAccessPair Found, |
15601 | FunctionDecl *Fn) { |
15602 | return FixOverloadedFunctionReference(E.get(), Found, Fn); |
15603 | } |
15604 | |
15605 | bool clang::shouldEnforceArgLimit(bool PartialOverloading, |
15606 | FunctionDecl *Function) { |
15607 | if (!PartialOverloading || !Function) |
15608 | return true; |
15609 | if (Function->isVariadic()) |
15610 | return false; |
15611 | if (const auto *Proto = |
15612 | dyn_cast<FunctionProtoType>(Function->getFunctionType())) |
15613 | if (Proto->isTemplateVariadic()) |
15614 | return false; |
15615 | if (auto *Pattern = Function->getTemplateInstantiationPattern()) |
15616 | if (const auto *Proto = |
15617 | dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) |
15618 | if (Proto->isTemplateVariadic()) |
15619 | return false; |
15620 | return true; |
15621 | } |