File: | clang/lib/Sema/SemaOverload.cpp |
Warning: | line 12949, column 21 Although the value stored to 'RHS' is used in the enclosing expression, the value is never actually read from 'RHS' |
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/Sema/Overload.h" |
14 | #include "clang/AST/ASTContext.h" |
15 | #include "clang/AST/CXXInheritance.h" |
16 | #include "clang/AST/DeclObjC.h" |
17 | #include "clang/AST/Expr.h" |
18 | #include "clang/AST/ExprCXX.h" |
19 | #include "clang/AST/ExprObjC.h" |
20 | #include "clang/AST/TypeOrdering.h" |
21 | #include "clang/Basic/Diagnostic.h" |
22 | #include "clang/Basic/DiagnosticOptions.h" |
23 | #include "clang/Basic/PartialDiagnostic.h" |
24 | #include "clang/Basic/TargetInfo.h" |
25 | #include "clang/Sema/Initialization.h" |
26 | #include "clang/Sema/Lookup.h" |
27 | #include "clang/Sema/SemaInternal.h" |
28 | #include "clang/Sema/Template.h" |
29 | #include "clang/Sema/TemplateDeduction.h" |
30 | #include "llvm/ADT/DenseSet.h" |
31 | #include "llvm/ADT/Optional.h" |
32 | #include "llvm/ADT/STLExtras.h" |
33 | #include "llvm/ADT/SmallPtrSet.h" |
34 | #include "llvm/ADT/SmallString.h" |
35 | #include <algorithm> |
36 | #include <cstdlib> |
37 | |
38 | using namespace clang; |
39 | using namespace sema; |
40 | |
41 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { |
42 | return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { |
43 | return P->hasAttr<PassObjectSizeAttr>(); |
44 | }); |
45 | } |
46 | |
47 | /// A convenience routine for creating a decayed reference to a function. |
48 | static ExprResult |
49 | CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, |
50 | const Expr *Base, bool HadMultipleCandidates, |
51 | SourceLocation Loc = SourceLocation(), |
52 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ |
53 | if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) |
54 | return ExprError(); |
55 | // If FoundDecl is different from Fn (such as if one is a template |
56 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
57 | // called on both. |
58 | // FIXME: This would be more comprehensively addressed by modifying |
59 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
60 | // being used. |
61 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) |
62 | return ExprError(); |
63 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
64 | S.ResolveExceptionSpec(Loc, FPT); |
65 | DeclRefExpr *DRE = new (S.Context) |
66 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); |
67 | if (HadMultipleCandidates) |
68 | DRE->setHadMultipleCandidates(true); |
69 | |
70 | S.MarkDeclRefReferenced(DRE, Base); |
71 | return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), |
72 | CK_FunctionToPointerDecay); |
73 | } |
74 | |
75 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
76 | bool InOverloadResolution, |
77 | StandardConversionSequence &SCS, |
78 | bool CStyle, |
79 | bool AllowObjCWritebackConversion); |
80 | |
81 | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
82 | QualType &ToType, |
83 | bool InOverloadResolution, |
84 | StandardConversionSequence &SCS, |
85 | bool CStyle); |
86 | static OverloadingResult |
87 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
88 | UserDefinedConversionSequence& User, |
89 | OverloadCandidateSet& Conversions, |
90 | bool AllowExplicit, |
91 | bool AllowObjCConversionOnExplicit); |
92 | |
93 | |
94 | static ImplicitConversionSequence::CompareKind |
95 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
96 | const StandardConversionSequence& SCS1, |
97 | const StandardConversionSequence& SCS2); |
98 | |
99 | static ImplicitConversionSequence::CompareKind |
100 | CompareQualificationConversions(Sema &S, |
101 | const StandardConversionSequence& SCS1, |
102 | const StandardConversionSequence& SCS2); |
103 | |
104 | static ImplicitConversionSequence::CompareKind |
105 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
106 | const StandardConversionSequence& SCS1, |
107 | const StandardConversionSequence& SCS2); |
108 | |
109 | /// GetConversionRank - Retrieve the implicit conversion rank |
110 | /// corresponding to the given implicit conversion kind. |
111 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { |
112 | static const ImplicitConversionRank |
113 | Rank[(int)ICK_Num_Conversion_Kinds] = { |
114 | ICR_Exact_Match, |
115 | ICR_Exact_Match, |
116 | ICR_Exact_Match, |
117 | ICR_Exact_Match, |
118 | ICR_Exact_Match, |
119 | ICR_Exact_Match, |
120 | ICR_Promotion, |
121 | ICR_Promotion, |
122 | ICR_Promotion, |
123 | ICR_Conversion, |
124 | ICR_Conversion, |
125 | ICR_Conversion, |
126 | ICR_Conversion, |
127 | ICR_Conversion, |
128 | ICR_Conversion, |
129 | ICR_Conversion, |
130 | ICR_Conversion, |
131 | ICR_Conversion, |
132 | ICR_Conversion, |
133 | ICR_OCL_Scalar_Widening, |
134 | ICR_Complex_Real_Conversion, |
135 | ICR_Conversion, |
136 | ICR_Conversion, |
137 | ICR_Writeback_Conversion, |
138 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- |
139 | // it was omitted by the patch that added |
140 | // ICK_Zero_Event_Conversion |
141 | ICR_C_Conversion, |
142 | ICR_C_Conversion_Extension |
143 | }; |
144 | return Rank[(int)Kind]; |
145 | } |
146 | |
147 | /// GetImplicitConversionName - Return the name of this kind of |
148 | /// implicit conversion. |
149 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { |
150 | static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { |
151 | "No conversion", |
152 | "Lvalue-to-rvalue", |
153 | "Array-to-pointer", |
154 | "Function-to-pointer", |
155 | "Function pointer conversion", |
156 | "Qualification", |
157 | "Integral promotion", |
158 | "Floating point promotion", |
159 | "Complex promotion", |
160 | "Integral conversion", |
161 | "Floating conversion", |
162 | "Complex conversion", |
163 | "Floating-integral conversion", |
164 | "Pointer conversion", |
165 | "Pointer-to-member conversion", |
166 | "Boolean conversion", |
167 | "Compatible-types conversion", |
168 | "Derived-to-base conversion", |
169 | "Vector conversion", |
170 | "Vector splat", |
171 | "Complex-real conversion", |
172 | "Block Pointer conversion", |
173 | "Transparent Union Conversion", |
174 | "Writeback conversion", |
175 | "OpenCL Zero Event Conversion", |
176 | "C specific type conversion", |
177 | "Incompatible pointer conversion" |
178 | }; |
179 | return Name[Kind]; |
180 | } |
181 | |
182 | /// StandardConversionSequence - Set the standard conversion |
183 | /// sequence to the identity conversion. |
184 | void StandardConversionSequence::setAsIdentityConversion() { |
185 | First = ICK_Identity; |
186 | Second = ICK_Identity; |
187 | Third = ICK_Identity; |
188 | DeprecatedStringLiteralToCharPtr = false; |
189 | QualificationIncludesObjCLifetime = false; |
190 | ReferenceBinding = false; |
191 | DirectBinding = false; |
192 | IsLvalueReference = true; |
193 | BindsToFunctionLvalue = false; |
194 | BindsToRvalue = false; |
195 | BindsImplicitObjectArgumentWithoutRefQualifier = false; |
196 | ObjCLifetimeConversionBinding = false; |
197 | CopyConstructor = nullptr; |
198 | } |
199 | |
200 | /// getRank - Retrieve the rank of this standard conversion sequence |
201 | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the |
202 | /// implicit conversions. |
203 | ImplicitConversionRank StandardConversionSequence::getRank() const { |
204 | ImplicitConversionRank Rank = ICR_Exact_Match; |
205 | if (GetConversionRank(First) > Rank) |
206 | Rank = GetConversionRank(First); |
207 | if (GetConversionRank(Second) > Rank) |
208 | Rank = GetConversionRank(Second); |
209 | if (GetConversionRank(Third) > Rank) |
210 | Rank = GetConversionRank(Third); |
211 | return Rank; |
212 | } |
213 | |
214 | /// isPointerConversionToBool - Determines whether this conversion is |
215 | /// a conversion of a pointer or pointer-to-member to bool. This is |
216 | /// used as part of the ranking of standard conversion sequences |
217 | /// (C++ 13.3.3.2p4). |
218 | bool StandardConversionSequence::isPointerConversionToBool() const { |
219 | // Note that FromType has not necessarily been transformed by the |
220 | // array-to-pointer or function-to-pointer implicit conversions, so |
221 | // check for their presence as well as checking whether FromType is |
222 | // a pointer. |
223 | if (getToType(1)->isBooleanType() && |
224 | (getFromType()->isPointerType() || |
225 | getFromType()->isMemberPointerType() || |
226 | getFromType()->isObjCObjectPointerType() || |
227 | getFromType()->isBlockPointerType() || |
228 | getFromType()->isNullPtrType() || |
229 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) |
230 | return true; |
231 | |
232 | return false; |
233 | } |
234 | |
235 | /// isPointerConversionToVoidPointer - Determines whether this |
236 | /// conversion is a conversion of a pointer to a void pointer. This is |
237 | /// used as part of the ranking of standard conversion sequences (C++ |
238 | /// 13.3.3.2p4). |
239 | bool |
240 | StandardConversionSequence:: |
241 | isPointerConversionToVoidPointer(ASTContext& Context) const { |
242 | QualType FromType = getFromType(); |
243 | QualType ToType = getToType(1); |
244 | |
245 | // Note that FromType has not necessarily been transformed by the |
246 | // array-to-pointer implicit conversion, so check for its presence |
247 | // and redo the conversion to get a pointer. |
248 | if (First == ICK_Array_To_Pointer) |
249 | FromType = Context.getArrayDecayedType(FromType); |
250 | |
251 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) |
252 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) |
253 | return ToPtrType->getPointeeType()->isVoidType(); |
254 | |
255 | return false; |
256 | } |
257 | |
258 | /// Skip any implicit casts which could be either part of a narrowing conversion |
259 | /// or after one in an implicit conversion. |
260 | static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, |
261 | const Expr *Converted) { |
262 | // We can have cleanups wrapping the converted expression; these need to be |
263 | // preserved so that destructors run if necessary. |
264 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { |
265 | Expr *Inner = |
266 | const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); |
267 | return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), |
268 | EWC->getObjects()); |
269 | } |
270 | |
271 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { |
272 | switch (ICE->getCastKind()) { |
273 | case CK_NoOp: |
274 | case CK_IntegralCast: |
275 | case CK_IntegralToBoolean: |
276 | case CK_IntegralToFloating: |
277 | case CK_BooleanToSignedIntegral: |
278 | case CK_FloatingToIntegral: |
279 | case CK_FloatingToBoolean: |
280 | case CK_FloatingCast: |
281 | Converted = ICE->getSubExpr(); |
282 | continue; |
283 | |
284 | default: |
285 | return Converted; |
286 | } |
287 | } |
288 | |
289 | return Converted; |
290 | } |
291 | |
292 | /// Check if this standard conversion sequence represents a narrowing |
293 | /// conversion, according to C++11 [dcl.init.list]p7. |
294 | /// |
295 | /// \param Ctx The AST context. |
296 | /// \param Converted The result of applying this standard conversion sequence. |
297 | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the |
298 | /// value of the expression prior to the narrowing conversion. |
299 | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the |
300 | /// type of the expression prior to the narrowing conversion. |
301 | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions |
302 | /// from floating point types to integral types should be ignored. |
303 | NarrowingKind StandardConversionSequence::getNarrowingKind( |
304 | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, |
305 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { |
306 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++" ) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 306, __PRETTY_FUNCTION__)); |
307 | |
308 | // C++11 [dcl.init.list]p7: |
309 | // A narrowing conversion is an implicit conversion ... |
310 | QualType FromType = getToType(0); |
311 | QualType ToType = getToType(1); |
312 | |
313 | // A conversion to an enumeration type is narrowing if the conversion to |
314 | // the underlying type is narrowing. This only arises for expressions of |
315 | // the form 'Enum{init}'. |
316 | if (auto *ET = ToType->getAs<EnumType>()) |
317 | ToType = ET->getDecl()->getIntegerType(); |
318 | |
319 | switch (Second) { |
320 | // 'bool' is an integral type; dispatch to the right place to handle it. |
321 | case ICK_Boolean_Conversion: |
322 | if (FromType->isRealFloatingType()) |
323 | goto FloatingIntegralConversion; |
324 | if (FromType->isIntegralOrUnscopedEnumerationType()) |
325 | goto IntegralConversion; |
326 | // Boolean conversions can be from pointers and pointers to members |
327 | // [conv.bool], and those aren't considered narrowing conversions. |
328 | return NK_Not_Narrowing; |
329 | |
330 | // -- from a floating-point type to an integer type, or |
331 | // |
332 | // -- from an integer type or unscoped enumeration type to a floating-point |
333 | // type, except where the source is a constant expression and the actual |
334 | // value after conversion will fit into the target type and will produce |
335 | // the original value when converted back to the original type, or |
336 | case ICK_Floating_Integral: |
337 | FloatingIntegralConversion: |
338 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { |
339 | return NK_Type_Narrowing; |
340 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
341 | ToType->isRealFloatingType()) { |
342 | if (IgnoreFloatToIntegralConversion) |
343 | return NK_Not_Narrowing; |
344 | llvm::APSInt IntConstantValue; |
345 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
346 | assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast <void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 346, __PRETTY_FUNCTION__)); |
347 | |
348 | // If it's value-dependent, we can't tell whether it's narrowing. |
349 | if (Initializer->isValueDependent()) |
350 | return NK_Dependent_Narrowing; |
351 | |
352 | if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { |
353 | // Convert the integer to the floating type. |
354 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); |
355 | Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), |
356 | llvm::APFloat::rmNearestTiesToEven); |
357 | // And back. |
358 | llvm::APSInt ConvertedValue = IntConstantValue; |
359 | bool ignored; |
360 | Result.convertToInteger(ConvertedValue, |
361 | llvm::APFloat::rmTowardZero, &ignored); |
362 | // If the resulting value is different, this was a narrowing conversion. |
363 | if (IntConstantValue != ConvertedValue) { |
364 | ConstantValue = APValue(IntConstantValue); |
365 | ConstantType = Initializer->getType(); |
366 | return NK_Constant_Narrowing; |
367 | } |
368 | } else { |
369 | // Variables are always narrowings. |
370 | return NK_Variable_Narrowing; |
371 | } |
372 | } |
373 | return NK_Not_Narrowing; |
374 | |
375 | // -- from long double to double or float, or from double to float, except |
376 | // where the source is a constant expression and the actual value after |
377 | // conversion is within the range of values that can be represented (even |
378 | // if it cannot be represented exactly), or |
379 | case ICK_Floating_Conversion: |
380 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && |
381 | Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { |
382 | // FromType is larger than ToType. |
383 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
384 | |
385 | // If it's value-dependent, we can't tell whether it's narrowing. |
386 | if (Initializer->isValueDependent()) |
387 | return NK_Dependent_Narrowing; |
388 | |
389 | if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { |
390 | // Constant! |
391 | assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail ("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 391, __PRETTY_FUNCTION__)); |
392 | llvm::APFloat FloatVal = ConstantValue.getFloat(); |
393 | // Convert the source value into the target type. |
394 | bool ignored; |
395 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( |
396 | Ctx.getFloatTypeSemantics(ToType), |
397 | llvm::APFloat::rmNearestTiesToEven, &ignored); |
398 | // If there was no overflow, the source value is within the range of |
399 | // values that can be represented. |
400 | if (ConvertStatus & llvm::APFloat::opOverflow) { |
401 | ConstantType = Initializer->getType(); |
402 | return NK_Constant_Narrowing; |
403 | } |
404 | } else { |
405 | return NK_Variable_Narrowing; |
406 | } |
407 | } |
408 | return NK_Not_Narrowing; |
409 | |
410 | // -- from an integer type or unscoped enumeration type to an integer type |
411 | // that cannot represent all the values of the original type, except where |
412 | // the source is a constant expression and the actual value after |
413 | // conversion will fit into the target type and will produce the original |
414 | // value when converted back to the original type. |
415 | case ICK_Integral_Conversion: |
416 | IntegralConversion: { |
417 | assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast <void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 417, __PRETTY_FUNCTION__)); |
418 | assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast <void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 418, __PRETTY_FUNCTION__)); |
419 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); |
420 | const unsigned FromWidth = Ctx.getIntWidth(FromType); |
421 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); |
422 | const unsigned ToWidth = Ctx.getIntWidth(ToType); |
423 | |
424 | if (FromWidth > ToWidth || |
425 | (FromWidth == ToWidth && FromSigned != ToSigned) || |
426 | (FromSigned && !ToSigned)) { |
427 | // Not all values of FromType can be represented in ToType. |
428 | llvm::APSInt InitializerValue; |
429 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
430 | |
431 | // If it's value-dependent, we can't tell whether it's narrowing. |
432 | if (Initializer->isValueDependent()) |
433 | return NK_Dependent_Narrowing; |
434 | |
435 | if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { |
436 | // Such conversions on variables are always narrowing. |
437 | return NK_Variable_Narrowing; |
438 | } |
439 | bool Narrowing = false; |
440 | if (FromWidth < ToWidth) { |
441 | // Negative -> unsigned is narrowing. Otherwise, more bits is never |
442 | // narrowing. |
443 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) |
444 | Narrowing = true; |
445 | } else { |
446 | // Add a bit to the InitializerValue so we don't have to worry about |
447 | // signed vs. unsigned comparisons. |
448 | InitializerValue = InitializerValue.extend( |
449 | InitializerValue.getBitWidth() + 1); |
450 | // Convert the initializer to and from the target width and signed-ness. |
451 | llvm::APSInt ConvertedValue = InitializerValue; |
452 | ConvertedValue = ConvertedValue.trunc(ToWidth); |
453 | ConvertedValue.setIsSigned(ToSigned); |
454 | ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); |
455 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); |
456 | // If the result is different, this was a narrowing conversion. |
457 | if (ConvertedValue != InitializerValue) |
458 | Narrowing = true; |
459 | } |
460 | if (Narrowing) { |
461 | ConstantType = Initializer->getType(); |
462 | ConstantValue = APValue(InitializerValue); |
463 | return NK_Constant_Narrowing; |
464 | } |
465 | } |
466 | return NK_Not_Narrowing; |
467 | } |
468 | |
469 | default: |
470 | // Other kinds of conversions are not narrowings. |
471 | return NK_Not_Narrowing; |
472 | } |
473 | } |
474 | |
475 | /// dump - Print this standard conversion sequence to standard |
476 | /// error. Useful for debugging overloading issues. |
477 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const { |
478 | raw_ostream &OS = llvm::errs(); |
479 | bool PrintedSomething = false; |
480 | if (First != ICK_Identity) { |
481 | OS << GetImplicitConversionName(First); |
482 | PrintedSomething = true; |
483 | } |
484 | |
485 | if (Second != ICK_Identity) { |
486 | if (PrintedSomething) { |
487 | OS << " -> "; |
488 | } |
489 | OS << GetImplicitConversionName(Second); |
490 | |
491 | if (CopyConstructor) { |
492 | OS << " (by copy constructor)"; |
493 | } else if (DirectBinding) { |
494 | OS << " (direct reference binding)"; |
495 | } else if (ReferenceBinding) { |
496 | OS << " (reference binding)"; |
497 | } |
498 | PrintedSomething = true; |
499 | } |
500 | |
501 | if (Third != ICK_Identity) { |
502 | if (PrintedSomething) { |
503 | OS << " -> "; |
504 | } |
505 | OS << GetImplicitConversionName(Third); |
506 | PrintedSomething = true; |
507 | } |
508 | |
509 | if (!PrintedSomething) { |
510 | OS << "No conversions required"; |
511 | } |
512 | } |
513 | |
514 | /// dump - Print this user-defined conversion sequence to standard |
515 | /// error. Useful for debugging overloading issues. |
516 | void UserDefinedConversionSequence::dump() const { |
517 | raw_ostream &OS = llvm::errs(); |
518 | if (Before.First || Before.Second || Before.Third) { |
519 | Before.dump(); |
520 | OS << " -> "; |
521 | } |
522 | if (ConversionFunction) |
523 | OS << '\'' << *ConversionFunction << '\''; |
524 | else |
525 | OS << "aggregate initialization"; |
526 | if (After.First || After.Second || After.Third) { |
527 | OS << " -> "; |
528 | After.dump(); |
529 | } |
530 | } |
531 | |
532 | /// dump - Print this implicit conversion sequence to standard |
533 | /// error. Useful for debugging overloading issues. |
534 | void ImplicitConversionSequence::dump() const { |
535 | raw_ostream &OS = llvm::errs(); |
536 | if (isStdInitializerListElement()) |
537 | OS << "Worst std::initializer_list element conversion: "; |
538 | switch (ConversionKind) { |
539 | case StandardConversion: |
540 | OS << "Standard conversion: "; |
541 | Standard.dump(); |
542 | break; |
543 | case UserDefinedConversion: |
544 | OS << "User-defined conversion: "; |
545 | UserDefined.dump(); |
546 | break; |
547 | case EllipsisConversion: |
548 | OS << "Ellipsis conversion"; |
549 | break; |
550 | case AmbiguousConversion: |
551 | OS << "Ambiguous conversion"; |
552 | break; |
553 | case BadConversion: |
554 | OS << "Bad conversion"; |
555 | break; |
556 | } |
557 | |
558 | OS << "\n"; |
559 | } |
560 | |
561 | void AmbiguousConversionSequence::construct() { |
562 | new (&conversions()) ConversionSet(); |
563 | } |
564 | |
565 | void AmbiguousConversionSequence::destruct() { |
566 | conversions().~ConversionSet(); |
567 | } |
568 | |
569 | void |
570 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { |
571 | FromTypePtr = O.FromTypePtr; |
572 | ToTypePtr = O.ToTypePtr; |
573 | new (&conversions()) ConversionSet(O.conversions()); |
574 | } |
575 | |
576 | namespace { |
577 | // Structure used by DeductionFailureInfo to store |
578 | // template argument information. |
579 | struct DFIArguments { |
580 | TemplateArgument FirstArg; |
581 | TemplateArgument SecondArg; |
582 | }; |
583 | // Structure used by DeductionFailureInfo to store |
584 | // template parameter and template argument information. |
585 | struct DFIParamWithArguments : DFIArguments { |
586 | TemplateParameter Param; |
587 | }; |
588 | // Structure used by DeductionFailureInfo to store template argument |
589 | // information and the index of the problematic call argument. |
590 | struct DFIDeducedMismatchArgs : DFIArguments { |
591 | TemplateArgumentList *TemplateArgs; |
592 | unsigned CallArgIndex; |
593 | }; |
594 | } |
595 | |
596 | /// Convert from Sema's representation of template deduction information |
597 | /// to the form used in overload-candidate information. |
598 | DeductionFailureInfo |
599 | clang::MakeDeductionFailureInfo(ASTContext &Context, |
600 | Sema::TemplateDeductionResult TDK, |
601 | TemplateDeductionInfo &Info) { |
602 | DeductionFailureInfo Result; |
603 | Result.Result = static_cast<unsigned>(TDK); |
604 | Result.HasDiagnostic = false; |
605 | switch (TDK) { |
606 | case Sema::TDK_Invalid: |
607 | case Sema::TDK_InstantiationDepth: |
608 | case Sema::TDK_TooManyArguments: |
609 | case Sema::TDK_TooFewArguments: |
610 | case Sema::TDK_MiscellaneousDeductionFailure: |
611 | case Sema::TDK_CUDATargetMismatch: |
612 | Result.Data = nullptr; |
613 | break; |
614 | |
615 | case Sema::TDK_Incomplete: |
616 | case Sema::TDK_InvalidExplicitArguments: |
617 | Result.Data = Info.Param.getOpaqueValue(); |
618 | break; |
619 | |
620 | case Sema::TDK_DeducedMismatch: |
621 | case Sema::TDK_DeducedMismatchNested: { |
622 | // FIXME: Should allocate from normal heap so that we can free this later. |
623 | auto *Saved = new (Context) DFIDeducedMismatchArgs; |
624 | Saved->FirstArg = Info.FirstArg; |
625 | Saved->SecondArg = Info.SecondArg; |
626 | Saved->TemplateArgs = Info.take(); |
627 | Saved->CallArgIndex = Info.CallArgIndex; |
628 | Result.Data = Saved; |
629 | break; |
630 | } |
631 | |
632 | case Sema::TDK_NonDeducedMismatch: { |
633 | // FIXME: Should allocate from normal heap so that we can free this later. |
634 | DFIArguments *Saved = new (Context) DFIArguments; |
635 | Saved->FirstArg = Info.FirstArg; |
636 | Saved->SecondArg = Info.SecondArg; |
637 | Result.Data = Saved; |
638 | break; |
639 | } |
640 | |
641 | case Sema::TDK_IncompletePack: |
642 | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. |
643 | case Sema::TDK_Inconsistent: |
644 | case Sema::TDK_Underqualified: { |
645 | // FIXME: Should allocate from normal heap so that we can free this later. |
646 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; |
647 | Saved->Param = Info.Param; |
648 | Saved->FirstArg = Info.FirstArg; |
649 | Saved->SecondArg = Info.SecondArg; |
650 | Result.Data = Saved; |
651 | break; |
652 | } |
653 | |
654 | case Sema::TDK_SubstitutionFailure: |
655 | Result.Data = Info.take(); |
656 | if (Info.hasSFINAEDiagnostic()) { |
657 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( |
658 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); |
659 | Info.takeSFINAEDiagnostic(*Diag); |
660 | Result.HasDiagnostic = true; |
661 | } |
662 | break; |
663 | |
664 | case Sema::TDK_Success: |
665 | case Sema::TDK_NonDependentConversionFailure: |
666 | llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 666); |
667 | } |
668 | |
669 | return Result; |
670 | } |
671 | |
672 | void DeductionFailureInfo::Destroy() { |
673 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
674 | case Sema::TDK_Success: |
675 | case Sema::TDK_Invalid: |
676 | case Sema::TDK_InstantiationDepth: |
677 | case Sema::TDK_Incomplete: |
678 | case Sema::TDK_TooManyArguments: |
679 | case Sema::TDK_TooFewArguments: |
680 | case Sema::TDK_InvalidExplicitArguments: |
681 | case Sema::TDK_CUDATargetMismatch: |
682 | case Sema::TDK_NonDependentConversionFailure: |
683 | break; |
684 | |
685 | case Sema::TDK_IncompletePack: |
686 | case Sema::TDK_Inconsistent: |
687 | case Sema::TDK_Underqualified: |
688 | case Sema::TDK_DeducedMismatch: |
689 | case Sema::TDK_DeducedMismatchNested: |
690 | case Sema::TDK_NonDeducedMismatch: |
691 | // FIXME: Destroy the data? |
692 | Data = nullptr; |
693 | break; |
694 | |
695 | case Sema::TDK_SubstitutionFailure: |
696 | // FIXME: Destroy the template argument list? |
697 | Data = nullptr; |
698 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
699 | Diag->~PartialDiagnosticAt(); |
700 | HasDiagnostic = false; |
701 | } |
702 | break; |
703 | |
704 | // Unhandled |
705 | case Sema::TDK_MiscellaneousDeductionFailure: |
706 | break; |
707 | } |
708 | } |
709 | |
710 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { |
711 | if (HasDiagnostic) |
712 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); |
713 | return nullptr; |
714 | } |
715 | |
716 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { |
717 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
718 | case Sema::TDK_Success: |
719 | case Sema::TDK_Invalid: |
720 | case Sema::TDK_InstantiationDepth: |
721 | case Sema::TDK_TooManyArguments: |
722 | case Sema::TDK_TooFewArguments: |
723 | case Sema::TDK_SubstitutionFailure: |
724 | case Sema::TDK_DeducedMismatch: |
725 | case Sema::TDK_DeducedMismatchNested: |
726 | case Sema::TDK_NonDeducedMismatch: |
727 | case Sema::TDK_CUDATargetMismatch: |
728 | case Sema::TDK_NonDependentConversionFailure: |
729 | return TemplateParameter(); |
730 | |
731 | case Sema::TDK_Incomplete: |
732 | case Sema::TDK_InvalidExplicitArguments: |
733 | return TemplateParameter::getFromOpaqueValue(Data); |
734 | |
735 | case Sema::TDK_IncompletePack: |
736 | case Sema::TDK_Inconsistent: |
737 | case Sema::TDK_Underqualified: |
738 | return static_cast<DFIParamWithArguments*>(Data)->Param; |
739 | |
740 | // Unhandled |
741 | case Sema::TDK_MiscellaneousDeductionFailure: |
742 | break; |
743 | } |
744 | |
745 | return TemplateParameter(); |
746 | } |
747 | |
748 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { |
749 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
750 | case Sema::TDK_Success: |
751 | case Sema::TDK_Invalid: |
752 | case Sema::TDK_InstantiationDepth: |
753 | case Sema::TDK_TooManyArguments: |
754 | case Sema::TDK_TooFewArguments: |
755 | case Sema::TDK_Incomplete: |
756 | case Sema::TDK_IncompletePack: |
757 | case Sema::TDK_InvalidExplicitArguments: |
758 | case Sema::TDK_Inconsistent: |
759 | case Sema::TDK_Underqualified: |
760 | case Sema::TDK_NonDeducedMismatch: |
761 | case Sema::TDK_CUDATargetMismatch: |
762 | case Sema::TDK_NonDependentConversionFailure: |
763 | return nullptr; |
764 | |
765 | case Sema::TDK_DeducedMismatch: |
766 | case Sema::TDK_DeducedMismatchNested: |
767 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; |
768 | |
769 | case Sema::TDK_SubstitutionFailure: |
770 | return static_cast<TemplateArgumentList*>(Data); |
771 | |
772 | // Unhandled |
773 | case Sema::TDK_MiscellaneousDeductionFailure: |
774 | break; |
775 | } |
776 | |
777 | return nullptr; |
778 | } |
779 | |
780 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { |
781 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
782 | case Sema::TDK_Success: |
783 | case Sema::TDK_Invalid: |
784 | case Sema::TDK_InstantiationDepth: |
785 | case Sema::TDK_Incomplete: |
786 | case Sema::TDK_TooManyArguments: |
787 | case Sema::TDK_TooFewArguments: |
788 | case Sema::TDK_InvalidExplicitArguments: |
789 | case Sema::TDK_SubstitutionFailure: |
790 | case Sema::TDK_CUDATargetMismatch: |
791 | case Sema::TDK_NonDependentConversionFailure: |
792 | return nullptr; |
793 | |
794 | case Sema::TDK_IncompletePack: |
795 | case Sema::TDK_Inconsistent: |
796 | case Sema::TDK_Underqualified: |
797 | case Sema::TDK_DeducedMismatch: |
798 | case Sema::TDK_DeducedMismatchNested: |
799 | case Sema::TDK_NonDeducedMismatch: |
800 | return &static_cast<DFIArguments*>(Data)->FirstArg; |
801 | |
802 | // Unhandled |
803 | case Sema::TDK_MiscellaneousDeductionFailure: |
804 | break; |
805 | } |
806 | |
807 | return nullptr; |
808 | } |
809 | |
810 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { |
811 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
812 | case Sema::TDK_Success: |
813 | case Sema::TDK_Invalid: |
814 | case Sema::TDK_InstantiationDepth: |
815 | case Sema::TDK_Incomplete: |
816 | case Sema::TDK_IncompletePack: |
817 | case Sema::TDK_TooManyArguments: |
818 | case Sema::TDK_TooFewArguments: |
819 | case Sema::TDK_InvalidExplicitArguments: |
820 | case Sema::TDK_SubstitutionFailure: |
821 | case Sema::TDK_CUDATargetMismatch: |
822 | case Sema::TDK_NonDependentConversionFailure: |
823 | return nullptr; |
824 | |
825 | case Sema::TDK_Inconsistent: |
826 | case Sema::TDK_Underqualified: |
827 | case Sema::TDK_DeducedMismatch: |
828 | case Sema::TDK_DeducedMismatchNested: |
829 | case Sema::TDK_NonDeducedMismatch: |
830 | return &static_cast<DFIArguments*>(Data)->SecondArg; |
831 | |
832 | // Unhandled |
833 | case Sema::TDK_MiscellaneousDeductionFailure: |
834 | break; |
835 | } |
836 | |
837 | return nullptr; |
838 | } |
839 | |
840 | llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { |
841 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
842 | case Sema::TDK_DeducedMismatch: |
843 | case Sema::TDK_DeducedMismatchNested: |
844 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; |
845 | |
846 | default: |
847 | return llvm::None; |
848 | } |
849 | } |
850 | |
851 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( |
852 | OverloadedOperatorKind Op) { |
853 | if (!AllowRewrittenCandidates) |
854 | return false; |
855 | return Op == OO_EqualEqual || Op == OO_Spaceship; |
856 | } |
857 | |
858 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( |
859 | ASTContext &Ctx, const FunctionDecl *FD) { |
860 | if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) |
861 | return false; |
862 | // Don't bother adding a reversed candidate that can never be a better |
863 | // match than the non-reversed version. |
864 | return FD->getNumParams() != 2 || |
865 | !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), |
866 | FD->getParamDecl(1)->getType()) || |
867 | FD->hasAttr<EnableIfAttr>(); |
868 | } |
869 | |
870 | void OverloadCandidateSet::destroyCandidates() { |
871 | for (iterator i = begin(), e = end(); i != e; ++i) { |
872 | for (auto &C : i->Conversions) |
873 | C.~ImplicitConversionSequence(); |
874 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) |
875 | i->DeductionFailure.Destroy(); |
876 | } |
877 | } |
878 | |
879 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { |
880 | destroyCandidates(); |
881 | SlabAllocator.Reset(); |
882 | NumInlineBytesUsed = 0; |
883 | Candidates.clear(); |
884 | Functions.clear(); |
885 | Kind = CSK; |
886 | } |
887 | |
888 | namespace { |
889 | class UnbridgedCastsSet { |
890 | struct Entry { |
891 | Expr **Addr; |
892 | Expr *Saved; |
893 | }; |
894 | SmallVector<Entry, 2> Entries; |
895 | |
896 | public: |
897 | void save(Sema &S, Expr *&E) { |
898 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast <void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 898, __PRETTY_FUNCTION__)); |
899 | Entry entry = { &E, E }; |
900 | Entries.push_back(entry); |
901 | E = S.stripARCUnbridgedCast(E); |
902 | } |
903 | |
904 | void restore() { |
905 | for (SmallVectorImpl<Entry>::iterator |
906 | i = Entries.begin(), e = Entries.end(); i != e; ++i) |
907 | *i->Addr = i->Saved; |
908 | } |
909 | }; |
910 | } |
911 | |
912 | /// checkPlaceholderForOverload - Do any interesting placeholder-like |
913 | /// preprocessing on the given expression. |
914 | /// |
915 | /// \param unbridgedCasts a collection to which to add unbridged casts; |
916 | /// without this, they will be immediately diagnosed as errors |
917 | /// |
918 | /// Return true on unrecoverable error. |
919 | static bool |
920 | checkPlaceholderForOverload(Sema &S, Expr *&E, |
921 | UnbridgedCastsSet *unbridgedCasts = nullptr) { |
922 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { |
923 | // We can't handle overloaded expressions here because overload |
924 | // resolution might reasonably tweak them. |
925 | if (placeholder->getKind() == BuiltinType::Overload) return false; |
926 | |
927 | // If the context potentially accepts unbridged ARC casts, strip |
928 | // the unbridged cast and add it to the collection for later restoration. |
929 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && |
930 | unbridgedCasts) { |
931 | unbridgedCasts->save(S, E); |
932 | return false; |
933 | } |
934 | |
935 | // Go ahead and check everything else. |
936 | ExprResult result = S.CheckPlaceholderExpr(E); |
937 | if (result.isInvalid()) |
938 | return true; |
939 | |
940 | E = result.get(); |
941 | return false; |
942 | } |
943 | |
944 | // Nothing to do. |
945 | return false; |
946 | } |
947 | |
948 | /// checkArgPlaceholdersForOverload - Check a set of call operands for |
949 | /// placeholders. |
950 | static bool checkArgPlaceholdersForOverload(Sema &S, |
951 | MultiExprArg Args, |
952 | UnbridgedCastsSet &unbridged) { |
953 | for (unsigned i = 0, e = Args.size(); i != e; ++i) |
954 | if (checkPlaceholderForOverload(S, Args[i], &unbridged)) |
955 | return true; |
956 | |
957 | return false; |
958 | } |
959 | |
960 | /// Determine whether the given New declaration is an overload of the |
961 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if |
962 | /// New and Old cannot be overloaded, e.g., if New has the same signature as |
963 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't |
964 | /// functions (or function templates) at all. When it does return Ovl_Match or |
965 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be |
966 | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying |
967 | /// declaration. |
968 | /// |
969 | /// Example: Given the following input: |
970 | /// |
971 | /// void f(int, float); // #1 |
972 | /// void f(int, int); // #2 |
973 | /// int f(int, int); // #3 |
974 | /// |
975 | /// When we process #1, there is no previous declaration of "f", so IsOverload |
976 | /// will not be used. |
977 | /// |
978 | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing |
979 | /// the parameter types, we see that #1 and #2 are overloaded (since they have |
980 | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is |
981 | /// unchanged. |
982 | /// |
983 | /// When we process #3, Old is an overload set containing #1 and #2. We compare |
984 | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then |
985 | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of |
986 | /// functions are not part of the signature), IsOverload returns Ovl_Match and |
987 | /// MatchedDecl will be set to point to the FunctionDecl for #2. |
988 | /// |
989 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class |
990 | /// by a using declaration. The rules for whether to hide shadow declarations |
991 | /// ignore some properties which otherwise figure into a function template's |
992 | /// signature. |
993 | Sema::OverloadKind |
994 | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, |
995 | NamedDecl *&Match, bool NewIsUsingDecl) { |
996 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); |
997 | I != E; ++I) { |
998 | NamedDecl *OldD = *I; |
999 | |
1000 | bool OldIsUsingDecl = false; |
1001 | if (isa<UsingShadowDecl>(OldD)) { |
1002 | OldIsUsingDecl = true; |
1003 | |
1004 | // We can always introduce two using declarations into the same |
1005 | // context, even if they have identical signatures. |
1006 | if (NewIsUsingDecl) continue; |
1007 | |
1008 | OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); |
1009 | } |
1010 | |
1011 | // A using-declaration does not conflict with another declaration |
1012 | // if one of them is hidden. |
1013 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) |
1014 | continue; |
1015 | |
1016 | // If either declaration was introduced by a using declaration, |
1017 | // we'll need to use slightly different rules for matching. |
1018 | // Essentially, these rules are the normal rules, except that |
1019 | // function templates hide function templates with different |
1020 | // return types or template parameter lists. |
1021 | bool UseMemberUsingDeclRules = |
1022 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && |
1023 | !New->getFriendObjectKind(); |
1024 | |
1025 | if (FunctionDecl *OldF = OldD->getAsFunction()) { |
1026 | if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { |
1027 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { |
1028 | HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); |
1029 | continue; |
1030 | } |
1031 | |
1032 | if (!isa<FunctionTemplateDecl>(OldD) && |
1033 | !shouldLinkPossiblyHiddenDecl(*I, New)) |
1034 | continue; |
1035 | |
1036 | Match = *I; |
1037 | return Ovl_Match; |
1038 | } |
1039 | |
1040 | // Builtins that have custom typechecking or have a reference should |
1041 | // not be overloadable or redeclarable. |
1042 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { |
1043 | Match = *I; |
1044 | return Ovl_NonFunction; |
1045 | } |
1046 | } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { |
1047 | // We can overload with these, which can show up when doing |
1048 | // redeclaration checks for UsingDecls. |
1049 | assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast< void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1049, __PRETTY_FUNCTION__)); |
1050 | } else if (isa<TagDecl>(OldD)) { |
1051 | // We can always overload with tags by hiding them. |
1052 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { |
1053 | // Optimistically assume that an unresolved using decl will |
1054 | // overload; if it doesn't, we'll have to diagnose during |
1055 | // template instantiation. |
1056 | // |
1057 | // Exception: if the scope is dependent and this is not a class |
1058 | // member, the using declaration can only introduce an enumerator. |
1059 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { |
1060 | Match = *I; |
1061 | return Ovl_NonFunction; |
1062 | } |
1063 | } else { |
1064 | // (C++ 13p1): |
1065 | // Only function declarations can be overloaded; object and type |
1066 | // declarations cannot be overloaded. |
1067 | Match = *I; |
1068 | return Ovl_NonFunction; |
1069 | } |
1070 | } |
1071 | |
1072 | // C++ [temp.friend]p1: |
1073 | // For a friend function declaration that is not a template declaration: |
1074 | // -- if the name of the friend is a qualified or unqualified template-id, |
1075 | // [...], otherwise |
1076 | // -- if the name of the friend is a qualified-id and a matching |
1077 | // non-template function is found in the specified class or namespace, |
1078 | // the friend declaration refers to that function, otherwise, |
1079 | // -- if the name of the friend is a qualified-id and a matching function |
1080 | // template is found in the specified class or namespace, the friend |
1081 | // declaration refers to the deduced specialization of that function |
1082 | // template, otherwise |
1083 | // -- the name shall be an unqualified-id [...] |
1084 | // If we get here for a qualified friend declaration, we've just reached the |
1085 | // third bullet. If the type of the friend is dependent, skip this lookup |
1086 | // until instantiation. |
1087 | if (New->getFriendObjectKind() && New->getQualifier() && |
1088 | !New->getDescribedFunctionTemplate() && |
1089 | !New->getDependentSpecializationInfo() && |
1090 | !New->getType()->isDependentType()) { |
1091 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); |
1092 | TemplateSpecResult.addAllDecls(Old); |
1093 | if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, |
1094 | /*QualifiedFriend*/true)) { |
1095 | New->setInvalidDecl(); |
1096 | return Ovl_Overload; |
1097 | } |
1098 | |
1099 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); |
1100 | return Ovl_Match; |
1101 | } |
1102 | |
1103 | return Ovl_Overload; |
1104 | } |
1105 | |
1106 | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, |
1107 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { |
1108 | // C++ [basic.start.main]p2: This function shall not be overloaded. |
1109 | if (New->isMain()) |
1110 | return false; |
1111 | |
1112 | // MSVCRT user defined entry points cannot be overloaded. |
1113 | if (New->isMSVCRTEntryPoint()) |
1114 | return false; |
1115 | |
1116 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); |
1117 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); |
1118 | |
1119 | // C++ [temp.fct]p2: |
1120 | // A function template can be overloaded with other function templates |
1121 | // and with normal (non-template) functions. |
1122 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) |
1123 | return true; |
1124 | |
1125 | // Is the function New an overload of the function Old? |
1126 | QualType OldQType = Context.getCanonicalType(Old->getType()); |
1127 | QualType NewQType = Context.getCanonicalType(New->getType()); |
1128 | |
1129 | // Compare the signatures (C++ 1.3.10) of the two functions to |
1130 | // determine whether they are overloads. If we find any mismatch |
1131 | // in the signature, they are overloads. |
1132 | |
1133 | // If either of these functions is a K&R-style function (no |
1134 | // prototype), then we consider them to have matching signatures. |
1135 | if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || |
1136 | isa<FunctionNoProtoType>(NewQType.getTypePtr())) |
1137 | return false; |
1138 | |
1139 | const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); |
1140 | const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); |
1141 | |
1142 | // The signature of a function includes the types of its |
1143 | // parameters (C++ 1.3.10), which includes the presence or absence |
1144 | // of the ellipsis; see C++ DR 357). |
1145 | if (OldQType != NewQType && |
1146 | (OldType->getNumParams() != NewType->getNumParams() || |
1147 | OldType->isVariadic() != NewType->isVariadic() || |
1148 | !FunctionParamTypesAreEqual(OldType, NewType))) |
1149 | return true; |
1150 | |
1151 | // C++ [temp.over.link]p4: |
1152 | // The signature of a function template consists of its function |
1153 | // signature, its return type and its template parameter list. The names |
1154 | // of the template parameters are significant only for establishing the |
1155 | // relationship between the template parameters and the rest of the |
1156 | // signature. |
1157 | // |
1158 | // We check the return type and template parameter lists for function |
1159 | // templates first; the remaining checks follow. |
1160 | // |
1161 | // However, we don't consider either of these when deciding whether |
1162 | // a member introduced by a shadow declaration is hidden. |
1163 | if (!UseMemberUsingDeclRules && NewTemplate && |
1164 | (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), |
1165 | OldTemplate->getTemplateParameters(), |
1166 | false, TPL_TemplateMatch) || |
1167 | !Context.hasSameType(Old->getDeclaredReturnType(), |
1168 | New->getDeclaredReturnType()))) |
1169 | return true; |
1170 | |
1171 | // If the function is a class member, its signature includes the |
1172 | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. |
1173 | // |
1174 | // As part of this, also check whether one of the member functions |
1175 | // is static, in which case they are not overloads (C++ |
1176 | // 13.1p2). While not part of the definition of the signature, |
1177 | // this check is important to determine whether these functions |
1178 | // can be overloaded. |
1179 | CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); |
1180 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); |
1181 | if (OldMethod && NewMethod && |
1182 | !OldMethod->isStatic() && !NewMethod->isStatic()) { |
1183 | if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { |
1184 | if (!UseMemberUsingDeclRules && |
1185 | (OldMethod->getRefQualifier() == RQ_None || |
1186 | NewMethod->getRefQualifier() == RQ_None)) { |
1187 | // C++0x [over.load]p2: |
1188 | // - Member function declarations with the same name and the same |
1189 | // parameter-type-list as well as member function template |
1190 | // declarations with the same name, the same parameter-type-list, and |
1191 | // the same template parameter lists cannot be overloaded if any of |
1192 | // them, but not all, have a ref-qualifier (8.3.5). |
1193 | Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) |
1194 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); |
1195 | Diag(OldMethod->getLocation(), diag::note_previous_declaration); |
1196 | } |
1197 | return true; |
1198 | } |
1199 | |
1200 | // We may not have applied the implicit const for a constexpr member |
1201 | // function yet (because we haven't yet resolved whether this is a static |
1202 | // or non-static member function). Add it now, on the assumption that this |
1203 | // is a redeclaration of OldMethod. |
1204 | auto OldQuals = OldMethod->getMethodQualifiers(); |
1205 | auto NewQuals = NewMethod->getMethodQualifiers(); |
1206 | if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && |
1207 | !isa<CXXConstructorDecl>(NewMethod)) |
1208 | NewQuals.addConst(); |
1209 | // We do not allow overloading based off of '__restrict'. |
1210 | OldQuals.removeRestrict(); |
1211 | NewQuals.removeRestrict(); |
1212 | if (OldQuals != NewQuals) |
1213 | return true; |
1214 | } |
1215 | |
1216 | // Though pass_object_size is placed on parameters and takes an argument, we |
1217 | // consider it to be a function-level modifier for the sake of function |
1218 | // identity. Either the function has one or more parameters with |
1219 | // pass_object_size or it doesn't. |
1220 | if (functionHasPassObjectSizeParams(New) != |
1221 | functionHasPassObjectSizeParams(Old)) |
1222 | return true; |
1223 | |
1224 | // enable_if attributes are an order-sensitive part of the signature. |
1225 | for (specific_attr_iterator<EnableIfAttr> |
1226 | NewI = New->specific_attr_begin<EnableIfAttr>(), |
1227 | NewE = New->specific_attr_end<EnableIfAttr>(), |
1228 | OldI = Old->specific_attr_begin<EnableIfAttr>(), |
1229 | OldE = Old->specific_attr_end<EnableIfAttr>(); |
1230 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { |
1231 | if (NewI == NewE || OldI == OldE) |
1232 | return true; |
1233 | llvm::FoldingSetNodeID NewID, OldID; |
1234 | NewI->getCond()->Profile(NewID, Context, true); |
1235 | OldI->getCond()->Profile(OldID, Context, true); |
1236 | if (NewID != OldID) |
1237 | return true; |
1238 | } |
1239 | |
1240 | if (getLangOpts().CUDA && ConsiderCudaAttrs) { |
1241 | // Don't allow overloading of destructors. (In theory we could, but it |
1242 | // would be a giant change to clang.) |
1243 | if (isa<CXXDestructorDecl>(New)) |
1244 | return false; |
1245 | |
1246 | CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), |
1247 | OldTarget = IdentifyCUDATarget(Old); |
1248 | if (NewTarget == CFT_InvalidTarget) |
1249 | return false; |
1250 | |
1251 | assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target." ) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1251, __PRETTY_FUNCTION__)); |
1252 | |
1253 | // Allow overloading of functions with same signature and different CUDA |
1254 | // target attributes. |
1255 | return NewTarget != OldTarget; |
1256 | } |
1257 | |
1258 | // The signatures match; this is not an overload. |
1259 | return false; |
1260 | } |
1261 | |
1262 | /// Tries a user-defined conversion from From to ToType. |
1263 | /// |
1264 | /// Produces an implicit conversion sequence for when a standard conversion |
1265 | /// is not an option. See TryImplicitConversion for more information. |
1266 | static ImplicitConversionSequence |
1267 | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
1268 | bool SuppressUserConversions, |
1269 | bool AllowExplicit, |
1270 | bool InOverloadResolution, |
1271 | bool CStyle, |
1272 | bool AllowObjCWritebackConversion, |
1273 | bool AllowObjCConversionOnExplicit) { |
1274 | ImplicitConversionSequence ICS; |
1275 | |
1276 | if (SuppressUserConversions) { |
1277 | // We're not in the case above, so there is no conversion that |
1278 | // we can perform. |
1279 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1280 | return ICS; |
1281 | } |
1282 | |
1283 | // Attempt user-defined conversion. |
1284 | OverloadCandidateSet Conversions(From->getExprLoc(), |
1285 | OverloadCandidateSet::CSK_Normal); |
1286 | switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, |
1287 | Conversions, AllowExplicit, |
1288 | AllowObjCConversionOnExplicit)) { |
1289 | case OR_Success: |
1290 | case OR_Deleted: |
1291 | ICS.setUserDefined(); |
1292 | // C++ [over.ics.user]p4: |
1293 | // A conversion of an expression of class type to the same class |
1294 | // type is given Exact Match rank, and a conversion of an |
1295 | // expression of class type to a base class of that type is |
1296 | // given Conversion rank, in spite of the fact that a copy |
1297 | // constructor (i.e., a user-defined conversion function) is |
1298 | // called for those cases. |
1299 | if (CXXConstructorDecl *Constructor |
1300 | = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { |
1301 | QualType FromCanon |
1302 | = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); |
1303 | QualType ToCanon |
1304 | = S.Context.getCanonicalType(ToType).getUnqualifiedType(); |
1305 | if (Constructor->isCopyConstructor() && |
1306 | (FromCanon == ToCanon || |
1307 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { |
1308 | // Turn this into a "standard" conversion sequence, so that it |
1309 | // gets ranked with standard conversion sequences. |
1310 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; |
1311 | ICS.setStandard(); |
1312 | ICS.Standard.setAsIdentityConversion(); |
1313 | ICS.Standard.setFromType(From->getType()); |
1314 | ICS.Standard.setAllToTypes(ToType); |
1315 | ICS.Standard.CopyConstructor = Constructor; |
1316 | ICS.Standard.FoundCopyConstructor = Found; |
1317 | if (ToCanon != FromCanon) |
1318 | ICS.Standard.Second = ICK_Derived_To_Base; |
1319 | } |
1320 | } |
1321 | break; |
1322 | |
1323 | case OR_Ambiguous: |
1324 | ICS.setAmbiguous(); |
1325 | ICS.Ambiguous.setFromType(From->getType()); |
1326 | ICS.Ambiguous.setToType(ToType); |
1327 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); |
1328 | Cand != Conversions.end(); ++Cand) |
1329 | if (Cand->Best) |
1330 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
1331 | break; |
1332 | |
1333 | // Fall through. |
1334 | case OR_No_Viable_Function: |
1335 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1336 | break; |
1337 | } |
1338 | |
1339 | return ICS; |
1340 | } |
1341 | |
1342 | /// TryImplicitConversion - Attempt to perform an implicit conversion |
1343 | /// from the given expression (Expr) to the given type (ToType). This |
1344 | /// function returns an implicit conversion sequence that can be used |
1345 | /// to perform the initialization. Given |
1346 | /// |
1347 | /// void f(float f); |
1348 | /// void g(int i) { f(i); } |
1349 | /// |
1350 | /// this routine would produce an implicit conversion sequence to |
1351 | /// describe the initialization of f from i, which will be a standard |
1352 | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ |
1353 | /// 4.1) followed by a floating-integral conversion (C++ 4.9). |
1354 | // |
1355 | /// Note that this routine only determines how the conversion can be |
1356 | /// performed; it does not actually perform the conversion. As such, |
1357 | /// it will not produce any diagnostics if no conversion is available, |
1358 | /// but will instead return an implicit conversion sequence of kind |
1359 | /// "BadConversion". |
1360 | /// |
1361 | /// If @p SuppressUserConversions, then user-defined conversions are |
1362 | /// not permitted. |
1363 | /// If @p AllowExplicit, then explicit user-defined conversions are |
1364 | /// permitted. |
1365 | /// |
1366 | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C |
1367 | /// writeback conversion, which allows __autoreleasing id* parameters to |
1368 | /// be initialized with __strong id* or __weak id* arguments. |
1369 | static ImplicitConversionSequence |
1370 | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, |
1371 | bool SuppressUserConversions, |
1372 | bool AllowExplicit, |
1373 | bool InOverloadResolution, |
1374 | bool CStyle, |
1375 | bool AllowObjCWritebackConversion, |
1376 | bool AllowObjCConversionOnExplicit) { |
1377 | ImplicitConversionSequence ICS; |
1378 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, |
1379 | ICS.Standard, CStyle, AllowObjCWritebackConversion)){ |
1380 | ICS.setStandard(); |
1381 | return ICS; |
1382 | } |
1383 | |
1384 | if (!S.getLangOpts().CPlusPlus) { |
1385 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1386 | return ICS; |
1387 | } |
1388 | |
1389 | // C++ [over.ics.user]p4: |
1390 | // A conversion of an expression of class type to the same class |
1391 | // type is given Exact Match rank, and a conversion of an |
1392 | // expression of class type to a base class of that type is |
1393 | // given Conversion rank, in spite of the fact that a copy/move |
1394 | // constructor (i.e., a user-defined conversion function) is |
1395 | // called for those cases. |
1396 | QualType FromType = From->getType(); |
1397 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && |
1398 | (S.Context.hasSameUnqualifiedType(FromType, ToType) || |
1399 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { |
1400 | ICS.setStandard(); |
1401 | ICS.Standard.setAsIdentityConversion(); |
1402 | ICS.Standard.setFromType(FromType); |
1403 | ICS.Standard.setAllToTypes(ToType); |
1404 | |
1405 | // We don't actually check at this point whether there is a valid |
1406 | // copy/move constructor, since overloading just assumes that it |
1407 | // exists. When we actually perform initialization, we'll find the |
1408 | // appropriate constructor to copy the returned object, if needed. |
1409 | ICS.Standard.CopyConstructor = nullptr; |
1410 | |
1411 | // Determine whether this is considered a derived-to-base conversion. |
1412 | if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1413 | ICS.Standard.Second = ICK_Derived_To_Base; |
1414 | |
1415 | return ICS; |
1416 | } |
1417 | |
1418 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
1419 | AllowExplicit, InOverloadResolution, CStyle, |
1420 | AllowObjCWritebackConversion, |
1421 | AllowObjCConversionOnExplicit); |
1422 | } |
1423 | |
1424 | ImplicitConversionSequence |
1425 | Sema::TryImplicitConversion(Expr *From, QualType ToType, |
1426 | bool SuppressUserConversions, |
1427 | bool AllowExplicit, |
1428 | bool InOverloadResolution, |
1429 | bool CStyle, |
1430 | bool AllowObjCWritebackConversion) { |
1431 | return ::TryImplicitConversion(*this, From, ToType, |
1432 | SuppressUserConversions, AllowExplicit, |
1433 | InOverloadResolution, CStyle, |
1434 | AllowObjCWritebackConversion, |
1435 | /*AllowObjCConversionOnExplicit=*/false); |
1436 | } |
1437 | |
1438 | /// PerformImplicitConversion - Perform an implicit conversion of the |
1439 | /// expression From to the type ToType. Returns the |
1440 | /// converted expression. Flavor is the kind of conversion we're |
1441 | /// performing, used in the error message. If @p AllowExplicit, |
1442 | /// explicit user-defined conversions are permitted. |
1443 | ExprResult |
1444 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
1445 | AssignmentAction Action, bool AllowExplicit) { |
1446 | ImplicitConversionSequence ICS; |
1447 | return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); |
1448 | } |
1449 | |
1450 | ExprResult |
1451 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
1452 | AssignmentAction Action, bool AllowExplicit, |
1453 | ImplicitConversionSequence& ICS) { |
1454 | if (checkPlaceholderForOverload(*this, From)) |
1455 | return ExprError(); |
1456 | |
1457 | // Objective-C ARC: Determine whether we will allow the writeback conversion. |
1458 | bool AllowObjCWritebackConversion |
1459 | = getLangOpts().ObjCAutoRefCount && |
1460 | (Action == AA_Passing || Action == AA_Sending); |
1461 | if (getLangOpts().ObjC) |
1462 | CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, |
1463 | From->getType(), From); |
1464 | ICS = ::TryImplicitConversion(*this, From, ToType, |
1465 | /*SuppressUserConversions=*/false, |
1466 | AllowExplicit, |
1467 | /*InOverloadResolution=*/false, |
1468 | /*CStyle=*/false, |
1469 | AllowObjCWritebackConversion, |
1470 | /*AllowObjCConversionOnExplicit=*/false); |
1471 | return PerformImplicitConversion(From, ToType, ICS, Action); |
1472 | } |
1473 | |
1474 | /// Determine whether the conversion from FromType to ToType is a valid |
1475 | /// conversion that strips "noexcept" or "noreturn" off the nested function |
1476 | /// type. |
1477 | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, |
1478 | QualType &ResultTy) { |
1479 | if (Context.hasSameUnqualifiedType(FromType, ToType)) |
1480 | return false; |
1481 | |
1482 | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) |
1483 | // or F(t noexcept) -> F(t) |
1484 | // where F adds one of the following at most once: |
1485 | // - a pointer |
1486 | // - a member pointer |
1487 | // - a block pointer |
1488 | // Changes here need matching changes in FindCompositePointerType. |
1489 | CanQualType CanTo = Context.getCanonicalType(ToType); |
1490 | CanQualType CanFrom = Context.getCanonicalType(FromType); |
1491 | Type::TypeClass TyClass = CanTo->getTypeClass(); |
1492 | if (TyClass != CanFrom->getTypeClass()) return false; |
1493 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { |
1494 | if (TyClass == Type::Pointer) { |
1495 | CanTo = CanTo.castAs<PointerType>()->getPointeeType(); |
1496 | CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); |
1497 | } else if (TyClass == Type::BlockPointer) { |
1498 | CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); |
1499 | CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); |
1500 | } else if (TyClass == Type::MemberPointer) { |
1501 | auto ToMPT = CanTo.castAs<MemberPointerType>(); |
1502 | auto FromMPT = CanFrom.castAs<MemberPointerType>(); |
1503 | // A function pointer conversion cannot change the class of the function. |
1504 | if (ToMPT->getClass() != FromMPT->getClass()) |
1505 | return false; |
1506 | CanTo = ToMPT->getPointeeType(); |
1507 | CanFrom = FromMPT->getPointeeType(); |
1508 | } else { |
1509 | return false; |
1510 | } |
1511 | |
1512 | TyClass = CanTo->getTypeClass(); |
1513 | if (TyClass != CanFrom->getTypeClass()) return false; |
1514 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) |
1515 | return false; |
1516 | } |
1517 | |
1518 | const auto *FromFn = cast<FunctionType>(CanFrom); |
1519 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
1520 | |
1521 | const auto *ToFn = cast<FunctionType>(CanTo); |
1522 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
1523 | |
1524 | bool Changed = false; |
1525 | |
1526 | // Drop 'noreturn' if not present in target type. |
1527 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { |
1528 | FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); |
1529 | Changed = true; |
1530 | } |
1531 | |
1532 | // Drop 'noexcept' if not present in target type. |
1533 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { |
1534 | const auto *ToFPT = cast<FunctionProtoType>(ToFn); |
1535 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { |
1536 | FromFn = cast<FunctionType>( |
1537 | Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), |
1538 | EST_None) |
1539 | .getTypePtr()); |
1540 | Changed = true; |
1541 | } |
1542 | |
1543 | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid |
1544 | // only if the ExtParameterInfo lists of the two function prototypes can be |
1545 | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. |
1546 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
1547 | bool CanUseToFPT, CanUseFromFPT; |
1548 | if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, |
1549 | CanUseFromFPT, NewParamInfos) && |
1550 | CanUseToFPT && !CanUseFromFPT) { |
1551 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); |
1552 | ExtInfo.ExtParameterInfos = |
1553 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); |
1554 | QualType QT = Context.getFunctionType(FromFPT->getReturnType(), |
1555 | FromFPT->getParamTypes(), ExtInfo); |
1556 | FromFn = QT->getAs<FunctionType>(); |
1557 | Changed = true; |
1558 | } |
1559 | } |
1560 | |
1561 | if (!Changed) |
1562 | return false; |
1563 | |
1564 | assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void> (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1564, __PRETTY_FUNCTION__)); |
1565 | if (QualType(FromFn, 0) != CanTo) return false; |
1566 | |
1567 | ResultTy = ToType; |
1568 | return true; |
1569 | } |
1570 | |
1571 | /// Determine whether the conversion from FromType to ToType is a valid |
1572 | /// vector conversion. |
1573 | /// |
1574 | /// \param ICK Will be set to the vector conversion kind, if this is a vector |
1575 | /// conversion. |
1576 | static bool IsVectorConversion(Sema &S, QualType FromType, |
1577 | QualType ToType, ImplicitConversionKind &ICK) { |
1578 | // We need at least one of these types to be a vector type to have a vector |
1579 | // conversion. |
1580 | if (!ToType->isVectorType() && !FromType->isVectorType()) |
1581 | return false; |
1582 | |
1583 | // Identical types require no conversions. |
1584 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1585 | return false; |
1586 | |
1587 | // There are no conversions between extended vector types, only identity. |
1588 | if (ToType->isExtVectorType()) { |
1589 | // There are no conversions between extended vector types other than the |
1590 | // identity conversion. |
1591 | if (FromType->isExtVectorType()) |
1592 | return false; |
1593 | |
1594 | // Vector splat from any arithmetic type to a vector. |
1595 | if (FromType->isArithmeticType()) { |
1596 | ICK = ICK_Vector_Splat; |
1597 | return true; |
1598 | } |
1599 | } |
1600 | |
1601 | // We can perform the conversion between vector types in the following cases: |
1602 | // 1)vector types are equivalent AltiVec and GCC vector types |
1603 | // 2)lax vector conversions are permitted and the vector types are of the |
1604 | // same size |
1605 | if (ToType->isVectorType() && FromType->isVectorType()) { |
1606 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || |
1607 | S.isLaxVectorConversion(FromType, ToType)) { |
1608 | ICK = ICK_Vector_Conversion; |
1609 | return true; |
1610 | } |
1611 | } |
1612 | |
1613 | return false; |
1614 | } |
1615 | |
1616 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
1617 | bool InOverloadResolution, |
1618 | StandardConversionSequence &SCS, |
1619 | bool CStyle); |
1620 | |
1621 | /// IsStandardConversion - Determines whether there is a standard |
1622 | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the |
1623 | /// expression From to the type ToType. Standard conversion sequences |
1624 | /// only consider non-class types; for conversions that involve class |
1625 | /// types, use TryImplicitConversion. If a conversion exists, SCS will |
1626 | /// contain the standard conversion sequence required to perform this |
1627 | /// conversion and this routine will return true. Otherwise, this |
1628 | /// routine will return false and the value of SCS is unspecified. |
1629 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
1630 | bool InOverloadResolution, |
1631 | StandardConversionSequence &SCS, |
1632 | bool CStyle, |
1633 | bool AllowObjCWritebackConversion) { |
1634 | QualType FromType = From->getType(); |
1635 | |
1636 | // Standard conversions (C++ [conv]) |
1637 | SCS.setAsIdentityConversion(); |
1638 | SCS.IncompatibleObjC = false; |
1639 | SCS.setFromType(FromType); |
1640 | SCS.CopyConstructor = nullptr; |
1641 | |
1642 | // There are no standard conversions for class types in C++, so |
1643 | // abort early. When overloading in C, however, we do permit them. |
1644 | if (S.getLangOpts().CPlusPlus && |
1645 | (FromType->isRecordType() || ToType->isRecordType())) |
1646 | return false; |
1647 | |
1648 | // The first conversion can be an lvalue-to-rvalue conversion, |
1649 | // array-to-pointer conversion, or function-to-pointer conversion |
1650 | // (C++ 4p1). |
1651 | |
1652 | if (FromType == S.Context.OverloadTy) { |
1653 | DeclAccessPair AccessPair; |
1654 | if (FunctionDecl *Fn |
1655 | = S.ResolveAddressOfOverloadedFunction(From, ToType, false, |
1656 | AccessPair)) { |
1657 | // We were able to resolve the address of the overloaded function, |
1658 | // so we can convert to the type of that function. |
1659 | FromType = Fn->getType(); |
1660 | SCS.setFromType(FromType); |
1661 | |
1662 | // we can sometimes resolve &foo<int> regardless of ToType, so check |
1663 | // if the type matches (identity) or we are converting to bool |
1664 | if (!S.Context.hasSameUnqualifiedType( |
1665 | S.ExtractUnqualifiedFunctionType(ToType), FromType)) { |
1666 | QualType resultTy; |
1667 | // if the function type matches except for [[noreturn]], it's ok |
1668 | if (!S.IsFunctionConversion(FromType, |
1669 | S.ExtractUnqualifiedFunctionType(ToType), resultTy)) |
1670 | // otherwise, only a boolean conversion is standard |
1671 | if (!ToType->isBooleanType()) |
1672 | return false; |
1673 | } |
1674 | |
1675 | // Check if the "from" expression is taking the address of an overloaded |
1676 | // function and recompute the FromType accordingly. Take advantage of the |
1677 | // fact that non-static member functions *must* have such an address-of |
1678 | // expression. |
1679 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); |
1680 | if (Method && !Method->isStatic()) { |
1681 | assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) && "Non-unary operator on non-static member address") ? static_cast <void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1682, __PRETTY_FUNCTION__)) |
1682 | "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) && "Non-unary operator on non-static member address") ? static_cast <void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1682, __PRETTY_FUNCTION__)); |
1683 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1685, __PRETTY_FUNCTION__)) |
1684 | == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1685, __PRETTY_FUNCTION__)) |
1685 | "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1685, __PRETTY_FUNCTION__)); |
1686 | const Type *ClassType |
1687 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); |
1688 | FromType = S.Context.getMemberPointerType(FromType, ClassType); |
1689 | } else if (isa<UnaryOperator>(From->IgnoreParens())) { |
1690 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1692, __PRETTY_FUNCTION__)) |
1691 | UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1692, __PRETTY_FUNCTION__)) |
1692 | "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1692, __PRETTY_FUNCTION__)); |
1693 | FromType = S.Context.getPointerType(FromType); |
1694 | } |
1695 | |
1696 | // Check that we've computed the proper type after overload resolution. |
1697 | // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't |
1698 | // be calling it from within an NDEBUG block. |
1699 | assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1701, __PRETTY_FUNCTION__)) |
1700 | FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1701, __PRETTY_FUNCTION__)) |
1701 | S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 1701, __PRETTY_FUNCTION__)); |
1702 | } else { |
1703 | return false; |
1704 | } |
1705 | } |
1706 | // Lvalue-to-rvalue conversion (C++11 4.1): |
1707 | // A glvalue (3.10) of a non-function, non-array type T can |
1708 | // be converted to a prvalue. |
1709 | bool argIsLValue = From->isGLValue(); |
1710 | if (argIsLValue && |
1711 | !FromType->isFunctionType() && !FromType->isArrayType() && |
1712 | S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { |
1713 | SCS.First = ICK_Lvalue_To_Rvalue; |
1714 | |
1715 | // C11 6.3.2.1p2: |
1716 | // ... if the lvalue has atomic type, the value has the non-atomic version |
1717 | // of the type of the lvalue ... |
1718 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) |
1719 | FromType = Atomic->getValueType(); |
1720 | |
1721 | // If T is a non-class type, the type of the rvalue is the |
1722 | // cv-unqualified version of T. Otherwise, the type of the rvalue |
1723 | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we |
1724 | // just strip the qualifiers because they don't matter. |
1725 | FromType = FromType.getUnqualifiedType(); |
1726 | } else if (FromType->isArrayType()) { |
1727 | // Array-to-pointer conversion (C++ 4.2) |
1728 | SCS.First = ICK_Array_To_Pointer; |
1729 | |
1730 | // An lvalue or rvalue of type "array of N T" or "array of unknown |
1731 | // bound of T" can be converted to an rvalue of type "pointer to |
1732 | // T" (C++ 4.2p1). |
1733 | FromType = S.Context.getArrayDecayedType(FromType); |
1734 | |
1735 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { |
1736 | // This conversion is deprecated in C++03 (D.4) |
1737 | SCS.DeprecatedStringLiteralToCharPtr = true; |
1738 | |
1739 | // For the purpose of ranking in overload resolution |
1740 | // (13.3.3.1.1), this conversion is considered an |
1741 | // array-to-pointer conversion followed by a qualification |
1742 | // conversion (4.4). (C++ 4.2p2) |
1743 | SCS.Second = ICK_Identity; |
1744 | SCS.Third = ICK_Qualification; |
1745 | SCS.QualificationIncludesObjCLifetime = false; |
1746 | SCS.setAllToTypes(FromType); |
1747 | return true; |
1748 | } |
1749 | } else if (FromType->isFunctionType() && argIsLValue) { |
1750 | // Function-to-pointer conversion (C++ 4.3). |
1751 | SCS.First = ICK_Function_To_Pointer; |
1752 | |
1753 | if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) |
1754 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) |
1755 | if (!S.checkAddressOfFunctionIsAvailable(FD)) |
1756 | return false; |
1757 | |
1758 | // An lvalue of function type T can be converted to an rvalue of |
1759 | // type "pointer to T." The result is a pointer to the |
1760 | // function. (C++ 4.3p1). |
1761 | FromType = S.Context.getPointerType(FromType); |
1762 | } else { |
1763 | // We don't require any conversions for the first step. |
1764 | SCS.First = ICK_Identity; |
1765 | } |
1766 | SCS.setToType(0, FromType); |
1767 | |
1768 | // The second conversion can be an integral promotion, floating |
1769 | // point promotion, integral conversion, floating point conversion, |
1770 | // floating-integral conversion, pointer conversion, |
1771 | // pointer-to-member conversion, or boolean conversion (C++ 4p1). |
1772 | // For overloading in C, this can also be a "compatible-type" |
1773 | // conversion. |
1774 | bool IncompatibleObjC = false; |
1775 | ImplicitConversionKind SecondICK = ICK_Identity; |
1776 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { |
1777 | // The unqualified versions of the types are the same: there's no |
1778 | // conversion to do. |
1779 | SCS.Second = ICK_Identity; |
1780 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { |
1781 | // Integral promotion (C++ 4.5). |
1782 | SCS.Second = ICK_Integral_Promotion; |
1783 | FromType = ToType.getUnqualifiedType(); |
1784 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { |
1785 | // Floating point promotion (C++ 4.6). |
1786 | SCS.Second = ICK_Floating_Promotion; |
1787 | FromType = ToType.getUnqualifiedType(); |
1788 | } else if (S.IsComplexPromotion(FromType, ToType)) { |
1789 | // Complex promotion (Clang extension) |
1790 | SCS.Second = ICK_Complex_Promotion; |
1791 | FromType = ToType.getUnqualifiedType(); |
1792 | } else if (ToType->isBooleanType() && |
1793 | (FromType->isArithmeticType() || |
1794 | FromType->isAnyPointerType() || |
1795 | FromType->isBlockPointerType() || |
1796 | FromType->isMemberPointerType() || |
1797 | FromType->isNullPtrType())) { |
1798 | // Boolean conversions (C++ 4.12). |
1799 | SCS.Second = ICK_Boolean_Conversion; |
1800 | FromType = S.Context.BoolTy; |
1801 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
1802 | ToType->isIntegralType(S.Context)) { |
1803 | // Integral conversions (C++ 4.7). |
1804 | SCS.Second = ICK_Integral_Conversion; |
1805 | FromType = ToType.getUnqualifiedType(); |
1806 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { |
1807 | // Complex conversions (C99 6.3.1.6) |
1808 | SCS.Second = ICK_Complex_Conversion; |
1809 | FromType = ToType.getUnqualifiedType(); |
1810 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || |
1811 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { |
1812 | // Complex-real conversions (C99 6.3.1.7) |
1813 | SCS.Second = ICK_Complex_Real; |
1814 | FromType = ToType.getUnqualifiedType(); |
1815 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { |
1816 | // FIXME: disable conversions between long double and __float128 if |
1817 | // their representation is different until there is back end support |
1818 | // We of course allow this conversion if long double is really double. |
1819 | if (&S.Context.getFloatTypeSemantics(FromType) != |
1820 | &S.Context.getFloatTypeSemantics(ToType)) { |
1821 | bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && |
1822 | ToType == S.Context.LongDoubleTy) || |
1823 | (FromType == S.Context.LongDoubleTy && |
1824 | ToType == S.Context.Float128Ty)); |
1825 | if (Float128AndLongDouble && |
1826 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == |
1827 | &llvm::APFloat::PPCDoubleDouble())) |
1828 | return false; |
1829 | } |
1830 | // Floating point conversions (C++ 4.8). |
1831 | SCS.Second = ICK_Floating_Conversion; |
1832 | FromType = ToType.getUnqualifiedType(); |
1833 | } else if ((FromType->isRealFloatingType() && |
1834 | ToType->isIntegralType(S.Context)) || |
1835 | (FromType->isIntegralOrUnscopedEnumerationType() && |
1836 | ToType->isRealFloatingType())) { |
1837 | // Floating-integral conversions (C++ 4.9). |
1838 | SCS.Second = ICK_Floating_Integral; |
1839 | FromType = ToType.getUnqualifiedType(); |
1840 | } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { |
1841 | SCS.Second = ICK_Block_Pointer_Conversion; |
1842 | } else if (AllowObjCWritebackConversion && |
1843 | S.isObjCWritebackConversion(FromType, ToType, FromType)) { |
1844 | SCS.Second = ICK_Writeback_Conversion; |
1845 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, |
1846 | FromType, IncompatibleObjC)) { |
1847 | // Pointer conversions (C++ 4.10). |
1848 | SCS.Second = ICK_Pointer_Conversion; |
1849 | SCS.IncompatibleObjC = IncompatibleObjC; |
1850 | FromType = FromType.getUnqualifiedType(); |
1851 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, |
1852 | InOverloadResolution, FromType)) { |
1853 | // Pointer to member conversions (4.11). |
1854 | SCS.Second = ICK_Pointer_Member; |
1855 | } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { |
1856 | SCS.Second = SecondICK; |
1857 | FromType = ToType.getUnqualifiedType(); |
1858 | } else if (!S.getLangOpts().CPlusPlus && |
1859 | S.Context.typesAreCompatible(ToType, FromType)) { |
1860 | // Compatible conversions (Clang extension for C function overloading) |
1861 | SCS.Second = ICK_Compatible_Conversion; |
1862 | FromType = ToType.getUnqualifiedType(); |
1863 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, |
1864 | InOverloadResolution, |
1865 | SCS, CStyle)) { |
1866 | SCS.Second = ICK_TransparentUnionConversion; |
1867 | FromType = ToType; |
1868 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, |
1869 | CStyle)) { |
1870 | // tryAtomicConversion has updated the standard conversion sequence |
1871 | // appropriately. |
1872 | return true; |
1873 | } else if (ToType->isEventT() && |
1874 | From->isIntegerConstantExpr(S.getASTContext()) && |
1875 | From->EvaluateKnownConstInt(S.getASTContext()) == 0) { |
1876 | SCS.Second = ICK_Zero_Event_Conversion; |
1877 | FromType = ToType; |
1878 | } else if (ToType->isQueueT() && |
1879 | From->isIntegerConstantExpr(S.getASTContext()) && |
1880 | (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { |
1881 | SCS.Second = ICK_Zero_Queue_Conversion; |
1882 | FromType = ToType; |
1883 | } else if (ToType->isSamplerT() && |
1884 | From->isIntegerConstantExpr(S.getASTContext())) { |
1885 | SCS.Second = ICK_Compatible_Conversion; |
1886 | FromType = ToType; |
1887 | } else { |
1888 | // No second conversion required. |
1889 | SCS.Second = ICK_Identity; |
1890 | } |
1891 | SCS.setToType(1, FromType); |
1892 | |
1893 | // The third conversion can be a function pointer conversion or a |
1894 | // qualification conversion (C++ [conv.fctptr], [conv.qual]). |
1895 | bool ObjCLifetimeConversion; |
1896 | if (S.IsFunctionConversion(FromType, ToType, FromType)) { |
1897 | // Function pointer conversions (removing 'noexcept') including removal of |
1898 | // 'noreturn' (Clang extension). |
1899 | SCS.Third = ICK_Function_Conversion; |
1900 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, |
1901 | ObjCLifetimeConversion)) { |
1902 | SCS.Third = ICK_Qualification; |
1903 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; |
1904 | FromType = ToType; |
1905 | } else { |
1906 | // No conversion required |
1907 | SCS.Third = ICK_Identity; |
1908 | } |
1909 | |
1910 | // C++ [over.best.ics]p6: |
1911 | // [...] Any difference in top-level cv-qualification is |
1912 | // subsumed by the initialization itself and does not constitute |
1913 | // a conversion. [...] |
1914 | QualType CanonFrom = S.Context.getCanonicalType(FromType); |
1915 | QualType CanonTo = S.Context.getCanonicalType(ToType); |
1916 | if (CanonFrom.getLocalUnqualifiedType() |
1917 | == CanonTo.getLocalUnqualifiedType() && |
1918 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { |
1919 | FromType = ToType; |
1920 | CanonFrom = CanonTo; |
1921 | } |
1922 | |
1923 | SCS.setToType(2, FromType); |
1924 | |
1925 | if (CanonFrom == CanonTo) |
1926 | return true; |
1927 | |
1928 | // If we have not converted the argument type to the parameter type, |
1929 | // this is a bad conversion sequence, unless we're resolving an overload in C. |
1930 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) |
1931 | return false; |
1932 | |
1933 | ExprResult ER = ExprResult{From}; |
1934 | Sema::AssignConvertType Conv = |
1935 | S.CheckSingleAssignmentConstraints(ToType, ER, |
1936 | /*Diagnose=*/false, |
1937 | /*DiagnoseCFAudited=*/false, |
1938 | /*ConvertRHS=*/false); |
1939 | ImplicitConversionKind SecondConv; |
1940 | switch (Conv) { |
1941 | case Sema::Compatible: |
1942 | SecondConv = ICK_C_Only_Conversion; |
1943 | break; |
1944 | // For our purposes, discarding qualifiers is just as bad as using an |
1945 | // incompatible pointer. Note that an IncompatiblePointer conversion can drop |
1946 | // qualifiers, as well. |
1947 | case Sema::CompatiblePointerDiscardsQualifiers: |
1948 | case Sema::IncompatiblePointer: |
1949 | case Sema::IncompatiblePointerSign: |
1950 | SecondConv = ICK_Incompatible_Pointer_Conversion; |
1951 | break; |
1952 | default: |
1953 | return false; |
1954 | } |
1955 | |
1956 | // First can only be an lvalue conversion, so we pretend that this was the |
1957 | // second conversion. First should already be valid from earlier in the |
1958 | // function. |
1959 | SCS.Second = SecondConv; |
1960 | SCS.setToType(1, ToType); |
1961 | |
1962 | // Third is Identity, because Second should rank us worse than any other |
1963 | // conversion. This could also be ICK_Qualification, but it's simpler to just |
1964 | // lump everything in with the second conversion, and we don't gain anything |
1965 | // from making this ICK_Qualification. |
1966 | SCS.Third = ICK_Identity; |
1967 | SCS.setToType(2, ToType); |
1968 | return true; |
1969 | } |
1970 | |
1971 | static bool |
1972 | IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
1973 | QualType &ToType, |
1974 | bool InOverloadResolution, |
1975 | StandardConversionSequence &SCS, |
1976 | bool CStyle) { |
1977 | |
1978 | const RecordType *UT = ToType->getAsUnionType(); |
1979 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
1980 | return false; |
1981 | // The field to initialize within the transparent union. |
1982 | RecordDecl *UD = UT->getDecl(); |
1983 | // It's compatible if the expression matches any of the fields. |
1984 | for (const auto *it : UD->fields()) { |
1985 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, |
1986 | CStyle, /*AllowObjCWritebackConversion=*/false)) { |
1987 | ToType = it->getType(); |
1988 | return true; |
1989 | } |
1990 | } |
1991 | return false; |
1992 | } |
1993 | |
1994 | /// IsIntegralPromotion - Determines whether the conversion from the |
1995 | /// expression From (whose potentially-adjusted type is FromType) to |
1996 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and |
1997 | /// sets PromotedType to the promoted type. |
1998 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { |
1999 | const BuiltinType *To = ToType->getAs<BuiltinType>(); |
2000 | // All integers are built-in. |
2001 | if (!To) { |
2002 | return false; |
2003 | } |
2004 | |
2005 | // An rvalue of type char, signed char, unsigned char, short int, or |
2006 | // unsigned short int can be converted to an rvalue of type int if |
2007 | // int can represent all the values of the source type; otherwise, |
2008 | // the source rvalue can be converted to an rvalue of type unsigned |
2009 | // int (C++ 4.5p1). |
2010 | if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && |
2011 | !FromType->isEnumeralType()) { |
2012 | if (// We can promote any signed, promotable integer type to an int |
2013 | (FromType->isSignedIntegerType() || |
2014 | // We can promote any unsigned integer type whose size is |
2015 | // less than int to an int. |
2016 | Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { |
2017 | return To->getKind() == BuiltinType::Int; |
2018 | } |
2019 | |
2020 | return To->getKind() == BuiltinType::UInt; |
2021 | } |
2022 | |
2023 | // C++11 [conv.prom]p3: |
2024 | // A prvalue of an unscoped enumeration type whose underlying type is not |
2025 | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the |
2026 | // following types that can represent all the values of the enumeration |
2027 | // (i.e., the values in the range bmin to bmax as described in 7.2): int, |
2028 | // unsigned int, long int, unsigned long int, long long int, or unsigned |
2029 | // long long int. If none of the types in that list can represent all the |
2030 | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration |
2031 | // type can be converted to an rvalue a prvalue of the extended integer type |
2032 | // with lowest integer conversion rank (4.13) greater than the rank of long |
2033 | // long in which all the values of the enumeration can be represented. If |
2034 | // there are two such extended types, the signed one is chosen. |
2035 | // C++11 [conv.prom]p4: |
2036 | // A prvalue of an unscoped enumeration type whose underlying type is fixed |
2037 | // can be converted to a prvalue of its underlying type. Moreover, if |
2038 | // integral promotion can be applied to its underlying type, a prvalue of an |
2039 | // unscoped enumeration type whose underlying type is fixed can also be |
2040 | // converted to a prvalue of the promoted underlying type. |
2041 | if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { |
2042 | // C++0x 7.2p9: Note that this implicit enum to int conversion is not |
2043 | // provided for a scoped enumeration. |
2044 | if (FromEnumType->getDecl()->isScoped()) |
2045 | return false; |
2046 | |
2047 | // We can perform an integral promotion to the underlying type of the enum, |
2048 | // even if that's not the promoted type. Note that the check for promoting |
2049 | // the underlying type is based on the type alone, and does not consider |
2050 | // the bitfield-ness of the actual source expression. |
2051 | if (FromEnumType->getDecl()->isFixed()) { |
2052 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); |
2053 | return Context.hasSameUnqualifiedType(Underlying, ToType) || |
2054 | IsIntegralPromotion(nullptr, Underlying, ToType); |
2055 | } |
2056 | |
2057 | // We have already pre-calculated the promotion type, so this is trivial. |
2058 | if (ToType->isIntegerType() && |
2059 | isCompleteType(From->getBeginLoc(), FromType)) |
2060 | return Context.hasSameUnqualifiedType( |
2061 | ToType, FromEnumType->getDecl()->getPromotionType()); |
2062 | |
2063 | // C++ [conv.prom]p5: |
2064 | // If the bit-field has an enumerated type, it is treated as any other |
2065 | // value of that type for promotion purposes. |
2066 | // |
2067 | // ... so do not fall through into the bit-field checks below in C++. |
2068 | if (getLangOpts().CPlusPlus) |
2069 | return false; |
2070 | } |
2071 | |
2072 | // C++0x [conv.prom]p2: |
2073 | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted |
2074 | // to an rvalue a prvalue of the first of the following types that can |
2075 | // represent all the values of its underlying type: int, unsigned int, |
2076 | // long int, unsigned long int, long long int, or unsigned long long int. |
2077 | // If none of the types in that list can represent all the values of its |
2078 | // underlying type, an rvalue a prvalue of type char16_t, char32_t, |
2079 | // or wchar_t can be converted to an rvalue a prvalue of its underlying |
2080 | // type. |
2081 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && |
2082 | ToType->isIntegerType()) { |
2083 | // Determine whether the type we're converting from is signed or |
2084 | // unsigned. |
2085 | bool FromIsSigned = FromType->isSignedIntegerType(); |
2086 | uint64_t FromSize = Context.getTypeSize(FromType); |
2087 | |
2088 | // The types we'll try to promote to, in the appropriate |
2089 | // order. Try each of these types. |
2090 | QualType PromoteTypes[6] = { |
2091 | Context.IntTy, Context.UnsignedIntTy, |
2092 | Context.LongTy, Context.UnsignedLongTy , |
2093 | Context.LongLongTy, Context.UnsignedLongLongTy |
2094 | }; |
2095 | for (int Idx = 0; Idx < 6; ++Idx) { |
2096 | uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); |
2097 | if (FromSize < ToSize || |
2098 | (FromSize == ToSize && |
2099 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { |
2100 | // We found the type that we can promote to. If this is the |
2101 | // type we wanted, we have a promotion. Otherwise, no |
2102 | // promotion. |
2103 | return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); |
2104 | } |
2105 | } |
2106 | } |
2107 | |
2108 | // An rvalue for an integral bit-field (9.6) can be converted to an |
2109 | // rvalue of type int if int can represent all the values of the |
2110 | // bit-field; otherwise, it can be converted to unsigned int if |
2111 | // unsigned int can represent all the values of the bit-field. If |
2112 | // the bit-field is larger yet, no integral promotion applies to |
2113 | // it. If the bit-field has an enumerated type, it is treated as any |
2114 | // other value of that type for promotion purposes (C++ 4.5p3). |
2115 | // FIXME: We should delay checking of bit-fields until we actually perform the |
2116 | // conversion. |
2117 | // |
2118 | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be |
2119 | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum |
2120 | // bit-fields and those whose underlying type is larger than int) for GCC |
2121 | // compatibility. |
2122 | if (From) { |
2123 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { |
2124 | llvm::APSInt BitWidth; |
2125 | if (FromType->isIntegralType(Context) && |
2126 | MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { |
2127 | llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); |
2128 | ToSize = Context.getTypeSize(ToType); |
2129 | |
2130 | // Are we promoting to an int from a bitfield that fits in an int? |
2131 | if (BitWidth < ToSize || |
2132 | (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { |
2133 | return To->getKind() == BuiltinType::Int; |
2134 | } |
2135 | |
2136 | // Are we promoting to an unsigned int from an unsigned bitfield |
2137 | // that fits into an unsigned int? |
2138 | if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { |
2139 | return To->getKind() == BuiltinType::UInt; |
2140 | } |
2141 | |
2142 | return false; |
2143 | } |
2144 | } |
2145 | } |
2146 | |
2147 | // An rvalue of type bool can be converted to an rvalue of type int, |
2148 | // with false becoming zero and true becoming one (C++ 4.5p4). |
2149 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { |
2150 | return true; |
2151 | } |
2152 | |
2153 | return false; |
2154 | } |
2155 | |
2156 | /// IsFloatingPointPromotion - Determines whether the conversion from |
2157 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, |
2158 | /// returns true and sets PromotedType to the promoted type. |
2159 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { |
2160 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) |
2161 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { |
2162 | /// An rvalue of type float can be converted to an rvalue of type |
2163 | /// double. (C++ 4.6p1). |
2164 | if (FromBuiltin->getKind() == BuiltinType::Float && |
2165 | ToBuiltin->getKind() == BuiltinType::Double) |
2166 | return true; |
2167 | |
2168 | // C99 6.3.1.5p1: |
2169 | // When a float is promoted to double or long double, or a |
2170 | // double is promoted to long double [...]. |
2171 | if (!getLangOpts().CPlusPlus && |
2172 | (FromBuiltin->getKind() == BuiltinType::Float || |
2173 | FromBuiltin->getKind() == BuiltinType::Double) && |
2174 | (ToBuiltin->getKind() == BuiltinType::LongDouble || |
2175 | ToBuiltin->getKind() == BuiltinType::Float128)) |
2176 | return true; |
2177 | |
2178 | // Half can be promoted to float. |
2179 | if (!getLangOpts().NativeHalfType && |
2180 | FromBuiltin->getKind() == BuiltinType::Half && |
2181 | ToBuiltin->getKind() == BuiltinType::Float) |
2182 | return true; |
2183 | } |
2184 | |
2185 | return false; |
2186 | } |
2187 | |
2188 | /// Determine if a conversion is a complex promotion. |
2189 | /// |
2190 | /// A complex promotion is defined as a complex -> complex conversion |
2191 | /// where the conversion between the underlying real types is a |
2192 | /// floating-point or integral promotion. |
2193 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { |
2194 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); |
2195 | if (!FromComplex) |
2196 | return false; |
2197 | |
2198 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); |
2199 | if (!ToComplex) |
2200 | return false; |
2201 | |
2202 | return IsFloatingPointPromotion(FromComplex->getElementType(), |
2203 | ToComplex->getElementType()) || |
2204 | IsIntegralPromotion(nullptr, FromComplex->getElementType(), |
2205 | ToComplex->getElementType()); |
2206 | } |
2207 | |
2208 | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from |
2209 | /// the pointer type FromPtr to a pointer to type ToPointee, with the |
2210 | /// same type qualifiers as FromPtr has on its pointee type. ToType, |
2211 | /// if non-empty, will be a pointer to ToType that may or may not have |
2212 | /// the right set of qualifiers on its pointee. |
2213 | /// |
2214 | static QualType |
2215 | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, |
2216 | QualType ToPointee, QualType ToType, |
2217 | ASTContext &Context, |
2218 | bool StripObjCLifetime = false) { |
2219 | assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 2221, __PRETTY_FUNCTION__)) |
2220 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 2221, __PRETTY_FUNCTION__)) |
2221 | "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 2221, __PRETTY_FUNCTION__)); |
2222 | |
2223 | /// Conversions to 'id' subsume cv-qualifier conversions. |
2224 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) |
2225 | return ToType.getUnqualifiedType(); |
2226 | |
2227 | QualType CanonFromPointee |
2228 | = Context.getCanonicalType(FromPtr->getPointeeType()); |
2229 | QualType CanonToPointee = Context.getCanonicalType(ToPointee); |
2230 | Qualifiers Quals = CanonFromPointee.getQualifiers(); |
2231 | |
2232 | if (StripObjCLifetime) |
2233 | Quals.removeObjCLifetime(); |
2234 | |
2235 | // Exact qualifier match -> return the pointer type we're converting to. |
2236 | if (CanonToPointee.getLocalQualifiers() == Quals) { |
2237 | // ToType is exactly what we need. Return it. |
2238 | if (!ToType.isNull()) |
2239 | return ToType.getUnqualifiedType(); |
2240 | |
2241 | // Build a pointer to ToPointee. It has the right qualifiers |
2242 | // already. |
2243 | if (isa<ObjCObjectPointerType>(ToType)) |
2244 | return Context.getObjCObjectPointerType(ToPointee); |
2245 | return Context.getPointerType(ToPointee); |
2246 | } |
2247 | |
2248 | // Just build a canonical type that has the right qualifiers. |
2249 | QualType QualifiedCanonToPointee |
2250 | = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); |
2251 | |
2252 | if (isa<ObjCObjectPointerType>(ToType)) |
2253 | return Context.getObjCObjectPointerType(QualifiedCanonToPointee); |
2254 | return Context.getPointerType(QualifiedCanonToPointee); |
2255 | } |
2256 | |
2257 | static bool isNullPointerConstantForConversion(Expr *Expr, |
2258 | bool InOverloadResolution, |
2259 | ASTContext &Context) { |
2260 | // Handle value-dependent integral null pointer constants correctly. |
2261 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
2262 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && |
2263 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) |
2264 | return !InOverloadResolution; |
2265 | |
2266 | return Expr->isNullPointerConstant(Context, |
2267 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
2268 | : Expr::NPC_ValueDependentIsNull); |
2269 | } |
2270 | |
2271 | /// IsPointerConversion - Determines whether the conversion of the |
2272 | /// expression From, which has the (possibly adjusted) type FromType, |
2273 | /// can be converted to the type ToType via a pointer conversion (C++ |
2274 | /// 4.10). If so, returns true and places the converted type (that |
2275 | /// might differ from ToType in its cv-qualifiers at some level) into |
2276 | /// ConvertedType. |
2277 | /// |
2278 | /// This routine also supports conversions to and from block pointers |
2279 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and |
2280 | /// pointers to interfaces. FIXME: Once we've determined the |
2281 | /// appropriate overloading rules for Objective-C, we may want to |
2282 | /// split the Objective-C checks into a different routine; however, |
2283 | /// GCC seems to consider all of these conversions to be pointer |
2284 | /// conversions, so for now they live here. IncompatibleObjC will be |
2285 | /// set if the conversion is an allowed Objective-C conversion that |
2286 | /// should result in a warning. |
2287 | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2288 | bool InOverloadResolution, |
2289 | QualType& ConvertedType, |
2290 | bool &IncompatibleObjC) { |
2291 | IncompatibleObjC = false; |
2292 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, |
2293 | IncompatibleObjC)) |
2294 | return true; |
2295 | |
2296 | // Conversion from a null pointer constant to any Objective-C pointer type. |
2297 | if (ToType->isObjCObjectPointerType() && |
2298 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2299 | ConvertedType = ToType; |
2300 | return true; |
2301 | } |
2302 | |
2303 | // Blocks: Block pointers can be converted to void*. |
2304 | if (FromType->isBlockPointerType() && ToType->isPointerType() && |
2305 | ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
2306 | ConvertedType = ToType; |
2307 | return true; |
2308 | } |
2309 | // Blocks: A null pointer constant can be converted to a block |
2310 | // pointer type. |
2311 | if (ToType->isBlockPointerType() && |
2312 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2313 | ConvertedType = ToType; |
2314 | return true; |
2315 | } |
2316 | |
2317 | // If the left-hand-side is nullptr_t, the right side can be a null |
2318 | // pointer constant. |
2319 | if (ToType->isNullPtrType() && |
2320 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2321 | ConvertedType = ToType; |
2322 | return true; |
2323 | } |
2324 | |
2325 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); |
2326 | if (!ToTypePtr) |
2327 | return false; |
2328 | |
2329 | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). |
2330 | if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2331 | ConvertedType = ToType; |
2332 | return true; |
2333 | } |
2334 | |
2335 | // Beyond this point, both types need to be pointers |
2336 | // , including objective-c pointers. |
2337 | QualType ToPointeeType = ToTypePtr->getPointeeType(); |
2338 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && |
2339 | !getLangOpts().ObjCAutoRefCount) { |
2340 | ConvertedType = BuildSimilarlyQualifiedPointerType( |
2341 | FromType->getAs<ObjCObjectPointerType>(), |
2342 | ToPointeeType, |
2343 | ToType, Context); |
2344 | return true; |
2345 | } |
2346 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); |
2347 | if (!FromTypePtr) |
2348 | return false; |
2349 | |
2350 | QualType FromPointeeType = FromTypePtr->getPointeeType(); |
2351 | |
2352 | // If the unqualified pointee types are the same, this can't be a |
2353 | // pointer conversion, so don't do all of the work below. |
2354 | if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) |
2355 | return false; |
2356 | |
2357 | // An rvalue of type "pointer to cv T," where T is an object type, |
2358 | // can be converted to an rvalue of type "pointer to cv void" (C++ |
2359 | // 4.10p2). |
2360 | if (FromPointeeType->isIncompleteOrObjectType() && |
2361 | ToPointeeType->isVoidType()) { |
2362 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2363 | ToPointeeType, |
2364 | ToType, Context, |
2365 | /*StripObjCLifetime=*/true); |
2366 | return true; |
2367 | } |
2368 | |
2369 | // MSVC allows implicit function to void* type conversion. |
2370 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && |
2371 | ToPointeeType->isVoidType()) { |
2372 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2373 | ToPointeeType, |
2374 | ToType, Context); |
2375 | return true; |
2376 | } |
2377 | |
2378 | // When we're overloading in C, we allow a special kind of pointer |
2379 | // conversion for compatible-but-not-identical pointee types. |
2380 | if (!getLangOpts().CPlusPlus && |
2381 | Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { |
2382 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2383 | ToPointeeType, |
2384 | ToType, Context); |
2385 | return true; |
2386 | } |
2387 | |
2388 | // C++ [conv.ptr]p3: |
2389 | // |
2390 | // An rvalue of type "pointer to cv D," where D is a class type, |
2391 | // can be converted to an rvalue of type "pointer to cv B," where |
2392 | // B is a base class (clause 10) of D. If B is an inaccessible |
2393 | // (clause 11) or ambiguous (10.2) base class of D, a program that |
2394 | // necessitates this conversion is ill-formed. The result of the |
2395 | // conversion is a pointer to the base class sub-object of the |
2396 | // derived class object. The null pointer value is converted to |
2397 | // the null pointer value of the destination type. |
2398 | // |
2399 | // Note that we do not check for ambiguity or inaccessibility |
2400 | // here. That is handled by CheckPointerConversion. |
2401 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && |
2402 | ToPointeeType->isRecordType() && |
2403 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && |
2404 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { |
2405 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2406 | ToPointeeType, |
2407 | ToType, Context); |
2408 | return true; |
2409 | } |
2410 | |
2411 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && |
2412 | Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { |
2413 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2414 | ToPointeeType, |
2415 | ToType, Context); |
2416 | return true; |
2417 | } |
2418 | |
2419 | return false; |
2420 | } |
2421 | |
2422 | /// Adopt the given qualifiers for the given type. |
2423 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ |
2424 | Qualifiers TQs = T.getQualifiers(); |
2425 | |
2426 | // Check whether qualifiers already match. |
2427 | if (TQs == Qs) |
2428 | return T; |
2429 | |
2430 | if (Qs.compatiblyIncludes(TQs)) |
2431 | return Context.getQualifiedType(T, Qs); |
2432 | |
2433 | return Context.getQualifiedType(T.getUnqualifiedType(), Qs); |
2434 | } |
2435 | |
2436 | /// isObjCPointerConversion - Determines whether this is an |
2437 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, |
2438 | /// with the same arguments and return values. |
2439 | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, |
2440 | QualType& ConvertedType, |
2441 | bool &IncompatibleObjC) { |
2442 | if (!getLangOpts().ObjC) |
2443 | return false; |
2444 | |
2445 | // The set of qualifiers on the type we're converting from. |
2446 | Qualifiers FromQualifiers = FromType.getQualifiers(); |
2447 | |
2448 | // First, we handle all conversions on ObjC object pointer types. |
2449 | const ObjCObjectPointerType* ToObjCPtr = |
2450 | ToType->getAs<ObjCObjectPointerType>(); |
2451 | const ObjCObjectPointerType *FromObjCPtr = |
2452 | FromType->getAs<ObjCObjectPointerType>(); |
2453 | |
2454 | if (ToObjCPtr && FromObjCPtr) { |
2455 | // If the pointee types are the same (ignoring qualifications), |
2456 | // then this is not a pointer conversion. |
2457 | if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), |
2458 | FromObjCPtr->getPointeeType())) |
2459 | return false; |
2460 | |
2461 | // Conversion between Objective-C pointers. |
2462 | if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { |
2463 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); |
2464 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); |
2465 | if (getLangOpts().CPlusPlus && LHS && RHS && |
2466 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( |
2467 | FromObjCPtr->getPointeeType())) |
2468 | return false; |
2469 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2470 | ToObjCPtr->getPointeeType(), |
2471 | ToType, Context); |
2472 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2473 | return true; |
2474 | } |
2475 | |
2476 | if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { |
2477 | // Okay: this is some kind of implicit downcast of Objective-C |
2478 | // interfaces, which is permitted. However, we're going to |
2479 | // complain about it. |
2480 | IncompatibleObjC = true; |
2481 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2482 | ToObjCPtr->getPointeeType(), |
2483 | ToType, Context); |
2484 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2485 | return true; |
2486 | } |
2487 | } |
2488 | // Beyond this point, both types need to be C pointers or block pointers. |
2489 | QualType ToPointeeType; |
2490 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) |
2491 | ToPointeeType = ToCPtr->getPointeeType(); |
2492 | else if (const BlockPointerType *ToBlockPtr = |
2493 | ToType->getAs<BlockPointerType>()) { |
2494 | // Objective C++: We're able to convert from a pointer to any object |
2495 | // to a block pointer type. |
2496 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { |
2497 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2498 | return true; |
2499 | } |
2500 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2501 | } |
2502 | else if (FromType->getAs<BlockPointerType>() && |
2503 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { |
2504 | // Objective C++: We're able to convert from a block pointer type to a |
2505 | // pointer to any object. |
2506 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2507 | return true; |
2508 | } |
2509 | else |
2510 | return false; |
2511 | |
2512 | QualType FromPointeeType; |
2513 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) |
2514 | FromPointeeType = FromCPtr->getPointeeType(); |
2515 | else if (const BlockPointerType *FromBlockPtr = |
2516 | FromType->getAs<BlockPointerType>()) |
2517 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2518 | else |
2519 | return false; |
2520 | |
2521 | // If we have pointers to pointers, recursively check whether this |
2522 | // is an Objective-C conversion. |
2523 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && |
2524 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2525 | IncompatibleObjC)) { |
2526 | // We always complain about this conversion. |
2527 | IncompatibleObjC = true; |
2528 | ConvertedType = Context.getPointerType(ConvertedType); |
2529 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2530 | return true; |
2531 | } |
2532 | // Allow conversion of pointee being objective-c pointer to another one; |
2533 | // as in I* to id. |
2534 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && |
2535 | ToPointeeType->getAs<ObjCObjectPointerType>() && |
2536 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2537 | IncompatibleObjC)) { |
2538 | |
2539 | ConvertedType = Context.getPointerType(ConvertedType); |
2540 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2541 | return true; |
2542 | } |
2543 | |
2544 | // If we have pointers to functions or blocks, check whether the only |
2545 | // differences in the argument and result types are in Objective-C |
2546 | // pointer conversions. If so, we permit the conversion (but |
2547 | // complain about it). |
2548 | const FunctionProtoType *FromFunctionType |
2549 | = FromPointeeType->getAs<FunctionProtoType>(); |
2550 | const FunctionProtoType *ToFunctionType |
2551 | = ToPointeeType->getAs<FunctionProtoType>(); |
2552 | if (FromFunctionType && ToFunctionType) { |
2553 | // If the function types are exactly the same, this isn't an |
2554 | // Objective-C pointer conversion. |
2555 | if (Context.getCanonicalType(FromPointeeType) |
2556 | == Context.getCanonicalType(ToPointeeType)) |
2557 | return false; |
2558 | |
2559 | // Perform the quick checks that will tell us whether these |
2560 | // function types are obviously different. |
2561 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2562 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || |
2563 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) |
2564 | return false; |
2565 | |
2566 | bool HasObjCConversion = false; |
2567 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == |
2568 | Context.getCanonicalType(ToFunctionType->getReturnType())) { |
2569 | // Okay, the types match exactly. Nothing to do. |
2570 | } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), |
2571 | ToFunctionType->getReturnType(), |
2572 | ConvertedType, IncompatibleObjC)) { |
2573 | // Okay, we have an Objective-C pointer conversion. |
2574 | HasObjCConversion = true; |
2575 | } else { |
2576 | // Function types are too different. Abort. |
2577 | return false; |
2578 | } |
2579 | |
2580 | // Check argument types. |
2581 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2582 | ArgIdx != NumArgs; ++ArgIdx) { |
2583 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
2584 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
2585 | if (Context.getCanonicalType(FromArgType) |
2586 | == Context.getCanonicalType(ToArgType)) { |
2587 | // Okay, the types match exactly. Nothing to do. |
2588 | } else if (isObjCPointerConversion(FromArgType, ToArgType, |
2589 | ConvertedType, IncompatibleObjC)) { |
2590 | // Okay, we have an Objective-C pointer conversion. |
2591 | HasObjCConversion = true; |
2592 | } else { |
2593 | // Argument types are too different. Abort. |
2594 | return false; |
2595 | } |
2596 | } |
2597 | |
2598 | if (HasObjCConversion) { |
2599 | // We had an Objective-C conversion. Allow this pointer |
2600 | // conversion, but complain about it. |
2601 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2602 | IncompatibleObjC = true; |
2603 | return true; |
2604 | } |
2605 | } |
2606 | |
2607 | return false; |
2608 | } |
2609 | |
2610 | /// Determine whether this is an Objective-C writeback conversion, |
2611 | /// used for parameter passing when performing automatic reference counting. |
2612 | /// |
2613 | /// \param FromType The type we're converting form. |
2614 | /// |
2615 | /// \param ToType The type we're converting to. |
2616 | /// |
2617 | /// \param ConvertedType The type that will be produced after applying |
2618 | /// this conversion. |
2619 | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, |
2620 | QualType &ConvertedType) { |
2621 | if (!getLangOpts().ObjCAutoRefCount || |
2622 | Context.hasSameUnqualifiedType(FromType, ToType)) |
2623 | return false; |
2624 | |
2625 | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). |
2626 | QualType ToPointee; |
2627 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) |
2628 | ToPointee = ToPointer->getPointeeType(); |
2629 | else |
2630 | return false; |
2631 | |
2632 | Qualifiers ToQuals = ToPointee.getQualifiers(); |
2633 | if (!ToPointee->isObjCLifetimeType() || |
2634 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || |
2635 | !ToQuals.withoutObjCLifetime().empty()) |
2636 | return false; |
2637 | |
2638 | // Argument must be a pointer to __strong to __weak. |
2639 | QualType FromPointee; |
2640 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) |
2641 | FromPointee = FromPointer->getPointeeType(); |
2642 | else |
2643 | return false; |
2644 | |
2645 | Qualifiers FromQuals = FromPointee.getQualifiers(); |
2646 | if (!FromPointee->isObjCLifetimeType() || |
2647 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && |
2648 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) |
2649 | return false; |
2650 | |
2651 | // Make sure that we have compatible qualifiers. |
2652 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); |
2653 | if (!ToQuals.compatiblyIncludes(FromQuals)) |
2654 | return false; |
2655 | |
2656 | // Remove qualifiers from the pointee type we're converting from; they |
2657 | // aren't used in the compatibility check belong, and we'll be adding back |
2658 | // qualifiers (with __autoreleasing) if the compatibility check succeeds. |
2659 | FromPointee = FromPointee.getUnqualifiedType(); |
2660 | |
2661 | // The unqualified form of the pointee types must be compatible. |
2662 | ToPointee = ToPointee.getUnqualifiedType(); |
2663 | bool IncompatibleObjC; |
2664 | if (Context.typesAreCompatible(FromPointee, ToPointee)) |
2665 | FromPointee = ToPointee; |
2666 | else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, |
2667 | IncompatibleObjC)) |
2668 | return false; |
2669 | |
2670 | /// Construct the type we're converting to, which is a pointer to |
2671 | /// __autoreleasing pointee. |
2672 | FromPointee = Context.getQualifiedType(FromPointee, FromQuals); |
2673 | ConvertedType = Context.getPointerType(FromPointee); |
2674 | return true; |
2675 | } |
2676 | |
2677 | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, |
2678 | QualType& ConvertedType) { |
2679 | QualType ToPointeeType; |
2680 | if (const BlockPointerType *ToBlockPtr = |
2681 | ToType->getAs<BlockPointerType>()) |
2682 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2683 | else |
2684 | return false; |
2685 | |
2686 | QualType FromPointeeType; |
2687 | if (const BlockPointerType *FromBlockPtr = |
2688 | FromType->getAs<BlockPointerType>()) |
2689 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2690 | else |
2691 | return false; |
2692 | // We have pointer to blocks, check whether the only |
2693 | // differences in the argument and result types are in Objective-C |
2694 | // pointer conversions. If so, we permit the conversion. |
2695 | |
2696 | const FunctionProtoType *FromFunctionType |
2697 | = FromPointeeType->getAs<FunctionProtoType>(); |
2698 | const FunctionProtoType *ToFunctionType |
2699 | = ToPointeeType->getAs<FunctionProtoType>(); |
2700 | |
2701 | if (!FromFunctionType || !ToFunctionType) |
2702 | return false; |
2703 | |
2704 | if (Context.hasSameType(FromPointeeType, ToPointeeType)) |
2705 | return true; |
2706 | |
2707 | // Perform the quick checks that will tell us whether these |
2708 | // function types are obviously different. |
2709 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2710 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) |
2711 | return false; |
2712 | |
2713 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); |
2714 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); |
2715 | if (FromEInfo != ToEInfo) |
2716 | return false; |
2717 | |
2718 | bool IncompatibleObjC = false; |
2719 | if (Context.hasSameType(FromFunctionType->getReturnType(), |
2720 | ToFunctionType->getReturnType())) { |
2721 | // Okay, the types match exactly. Nothing to do. |
2722 | } else { |
2723 | QualType RHS = FromFunctionType->getReturnType(); |
2724 | QualType LHS = ToFunctionType->getReturnType(); |
2725 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && |
2726 | !RHS.hasQualifiers() && LHS.hasQualifiers()) |
2727 | LHS = LHS.getUnqualifiedType(); |
2728 | |
2729 | if (Context.hasSameType(RHS,LHS)) { |
2730 | // OK exact match. |
2731 | } else if (isObjCPointerConversion(RHS, LHS, |
2732 | ConvertedType, IncompatibleObjC)) { |
2733 | if (IncompatibleObjC) |
2734 | return false; |
2735 | // Okay, we have an Objective-C pointer conversion. |
2736 | } |
2737 | else |
2738 | return false; |
2739 | } |
2740 | |
2741 | // Check argument types. |
2742 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2743 | ArgIdx != NumArgs; ++ArgIdx) { |
2744 | IncompatibleObjC = false; |
2745 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
2746 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
2747 | if (Context.hasSameType(FromArgType, ToArgType)) { |
2748 | // Okay, the types match exactly. Nothing to do. |
2749 | } else if (isObjCPointerConversion(ToArgType, FromArgType, |
2750 | ConvertedType, IncompatibleObjC)) { |
2751 | if (IncompatibleObjC) |
2752 | return false; |
2753 | // Okay, we have an Objective-C pointer conversion. |
2754 | } else |
2755 | // Argument types are too different. Abort. |
2756 | return false; |
2757 | } |
2758 | |
2759 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
2760 | bool CanUseToFPT, CanUseFromFPT; |
2761 | if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, |
2762 | CanUseToFPT, CanUseFromFPT, |
2763 | NewParamInfos)) |
2764 | return false; |
2765 | |
2766 | ConvertedType = ToType; |
2767 | return true; |
2768 | } |
2769 | |
2770 | enum { |
2771 | ft_default, |
2772 | ft_different_class, |
2773 | ft_parameter_arity, |
2774 | ft_parameter_mismatch, |
2775 | ft_return_type, |
2776 | ft_qualifer_mismatch, |
2777 | ft_noexcept |
2778 | }; |
2779 | |
2780 | /// Attempts to get the FunctionProtoType from a Type. Handles |
2781 | /// MemberFunctionPointers properly. |
2782 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { |
2783 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) |
2784 | return FPT; |
2785 | |
2786 | if (auto *MPT = FromType->getAs<MemberPointerType>()) |
2787 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); |
2788 | |
2789 | return nullptr; |
2790 | } |
2791 | |
2792 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing |
2793 | /// function types. Catches different number of parameter, mismatch in |
2794 | /// parameter types, and different return types. |
2795 | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
2796 | QualType FromType, QualType ToType) { |
2797 | // If either type is not valid, include no extra info. |
2798 | if (FromType.isNull() || ToType.isNull()) { |
2799 | PDiag << ft_default; |
2800 | return; |
2801 | } |
2802 | |
2803 | // Get the function type from the pointers. |
2804 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { |
2805 | const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), |
2806 | *ToMember = ToType->getAs<MemberPointerType>(); |
2807 | if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { |
2808 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) |
2809 | << QualType(FromMember->getClass(), 0); |
2810 | return; |
2811 | } |
2812 | FromType = FromMember->getPointeeType(); |
2813 | ToType = ToMember->getPointeeType(); |
2814 | } |
2815 | |
2816 | if (FromType->isPointerType()) |
2817 | FromType = FromType->getPointeeType(); |
2818 | if (ToType->isPointerType()) |
2819 | ToType = ToType->getPointeeType(); |
2820 | |
2821 | // Remove references. |
2822 | FromType = FromType.getNonReferenceType(); |
2823 | ToType = ToType.getNonReferenceType(); |
2824 | |
2825 | // Don't print extra info for non-specialized template functions. |
2826 | if (FromType->isInstantiationDependentType() && |
2827 | !FromType->getAs<TemplateSpecializationType>()) { |
2828 | PDiag << ft_default; |
2829 | return; |
2830 | } |
2831 | |
2832 | // No extra info for same types. |
2833 | if (Context.hasSameType(FromType, ToType)) { |
2834 | PDiag << ft_default; |
2835 | return; |
2836 | } |
2837 | |
2838 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), |
2839 | *ToFunction = tryGetFunctionProtoType(ToType); |
2840 | |
2841 | // Both types need to be function types. |
2842 | if (!FromFunction || !ToFunction) { |
2843 | PDiag << ft_default; |
2844 | return; |
2845 | } |
2846 | |
2847 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { |
2848 | PDiag << ft_parameter_arity << ToFunction->getNumParams() |
2849 | << FromFunction->getNumParams(); |
2850 | return; |
2851 | } |
2852 | |
2853 | // Handle different parameter types. |
2854 | unsigned ArgPos; |
2855 | if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { |
2856 | PDiag << ft_parameter_mismatch << ArgPos + 1 |
2857 | << ToFunction->getParamType(ArgPos) |
2858 | << FromFunction->getParamType(ArgPos); |
2859 | return; |
2860 | } |
2861 | |
2862 | // Handle different return type. |
2863 | if (!Context.hasSameType(FromFunction->getReturnType(), |
2864 | ToFunction->getReturnType())) { |
2865 | PDiag << ft_return_type << ToFunction->getReturnType() |
2866 | << FromFunction->getReturnType(); |
2867 | return; |
2868 | } |
2869 | |
2870 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { |
2871 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() |
2872 | << FromFunction->getMethodQuals(); |
2873 | return; |
2874 | } |
2875 | |
2876 | // Handle exception specification differences on canonical type (in C++17 |
2877 | // onwards). |
2878 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) |
2879 | ->isNothrow() != |
2880 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) |
2881 | ->isNothrow()) { |
2882 | PDiag << ft_noexcept; |
2883 | return; |
2884 | } |
2885 | |
2886 | // Unable to find a difference, so add no extra info. |
2887 | PDiag << ft_default; |
2888 | } |
2889 | |
2890 | /// FunctionParamTypesAreEqual - This routine checks two function proto types |
2891 | /// for equality of their argument types. Caller has already checked that |
2892 | /// they have same number of arguments. If the parameters are different, |
2893 | /// ArgPos will have the parameter index of the first different parameter. |
2894 | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
2895 | const FunctionProtoType *NewType, |
2896 | unsigned *ArgPos) { |
2897 | for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), |
2898 | N = NewType->param_type_begin(), |
2899 | E = OldType->param_type_end(); |
2900 | O && (O != E); ++O, ++N) { |
2901 | if (!Context.hasSameType(O->getUnqualifiedType(), |
2902 | N->getUnqualifiedType())) { |
2903 | if (ArgPos) |
2904 | *ArgPos = O - OldType->param_type_begin(); |
2905 | return false; |
2906 | } |
2907 | } |
2908 | return true; |
2909 | } |
2910 | |
2911 | /// CheckPointerConversion - Check the pointer conversion from the |
2912 | /// expression From to the type ToType. This routine checks for |
2913 | /// ambiguous or inaccessible derived-to-base pointer |
2914 | /// conversions for which IsPointerConversion has already returned |
2915 | /// true. It returns true and produces a diagnostic if there was an |
2916 | /// error, or returns false otherwise. |
2917 | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, |
2918 | CastKind &Kind, |
2919 | CXXCastPath& BasePath, |
2920 | bool IgnoreBaseAccess, |
2921 | bool Diagnose) { |
2922 | QualType FromType = From->getType(); |
2923 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; |
2924 | |
2925 | Kind = CK_BitCast; |
2926 | |
2927 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && |
2928 | From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == |
2929 | Expr::NPCK_ZeroExpression) { |
2930 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) |
2931 | DiagRuntimeBehavior(From->getExprLoc(), From, |
2932 | PDiag(diag::warn_impcast_bool_to_null_pointer) |
2933 | << ToType << From->getSourceRange()); |
2934 | else if (!isUnevaluatedContext()) |
2935 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) |
2936 | << ToType << From->getSourceRange(); |
2937 | } |
2938 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { |
2939 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { |
2940 | QualType FromPointeeType = FromPtrType->getPointeeType(), |
2941 | ToPointeeType = ToPtrType->getPointeeType(); |
2942 | |
2943 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && |
2944 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { |
2945 | // We must have a derived-to-base conversion. Check an |
2946 | // ambiguous or inaccessible conversion. |
2947 | unsigned InaccessibleID = 0; |
2948 | unsigned AmbigiousID = 0; |
2949 | if (Diagnose) { |
2950 | InaccessibleID = diag::err_upcast_to_inaccessible_base; |
2951 | AmbigiousID = diag::err_ambiguous_derived_to_base_conv; |
2952 | } |
2953 | if (CheckDerivedToBaseConversion( |
2954 | FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, |
2955 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), |
2956 | &BasePath, IgnoreBaseAccess)) |
2957 | return true; |
2958 | |
2959 | // The conversion was successful. |
2960 | Kind = CK_DerivedToBase; |
2961 | } |
2962 | |
2963 | if (Diagnose && !IsCStyleOrFunctionalCast && |
2964 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { |
2965 | assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 2966, __PRETTY_FUNCTION__)) |
2966 | "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 2966, __PRETTY_FUNCTION__)); |
2967 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) |
2968 | << From->getSourceRange(); |
2969 | } |
2970 | } |
2971 | } else if (const ObjCObjectPointerType *ToPtrType = |
2972 | ToType->getAs<ObjCObjectPointerType>()) { |
2973 | if (const ObjCObjectPointerType *FromPtrType = |
2974 | FromType->getAs<ObjCObjectPointerType>()) { |
2975 | // Objective-C++ conversions are always okay. |
2976 | // FIXME: We should have a different class of conversions for the |
2977 | // Objective-C++ implicit conversions. |
2978 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) |
2979 | return false; |
2980 | } else if (FromType->isBlockPointerType()) { |
2981 | Kind = CK_BlockPointerToObjCPointerCast; |
2982 | } else { |
2983 | Kind = CK_CPointerToObjCPointerCast; |
2984 | } |
2985 | } else if (ToType->isBlockPointerType()) { |
2986 | if (!FromType->isBlockPointerType()) |
2987 | Kind = CK_AnyPointerToBlockPointerCast; |
2988 | } |
2989 | |
2990 | // We shouldn't fall into this case unless it's valid for other |
2991 | // reasons. |
2992 | if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) |
2993 | Kind = CK_NullToPointer; |
2994 | |
2995 | return false; |
2996 | } |
2997 | |
2998 | /// IsMemberPointerConversion - Determines whether the conversion of the |
2999 | /// expression From, which has the (possibly adjusted) type FromType, can be |
3000 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). |
3001 | /// If so, returns true and places the converted type (that might differ from |
3002 | /// ToType in its cv-qualifiers at some level) into ConvertedType. |
3003 | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, |
3004 | QualType ToType, |
3005 | bool InOverloadResolution, |
3006 | QualType &ConvertedType) { |
3007 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); |
3008 | if (!ToTypePtr) |
3009 | return false; |
3010 | |
3011 | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) |
3012 | if (From->isNullPointerConstant(Context, |
3013 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
3014 | : Expr::NPC_ValueDependentIsNull)) { |
3015 | ConvertedType = ToType; |
3016 | return true; |
3017 | } |
3018 | |
3019 | // Otherwise, both types have to be member pointers. |
3020 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); |
3021 | if (!FromTypePtr) |
3022 | return false; |
3023 | |
3024 | // A pointer to member of B can be converted to a pointer to member of D, |
3025 | // where D is derived from B (C++ 4.11p2). |
3026 | QualType FromClass(FromTypePtr->getClass(), 0); |
3027 | QualType ToClass(ToTypePtr->getClass(), 0); |
3028 | |
3029 | if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && |
3030 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { |
3031 | ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), |
3032 | ToClass.getTypePtr()); |
3033 | return true; |
3034 | } |
3035 | |
3036 | return false; |
3037 | } |
3038 | |
3039 | /// CheckMemberPointerConversion - Check the member pointer conversion from the |
3040 | /// expression From to the type ToType. This routine checks for ambiguous or |
3041 | /// virtual or inaccessible base-to-derived member pointer conversions |
3042 | /// for which IsMemberPointerConversion has already returned true. It returns |
3043 | /// true and produces a diagnostic if there was an error, or returns false |
3044 | /// otherwise. |
3045 | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, |
3046 | CastKind &Kind, |
3047 | CXXCastPath &BasePath, |
3048 | bool IgnoreBaseAccess) { |
3049 | QualType FromType = From->getType(); |
3050 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); |
3051 | if (!FromPtrType) { |
3052 | // This must be a null pointer to member pointer conversion |
3053 | assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3055, __PRETTY_FUNCTION__)) |
3054 | Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3055, __PRETTY_FUNCTION__)) |
3055 | "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3055, __PRETTY_FUNCTION__)); |
3056 | Kind = CK_NullToMemberPointer; |
3057 | return false; |
3058 | } |
3059 | |
3060 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); |
3061 | assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? static_cast<void> ( 0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3062, __PRETTY_FUNCTION__)) |
3062 | "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? static_cast<void> ( 0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3062, __PRETTY_FUNCTION__)); |
3063 | |
3064 | QualType FromClass = QualType(FromPtrType->getClass(), 0); |
3065 | QualType ToClass = QualType(ToPtrType->getClass(), 0); |
3066 | |
3067 | // FIXME: What about dependent types? |
3068 | assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class." ) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3068, __PRETTY_FUNCTION__)); |
3069 | assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class." ) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3069, __PRETTY_FUNCTION__)); |
3070 | |
3071 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3072 | /*DetectVirtual=*/true); |
3073 | bool DerivationOkay = |
3074 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); |
3075 | assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK." ) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3076, __PRETTY_FUNCTION__)) |
3076 | "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK." ) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3076, __PRETTY_FUNCTION__)); |
3077 | (void)DerivationOkay; |
3078 | |
3079 | if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). |
3080 | getUnqualifiedType())) { |
3081 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3082 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) |
3083 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); |
3084 | return true; |
3085 | } |
3086 | |
3087 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { |
3088 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) |
3089 | << FromClass << ToClass << QualType(VBase, 0) |
3090 | << From->getSourceRange(); |
3091 | return true; |
3092 | } |
3093 | |
3094 | if (!IgnoreBaseAccess) |
3095 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, |
3096 | Paths.front(), |
3097 | diag::err_downcast_from_inaccessible_base); |
3098 | |
3099 | // Must be a base to derived member conversion. |
3100 | BuildBasePathArray(Paths, BasePath); |
3101 | Kind = CK_BaseToDerivedMemberPointer; |
3102 | return false; |
3103 | } |
3104 | |
3105 | /// Determine whether the lifetime conversion between the two given |
3106 | /// qualifiers sets is nontrivial. |
3107 | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, |
3108 | Qualifiers ToQuals) { |
3109 | // Converting anything to const __unsafe_unretained is trivial. |
3110 | if (ToQuals.hasConst() && |
3111 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) |
3112 | return false; |
3113 | |
3114 | return true; |
3115 | } |
3116 | |
3117 | /// IsQualificationConversion - Determines whether the conversion from |
3118 | /// an rvalue of type FromType to ToType is a qualification conversion |
3119 | /// (C++ 4.4). |
3120 | /// |
3121 | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate |
3122 | /// when the qualification conversion involves a change in the Objective-C |
3123 | /// object lifetime. |
3124 | bool |
3125 | Sema::IsQualificationConversion(QualType FromType, QualType ToType, |
3126 | bool CStyle, bool &ObjCLifetimeConversion) { |
3127 | FromType = Context.getCanonicalType(FromType); |
3128 | ToType = Context.getCanonicalType(ToType); |
3129 | ObjCLifetimeConversion = false; |
3130 | |
3131 | // If FromType and ToType are the same type, this is not a |
3132 | // qualification conversion. |
3133 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) |
3134 | return false; |
3135 | |
3136 | // (C++ 4.4p4): |
3137 | // A conversion can add cv-qualifiers at levels other than the first |
3138 | // in multi-level pointers, subject to the following rules: [...] |
3139 | bool PreviousToQualsIncludeConst = true; |
3140 | bool UnwrappedAnyPointer = false; |
3141 | while (Context.UnwrapSimilarTypes(FromType, ToType)) { |
3142 | // Within each iteration of the loop, we check the qualifiers to |
3143 | // determine if this still looks like a qualification |
3144 | // conversion. Then, if all is well, we unwrap one more level of |
3145 | // pointers or pointers-to-members and do it all again |
3146 | // until there are no more pointers or pointers-to-members left to |
3147 | // unwrap. |
3148 | UnwrappedAnyPointer = true; |
3149 | |
3150 | Qualifiers FromQuals = FromType.getQualifiers(); |
3151 | Qualifiers ToQuals = ToType.getQualifiers(); |
3152 | |
3153 | // Ignore __unaligned qualifier if this type is void. |
3154 | if (ToType.getUnqualifiedType()->isVoidType()) |
3155 | FromQuals.removeUnaligned(); |
3156 | |
3157 | // Objective-C ARC: |
3158 | // Check Objective-C lifetime conversions. |
3159 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && |
3160 | UnwrappedAnyPointer) { |
3161 | if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { |
3162 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) |
3163 | ObjCLifetimeConversion = true; |
3164 | FromQuals.removeObjCLifetime(); |
3165 | ToQuals.removeObjCLifetime(); |
3166 | } else { |
3167 | // Qualification conversions cannot cast between different |
3168 | // Objective-C lifetime qualifiers. |
3169 | return false; |
3170 | } |
3171 | } |
3172 | |
3173 | // Allow addition/removal of GC attributes but not changing GC attributes. |
3174 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && |
3175 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { |
3176 | FromQuals.removeObjCGCAttr(); |
3177 | ToQuals.removeObjCGCAttr(); |
3178 | } |
3179 | |
3180 | // -- for every j > 0, if const is in cv 1,j then const is in cv |
3181 | // 2,j, and similarly for volatile. |
3182 | if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) |
3183 | return false; |
3184 | |
3185 | // -- if the cv 1,j and cv 2,j are different, then const is in |
3186 | // every cv for 0 < k < j. |
3187 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() |
3188 | && !PreviousToQualsIncludeConst) |
3189 | return false; |
3190 | |
3191 | // Keep track of whether all prior cv-qualifiers in the "to" type |
3192 | // include const. |
3193 | PreviousToQualsIncludeConst |
3194 | = PreviousToQualsIncludeConst && ToQuals.hasConst(); |
3195 | } |
3196 | |
3197 | // Allows address space promotion by language rules implemented in |
3198 | // Type::Qualifiers::isAddressSpaceSupersetOf. |
3199 | Qualifiers FromQuals = FromType.getQualifiers(); |
3200 | Qualifiers ToQuals = ToType.getQualifiers(); |
3201 | if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && |
3202 | !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { |
3203 | return false; |
3204 | } |
3205 | |
3206 | // We are left with FromType and ToType being the pointee types |
3207 | // after unwrapping the original FromType and ToType the same number |
3208 | // of types. If we unwrapped any pointers, and if FromType and |
3209 | // ToType have the same unqualified type (since we checked |
3210 | // qualifiers above), then this is a qualification conversion. |
3211 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); |
3212 | } |
3213 | |
3214 | /// - Determine whether this is a conversion from a scalar type to an |
3215 | /// atomic type. |
3216 | /// |
3217 | /// If successful, updates \c SCS's second and third steps in the conversion |
3218 | /// sequence to finish the conversion. |
3219 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
3220 | bool InOverloadResolution, |
3221 | StandardConversionSequence &SCS, |
3222 | bool CStyle) { |
3223 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); |
3224 | if (!ToAtomic) |
3225 | return false; |
3226 | |
3227 | StandardConversionSequence InnerSCS; |
3228 | if (!IsStandardConversion(S, From, ToAtomic->getValueType(), |
3229 | InOverloadResolution, InnerSCS, |
3230 | CStyle, /*AllowObjCWritebackConversion=*/false)) |
3231 | return false; |
3232 | |
3233 | SCS.Second = InnerSCS.Second; |
3234 | SCS.setToType(1, InnerSCS.getToType(1)); |
3235 | SCS.Third = InnerSCS.Third; |
3236 | SCS.QualificationIncludesObjCLifetime |
3237 | = InnerSCS.QualificationIncludesObjCLifetime; |
3238 | SCS.setToType(2, InnerSCS.getToType(2)); |
3239 | return true; |
3240 | } |
3241 | |
3242 | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, |
3243 | CXXConstructorDecl *Constructor, |
3244 | QualType Type) { |
3245 | const FunctionProtoType *CtorType = |
3246 | Constructor->getType()->getAs<FunctionProtoType>(); |
3247 | if (CtorType->getNumParams() > 0) { |
3248 | QualType FirstArg = CtorType->getParamType(0); |
3249 | if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) |
3250 | return true; |
3251 | } |
3252 | return false; |
3253 | } |
3254 | |
3255 | static OverloadingResult |
3256 | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, |
3257 | CXXRecordDecl *To, |
3258 | UserDefinedConversionSequence &User, |
3259 | OverloadCandidateSet &CandidateSet, |
3260 | bool AllowExplicit) { |
3261 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3262 | for (auto *D : S.LookupConstructors(To)) { |
3263 | auto Info = getConstructorInfo(D); |
3264 | if (!Info) |
3265 | continue; |
3266 | |
3267 | bool Usable = !Info.Constructor->isInvalidDecl() && |
3268 | S.isInitListConstructor(Info.Constructor) && |
3269 | (AllowExplicit || !Info.Constructor->isExplicit()); |
3270 | if (Usable) { |
3271 | // If the first argument is (a reference to) the target type, |
3272 | // suppress conversions. |
3273 | bool SuppressUserConversions = isFirstArgumentCompatibleWithType( |
3274 | S.Context, Info.Constructor, ToType); |
3275 | if (Info.ConstructorTmpl) |
3276 | S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, |
3277 | /*ExplicitArgs*/ nullptr, From, |
3278 | CandidateSet, SuppressUserConversions, |
3279 | /*PartialOverloading*/ false, |
3280 | AllowExplicit); |
3281 | else |
3282 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, |
3283 | CandidateSet, SuppressUserConversions, |
3284 | /*PartialOverloading*/ false, AllowExplicit); |
3285 | } |
3286 | } |
3287 | |
3288 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3289 | |
3290 | OverloadCandidateSet::iterator Best; |
3291 | switch (auto Result = |
3292 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3293 | case OR_Deleted: |
3294 | case OR_Success: { |
3295 | // Record the standard conversion we used and the conversion function. |
3296 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); |
3297 | QualType ThisType = Constructor->getThisType(); |
3298 | // Initializer lists don't have conversions as such. |
3299 | User.Before.setAsIdentityConversion(); |
3300 | User.HadMultipleCandidates = HadMultipleCandidates; |
3301 | User.ConversionFunction = Constructor; |
3302 | User.FoundConversionFunction = Best->FoundDecl; |
3303 | User.After.setAsIdentityConversion(); |
3304 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); |
3305 | User.After.setAllToTypes(ToType); |
3306 | return Result; |
3307 | } |
3308 | |
3309 | case OR_No_Viable_Function: |
3310 | return OR_No_Viable_Function; |
3311 | case OR_Ambiguous: |
3312 | return OR_Ambiguous; |
3313 | } |
3314 | |
3315 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3315); |
3316 | } |
3317 | |
3318 | /// Determines whether there is a user-defined conversion sequence |
3319 | /// (C++ [over.ics.user]) that converts expression From to the type |
3320 | /// ToType. If such a conversion exists, User will contain the |
3321 | /// user-defined conversion sequence that performs such a conversion |
3322 | /// and this routine will return true. Otherwise, this routine returns |
3323 | /// false and User is unspecified. |
3324 | /// |
3325 | /// \param AllowExplicit true if the conversion should consider C++0x |
3326 | /// "explicit" conversion functions as well as non-explicit conversion |
3327 | /// functions (C++0x [class.conv.fct]p2). |
3328 | /// |
3329 | /// \param AllowObjCConversionOnExplicit true if the conversion should |
3330 | /// allow an extra Objective-C pointer conversion on uses of explicit |
3331 | /// constructors. Requires \c AllowExplicit to also be set. |
3332 | static OverloadingResult |
3333 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
3334 | UserDefinedConversionSequence &User, |
3335 | OverloadCandidateSet &CandidateSet, |
3336 | bool AllowExplicit, |
3337 | bool AllowObjCConversionOnExplicit) { |
3338 | assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast <void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3338, __PRETTY_FUNCTION__)); |
3339 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3340 | |
3341 | // Whether we will only visit constructors. |
3342 | bool ConstructorsOnly = false; |
3343 | |
3344 | // If the type we are conversion to is a class type, enumerate its |
3345 | // constructors. |
3346 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { |
3347 | // C++ [over.match.ctor]p1: |
3348 | // When objects of class type are direct-initialized (8.5), or |
3349 | // copy-initialized from an expression of the same or a |
3350 | // derived class type (8.5), overload resolution selects the |
3351 | // constructor. [...] For copy-initialization, the candidate |
3352 | // functions are all the converting constructors (12.3.1) of |
3353 | // that class. The argument list is the expression-list within |
3354 | // the parentheses of the initializer. |
3355 | if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || |
3356 | (From->getType()->getAs<RecordType>() && |
3357 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) |
3358 | ConstructorsOnly = true; |
3359 | |
3360 | if (!S.isCompleteType(From->getExprLoc(), ToType)) { |
3361 | // We're not going to find any constructors. |
3362 | } else if (CXXRecordDecl *ToRecordDecl |
3363 | = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { |
3364 | |
3365 | Expr **Args = &From; |
3366 | unsigned NumArgs = 1; |
3367 | bool ListInitializing = false; |
3368 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { |
3369 | // But first, see if there is an init-list-constructor that will work. |
3370 | OverloadingResult Result = IsInitializerListConstructorConversion( |
3371 | S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); |
3372 | if (Result != OR_No_Viable_Function) |
3373 | return Result; |
3374 | // Never mind. |
3375 | CandidateSet.clear( |
3376 | OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3377 | |
3378 | // If we're list-initializing, we pass the individual elements as |
3379 | // arguments, not the entire list. |
3380 | Args = InitList->getInits(); |
3381 | NumArgs = InitList->getNumInits(); |
3382 | ListInitializing = true; |
3383 | } |
3384 | |
3385 | for (auto *D : S.LookupConstructors(ToRecordDecl)) { |
3386 | auto Info = getConstructorInfo(D); |
3387 | if (!Info) |
3388 | continue; |
3389 | |
3390 | bool Usable = !Info.Constructor->isInvalidDecl(); |
3391 | if (ListInitializing) |
3392 | Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); |
3393 | else |
3394 | Usable = Usable && |
3395 | Info.Constructor->isConvertingConstructor(AllowExplicit); |
3396 | if (Usable) { |
3397 | bool SuppressUserConversions = !ConstructorsOnly; |
3398 | if (SuppressUserConversions && ListInitializing) { |
3399 | SuppressUserConversions = false; |
3400 | if (NumArgs == 1) { |
3401 | // If the first argument is (a reference to) the target type, |
3402 | // suppress conversions. |
3403 | SuppressUserConversions = isFirstArgumentCompatibleWithType( |
3404 | S.Context, Info.Constructor, ToType); |
3405 | } |
3406 | } |
3407 | if (Info.ConstructorTmpl) |
3408 | S.AddTemplateOverloadCandidate( |
3409 | Info.ConstructorTmpl, Info.FoundDecl, |
3410 | /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), |
3411 | CandidateSet, SuppressUserConversions, |
3412 | /*PartialOverloading*/ false, AllowExplicit); |
3413 | else |
3414 | // Allow one user-defined conversion when user specifies a |
3415 | // From->ToType conversion via an static cast (c-style, etc). |
3416 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, |
3417 | llvm::makeArrayRef(Args, NumArgs), |
3418 | CandidateSet, SuppressUserConversions, |
3419 | /*PartialOverloading*/ false, AllowExplicit); |
3420 | } |
3421 | } |
3422 | } |
3423 | } |
3424 | |
3425 | // Enumerate conversion functions, if we're allowed to. |
3426 | if (ConstructorsOnly || isa<InitListExpr>(From)) { |
3427 | } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { |
3428 | // No conversion functions from incomplete types. |
3429 | } else if (const RecordType *FromRecordType = |
3430 | From->getType()->getAs<RecordType>()) { |
3431 | if (CXXRecordDecl *FromRecordDecl |
3432 | = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { |
3433 | // Add all of the conversion functions as candidates. |
3434 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); |
3435 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
3436 | DeclAccessPair FoundDecl = I.getPair(); |
3437 | NamedDecl *D = FoundDecl.getDecl(); |
3438 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
3439 | if (isa<UsingShadowDecl>(D)) |
3440 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
3441 | |
3442 | CXXConversionDecl *Conv; |
3443 | FunctionTemplateDecl *ConvTemplate; |
3444 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
3445 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
3446 | else |
3447 | Conv = cast<CXXConversionDecl>(D); |
3448 | |
3449 | if (AllowExplicit || !Conv->isExplicit()) { |
3450 | if (ConvTemplate) |
3451 | S.AddTemplateConversionCandidate( |
3452 | ConvTemplate, FoundDecl, ActingContext, From, ToType, |
3453 | CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); |
3454 | else |
3455 | S.AddConversionCandidate( |
3456 | Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, |
3457 | AllowObjCConversionOnExplicit, AllowExplicit); |
3458 | } |
3459 | } |
3460 | } |
3461 | } |
3462 | |
3463 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3464 | |
3465 | OverloadCandidateSet::iterator Best; |
3466 | switch (auto Result = |
3467 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3468 | case OR_Success: |
3469 | case OR_Deleted: |
3470 | // Record the standard conversion we used and the conversion function. |
3471 | if (CXXConstructorDecl *Constructor |
3472 | = dyn_cast<CXXConstructorDecl>(Best->Function)) { |
3473 | // C++ [over.ics.user]p1: |
3474 | // If the user-defined conversion is specified by a |
3475 | // constructor (12.3.1), the initial standard conversion |
3476 | // sequence converts the source type to the type required by |
3477 | // the argument of the constructor. |
3478 | // |
3479 | QualType ThisType = Constructor->getThisType(); |
3480 | if (isa<InitListExpr>(From)) { |
3481 | // Initializer lists don't have conversions as such. |
3482 | User.Before.setAsIdentityConversion(); |
3483 | } else { |
3484 | if (Best->Conversions[0].isEllipsis()) |
3485 | User.EllipsisConversion = true; |
3486 | else { |
3487 | User.Before = Best->Conversions[0].Standard; |
3488 | User.EllipsisConversion = false; |
3489 | } |
3490 | } |
3491 | User.HadMultipleCandidates = HadMultipleCandidates; |
3492 | User.ConversionFunction = Constructor; |
3493 | User.FoundConversionFunction = Best->FoundDecl; |
3494 | User.After.setAsIdentityConversion(); |
3495 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); |
3496 | User.After.setAllToTypes(ToType); |
3497 | return Result; |
3498 | } |
3499 | if (CXXConversionDecl *Conversion |
3500 | = dyn_cast<CXXConversionDecl>(Best->Function)) { |
3501 | // C++ [over.ics.user]p1: |
3502 | // |
3503 | // [...] If the user-defined conversion is specified by a |
3504 | // conversion function (12.3.2), the initial standard |
3505 | // conversion sequence converts the source type to the |
3506 | // implicit object parameter of the conversion function. |
3507 | User.Before = Best->Conversions[0].Standard; |
3508 | User.HadMultipleCandidates = HadMultipleCandidates; |
3509 | User.ConversionFunction = Conversion; |
3510 | User.FoundConversionFunction = Best->FoundDecl; |
3511 | User.EllipsisConversion = false; |
3512 | |
3513 | // C++ [over.ics.user]p2: |
3514 | // The second standard conversion sequence converts the |
3515 | // result of the user-defined conversion to the target type |
3516 | // for the sequence. Since an implicit conversion sequence |
3517 | // is an initialization, the special rules for |
3518 | // initialization by user-defined conversion apply when |
3519 | // selecting the best user-defined conversion for a |
3520 | // user-defined conversion sequence (see 13.3.3 and |
3521 | // 13.3.3.1). |
3522 | User.After = Best->FinalConversion; |
3523 | return Result; |
3524 | } |
3525 | llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3525); |
3526 | |
3527 | case OR_No_Viable_Function: |
3528 | return OR_No_Viable_Function; |
3529 | |
3530 | case OR_Ambiguous: |
3531 | return OR_Ambiguous; |
3532 | } |
3533 | |
3534 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 3534); |
3535 | } |
3536 | |
3537 | bool |
3538 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { |
3539 | ImplicitConversionSequence ICS; |
3540 | OverloadCandidateSet CandidateSet(From->getExprLoc(), |
3541 | OverloadCandidateSet::CSK_Normal); |
3542 | OverloadingResult OvResult = |
3543 | IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, |
3544 | CandidateSet, false, false); |
3545 | |
3546 | if (!(OvResult == OR_Ambiguous || |
3547 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) |
3548 | return false; |
3549 | |
3550 | auto Cands = CandidateSet.CompleteCandidates( |
3551 | *this, |
3552 | OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, |
3553 | From); |
3554 | if (OvResult == OR_Ambiguous) |
3555 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) |
3556 | << From->getType() << ToType << From->getSourceRange(); |
3557 | else { // OR_No_Viable_Function && !CandidateSet.empty() |
3558 | if (!RequireCompleteType(From->getBeginLoc(), ToType, |
3559 | diag::err_typecheck_nonviable_condition_incomplete, |
3560 | From->getType(), From->getSourceRange())) |
3561 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) |
3562 | << false << From->getType() << From->getSourceRange() << ToType; |
3563 | } |
3564 | |
3565 | CandidateSet.NoteCandidates( |
3566 | *this, From, Cands); |
3567 | return true; |
3568 | } |
3569 | |
3570 | /// Compare the user-defined conversion functions or constructors |
3571 | /// of two user-defined conversion sequences to determine whether any ordering |
3572 | /// is possible. |
3573 | static ImplicitConversionSequence::CompareKind |
3574 | compareConversionFunctions(Sema &S, FunctionDecl *Function1, |
3575 | FunctionDecl *Function2) { |
3576 | if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) |
3577 | return ImplicitConversionSequence::Indistinguishable; |
3578 | |
3579 | // Objective-C++: |
3580 | // If both conversion functions are implicitly-declared conversions from |
3581 | // a lambda closure type to a function pointer and a block pointer, |
3582 | // respectively, always prefer the conversion to a function pointer, |
3583 | // because the function pointer is more lightweight and is more likely |
3584 | // to keep code working. |
3585 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); |
3586 | if (!Conv1) |
3587 | return ImplicitConversionSequence::Indistinguishable; |
3588 | |
3589 | CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); |
3590 | if (!Conv2) |
3591 | return ImplicitConversionSequence::Indistinguishable; |
3592 | |
3593 | if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { |
3594 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); |
3595 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); |
3596 | if (Block1 != Block2) |
3597 | return Block1 ? ImplicitConversionSequence::Worse |
3598 | : ImplicitConversionSequence::Better; |
3599 | } |
3600 | |
3601 | return ImplicitConversionSequence::Indistinguishable; |
3602 | } |
3603 | |
3604 | static bool hasDeprecatedStringLiteralToCharPtrConversion( |
3605 | const ImplicitConversionSequence &ICS) { |
3606 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || |
3607 | (ICS.isUserDefined() && |
3608 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); |
3609 | } |
3610 | |
3611 | /// CompareImplicitConversionSequences - Compare two implicit |
3612 | /// conversion sequences to determine whether one is better than the |
3613 | /// other or if they are indistinguishable (C++ 13.3.3.2). |
3614 | static ImplicitConversionSequence::CompareKind |
3615 | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, |
3616 | const ImplicitConversionSequence& ICS1, |
3617 | const ImplicitConversionSequence& ICS2) |
3618 | { |
3619 | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit |
3620 | // conversion sequences (as defined in 13.3.3.1) |
3621 | // -- a standard conversion sequence (13.3.3.1.1) is a better |
3622 | // conversion sequence than a user-defined conversion sequence or |
3623 | // an ellipsis conversion sequence, and |
3624 | // -- a user-defined conversion sequence (13.3.3.1.2) is a better |
3625 | // conversion sequence than an ellipsis conversion sequence |
3626 | // (13.3.3.1.3). |
3627 | // |
3628 | // C++0x [over.best.ics]p10: |
3629 | // For the purpose of ranking implicit conversion sequences as |
3630 | // described in 13.3.3.2, the ambiguous conversion sequence is |
3631 | // treated as a user-defined sequence that is indistinguishable |
3632 | // from any other user-defined conversion sequence. |
3633 | |
3634 | // String literal to 'char *' conversion has been deprecated in C++03. It has |
3635 | // been removed from C++11. We still accept this conversion, if it happens at |
3636 | // the best viable function. Otherwise, this conversion is considered worse |
3637 | // than ellipsis conversion. Consider this as an extension; this is not in the |
3638 | // standard. For example: |
3639 | // |
3640 | // int &f(...); // #1 |
3641 | // void f(char*); // #2 |
3642 | // void g() { int &r = f("foo"); } |
3643 | // |
3644 | // In C++03, we pick #2 as the best viable function. |
3645 | // In C++11, we pick #1 as the best viable function, because ellipsis |
3646 | // conversion is better than string-literal to char* conversion (since there |
3647 | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't |
3648 | // convert arguments, #2 would be the best viable function in C++11. |
3649 | // If the best viable function has this conversion, a warning will be issued |
3650 | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. |
3651 | |
3652 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
3653 | hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != |
3654 | hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) |
3655 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) |
3656 | ? ImplicitConversionSequence::Worse |
3657 | : ImplicitConversionSequence::Better; |
3658 | |
3659 | if (ICS1.getKindRank() < ICS2.getKindRank()) |
3660 | return ImplicitConversionSequence::Better; |
3661 | if (ICS2.getKindRank() < ICS1.getKindRank()) |
3662 | return ImplicitConversionSequence::Worse; |
3663 | |
3664 | // The following checks require both conversion sequences to be of |
3665 | // the same kind. |
3666 | if (ICS1.getKind() != ICS2.getKind()) |
3667 | return ImplicitConversionSequence::Indistinguishable; |
3668 | |
3669 | ImplicitConversionSequence::CompareKind Result = |
3670 | ImplicitConversionSequence::Indistinguishable; |
3671 | |
3672 | // Two implicit conversion sequences of the same form are |
3673 | // indistinguishable conversion sequences unless one of the |
3674 | // following rules apply: (C++ 13.3.3.2p3): |
3675 | |
3676 | // List-initialization sequence L1 is a better conversion sequence than |
3677 | // list-initialization sequence L2 if: |
3678 | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, |
3679 | // if not that, |
3680 | // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", |
3681 | // and N1 is smaller than N2., |
3682 | // even if one of the other rules in this paragraph would otherwise apply. |
3683 | if (!ICS1.isBad()) { |
3684 | if (ICS1.isStdInitializerListElement() && |
3685 | !ICS2.isStdInitializerListElement()) |
3686 | return ImplicitConversionSequence::Better; |
3687 | if (!ICS1.isStdInitializerListElement() && |
3688 | ICS2.isStdInitializerListElement()) |
3689 | return ImplicitConversionSequence::Worse; |
3690 | } |
3691 | |
3692 | if (ICS1.isStandard()) |
3693 | // Standard conversion sequence S1 is a better conversion sequence than |
3694 | // standard conversion sequence S2 if [...] |
3695 | Result = CompareStandardConversionSequences(S, Loc, |
3696 | ICS1.Standard, ICS2.Standard); |
3697 | else if (ICS1.isUserDefined()) { |
3698 | // User-defined conversion sequence U1 is a better conversion |
3699 | // sequence than another user-defined conversion sequence U2 if |
3700 | // they contain the same user-defined conversion function or |
3701 | // constructor and if the second standard conversion sequence of |
3702 | // U1 is better than the second standard conversion sequence of |
3703 | // U2 (C++ 13.3.3.2p3). |
3704 | if (ICS1.UserDefined.ConversionFunction == |
3705 | ICS2.UserDefined.ConversionFunction) |
3706 | Result = CompareStandardConversionSequences(S, Loc, |
3707 | ICS1.UserDefined.After, |
3708 | ICS2.UserDefined.After); |
3709 | else |
3710 | Result = compareConversionFunctions(S, |
3711 | ICS1.UserDefined.ConversionFunction, |
3712 | ICS2.UserDefined.ConversionFunction); |
3713 | } |
3714 | |
3715 | return Result; |
3716 | } |
3717 | |
3718 | // Per 13.3.3.2p3, compare the given standard conversion sequences to |
3719 | // determine if one is a proper subset of the other. |
3720 | static ImplicitConversionSequence::CompareKind |
3721 | compareStandardConversionSubsets(ASTContext &Context, |
3722 | const StandardConversionSequence& SCS1, |
3723 | const StandardConversionSequence& SCS2) { |
3724 | ImplicitConversionSequence::CompareKind Result |
3725 | = ImplicitConversionSequence::Indistinguishable; |
3726 | |
3727 | // the identity conversion sequence is considered to be a subsequence of |
3728 | // any non-identity conversion sequence |
3729 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) |
3730 | return ImplicitConversionSequence::Better; |
3731 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) |
3732 | return ImplicitConversionSequence::Worse; |
3733 | |
3734 | if (SCS1.Second != SCS2.Second) { |
3735 | if (SCS1.Second == ICK_Identity) |
3736 | Result = ImplicitConversionSequence::Better; |
3737 | else if (SCS2.Second == ICK_Identity) |
3738 | Result = ImplicitConversionSequence::Worse; |
3739 | else |
3740 | return ImplicitConversionSequence::Indistinguishable; |
3741 | } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) |
3742 | return ImplicitConversionSequence::Indistinguishable; |
3743 | |
3744 | if (SCS1.Third == SCS2.Third) { |
3745 | return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result |
3746 | : ImplicitConversionSequence::Indistinguishable; |
3747 | } |
3748 | |
3749 | if (SCS1.Third == ICK_Identity) |
3750 | return Result == ImplicitConversionSequence::Worse |
3751 | ? ImplicitConversionSequence::Indistinguishable |
3752 | : ImplicitConversionSequence::Better; |
3753 | |
3754 | if (SCS2.Third == ICK_Identity) |
3755 | return Result == ImplicitConversionSequence::Better |
3756 | ? ImplicitConversionSequence::Indistinguishable |
3757 | : ImplicitConversionSequence::Worse; |
3758 | |
3759 | return ImplicitConversionSequence::Indistinguishable; |
3760 | } |
3761 | |
3762 | /// Determine whether one of the given reference bindings is better |
3763 | /// than the other based on what kind of bindings they are. |
3764 | static bool |
3765 | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, |
3766 | const StandardConversionSequence &SCS2) { |
3767 | // C++0x [over.ics.rank]p3b4: |
3768 | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an |
3769 | // implicit object parameter of a non-static member function declared |
3770 | // without a ref-qualifier, and *either* S1 binds an rvalue reference |
3771 | // to an rvalue and S2 binds an lvalue reference *or S1 binds an |
3772 | // lvalue reference to a function lvalue and S2 binds an rvalue |
3773 | // reference*. |
3774 | // |
3775 | // FIXME: Rvalue references. We're going rogue with the above edits, |
3776 | // because the semantics in the current C++0x working paper (N3225 at the |
3777 | // time of this writing) break the standard definition of std::forward |
3778 | // and std::reference_wrapper when dealing with references to functions. |
3779 | // Proposed wording changes submitted to CWG for consideration. |
3780 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || |
3781 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) |
3782 | return false; |
3783 | |
3784 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && |
3785 | SCS2.IsLvalueReference) || |
3786 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && |
3787 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); |
3788 | } |
3789 | |
3790 | enum class FixedEnumPromotion { |
3791 | None, |
3792 | ToUnderlyingType, |
3793 | ToPromotedUnderlyingType |
3794 | }; |
3795 | |
3796 | /// Returns kind of fixed enum promotion the \a SCS uses. |
3797 | static FixedEnumPromotion |
3798 | getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { |
3799 | |
3800 | if (SCS.Second != ICK_Integral_Promotion) |
3801 | return FixedEnumPromotion::None; |
3802 | |
3803 | QualType FromType = SCS.getFromType(); |
3804 | if (!FromType->isEnumeralType()) |
3805 | return FixedEnumPromotion::None; |
3806 | |
3807 | EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); |
3808 | if (!Enum->isFixed()) |
3809 | return FixedEnumPromotion::None; |
3810 | |
3811 | QualType UnderlyingType = Enum->getIntegerType(); |
3812 | if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) |
3813 | return FixedEnumPromotion::ToUnderlyingType; |
3814 | |
3815 | return FixedEnumPromotion::ToPromotedUnderlyingType; |
3816 | } |
3817 | |
3818 | /// CompareStandardConversionSequences - Compare two standard |
3819 | /// conversion sequences to determine whether one is better than the |
3820 | /// other or if they are indistinguishable (C++ 13.3.3.2p3). |
3821 | static ImplicitConversionSequence::CompareKind |
3822 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
3823 | const StandardConversionSequence& SCS1, |
3824 | const StandardConversionSequence& SCS2) |
3825 | { |
3826 | // Standard conversion sequence S1 is a better conversion sequence |
3827 | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): |
3828 | |
3829 | // -- S1 is a proper subsequence of S2 (comparing the conversion |
3830 | // sequences in the canonical form defined by 13.3.3.1.1, |
3831 | // excluding any Lvalue Transformation; the identity conversion |
3832 | // sequence is considered to be a subsequence of any |
3833 | // non-identity conversion sequence) or, if not that, |
3834 | if (ImplicitConversionSequence::CompareKind CK |
3835 | = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) |
3836 | return CK; |
3837 | |
3838 | // -- the rank of S1 is better than the rank of S2 (by the rules |
3839 | // defined below), or, if not that, |
3840 | ImplicitConversionRank Rank1 = SCS1.getRank(); |
3841 | ImplicitConversionRank Rank2 = SCS2.getRank(); |
3842 | if (Rank1 < Rank2) |
3843 | return ImplicitConversionSequence::Better; |
3844 | else if (Rank2 < Rank1) |
3845 | return ImplicitConversionSequence::Worse; |
3846 | |
3847 | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank |
3848 | // are indistinguishable unless one of the following rules |
3849 | // applies: |
3850 | |
3851 | // A conversion that is not a conversion of a pointer, or |
3852 | // pointer to member, to bool is better than another conversion |
3853 | // that is such a conversion. |
3854 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) |
3855 | return SCS2.isPointerConversionToBool() |
3856 | ? ImplicitConversionSequence::Better |
3857 | : ImplicitConversionSequence::Worse; |
3858 | |
3859 | // C++14 [over.ics.rank]p4b2: |
3860 | // This is retroactively applied to C++11 by CWG 1601. |
3861 | // |
3862 | // A conversion that promotes an enumeration whose underlying type is fixed |
3863 | // to its underlying type is better than one that promotes to the promoted |
3864 | // underlying type, if the two are different. |
3865 | FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); |
3866 | FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); |
3867 | if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && |
3868 | FEP1 != FEP2) |
3869 | return FEP1 == FixedEnumPromotion::ToUnderlyingType |
3870 | ? ImplicitConversionSequence::Better |
3871 | : ImplicitConversionSequence::Worse; |
3872 | |
3873 | // C++ [over.ics.rank]p4b2: |
3874 | // |
3875 | // If class B is derived directly or indirectly from class A, |
3876 | // conversion of B* to A* is better than conversion of B* to |
3877 | // void*, and conversion of A* to void* is better than conversion |
3878 | // of B* to void*. |
3879 | bool SCS1ConvertsToVoid |
3880 | = SCS1.isPointerConversionToVoidPointer(S.Context); |
3881 | bool SCS2ConvertsToVoid |
3882 | = SCS2.isPointerConversionToVoidPointer(S.Context); |
3883 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { |
3884 | // Exactly one of the conversion sequences is a conversion to |
3885 | // a void pointer; it's the worse conversion. |
3886 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better |
3887 | : ImplicitConversionSequence::Worse; |
3888 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { |
3889 | // Neither conversion sequence converts to a void pointer; compare |
3890 | // their derived-to-base conversions. |
3891 | if (ImplicitConversionSequence::CompareKind DerivedCK |
3892 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) |
3893 | return DerivedCK; |
3894 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && |
3895 | !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { |
3896 | // Both conversion sequences are conversions to void |
3897 | // pointers. Compare the source types to determine if there's an |
3898 | // inheritance relationship in their sources. |
3899 | QualType FromType1 = SCS1.getFromType(); |
3900 | QualType FromType2 = SCS2.getFromType(); |
3901 | |
3902 | // Adjust the types we're converting from via the array-to-pointer |
3903 | // conversion, if we need to. |
3904 | if (SCS1.First == ICK_Array_To_Pointer) |
3905 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
3906 | if (SCS2.First == ICK_Array_To_Pointer) |
3907 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
3908 | |
3909 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); |
3910 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); |
3911 | |
3912 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
3913 | return ImplicitConversionSequence::Better; |
3914 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
3915 | return ImplicitConversionSequence::Worse; |
3916 | |
3917 | // Objective-C++: If one interface is more specific than the |
3918 | // other, it is the better one. |
3919 | const ObjCObjectPointerType* FromObjCPtr1 |
3920 | = FromType1->getAs<ObjCObjectPointerType>(); |
3921 | const ObjCObjectPointerType* FromObjCPtr2 |
3922 | = FromType2->getAs<ObjCObjectPointerType>(); |
3923 | if (FromObjCPtr1 && FromObjCPtr2) { |
3924 | bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, |
3925 | FromObjCPtr2); |
3926 | bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, |
3927 | FromObjCPtr1); |
3928 | if (AssignLeft != AssignRight) { |
3929 | return AssignLeft? ImplicitConversionSequence::Better |
3930 | : ImplicitConversionSequence::Worse; |
3931 | } |
3932 | } |
3933 | } |
3934 | |
3935 | // Compare based on qualification conversions (C++ 13.3.3.2p3, |
3936 | // bullet 3). |
3937 | if (ImplicitConversionSequence::CompareKind QualCK |
3938 | = CompareQualificationConversions(S, SCS1, SCS2)) |
3939 | return QualCK; |
3940 | |
3941 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
3942 | // Check for a better reference binding based on the kind of bindings. |
3943 | if (isBetterReferenceBindingKind(SCS1, SCS2)) |
3944 | return ImplicitConversionSequence::Better; |
3945 | else if (isBetterReferenceBindingKind(SCS2, SCS1)) |
3946 | return ImplicitConversionSequence::Worse; |
3947 | |
3948 | // C++ [over.ics.rank]p3b4: |
3949 | // -- S1 and S2 are reference bindings (8.5.3), and the types to |
3950 | // which the references refer are the same type except for |
3951 | // top-level cv-qualifiers, and the type to which the reference |
3952 | // initialized by S2 refers is more cv-qualified than the type |
3953 | // to which the reference initialized by S1 refers. |
3954 | QualType T1 = SCS1.getToType(2); |
3955 | QualType T2 = SCS2.getToType(2); |
3956 | T1 = S.Context.getCanonicalType(T1); |
3957 | T2 = S.Context.getCanonicalType(T2); |
3958 | Qualifiers T1Quals, T2Quals; |
3959 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
3960 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
3961 | if (UnqualT1 == UnqualT2) { |
3962 | // Objective-C++ ARC: If the references refer to objects with different |
3963 | // lifetimes, prefer bindings that don't change lifetime. |
3964 | if (SCS1.ObjCLifetimeConversionBinding != |
3965 | SCS2.ObjCLifetimeConversionBinding) { |
3966 | return SCS1.ObjCLifetimeConversionBinding |
3967 | ? ImplicitConversionSequence::Worse |
3968 | : ImplicitConversionSequence::Better; |
3969 | } |
3970 | |
3971 | // If the type is an array type, promote the element qualifiers to the |
3972 | // type for comparison. |
3973 | if (isa<ArrayType>(T1) && T1Quals) |
3974 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); |
3975 | if (isa<ArrayType>(T2) && T2Quals) |
3976 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); |
3977 | if (T2.isMoreQualifiedThan(T1)) |
3978 | return ImplicitConversionSequence::Better; |
3979 | else if (T1.isMoreQualifiedThan(T2)) |
3980 | return ImplicitConversionSequence::Worse; |
3981 | } |
3982 | } |
3983 | |
3984 | // In Microsoft mode, prefer an integral conversion to a |
3985 | // floating-to-integral conversion if the integral conversion |
3986 | // is between types of the same size. |
3987 | // For example: |
3988 | // void f(float); |
3989 | // void f(int); |
3990 | // int main { |
3991 | // long a; |
3992 | // f(a); |
3993 | // } |
3994 | // Here, MSVC will call f(int) instead of generating a compile error |
3995 | // as clang will do in standard mode. |
3996 | if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && |
3997 | SCS2.Second == ICK_Floating_Integral && |
3998 | S.Context.getTypeSize(SCS1.getFromType()) == |
3999 | S.Context.getTypeSize(SCS1.getToType(2))) |
4000 | return ImplicitConversionSequence::Better; |
4001 | |
4002 | // Prefer a compatible vector conversion over a lax vector conversion |
4003 | // For example: |
4004 | // |
4005 | // typedef float __v4sf __attribute__((__vector_size__(16))); |
4006 | // void f(vector float); |
4007 | // void f(vector signed int); |
4008 | // int main() { |
4009 | // __v4sf a; |
4010 | // f(a); |
4011 | // } |
4012 | // Here, we'd like to choose f(vector float) and not |
4013 | // report an ambiguous call error |
4014 | if (SCS1.Second == ICK_Vector_Conversion && |
4015 | SCS2.Second == ICK_Vector_Conversion) { |
4016 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4017 | SCS1.getFromType(), SCS1.getToType(2)); |
4018 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4019 | SCS2.getFromType(), SCS2.getToType(2)); |
4020 | |
4021 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) |
4022 | return SCS1IsCompatibleVectorConversion |
4023 | ? ImplicitConversionSequence::Better |
4024 | : ImplicitConversionSequence::Worse; |
4025 | } |
4026 | |
4027 | return ImplicitConversionSequence::Indistinguishable; |
4028 | } |
4029 | |
4030 | /// CompareQualificationConversions - Compares two standard conversion |
4031 | /// sequences to determine whether they can be ranked based on their |
4032 | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). |
4033 | static ImplicitConversionSequence::CompareKind |
4034 | CompareQualificationConversions(Sema &S, |
4035 | const StandardConversionSequence& SCS1, |
4036 | const StandardConversionSequence& SCS2) { |
4037 | // C++ 13.3.3.2p3: |
4038 | // -- S1 and S2 differ only in their qualification conversion and |
4039 | // yield similar types T1 and T2 (C++ 4.4), respectively, and the |
4040 | // cv-qualification signature of type T1 is a proper subset of |
4041 | // the cv-qualification signature of type T2, and S1 is not the |
4042 | // deprecated string literal array-to-pointer conversion (4.2). |
4043 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || |
4044 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) |
4045 | return ImplicitConversionSequence::Indistinguishable; |
4046 | |
4047 | // FIXME: the example in the standard doesn't use a qualification |
4048 | // conversion (!) |
4049 | QualType T1 = SCS1.getToType(2); |
4050 | QualType T2 = SCS2.getToType(2); |
4051 | T1 = S.Context.getCanonicalType(T1); |
4052 | T2 = S.Context.getCanonicalType(T2); |
4053 | Qualifiers T1Quals, T2Quals; |
4054 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
4055 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
4056 | |
4057 | // If the types are the same, we won't learn anything by unwrapped |
4058 | // them. |
4059 | if (UnqualT1 == UnqualT2) |
4060 | return ImplicitConversionSequence::Indistinguishable; |
4061 | |
4062 | // If the type is an array type, promote the element qualifiers to the type |
4063 | // for comparison. |
4064 | if (isa<ArrayType>(T1) && T1Quals) |
4065 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); |
4066 | if (isa<ArrayType>(T2) && T2Quals) |
4067 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); |
4068 | |
4069 | ImplicitConversionSequence::CompareKind Result |
4070 | = ImplicitConversionSequence::Indistinguishable; |
4071 | |
4072 | // Objective-C++ ARC: |
4073 | // Prefer qualification conversions not involving a change in lifetime |
4074 | // to qualification conversions that do not change lifetime. |
4075 | if (SCS1.QualificationIncludesObjCLifetime != |
4076 | SCS2.QualificationIncludesObjCLifetime) { |
4077 | Result = SCS1.QualificationIncludesObjCLifetime |
4078 | ? ImplicitConversionSequence::Worse |
4079 | : ImplicitConversionSequence::Better; |
4080 | } |
4081 | |
4082 | while (S.Context.UnwrapSimilarTypes(T1, T2)) { |
4083 | // Within each iteration of the loop, we check the qualifiers to |
4084 | // determine if this still looks like a qualification |
4085 | // conversion. Then, if all is well, we unwrap one more level of |
4086 | // pointers or pointers-to-members and do it all again |
4087 | // until there are no more pointers or pointers-to-members left |
4088 | // to unwrap. This essentially mimics what |
4089 | // IsQualificationConversion does, but here we're checking for a |
4090 | // strict subset of qualifiers. |
4091 | if (T1.getQualifiers().withoutObjCLifetime() == |
4092 | T2.getQualifiers().withoutObjCLifetime()) |
4093 | // The qualifiers are the same, so this doesn't tell us anything |
4094 | // about how the sequences rank. |
4095 | // ObjC ownership quals are omitted above as they interfere with |
4096 | // the ARC overload rule. |
4097 | ; |
4098 | else if (T2.isMoreQualifiedThan(T1)) { |
4099 | // T1 has fewer qualifiers, so it could be the better sequence. |
4100 | if (Result == ImplicitConversionSequence::Worse) |
4101 | // Neither has qualifiers that are a subset of the other's |
4102 | // qualifiers. |
4103 | return ImplicitConversionSequence::Indistinguishable; |
4104 | |
4105 | Result = ImplicitConversionSequence::Better; |
4106 | } else if (T1.isMoreQualifiedThan(T2)) { |
4107 | // T2 has fewer qualifiers, so it could be the better sequence. |
4108 | if (Result == ImplicitConversionSequence::Better) |
4109 | // Neither has qualifiers that are a subset of the other's |
4110 | // qualifiers. |
4111 | return ImplicitConversionSequence::Indistinguishable; |
4112 | |
4113 | Result = ImplicitConversionSequence::Worse; |
4114 | } else { |
4115 | // Qualifiers are disjoint. |
4116 | return ImplicitConversionSequence::Indistinguishable; |
4117 | } |
4118 | |
4119 | // If the types after this point are equivalent, we're done. |
4120 | if (S.Context.hasSameUnqualifiedType(T1, T2)) |
4121 | break; |
4122 | } |
4123 | |
4124 | // Check that the winning standard conversion sequence isn't using |
4125 | // the deprecated string literal array to pointer conversion. |
4126 | switch (Result) { |
4127 | case ImplicitConversionSequence::Better: |
4128 | if (SCS1.DeprecatedStringLiteralToCharPtr) |
4129 | Result = ImplicitConversionSequence::Indistinguishable; |
4130 | break; |
4131 | |
4132 | case ImplicitConversionSequence::Indistinguishable: |
4133 | break; |
4134 | |
4135 | case ImplicitConversionSequence::Worse: |
4136 | if (SCS2.DeprecatedStringLiteralToCharPtr) |
4137 | Result = ImplicitConversionSequence::Indistinguishable; |
4138 | break; |
4139 | } |
4140 | |
4141 | return Result; |
4142 | } |
4143 | |
4144 | /// CompareDerivedToBaseConversions - Compares two standard conversion |
4145 | /// sequences to determine whether they can be ranked based on their |
4146 | /// various kinds of derived-to-base conversions (C++ |
4147 | /// [over.ics.rank]p4b3). As part of these checks, we also look at |
4148 | /// conversions between Objective-C interface types. |
4149 | static ImplicitConversionSequence::CompareKind |
4150 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
4151 | const StandardConversionSequence& SCS1, |
4152 | const StandardConversionSequence& SCS2) { |
4153 | QualType FromType1 = SCS1.getFromType(); |
4154 | QualType ToType1 = SCS1.getToType(1); |
4155 | QualType FromType2 = SCS2.getFromType(); |
4156 | QualType ToType2 = SCS2.getToType(1); |
4157 | |
4158 | // Adjust the types we're converting from via the array-to-pointer |
4159 | // conversion, if we need to. |
4160 | if (SCS1.First == ICK_Array_To_Pointer) |
4161 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
4162 | if (SCS2.First == ICK_Array_To_Pointer) |
4163 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
4164 | |
4165 | // Canonicalize all of the types. |
4166 | FromType1 = S.Context.getCanonicalType(FromType1); |
4167 | ToType1 = S.Context.getCanonicalType(ToType1); |
4168 | FromType2 = S.Context.getCanonicalType(FromType2); |
4169 | ToType2 = S.Context.getCanonicalType(ToType2); |
4170 | |
4171 | // C++ [over.ics.rank]p4b3: |
4172 | // |
4173 | // If class B is derived directly or indirectly from class A and |
4174 | // class C is derived directly or indirectly from B, |
4175 | // |
4176 | // Compare based on pointer conversions. |
4177 | if (SCS1.Second == ICK_Pointer_Conversion && |
4178 | SCS2.Second == ICK_Pointer_Conversion && |
4179 | /*FIXME: Remove if Objective-C id conversions get their own rank*/ |
4180 | FromType1->isPointerType() && FromType2->isPointerType() && |
4181 | ToType1->isPointerType() && ToType2->isPointerType()) { |
4182 | QualType FromPointee1 = |
4183 | FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4184 | QualType ToPointee1 = |
4185 | ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4186 | QualType FromPointee2 = |
4187 | FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4188 | QualType ToPointee2 = |
4189 | ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4190 | |
4191 | // -- conversion of C* to B* is better than conversion of C* to A*, |
4192 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4193 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4194 | return ImplicitConversionSequence::Better; |
4195 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4196 | return ImplicitConversionSequence::Worse; |
4197 | } |
4198 | |
4199 | // -- conversion of B* to A* is better than conversion of C* to A*, |
4200 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { |
4201 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4202 | return ImplicitConversionSequence::Better; |
4203 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4204 | return ImplicitConversionSequence::Worse; |
4205 | } |
4206 | } else if (SCS1.Second == ICK_Pointer_Conversion && |
4207 | SCS2.Second == ICK_Pointer_Conversion) { |
4208 | const ObjCObjectPointerType *FromPtr1 |
4209 | = FromType1->getAs<ObjCObjectPointerType>(); |
4210 | const ObjCObjectPointerType *FromPtr2 |
4211 | = FromType2->getAs<ObjCObjectPointerType>(); |
4212 | const ObjCObjectPointerType *ToPtr1 |
4213 | = ToType1->getAs<ObjCObjectPointerType>(); |
4214 | const ObjCObjectPointerType *ToPtr2 |
4215 | = ToType2->getAs<ObjCObjectPointerType>(); |
4216 | |
4217 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { |
4218 | // Apply the same conversion ranking rules for Objective-C pointer types |
4219 | // that we do for C++ pointers to class types. However, we employ the |
4220 | // Objective-C pseudo-subtyping relationship used for assignment of |
4221 | // Objective-C pointer types. |
4222 | bool FromAssignLeft |
4223 | = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); |
4224 | bool FromAssignRight |
4225 | = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); |
4226 | bool ToAssignLeft |
4227 | = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); |
4228 | bool ToAssignRight |
4229 | = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); |
4230 | |
4231 | // A conversion to an a non-id object pointer type or qualified 'id' |
4232 | // type is better than a conversion to 'id'. |
4233 | if (ToPtr1->isObjCIdType() && |
4234 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) |
4235 | return ImplicitConversionSequence::Worse; |
4236 | if (ToPtr2->isObjCIdType() && |
4237 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) |
4238 | return ImplicitConversionSequence::Better; |
4239 | |
4240 | // A conversion to a non-id object pointer type is better than a |
4241 | // conversion to a qualified 'id' type |
4242 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) |
4243 | return ImplicitConversionSequence::Worse; |
4244 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) |
4245 | return ImplicitConversionSequence::Better; |
4246 | |
4247 | // A conversion to an a non-Class object pointer type or qualified 'Class' |
4248 | // type is better than a conversion to 'Class'. |
4249 | if (ToPtr1->isObjCClassType() && |
4250 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) |
4251 | return ImplicitConversionSequence::Worse; |
4252 | if (ToPtr2->isObjCClassType() && |
4253 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) |
4254 | return ImplicitConversionSequence::Better; |
4255 | |
4256 | // A conversion to a non-Class object pointer type is better than a |
4257 | // conversion to a qualified 'Class' type. |
4258 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) |
4259 | return ImplicitConversionSequence::Worse; |
4260 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) |
4261 | return ImplicitConversionSequence::Better; |
4262 | |
4263 | // -- "conversion of C* to B* is better than conversion of C* to A*," |
4264 | if (S.Context.hasSameType(FromType1, FromType2) && |
4265 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && |
4266 | (ToAssignLeft != ToAssignRight)) { |
4267 | if (FromPtr1->isSpecialized()) { |
4268 | // "conversion of B<A> * to B * is better than conversion of B * to |
4269 | // C *. |
4270 | bool IsFirstSame = |
4271 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); |
4272 | bool IsSecondSame = |
4273 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); |
4274 | if (IsFirstSame) { |
4275 | if (!IsSecondSame) |
4276 | return ImplicitConversionSequence::Better; |
4277 | } else if (IsSecondSame) |
4278 | return ImplicitConversionSequence::Worse; |
4279 | } |
4280 | return ToAssignLeft? ImplicitConversionSequence::Worse |
4281 | : ImplicitConversionSequence::Better; |
4282 | } |
4283 | |
4284 | // -- "conversion of B* to A* is better than conversion of C* to A*," |
4285 | if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && |
4286 | (FromAssignLeft != FromAssignRight)) |
4287 | return FromAssignLeft? ImplicitConversionSequence::Better |
4288 | : ImplicitConversionSequence::Worse; |
4289 | } |
4290 | } |
4291 | |
4292 | // Ranking of member-pointer types. |
4293 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && |
4294 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && |
4295 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { |
4296 | const MemberPointerType * FromMemPointer1 = |
4297 | FromType1->getAs<MemberPointerType>(); |
4298 | const MemberPointerType * ToMemPointer1 = |
4299 | ToType1->getAs<MemberPointerType>(); |
4300 | const MemberPointerType * FromMemPointer2 = |
4301 | FromType2->getAs<MemberPointerType>(); |
4302 | const MemberPointerType * ToMemPointer2 = |
4303 | ToType2->getAs<MemberPointerType>(); |
4304 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); |
4305 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); |
4306 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); |
4307 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); |
4308 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); |
4309 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); |
4310 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); |
4311 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); |
4312 | // conversion of A::* to B::* is better than conversion of A::* to C::*, |
4313 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4314 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4315 | return ImplicitConversionSequence::Worse; |
4316 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4317 | return ImplicitConversionSequence::Better; |
4318 | } |
4319 | // conversion of B::* to C::* is better than conversion of A::* to C::* |
4320 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { |
4321 | if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4322 | return ImplicitConversionSequence::Better; |
4323 | else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4324 | return ImplicitConversionSequence::Worse; |
4325 | } |
4326 | } |
4327 | |
4328 | if (SCS1.Second == ICK_Derived_To_Base) { |
4329 | // -- conversion of C to B is better than conversion of C to A, |
4330 | // -- binding of an expression of type C to a reference of type |
4331 | // B& is better than binding an expression of type C to a |
4332 | // reference of type A&, |
4333 | if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4334 | !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4335 | if (S.IsDerivedFrom(Loc, ToType1, ToType2)) |
4336 | return ImplicitConversionSequence::Better; |
4337 | else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) |
4338 | return ImplicitConversionSequence::Worse; |
4339 | } |
4340 | |
4341 | // -- conversion of B to A is better than conversion of C to A. |
4342 | // -- binding of an expression of type B to a reference of type |
4343 | // A& is better than binding an expression of type C to a |
4344 | // reference of type A&, |
4345 | if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4346 | S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4347 | if (S.IsDerivedFrom(Loc, FromType2, FromType1)) |
4348 | return ImplicitConversionSequence::Better; |
4349 | else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) |
4350 | return ImplicitConversionSequence::Worse; |
4351 | } |
4352 | } |
4353 | |
4354 | return ImplicitConversionSequence::Indistinguishable; |
4355 | } |
4356 | |
4357 | /// Determine whether the given type is valid, e.g., it is not an invalid |
4358 | /// C++ class. |
4359 | static bool isTypeValid(QualType T) { |
4360 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) |
4361 | return !Record->isInvalidDecl(); |
4362 | |
4363 | return true; |
4364 | } |
4365 | |
4366 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to |
4367 | /// determine whether they are reference-related, |
4368 | /// reference-compatible, reference-compatible with added |
4369 | /// qualification, or incompatible, for use in C++ initialization by |
4370 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference |
4371 | /// type, and the first type (T1) is the pointee type of the reference |
4372 | /// type being initialized. |
4373 | Sema::ReferenceCompareResult |
4374 | Sema::CompareReferenceRelationship(SourceLocation Loc, |
4375 | QualType OrigT1, QualType OrigT2, |
4376 | bool &DerivedToBase, |
4377 | bool &ObjCConversion, |
4378 | bool &ObjCLifetimeConversion, |
4379 | bool &FunctionConversion) { |
4380 | assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4381, __PRETTY_FUNCTION__)) |
4381 | "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4381, __PRETTY_FUNCTION__)); |
4382 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4382, __PRETTY_FUNCTION__)); |
4383 | |
4384 | QualType T1 = Context.getCanonicalType(OrigT1); |
4385 | QualType T2 = Context.getCanonicalType(OrigT2); |
4386 | Qualifiers T1Quals, T2Quals; |
4387 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); |
4388 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); |
4389 | |
4390 | // C++ [dcl.init.ref]p4: |
4391 | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is |
4392 | // reference-related to "cv2 T2" if T1 is the same type as T2, or |
4393 | // T1 is a base class of T2. |
4394 | DerivedToBase = false; |
4395 | ObjCConversion = false; |
4396 | ObjCLifetimeConversion = false; |
4397 | QualType ConvertedT2; |
4398 | if (UnqualT1 == UnqualT2) { |
4399 | // Nothing to do. |
4400 | } else if (isCompleteType(Loc, OrigT2) && |
4401 | isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && |
4402 | IsDerivedFrom(Loc, UnqualT2, UnqualT1)) |
4403 | DerivedToBase = true; |
4404 | else if (UnqualT1->isObjCObjectOrInterfaceType() && |
4405 | UnqualT2->isObjCObjectOrInterfaceType() && |
4406 | Context.canBindObjCObjectType(UnqualT1, UnqualT2)) |
4407 | ObjCConversion = true; |
4408 | else if (UnqualT2->isFunctionType() && |
4409 | IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { |
4410 | // C++1z [dcl.init.ref]p4: |
4411 | // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept |
4412 | // function" and T1 is "function" |
4413 | // |
4414 | // We extend this to also apply to 'noreturn', so allow any function |
4415 | // conversion between function types. |
4416 | FunctionConversion = true; |
4417 | return Ref_Compatible; |
4418 | } else |
4419 | return Ref_Incompatible; |
4420 | |
4421 | // At this point, we know that T1 and T2 are reference-related (at |
4422 | // least). |
4423 | |
4424 | // If the type is an array type, promote the element qualifiers to the type |
4425 | // for comparison. |
4426 | if (isa<ArrayType>(T1) && T1Quals) |
4427 | T1 = Context.getQualifiedType(UnqualT1, T1Quals); |
4428 | if (isa<ArrayType>(T2) && T2Quals) |
4429 | T2 = Context.getQualifiedType(UnqualT2, T2Quals); |
4430 | |
4431 | // C++ [dcl.init.ref]p4: |
4432 | // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is |
4433 | // reference-related to T2 and cv1 is the same cv-qualification |
4434 | // as, or greater cv-qualification than, cv2. For purposes of |
4435 | // overload resolution, cases for which cv1 is greater |
4436 | // cv-qualification than cv2 are identified as |
4437 | // reference-compatible with added qualification (see 13.3.3.2). |
4438 | // |
4439 | // Note that we also require equivalence of Objective-C GC and address-space |
4440 | // qualifiers when performing these computations, so that e.g., an int in |
4441 | // address space 1 is not reference-compatible with an int in address |
4442 | // space 2. |
4443 | if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && |
4444 | T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { |
4445 | if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) |
4446 | ObjCLifetimeConversion = true; |
4447 | |
4448 | T1Quals.removeObjCLifetime(); |
4449 | T2Quals.removeObjCLifetime(); |
4450 | } |
4451 | |
4452 | // MS compiler ignores __unaligned qualifier for references; do the same. |
4453 | T1Quals.removeUnaligned(); |
4454 | T2Quals.removeUnaligned(); |
4455 | |
4456 | if (T1Quals.compatiblyIncludes(T2Quals)) |
4457 | return Ref_Compatible; |
4458 | else |
4459 | return Ref_Related; |
4460 | } |
4461 | |
4462 | /// Look for a user-defined conversion to a value reference-compatible |
4463 | /// with DeclType. Return true if something definite is found. |
4464 | static bool |
4465 | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, |
4466 | QualType DeclType, SourceLocation DeclLoc, |
4467 | Expr *Init, QualType T2, bool AllowRvalues, |
4468 | bool AllowExplicit) { |
4469 | assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types." ) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4469, __PRETTY_FUNCTION__)); |
4470 | CXXRecordDecl *T2RecordDecl |
4471 | = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); |
4472 | |
4473 | OverloadCandidateSet CandidateSet( |
4474 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
4475 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
4476 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4477 | NamedDecl *D = *I; |
4478 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4479 | if (isa<UsingShadowDecl>(D)) |
4480 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
4481 | |
4482 | FunctionTemplateDecl *ConvTemplate |
4483 | = dyn_cast<FunctionTemplateDecl>(D); |
4484 | CXXConversionDecl *Conv; |
4485 | if (ConvTemplate) |
4486 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
4487 | else |
4488 | Conv = cast<CXXConversionDecl>(D); |
4489 | |
4490 | // If this is an explicit conversion, and we're not allowed to consider |
4491 | // explicit conversions, skip it. |
4492 | if (!AllowExplicit && Conv->isExplicit()) |
4493 | continue; |
4494 | |
4495 | if (AllowRvalues) { |
4496 | bool DerivedToBase = false; |
4497 | bool ObjCConversion = false; |
4498 | bool ObjCLifetimeConversion = false; |
4499 | bool FunctionConversion = false; |
4500 | |
4501 | // If we are initializing an rvalue reference, don't permit conversion |
4502 | // functions that return lvalues. |
4503 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { |
4504 | const ReferenceType *RefType |
4505 | = Conv->getConversionType()->getAs<LValueReferenceType>(); |
4506 | if (RefType && !RefType->getPointeeType()->isFunctionType()) |
4507 | continue; |
4508 | } |
4509 | |
4510 | if (!ConvTemplate && |
4511 | S.CompareReferenceRelationship( |
4512 | DeclLoc, |
4513 | Conv->getConversionType() |
4514 | .getNonReferenceType() |
4515 | .getUnqualifiedType(), |
4516 | DeclType.getNonReferenceType().getUnqualifiedType(), |
4517 | DerivedToBase, ObjCConversion, ObjCLifetimeConversion, |
4518 | FunctionConversion) == Sema::Ref_Incompatible) |
4519 | continue; |
4520 | } else { |
4521 | // If the conversion function doesn't return a reference type, |
4522 | // it can't be considered for this conversion. An rvalue reference |
4523 | // is only acceptable if its referencee is a function type. |
4524 | |
4525 | const ReferenceType *RefType = |
4526 | Conv->getConversionType()->getAs<ReferenceType>(); |
4527 | if (!RefType || |
4528 | (!RefType->isLValueReferenceType() && |
4529 | !RefType->getPointeeType()->isFunctionType())) |
4530 | continue; |
4531 | } |
4532 | |
4533 | if (ConvTemplate) |
4534 | S.AddTemplateConversionCandidate( |
4535 | ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4536 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4537 | else |
4538 | S.AddConversionCandidate( |
4539 | Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4540 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4541 | } |
4542 | |
4543 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4544 | |
4545 | OverloadCandidateSet::iterator Best; |
4546 | switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { |
4547 | case OR_Success: |
4548 | // C++ [over.ics.ref]p1: |
4549 | // |
4550 | // [...] If the parameter binds directly to the result of |
4551 | // applying a conversion function to the argument |
4552 | // expression, the implicit conversion sequence is a |
4553 | // user-defined conversion sequence (13.3.3.1.2), with the |
4554 | // second standard conversion sequence either an identity |
4555 | // conversion or, if the conversion function returns an |
4556 | // entity of a type that is a derived class of the parameter |
4557 | // type, a derived-to-base Conversion. |
4558 | if (!Best->FinalConversion.DirectBinding) |
4559 | return false; |
4560 | |
4561 | ICS.setUserDefined(); |
4562 | ICS.UserDefined.Before = Best->Conversions[0].Standard; |
4563 | ICS.UserDefined.After = Best->FinalConversion; |
4564 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; |
4565 | ICS.UserDefined.ConversionFunction = Best->Function; |
4566 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; |
4567 | ICS.UserDefined.EllipsisConversion = false; |
4568 | assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4570, __PRETTY_FUNCTION__)) |
4569 | ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4570, __PRETTY_FUNCTION__)) |
4570 | "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4570, __PRETTY_FUNCTION__)); |
4571 | return true; |
4572 | |
4573 | case OR_Ambiguous: |
4574 | ICS.setAmbiguous(); |
4575 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); |
4576 | Cand != CandidateSet.end(); ++Cand) |
4577 | if (Cand->Best) |
4578 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
4579 | return true; |
4580 | |
4581 | case OR_No_Viable_Function: |
4582 | case OR_Deleted: |
4583 | // There was no suitable conversion, or we found a deleted |
4584 | // conversion; continue with other checks. |
4585 | return false; |
4586 | } |
4587 | |
4588 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4588); |
4589 | } |
4590 | |
4591 | /// Compute an implicit conversion sequence for reference |
4592 | /// initialization. |
4593 | static ImplicitConversionSequence |
4594 | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, |
4595 | SourceLocation DeclLoc, |
4596 | bool SuppressUserConversions, |
4597 | bool AllowExplicit) { |
4598 | assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference" ) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 4598, __PRETTY_FUNCTION__)); |
4599 | |
4600 | // Most paths end in a failed conversion. |
4601 | ImplicitConversionSequence ICS; |
4602 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
4603 | |
4604 | QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); |
4605 | QualType T2 = Init->getType(); |
4606 | |
4607 | // If the initializer is the address of an overloaded function, try |
4608 | // to resolve the overloaded function. If all goes well, T2 is the |
4609 | // type of the resulting function. |
4610 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
4611 | DeclAccessPair Found; |
4612 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, |
4613 | false, Found)) |
4614 | T2 = Fn->getType(); |
4615 | } |
4616 | |
4617 | // Compute some basic properties of the types and the initializer. |
4618 | bool isRValRef = DeclType->isRValueReferenceType(); |
4619 | bool DerivedToBase = false; |
4620 | bool ObjCConversion = false; |
4621 | bool ObjCLifetimeConversion = false; |
4622 | bool FunctionConversion = false; |
4623 | Expr::Classification InitCategory = Init->Classify(S.Context); |
4624 | Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship( |
4625 | DeclLoc, T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion, |
4626 | FunctionConversion); |
4627 | |
4628 | // C++0x [dcl.init.ref]p5: |
4629 | // A reference to type "cv1 T1" is initialized by an expression |
4630 | // of type "cv2 T2" as follows: |
4631 | |
4632 | // -- If reference is an lvalue reference and the initializer expression |
4633 | if (!isRValRef) { |
4634 | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is |
4635 | // reference-compatible with "cv2 T2," or |
4636 | // |
4637 | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. |
4638 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { |
4639 | // C++ [over.ics.ref]p1: |
4640 | // When a parameter of reference type binds directly (8.5.3) |
4641 | // to an argument expression, the implicit conversion sequence |
4642 | // is the identity conversion, unless the argument expression |
4643 | // has a type that is a derived class of the parameter type, |
4644 | // in which case the implicit conversion sequence is a |
4645 | // derived-to-base Conversion (13.3.3.1). |
4646 | ICS.setStandard(); |
4647 | ICS.Standard.First = ICK_Identity; |
4648 | ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base |
4649 | : ObjCConversion? ICK_Compatible_Conversion |
4650 | : ICK_Identity; |
4651 | ICS.Standard.Third = ICK_Identity; |
4652 | ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); |
4653 | ICS.Standard.setToType(0, T2); |
4654 | ICS.Standard.setToType(1, T1); |
4655 | ICS.Standard.setToType(2, T1); |
4656 | ICS.Standard.ReferenceBinding = true; |
4657 | ICS.Standard.DirectBinding = true; |
4658 | ICS.Standard.IsLvalueReference = !isRValRef; |
4659 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); |
4660 | ICS.Standard.BindsToRvalue = false; |
4661 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
4662 | ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; |
4663 | ICS.Standard.CopyConstructor = nullptr; |
4664 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; |
4665 | |
4666 | // Nothing more to do: the inaccessibility/ambiguity check for |
4667 | // derived-to-base conversions is suppressed when we're |
4668 | // computing the implicit conversion sequence (C++ |
4669 | // [over.best.ics]p2). |
4670 | return ICS; |
4671 | } |
4672 | |
4673 | // -- has a class type (i.e., T2 is a class type), where T1 is |
4674 | // not reference-related to T2, and can be implicitly |
4675 | // converted to an lvalue of type "cv3 T3," where "cv1 T1" |
4676 | // is reference-compatible with "cv3 T3" 92) (this |
4677 | // conversion is selected by enumerating the applicable |
4678 | // conversion functions (13.3.1.6) and choosing the best |
4679 | // one through overload resolution (13.3)), |
4680 | if (!SuppressUserConversions && T2->isRecordType() && |
4681 | S.isCompleteType(DeclLoc, T2) && |
4682 | RefRelationship == Sema::Ref_Incompatible) { |
4683 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
4684 | Init, T2, /*AllowRvalues=*/false, |
4685 | AllowExplicit)) |
4686 | return ICS; |
4687 | } |
4688 | } |
4689 | |
4690 | // -- Otherwise, the reference shall be an lvalue reference to a |
4691 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
4692 | // shall be an rvalue reference. |
4693 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) |
4694 | return ICS; |
4695 | |
4696 | // -- If the initializer expression |
4697 | // |
4698 | // -- is an xvalue, class prvalue, array prvalue or function |
4699 | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or |
4700 | if (RefRelationship == Sema::Ref_Compatible && |
4701 | (InitCategory.isXValue() || |
4702 | (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || |
4703 | (InitCategory.isLValue() && T2->isFunctionType()))) { |
4704 | ICS.setStandard(); |
4705 | ICS.Standard.First = ICK_Identity; |
4706 | ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base |
4707 | : ObjCConversion? ICK_Compatible_Conversion |
4708 | : ICK_Identity; |
4709 | ICS.Standard.Third = ICK_Identity; |
4710 | ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); |
4711 | ICS.Standard.setToType(0, T2); |
4712 | ICS.Standard.setToType(1, T1); |
4713 | ICS.Standard.setToType(2, T1); |
4714 | ICS.Standard.ReferenceBinding = true; |
4715 | // In C++0x, this is always a direct binding. In C++98/03, it's a direct |
4716 | // binding unless we're binding to a class prvalue. |
4717 | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we |
4718 | // allow the use of rvalue references in C++98/03 for the benefit of |
4719 | // standard library implementors; therefore, we need the xvalue check here. |
4720 | ICS.Standard.DirectBinding = |
4721 | S.getLangOpts().CPlusPlus11 || |
4722 | !(InitCategory.isPRValue() || T2->isRecordType()); |
4723 | ICS.Standard.IsLvalueReference = !isRValRef; |
4724 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); |
4725 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); |
4726 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
4727 | ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; |
4728 | ICS.Standard.CopyConstructor = nullptr; |
4729 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; |
4730 | return ICS; |
4731 | } |
4732 | |
4733 | // -- has a class type (i.e., T2 is a class type), where T1 is not |
4734 | // reference-related to T2, and can be implicitly converted to |
4735 | // an xvalue, class prvalue, or function lvalue of type |
4736 | // "cv3 T3", where "cv1 T1" is reference-compatible with |
4737 | // "cv3 T3", |
4738 | // |
4739 | // then the reference is bound to the value of the initializer |
4740 | // expression in the first case and to the result of the conversion |
4741 | // in the second case (or, in either case, to an appropriate base |
4742 | // class subobject). |
4743 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
4744 | T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && |
4745 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
4746 | Init, T2, /*AllowRvalues=*/true, |
4747 | AllowExplicit)) { |
4748 | // In the second case, if the reference is an rvalue reference |
4749 | // and the second standard conversion sequence of the |
4750 | // user-defined conversion sequence includes an lvalue-to-rvalue |
4751 | // conversion, the program is ill-formed. |
4752 | if (ICS.isUserDefined() && isRValRef && |
4753 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) |
4754 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
4755 | |
4756 | return ICS; |
4757 | } |
4758 | |
4759 | // A temporary of function type cannot be created; don't even try. |
4760 | if (T1->isFunctionType()) |
4761 | return ICS; |
4762 | |
4763 | // -- Otherwise, a temporary of type "cv1 T1" is created and |
4764 | // initialized from the initializer expression using the |
4765 | // rules for a non-reference copy initialization (8.5). The |
4766 | // reference is then bound to the temporary. If T1 is |
4767 | // reference-related to T2, cv1 must be the same |
4768 | // cv-qualification as, or greater cv-qualification than, |
4769 | // cv2; otherwise, the program is ill-formed. |
4770 | if (RefRelationship == Sema::Ref_Related) { |
4771 | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then |
4772 | // we would be reference-compatible or reference-compatible with |
4773 | // added qualification. But that wasn't the case, so the reference |
4774 | // initialization fails. |
4775 | // |
4776 | // Note that we only want to check address spaces and cvr-qualifiers here. |
4777 | // ObjC GC, lifetime and unaligned qualifiers aren't important. |
4778 | Qualifiers T1Quals = T1.getQualifiers(); |
4779 | Qualifiers T2Quals = T2.getQualifiers(); |
4780 | T1Quals.removeObjCGCAttr(); |
4781 | T1Quals.removeObjCLifetime(); |
4782 | T2Quals.removeObjCGCAttr(); |
4783 | T2Quals.removeObjCLifetime(); |
4784 | // MS compiler ignores __unaligned qualifier for references; do the same. |
4785 | T1Quals.removeUnaligned(); |
4786 | T2Quals.removeUnaligned(); |
4787 | if (!T1Quals.compatiblyIncludes(T2Quals)) |
4788 | return ICS; |
4789 | } |
4790 | |
4791 | // If at least one of the types is a class type, the types are not |
4792 | // related, and we aren't allowed any user conversions, the |
4793 | // reference binding fails. This case is important for breaking |
4794 | // recursion, since TryImplicitConversion below will attempt to |
4795 | // create a temporary through the use of a copy constructor. |
4796 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
4797 | (T1->isRecordType() || T2->isRecordType())) |
4798 | return ICS; |
4799 | |
4800 | // If T1 is reference-related to T2 and the reference is an rvalue |
4801 | // reference, the initializer expression shall not be an lvalue. |
4802 | if (RefRelationship >= Sema::Ref_Related && |
4803 | isRValRef && Init->Classify(S.Context).isLValue()) |
4804 | return ICS; |
4805 | |
4806 | // C++ [over.ics.ref]p2: |
4807 | // When a parameter of reference type is not bound directly to |
4808 | // an argument expression, the conversion sequence is the one |
4809 | // required to convert the argument expression to the |
4810 | // underlying type of the reference according to |
4811 | // 13.3.3.1. Conceptually, this conversion sequence corresponds |
4812 | // to copy-initializing a temporary of the underlying type with |
4813 | // the argument expression. Any difference in top-level |
4814 | // cv-qualification is subsumed by the initialization itself |
4815 | // and does not constitute a conversion. |
4816 | ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, |
4817 | /*AllowExplicit=*/false, |
4818 | /*InOverloadResolution=*/false, |
4819 | /*CStyle=*/false, |
4820 | /*AllowObjCWritebackConversion=*/false, |
4821 | /*AllowObjCConversionOnExplicit=*/false); |
4822 | |
4823 | // Of course, that's still a reference binding. |
4824 | if (ICS.isStandard()) { |
4825 | ICS.Standard.ReferenceBinding = true; |
4826 | ICS.Standard.IsLvalueReference = !isRValRef; |
4827 | ICS.Standard.BindsToFunctionLvalue = false; |
4828 | ICS.Standard.BindsToRvalue = true; |
4829 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
4830 | ICS.Standard.ObjCLifetimeConversionBinding = false; |
4831 | } else if (ICS.isUserDefined()) { |
4832 | const ReferenceType *LValRefType = |
4833 | ICS.UserDefined.ConversionFunction->getReturnType() |
4834 | ->getAs<LValueReferenceType>(); |
4835 | |
4836 | // C++ [over.ics.ref]p3: |
4837 | // Except for an implicit object parameter, for which see 13.3.1, a |
4838 | // standard conversion sequence cannot be formed if it requires [...] |
4839 | // binding an rvalue reference to an lvalue other than a function |
4840 | // lvalue. |
4841 | // Note that the function case is not possible here. |
4842 | if (DeclType->isRValueReferenceType() && LValRefType) { |
4843 | // FIXME: This is the wrong BadConversionSequence. The problem is binding |
4844 | // an rvalue reference to a (non-function) lvalue, not binding an lvalue |
4845 | // reference to an rvalue! |
4846 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); |
4847 | return ICS; |
4848 | } |
4849 | |
4850 | ICS.UserDefined.After.ReferenceBinding = true; |
4851 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; |
4852 | ICS.UserDefined.After.BindsToFunctionLvalue = false; |
4853 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; |
4854 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
4855 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; |
4856 | } |
4857 | |
4858 | return ICS; |
4859 | } |
4860 | |
4861 | static ImplicitConversionSequence |
4862 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
4863 | bool SuppressUserConversions, |
4864 | bool InOverloadResolution, |
4865 | bool AllowObjCWritebackConversion, |
4866 | bool AllowExplicit = false); |
4867 | |
4868 | /// TryListConversion - Try to copy-initialize a value of type ToType from the |
4869 | /// initializer list From. |
4870 | static ImplicitConversionSequence |
4871 | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, |
4872 | bool SuppressUserConversions, |
4873 | bool InOverloadResolution, |
4874 | bool AllowObjCWritebackConversion) { |
4875 | // C++11 [over.ics.list]p1: |
4876 | // When an argument is an initializer list, it is not an expression and |
4877 | // special rules apply for converting it to a parameter type. |
4878 | |
4879 | ImplicitConversionSequence Result; |
4880 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); |
4881 | |
4882 | // We need a complete type for what follows. Incomplete types can never be |
4883 | // initialized from init lists. |
4884 | if (!S.isCompleteType(From->getBeginLoc(), ToType)) |
4885 | return Result; |
4886 | |
4887 | // Per DR1467: |
4888 | // If the parameter type is a class X and the initializer list has a single |
4889 | // element of type cv U, where U is X or a class derived from X, the |
4890 | // implicit conversion sequence is the one required to convert the element |
4891 | // to the parameter type. |
4892 | // |
4893 | // Otherwise, if the parameter type is a character array [... ] |
4894 | // and the initializer list has a single element that is an |
4895 | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the |
4896 | // implicit conversion sequence is the identity conversion. |
4897 | if (From->getNumInits() == 1) { |
4898 | if (ToType->isRecordType()) { |
4899 | QualType InitType = From->getInit(0)->getType(); |
4900 | if (S.Context.hasSameUnqualifiedType(InitType, ToType) || |
4901 | S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) |
4902 | return TryCopyInitialization(S, From->getInit(0), ToType, |
4903 | SuppressUserConversions, |
4904 | InOverloadResolution, |
4905 | AllowObjCWritebackConversion); |
4906 | } |
4907 | // FIXME: Check the other conditions here: array of character type, |
4908 | // initializer is a string literal. |
4909 | if (ToType->isArrayType()) { |
4910 | InitializedEntity Entity = |
4911 | InitializedEntity::InitializeParameter(S.Context, ToType, |
4912 | /*Consumed=*/false); |
4913 | if (S.CanPerformCopyInitialization(Entity, From)) { |
4914 | Result.setStandard(); |
4915 | Result.Standard.setAsIdentityConversion(); |
4916 | Result.Standard.setFromType(ToType); |
4917 | Result.Standard.setAllToTypes(ToType); |
4918 | return Result; |
4919 | } |
4920 | } |
4921 | } |
4922 | |
4923 | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). |
4924 | // C++11 [over.ics.list]p2: |
4925 | // If the parameter type is std::initializer_list<X> or "array of X" and |
4926 | // all the elements can be implicitly converted to X, the implicit |
4927 | // conversion sequence is the worst conversion necessary to convert an |
4928 | // element of the list to X. |
4929 | // |
4930 | // C++14 [over.ics.list]p3: |
4931 | // Otherwise, if the parameter type is "array of N X", if the initializer |
4932 | // list has exactly N elements or if it has fewer than N elements and X is |
4933 | // default-constructible, and if all the elements of the initializer list |
4934 | // can be implicitly converted to X, the implicit conversion sequence is |
4935 | // the worst conversion necessary to convert an element of the list to X. |
4936 | // |
4937 | // FIXME: We're missing a lot of these checks. |
4938 | bool toStdInitializerList = false; |
4939 | QualType X; |
4940 | if (ToType->isArrayType()) |
4941 | X = S.Context.getAsArrayType(ToType)->getElementType(); |
4942 | else |
4943 | toStdInitializerList = S.isStdInitializerList(ToType, &X); |
4944 | if (!X.isNull()) { |
4945 | for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { |
4946 | Expr *Init = From->getInit(i); |
4947 | ImplicitConversionSequence ICS = |
4948 | TryCopyInitialization(S, Init, X, SuppressUserConversions, |
4949 | InOverloadResolution, |
4950 | AllowObjCWritebackConversion); |
4951 | // If a single element isn't convertible, fail. |
4952 | if (ICS.isBad()) { |
4953 | Result = ICS; |
4954 | break; |
4955 | } |
4956 | // Otherwise, look for the worst conversion. |
4957 | if (Result.isBad() || CompareImplicitConversionSequences( |
4958 | S, From->getBeginLoc(), ICS, Result) == |
4959 | ImplicitConversionSequence::Worse) |
4960 | Result = ICS; |
4961 | } |
4962 | |
4963 | // For an empty list, we won't have computed any conversion sequence. |
4964 | // Introduce the identity conversion sequence. |
4965 | if (From->getNumInits() == 0) { |
4966 | Result.setStandard(); |
4967 | Result.Standard.setAsIdentityConversion(); |
4968 | Result.Standard.setFromType(ToType); |
4969 | Result.Standard.setAllToTypes(ToType); |
4970 | } |
4971 | |
4972 | Result.setStdInitializerListElement(toStdInitializerList); |
4973 | return Result; |
4974 | } |
4975 | |
4976 | // C++14 [over.ics.list]p4: |
4977 | // C++11 [over.ics.list]p3: |
4978 | // Otherwise, if the parameter is a non-aggregate class X and overload |
4979 | // resolution chooses a single best constructor [...] the implicit |
4980 | // conversion sequence is a user-defined conversion sequence. If multiple |
4981 | // constructors are viable but none is better than the others, the |
4982 | // implicit conversion sequence is a user-defined conversion sequence. |
4983 | if (ToType->isRecordType() && !ToType->isAggregateType()) { |
4984 | // This function can deal with initializer lists. |
4985 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
4986 | /*AllowExplicit=*/false, |
4987 | InOverloadResolution, /*CStyle=*/false, |
4988 | AllowObjCWritebackConversion, |
4989 | /*AllowObjCConversionOnExplicit=*/false); |
4990 | } |
4991 | |
4992 | // C++14 [over.ics.list]p5: |
4993 | // C++11 [over.ics.list]p4: |
4994 | // Otherwise, if the parameter has an aggregate type which can be |
4995 | // initialized from the initializer list [...] the implicit conversion |
4996 | // sequence is a user-defined conversion sequence. |
4997 | if (ToType->isAggregateType()) { |
4998 | // Type is an aggregate, argument is an init list. At this point it comes |
4999 | // down to checking whether the initialization works. |
5000 | // FIXME: Find out whether this parameter is consumed or not. |
5001 | InitializedEntity Entity = |
5002 | InitializedEntity::InitializeParameter(S.Context, ToType, |
5003 | /*Consumed=*/false); |
5004 | if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, |
5005 | From)) { |
5006 | Result.setUserDefined(); |
5007 | Result.UserDefined.Before.setAsIdentityConversion(); |
5008 | // Initializer lists don't have a type. |
5009 | Result.UserDefined.Before.setFromType(QualType()); |
5010 | Result.UserDefined.Before.setAllToTypes(QualType()); |
5011 | |
5012 | Result.UserDefined.After.setAsIdentityConversion(); |
5013 | Result.UserDefined.After.setFromType(ToType); |
5014 | Result.UserDefined.After.setAllToTypes(ToType); |
5015 | Result.UserDefined.ConversionFunction = nullptr; |
5016 | } |
5017 | return Result; |
5018 | } |
5019 | |
5020 | // C++14 [over.ics.list]p6: |
5021 | // C++11 [over.ics.list]p5: |
5022 | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. |
5023 | if (ToType->isReferenceType()) { |
5024 | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't |
5025 | // mention initializer lists in any way. So we go by what list- |
5026 | // initialization would do and try to extrapolate from that. |
5027 | |
5028 | QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); |
5029 | |
5030 | // If the initializer list has a single element that is reference-related |
5031 | // to the parameter type, we initialize the reference from that. |
5032 | if (From->getNumInits() == 1) { |
5033 | Expr *Init = From->getInit(0); |
5034 | |
5035 | QualType T2 = Init->getType(); |
5036 | |
5037 | // If the initializer is the address of an overloaded function, try |
5038 | // to resolve the overloaded function. If all goes well, T2 is the |
5039 | // type of the resulting function. |
5040 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
5041 | DeclAccessPair Found; |
5042 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( |
5043 | Init, ToType, false, Found)) |
5044 | T2 = Fn->getType(); |
5045 | } |
5046 | |
5047 | // Compute some basic properties of the types and the initializer. |
5048 | bool dummy1 = false; |
5049 | bool dummy2 = false; |
5050 | bool dummy3 = false; |
5051 | bool dummy4 = false; |
5052 | Sema::ReferenceCompareResult RefRelationship = |
5053 | S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, |
5054 | dummy2, dummy3, dummy4); |
5055 | |
5056 | if (RefRelationship >= Sema::Ref_Related) { |
5057 | return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), |
5058 | SuppressUserConversions, |
5059 | /*AllowExplicit=*/false); |
5060 | } |
5061 | } |
5062 | |
5063 | // Otherwise, we bind the reference to a temporary created from the |
5064 | // initializer list. |
5065 | Result = TryListConversion(S, From, T1, SuppressUserConversions, |
5066 | InOverloadResolution, |
5067 | AllowObjCWritebackConversion); |
5068 | if (Result.isFailure()) |
5069 | return Result; |
5070 | assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5071, __PRETTY_FUNCTION__)) |
5071 | "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5071, __PRETTY_FUNCTION__)); |
5072 | |
5073 | // Can we even bind to a temporary? |
5074 | if (ToType->isRValueReferenceType() || |
5075 | (T1.isConstQualified() && !T1.isVolatileQualified())) { |
5076 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : |
5077 | Result.UserDefined.After; |
5078 | SCS.ReferenceBinding = true; |
5079 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); |
5080 | SCS.BindsToRvalue = true; |
5081 | SCS.BindsToFunctionLvalue = false; |
5082 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5083 | SCS.ObjCLifetimeConversionBinding = false; |
5084 | } else |
5085 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, |
5086 | From, ToType); |
5087 | return Result; |
5088 | } |
5089 | |
5090 | // C++14 [over.ics.list]p7: |
5091 | // C++11 [over.ics.list]p6: |
5092 | // Otherwise, if the parameter type is not a class: |
5093 | if (!ToType->isRecordType()) { |
5094 | // - if the initializer list has one element that is not itself an |
5095 | // initializer list, the implicit conversion sequence is the one |
5096 | // required to convert the element to the parameter type. |
5097 | unsigned NumInits = From->getNumInits(); |
5098 | if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) |
5099 | Result = TryCopyInitialization(S, From->getInit(0), ToType, |
5100 | SuppressUserConversions, |
5101 | InOverloadResolution, |
5102 | AllowObjCWritebackConversion); |
5103 | // - if the initializer list has no elements, the implicit conversion |
5104 | // sequence is the identity conversion. |
5105 | else if (NumInits == 0) { |
5106 | Result.setStandard(); |
5107 | Result.Standard.setAsIdentityConversion(); |
5108 | Result.Standard.setFromType(ToType); |
5109 | Result.Standard.setAllToTypes(ToType); |
5110 | } |
5111 | return Result; |
5112 | } |
5113 | |
5114 | // C++14 [over.ics.list]p8: |
5115 | // C++11 [over.ics.list]p7: |
5116 | // In all cases other than those enumerated above, no conversion is possible |
5117 | return Result; |
5118 | } |
5119 | |
5120 | /// TryCopyInitialization - Try to copy-initialize a value of type |
5121 | /// ToType from the expression From. Return the implicit conversion |
5122 | /// sequence required to pass this argument, which may be a bad |
5123 | /// conversion sequence (meaning that the argument cannot be passed to |
5124 | /// a parameter of this type). If @p SuppressUserConversions, then we |
5125 | /// do not permit any user-defined conversion sequences. |
5126 | static ImplicitConversionSequence |
5127 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5128 | bool SuppressUserConversions, |
5129 | bool InOverloadResolution, |
5130 | bool AllowObjCWritebackConversion, |
5131 | bool AllowExplicit) { |
5132 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) |
5133 | return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, |
5134 | InOverloadResolution,AllowObjCWritebackConversion); |
5135 | |
5136 | if (ToType->isReferenceType()) |
5137 | return TryReferenceInit(S, From, ToType, |
5138 | /*FIXME:*/ From->getBeginLoc(), |
5139 | SuppressUserConversions, AllowExplicit); |
5140 | |
5141 | return TryImplicitConversion(S, From, ToType, |
5142 | SuppressUserConversions, |
5143 | /*AllowExplicit=*/false, |
5144 | InOverloadResolution, |
5145 | /*CStyle=*/false, |
5146 | AllowObjCWritebackConversion, |
5147 | /*AllowObjCConversionOnExplicit=*/false); |
5148 | } |
5149 | |
5150 | static bool TryCopyInitialization(const CanQualType FromQTy, |
5151 | const CanQualType ToQTy, |
5152 | Sema &S, |
5153 | SourceLocation Loc, |
5154 | ExprValueKind FromVK) { |
5155 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); |
5156 | ImplicitConversionSequence ICS = |
5157 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); |
5158 | |
5159 | return !ICS.isBad(); |
5160 | } |
5161 | |
5162 | /// TryObjectArgumentInitialization - Try to initialize the object |
5163 | /// parameter of the given member function (@c Method) from the |
5164 | /// expression @p From. |
5165 | static ImplicitConversionSequence |
5166 | TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, |
5167 | Expr::Classification FromClassification, |
5168 | CXXMethodDecl *Method, |
5169 | CXXRecordDecl *ActingContext) { |
5170 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); |
5171 | // [class.dtor]p2: A destructor can be invoked for a const, volatile or |
5172 | // const volatile object. |
5173 | Qualifiers Quals = Method->getMethodQualifiers(); |
5174 | if (isa<CXXDestructorDecl>(Method)) { |
5175 | Quals.addConst(); |
5176 | Quals.addVolatile(); |
5177 | } |
5178 | |
5179 | QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); |
5180 | |
5181 | // Set up the conversion sequence as a "bad" conversion, to allow us |
5182 | // to exit early. |
5183 | ImplicitConversionSequence ICS; |
5184 | |
5185 | // We need to have an object of class type. |
5186 | if (const PointerType *PT = FromType->getAs<PointerType>()) { |
5187 | FromType = PT->getPointeeType(); |
5188 | |
5189 | // When we had a pointer, it's implicitly dereferenced, so we |
5190 | // better have an lvalue. |
5191 | assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0 ) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5191, __PRETTY_FUNCTION__)); |
5192 | } |
5193 | |
5194 | assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5194, __PRETTY_FUNCTION__)); |
5195 | |
5196 | // C++0x [over.match.funcs]p4: |
5197 | // For non-static member functions, the type of the implicit object |
5198 | // parameter is |
5199 | // |
5200 | // - "lvalue reference to cv X" for functions declared without a |
5201 | // ref-qualifier or with the & ref-qualifier |
5202 | // - "rvalue reference to cv X" for functions declared with the && |
5203 | // ref-qualifier |
5204 | // |
5205 | // where X is the class of which the function is a member and cv is the |
5206 | // cv-qualification on the member function declaration. |
5207 | // |
5208 | // However, when finding an implicit conversion sequence for the argument, we |
5209 | // are not allowed to perform user-defined conversions |
5210 | // (C++ [over.match.funcs]p5). We perform a simplified version of |
5211 | // reference binding here, that allows class rvalues to bind to |
5212 | // non-constant references. |
5213 | |
5214 | // First check the qualifiers. |
5215 | QualType FromTypeCanon = S.Context.getCanonicalType(FromType); |
5216 | if (ImplicitParamType.getCVRQualifiers() |
5217 | != FromTypeCanon.getLocalCVRQualifiers() && |
5218 | !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { |
5219 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5220 | FromType, ImplicitParamType); |
5221 | return ICS; |
5222 | } |
5223 | |
5224 | if (FromTypeCanon.getQualifiers().hasAddressSpace()) { |
5225 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); |
5226 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); |
5227 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { |
5228 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5229 | FromType, ImplicitParamType); |
5230 | return ICS; |
5231 | } |
5232 | } |
5233 | |
5234 | // Check that we have either the same type or a derived type. It |
5235 | // affects the conversion rank. |
5236 | QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); |
5237 | ImplicitConversionKind SecondKind; |
5238 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { |
5239 | SecondKind = ICK_Identity; |
5240 | } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) |
5241 | SecondKind = ICK_Derived_To_Base; |
5242 | else { |
5243 | ICS.setBad(BadConversionSequence::unrelated_class, |
5244 | FromType, ImplicitParamType); |
5245 | return ICS; |
5246 | } |
5247 | |
5248 | // Check the ref-qualifier. |
5249 | switch (Method->getRefQualifier()) { |
5250 | case RQ_None: |
5251 | // Do nothing; we don't care about lvalueness or rvalueness. |
5252 | break; |
5253 | |
5254 | case RQ_LValue: |
5255 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { |
5256 | // non-const lvalue reference cannot bind to an rvalue |
5257 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, |
5258 | ImplicitParamType); |
5259 | return ICS; |
5260 | } |
5261 | break; |
5262 | |
5263 | case RQ_RValue: |
5264 | if (!FromClassification.isRValue()) { |
5265 | // rvalue reference cannot bind to an lvalue |
5266 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, |
5267 | ImplicitParamType); |
5268 | return ICS; |
5269 | } |
5270 | break; |
5271 | } |
5272 | |
5273 | // Success. Mark this as a reference binding. |
5274 | ICS.setStandard(); |
5275 | ICS.Standard.setAsIdentityConversion(); |
5276 | ICS.Standard.Second = SecondKind; |
5277 | ICS.Standard.setFromType(FromType); |
5278 | ICS.Standard.setAllToTypes(ImplicitParamType); |
5279 | ICS.Standard.ReferenceBinding = true; |
5280 | ICS.Standard.DirectBinding = true; |
5281 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; |
5282 | ICS.Standard.BindsToFunctionLvalue = false; |
5283 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); |
5284 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier |
5285 | = (Method->getRefQualifier() == RQ_None); |
5286 | return ICS; |
5287 | } |
5288 | |
5289 | /// PerformObjectArgumentInitialization - Perform initialization of |
5290 | /// the implicit object parameter for the given Method with the given |
5291 | /// expression. |
5292 | ExprResult |
5293 | Sema::PerformObjectArgumentInitialization(Expr *From, |
5294 | NestedNameSpecifier *Qualifier, |
5295 | NamedDecl *FoundDecl, |
5296 | CXXMethodDecl *Method) { |
5297 | QualType FromRecordType, DestType; |
5298 | QualType ImplicitParamRecordType = |
5299 | Method->getThisType()->castAs<PointerType>()->getPointeeType(); |
5300 | |
5301 | Expr::Classification FromClassification; |
5302 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { |
5303 | FromRecordType = PT->getPointeeType(); |
5304 | DestType = Method->getThisType(); |
5305 | FromClassification = Expr::Classification::makeSimpleLValue(); |
5306 | } else { |
5307 | FromRecordType = From->getType(); |
5308 | DestType = ImplicitParamRecordType; |
5309 | FromClassification = From->Classify(Context); |
5310 | |
5311 | // When performing member access on an rvalue, materialize a temporary. |
5312 | if (From->isRValue()) { |
5313 | From = CreateMaterializeTemporaryExpr(FromRecordType, From, |
5314 | Method->getRefQualifier() != |
5315 | RefQualifierKind::RQ_RValue); |
5316 | } |
5317 | } |
5318 | |
5319 | // Note that we always use the true parent context when performing |
5320 | // the actual argument initialization. |
5321 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( |
5322 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, |
5323 | Method->getParent()); |
5324 | if (ICS.isBad()) { |
5325 | switch (ICS.Bad.Kind) { |
5326 | case BadConversionSequence::bad_qualifiers: { |
5327 | Qualifiers FromQs = FromRecordType.getQualifiers(); |
5328 | Qualifiers ToQs = DestType.getQualifiers(); |
5329 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
5330 | if (CVR) { |
5331 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) |
5332 | << Method->getDeclName() << FromRecordType << (CVR - 1) |
5333 | << From->getSourceRange(); |
5334 | Diag(Method->getLocation(), diag::note_previous_decl) |
5335 | << Method->getDeclName(); |
5336 | return ExprError(); |
5337 | } |
5338 | break; |
5339 | } |
5340 | |
5341 | case BadConversionSequence::lvalue_ref_to_rvalue: |
5342 | case BadConversionSequence::rvalue_ref_to_lvalue: { |
5343 | bool IsRValueQualified = |
5344 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; |
5345 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) |
5346 | << Method->getDeclName() << FromClassification.isRValue() |
5347 | << IsRValueQualified; |
5348 | Diag(Method->getLocation(), diag::note_previous_decl) |
5349 | << Method->getDeclName(); |
5350 | return ExprError(); |
5351 | } |
5352 | |
5353 | case BadConversionSequence::no_conversion: |
5354 | case BadConversionSequence::unrelated_class: |
5355 | break; |
5356 | } |
5357 | |
5358 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) |
5359 | << ImplicitParamRecordType << FromRecordType |
5360 | << From->getSourceRange(); |
5361 | } |
5362 | |
5363 | if (ICS.Standard.Second == ICK_Derived_To_Base) { |
5364 | ExprResult FromRes = |
5365 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); |
5366 | if (FromRes.isInvalid()) |
5367 | return ExprError(); |
5368 | From = FromRes.get(); |
5369 | } |
5370 | |
5371 | if (!Context.hasSameType(From->getType(), DestType)) { |
5372 | CastKind CK; |
5373 | QualType PteeTy = DestType->getPointeeType(); |
5374 | LangAS DestAS = |
5375 | PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); |
5376 | if (FromRecordType.getAddressSpace() != DestAS) |
5377 | CK = CK_AddressSpaceConversion; |
5378 | else |
5379 | CK = CK_NoOp; |
5380 | From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); |
5381 | } |
5382 | return From; |
5383 | } |
5384 | |
5385 | /// TryContextuallyConvertToBool - Attempt to contextually convert the |
5386 | /// expression From to bool (C++0x [conv]p3). |
5387 | static ImplicitConversionSequence |
5388 | TryContextuallyConvertToBool(Sema &S, Expr *From) { |
5389 | return TryImplicitConversion(S, From, S.Context.BoolTy, |
5390 | /*SuppressUserConversions=*/false, |
5391 | /*AllowExplicit=*/true, |
5392 | /*InOverloadResolution=*/false, |
5393 | /*CStyle=*/false, |
5394 | /*AllowObjCWritebackConversion=*/false, |
5395 | /*AllowObjCConversionOnExplicit=*/false); |
5396 | } |
5397 | |
5398 | /// PerformContextuallyConvertToBool - Perform a contextual conversion |
5399 | /// of the expression From to bool (C++0x [conv]p3). |
5400 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { |
5401 | if (checkPlaceholderForOverload(*this, From)) |
5402 | return ExprError(); |
5403 | |
5404 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); |
5405 | if (!ICS.isBad()) |
5406 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); |
5407 | |
5408 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) |
5409 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) |
5410 | << From->getType() << From->getSourceRange(); |
5411 | return ExprError(); |
5412 | } |
5413 | |
5414 | /// Check that the specified conversion is permitted in a converted constant |
5415 | /// expression, according to C++11 [expr.const]p3. Return true if the conversion |
5416 | /// is acceptable. |
5417 | static bool CheckConvertedConstantConversions(Sema &S, |
5418 | StandardConversionSequence &SCS) { |
5419 | // Since we know that the target type is an integral or unscoped enumeration |
5420 | // type, most conversion kinds are impossible. All possible First and Third |
5421 | // conversions are fine. |
5422 | switch (SCS.Second) { |
5423 | case ICK_Identity: |
5424 | case ICK_Function_Conversion: |
5425 | case ICK_Integral_Promotion: |
5426 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. |
5427 | case ICK_Zero_Queue_Conversion: |
5428 | return true; |
5429 | |
5430 | case ICK_Boolean_Conversion: |
5431 | // Conversion from an integral or unscoped enumeration type to bool is |
5432 | // classified as ICK_Boolean_Conversion, but it's also arguably an integral |
5433 | // conversion, so we allow it in a converted constant expression. |
5434 | // |
5435 | // FIXME: Per core issue 1407, we should not allow this, but that breaks |
5436 | // a lot of popular code. We should at least add a warning for this |
5437 | // (non-conforming) extension. |
5438 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && |
5439 | SCS.getToType(2)->isBooleanType(); |
5440 | |
5441 | case ICK_Pointer_Conversion: |
5442 | case ICK_Pointer_Member: |
5443 | // C++1z: null pointer conversions and null member pointer conversions are |
5444 | // only permitted if the source type is std::nullptr_t. |
5445 | return SCS.getFromType()->isNullPtrType(); |
5446 | |
5447 | case ICK_Floating_Promotion: |
5448 | case ICK_Complex_Promotion: |
5449 | case ICK_Floating_Conversion: |
5450 | case ICK_Complex_Conversion: |
5451 | case ICK_Floating_Integral: |
5452 | case ICK_Compatible_Conversion: |
5453 | case ICK_Derived_To_Base: |
5454 | case ICK_Vector_Conversion: |
5455 | case ICK_Vector_Splat: |
5456 | case ICK_Complex_Real: |
5457 | case ICK_Block_Pointer_Conversion: |
5458 | case ICK_TransparentUnionConversion: |
5459 | case ICK_Writeback_Conversion: |
5460 | case ICK_Zero_Event_Conversion: |
5461 | case ICK_C_Only_Conversion: |
5462 | case ICK_Incompatible_Pointer_Conversion: |
5463 | return false; |
5464 | |
5465 | case ICK_Lvalue_To_Rvalue: |
5466 | case ICK_Array_To_Pointer: |
5467 | case ICK_Function_To_Pointer: |
5468 | llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5468); |
5469 | |
5470 | case ICK_Qualification: |
5471 | llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5471); |
5472 | |
5473 | case ICK_Num_Conversion_Kinds: |
5474 | break; |
5475 | } |
5476 | |
5477 | llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5477); |
5478 | } |
5479 | |
5480 | /// CheckConvertedConstantExpression - Check that the expression From is a |
5481 | /// converted constant expression of type T, perform the conversion and produce |
5482 | /// the converted expression, per C++11 [expr.const]p3. |
5483 | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, |
5484 | QualType T, APValue &Value, |
5485 | Sema::CCEKind CCE, |
5486 | bool RequireInt) { |
5487 | assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5488, __PRETTY_FUNCTION__)) |
5488 | "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5488, __PRETTY_FUNCTION__)); |
5489 | |
5490 | if (checkPlaceholderForOverload(S, From)) |
5491 | return ExprError(); |
5492 | |
5493 | // C++1z [expr.const]p3: |
5494 | // A converted constant expression of type T is an expression, |
5495 | // implicitly converted to type T, where the converted |
5496 | // expression is a constant expression and the implicit conversion |
5497 | // sequence contains only [... list of conversions ...]. |
5498 | // C++1z [stmt.if]p2: |
5499 | // If the if statement is of the form if constexpr, the value of the |
5500 | // condition shall be a contextually converted constant expression of type |
5501 | // bool. |
5502 | ImplicitConversionSequence ICS = |
5503 | CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool |
5504 | ? TryContextuallyConvertToBool(S, From) |
5505 | : TryCopyInitialization(S, From, T, |
5506 | /*SuppressUserConversions=*/false, |
5507 | /*InOverloadResolution=*/false, |
5508 | /*AllowObjCWritebackConversion=*/false, |
5509 | /*AllowExplicit=*/false); |
5510 | StandardConversionSequence *SCS = nullptr; |
5511 | switch (ICS.getKind()) { |
5512 | case ImplicitConversionSequence::StandardConversion: |
5513 | SCS = &ICS.Standard; |
5514 | break; |
5515 | case ImplicitConversionSequence::UserDefinedConversion: |
5516 | // We are converting to a non-class type, so the Before sequence |
5517 | // must be trivial. |
5518 | SCS = &ICS.UserDefined.After; |
5519 | break; |
5520 | case ImplicitConversionSequence::AmbiguousConversion: |
5521 | case ImplicitConversionSequence::BadConversion: |
5522 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) |
5523 | return S.Diag(From->getBeginLoc(), |
5524 | diag::err_typecheck_converted_constant_expression) |
5525 | << From->getType() << From->getSourceRange() << T; |
5526 | return ExprError(); |
5527 | |
5528 | case ImplicitConversionSequence::EllipsisConversion: |
5529 | llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5529); |
5530 | } |
5531 | |
5532 | // Check that we would only use permitted conversions. |
5533 | if (!CheckConvertedConstantConversions(S, *SCS)) { |
5534 | return S.Diag(From->getBeginLoc(), |
5535 | diag::err_typecheck_converted_constant_expression_disallowed) |
5536 | << From->getType() << From->getSourceRange() << T; |
5537 | } |
5538 | // [...] and where the reference binding (if any) binds directly. |
5539 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { |
5540 | return S.Diag(From->getBeginLoc(), |
5541 | diag::err_typecheck_converted_constant_expression_indirect) |
5542 | << From->getType() << From->getSourceRange() << T; |
5543 | } |
5544 | |
5545 | ExprResult Result = |
5546 | S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); |
5547 | if (Result.isInvalid()) |
5548 | return Result; |
5549 | |
5550 | // C++2a [intro.execution]p5: |
5551 | // A full-expression is [...] a constant-expression [...] |
5552 | Result = |
5553 | S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), |
5554 | /*DiscardedValue=*/false, /*IsConstexpr=*/true); |
5555 | if (Result.isInvalid()) |
5556 | return Result; |
5557 | |
5558 | // Check for a narrowing implicit conversion. |
5559 | APValue PreNarrowingValue; |
5560 | QualType PreNarrowingType; |
5561 | switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, |
5562 | PreNarrowingType)) { |
5563 | case NK_Dependent_Narrowing: |
5564 | // Implicit conversion to a narrower type, but the expression is |
5565 | // value-dependent so we can't tell whether it's actually narrowing. |
5566 | case NK_Variable_Narrowing: |
5567 | // Implicit conversion to a narrower type, and the value is not a constant |
5568 | // expression. We'll diagnose this in a moment. |
5569 | case NK_Not_Narrowing: |
5570 | break; |
5571 | |
5572 | case NK_Constant_Narrowing: |
5573 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
5574 | << CCE << /*Constant*/ 1 |
5575 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; |
5576 | break; |
5577 | |
5578 | case NK_Type_Narrowing: |
5579 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
5580 | << CCE << /*Constant*/ 0 << From->getType() << T; |
5581 | break; |
5582 | } |
5583 | |
5584 | if (Result.get()->isValueDependent()) { |
5585 | Value = APValue(); |
5586 | return Result; |
5587 | } |
5588 | |
5589 | // Check the expression is a constant expression. |
5590 | SmallVector<PartialDiagnosticAt, 8> Notes; |
5591 | Expr::EvalResult Eval; |
5592 | Eval.Diag = &Notes; |
5593 | Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg |
5594 | ? Expr::EvaluateForMangling |
5595 | : Expr::EvaluateForCodeGen; |
5596 | |
5597 | if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || |
5598 | (RequireInt && !Eval.Val.isInt())) { |
5599 | // The expression can't be folded, so we can't keep it at this position in |
5600 | // the AST. |
5601 | Result = ExprError(); |
5602 | } else { |
5603 | Value = Eval.Val; |
5604 | |
5605 | if (Notes.empty()) { |
5606 | // It's a constant expression. |
5607 | return ConstantExpr::Create(S.Context, Result.get(), Value); |
5608 | } |
5609 | } |
5610 | |
5611 | // It's not a constant expression. Produce an appropriate diagnostic. |
5612 | if (Notes.size() == 1 && |
5613 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) |
5614 | S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; |
5615 | else { |
5616 | S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) |
5617 | << CCE << From->getSourceRange(); |
5618 | for (unsigned I = 0; I < Notes.size(); ++I) |
5619 | S.Diag(Notes[I].first, Notes[I].second); |
5620 | } |
5621 | return ExprError(); |
5622 | } |
5623 | |
5624 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
5625 | APValue &Value, CCEKind CCE) { |
5626 | return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); |
5627 | } |
5628 | |
5629 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
5630 | llvm::APSInt &Value, |
5631 | CCEKind CCE) { |
5632 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type" ) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5632, __PRETTY_FUNCTION__)); |
5633 | |
5634 | APValue V; |
5635 | auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); |
5636 | if (!R.isInvalid() && !R.get()->isValueDependent()) |
5637 | Value = V.getInt(); |
5638 | return R; |
5639 | } |
5640 | |
5641 | |
5642 | /// dropPointerConversions - If the given standard conversion sequence |
5643 | /// involves any pointer conversions, remove them. This may change |
5644 | /// the result type of the conversion sequence. |
5645 | static void dropPointerConversion(StandardConversionSequence &SCS) { |
5646 | if (SCS.Second == ICK_Pointer_Conversion) { |
5647 | SCS.Second = ICK_Identity; |
5648 | SCS.Third = ICK_Identity; |
5649 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; |
5650 | } |
5651 | } |
5652 | |
5653 | /// TryContextuallyConvertToObjCPointer - Attempt to contextually |
5654 | /// convert the expression From to an Objective-C pointer type. |
5655 | static ImplicitConversionSequence |
5656 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { |
5657 | // Do an implicit conversion to 'id'. |
5658 | QualType Ty = S.Context.getObjCIdType(); |
5659 | ImplicitConversionSequence ICS |
5660 | = TryImplicitConversion(S, From, Ty, |
5661 | // FIXME: Are these flags correct? |
5662 | /*SuppressUserConversions=*/false, |
5663 | /*AllowExplicit=*/true, |
5664 | /*InOverloadResolution=*/false, |
5665 | /*CStyle=*/false, |
5666 | /*AllowObjCWritebackConversion=*/false, |
5667 | /*AllowObjCConversionOnExplicit=*/true); |
5668 | |
5669 | // Strip off any final conversions to 'id'. |
5670 | switch (ICS.getKind()) { |
5671 | case ImplicitConversionSequence::BadConversion: |
5672 | case ImplicitConversionSequence::AmbiguousConversion: |
5673 | case ImplicitConversionSequence::EllipsisConversion: |
5674 | break; |
5675 | |
5676 | case ImplicitConversionSequence::UserDefinedConversion: |
5677 | dropPointerConversion(ICS.UserDefined.After); |
5678 | break; |
5679 | |
5680 | case ImplicitConversionSequence::StandardConversion: |
5681 | dropPointerConversion(ICS.Standard); |
5682 | break; |
5683 | } |
5684 | |
5685 | return ICS; |
5686 | } |
5687 | |
5688 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual |
5689 | /// conversion of the expression From to an Objective-C pointer type. |
5690 | /// Returns a valid but null ExprResult if no conversion sequence exists. |
5691 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { |
5692 | if (checkPlaceholderForOverload(*this, From)) |
5693 | return ExprError(); |
5694 | |
5695 | QualType Ty = Context.getObjCIdType(); |
5696 | ImplicitConversionSequence ICS = |
5697 | TryContextuallyConvertToObjCPointer(*this, From); |
5698 | if (!ICS.isBad()) |
5699 | return PerformImplicitConversion(From, Ty, ICS, AA_Converting); |
5700 | return ExprResult(); |
5701 | } |
5702 | |
5703 | /// Determine whether the provided type is an integral type, or an enumeration |
5704 | /// type of a permitted flavor. |
5705 | bool Sema::ICEConvertDiagnoser::match(QualType T) { |
5706 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() |
5707 | : T->isIntegralOrUnscopedEnumerationType(); |
5708 | } |
5709 | |
5710 | static ExprResult |
5711 | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, |
5712 | Sema::ContextualImplicitConverter &Converter, |
5713 | QualType T, UnresolvedSetImpl &ViableConversions) { |
5714 | |
5715 | if (Converter.Suppress) |
5716 | return ExprError(); |
5717 | |
5718 | Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); |
5719 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
5720 | CXXConversionDecl *Conv = |
5721 | cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); |
5722 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); |
5723 | Converter.noteAmbiguous(SemaRef, Conv, ConvTy); |
5724 | } |
5725 | return From; |
5726 | } |
5727 | |
5728 | static bool |
5729 | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
5730 | Sema::ContextualImplicitConverter &Converter, |
5731 | QualType T, bool HadMultipleCandidates, |
5732 | UnresolvedSetImpl &ExplicitConversions) { |
5733 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { |
5734 | DeclAccessPair Found = ExplicitConversions[0]; |
5735 | CXXConversionDecl *Conversion = |
5736 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
5737 | |
5738 | // The user probably meant to invoke the given explicit |
5739 | // conversion; use it. |
5740 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); |
5741 | std::string TypeStr; |
5742 | ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); |
5743 | |
5744 | Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) |
5745 | << FixItHint::CreateInsertion(From->getBeginLoc(), |
5746 | "static_cast<" + TypeStr + ">(") |
5747 | << FixItHint::CreateInsertion( |
5748 | SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); |
5749 | Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); |
5750 | |
5751 | // If we aren't in a SFINAE context, build a call to the |
5752 | // explicit conversion function. |
5753 | if (SemaRef.isSFINAEContext()) |
5754 | return true; |
5755 | |
5756 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
5757 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
5758 | HadMultipleCandidates); |
5759 | if (Result.isInvalid()) |
5760 | return true; |
5761 | // Record usage of conversion in an implicit cast. |
5762 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
5763 | CK_UserDefinedConversion, Result.get(), |
5764 | nullptr, Result.get()->getValueKind()); |
5765 | } |
5766 | return false; |
5767 | } |
5768 | |
5769 | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
5770 | Sema::ContextualImplicitConverter &Converter, |
5771 | QualType T, bool HadMultipleCandidates, |
5772 | DeclAccessPair &Found) { |
5773 | CXXConversionDecl *Conversion = |
5774 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
5775 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
5776 | |
5777 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); |
5778 | if (!Converter.SuppressConversion) { |
5779 | if (SemaRef.isSFINAEContext()) |
5780 | return true; |
5781 | |
5782 | Converter.diagnoseConversion(SemaRef, Loc, T, ToType) |
5783 | << From->getSourceRange(); |
5784 | } |
5785 | |
5786 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
5787 | HadMultipleCandidates); |
5788 | if (Result.isInvalid()) |
5789 | return true; |
5790 | // Record usage of conversion in an implicit cast. |
5791 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
5792 | CK_UserDefinedConversion, Result.get(), |
5793 | nullptr, Result.get()->getValueKind()); |
5794 | return false; |
5795 | } |
5796 | |
5797 | static ExprResult finishContextualImplicitConversion( |
5798 | Sema &SemaRef, SourceLocation Loc, Expr *From, |
5799 | Sema::ContextualImplicitConverter &Converter) { |
5800 | if (!Converter.match(From->getType()) && !Converter.Suppress) |
5801 | Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) |
5802 | << From->getSourceRange(); |
5803 | |
5804 | return SemaRef.DefaultLvalueConversion(From); |
5805 | } |
5806 | |
5807 | static void |
5808 | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, |
5809 | UnresolvedSetImpl &ViableConversions, |
5810 | OverloadCandidateSet &CandidateSet) { |
5811 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
5812 | DeclAccessPair FoundDecl = ViableConversions[I]; |
5813 | NamedDecl *D = FoundDecl.getDecl(); |
5814 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
5815 | if (isa<UsingShadowDecl>(D)) |
5816 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
5817 | |
5818 | CXXConversionDecl *Conv; |
5819 | FunctionTemplateDecl *ConvTemplate; |
5820 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
5821 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
5822 | else |
5823 | Conv = cast<CXXConversionDecl>(D); |
5824 | |
5825 | if (ConvTemplate) |
5826 | SemaRef.AddTemplateConversionCandidate( |
5827 | ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, |
5828 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); |
5829 | else |
5830 | SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, |
5831 | ToType, CandidateSet, |
5832 | /*AllowObjCConversionOnExplicit=*/false, |
5833 | /*AllowExplicit*/ true); |
5834 | } |
5835 | } |
5836 | |
5837 | /// Attempt to convert the given expression to a type which is accepted |
5838 | /// by the given converter. |
5839 | /// |
5840 | /// This routine will attempt to convert an expression of class type to a |
5841 | /// type accepted by the specified converter. In C++11 and before, the class |
5842 | /// must have a single non-explicit conversion function converting to a matching |
5843 | /// type. In C++1y, there can be multiple such conversion functions, but only |
5844 | /// one target type. |
5845 | /// |
5846 | /// \param Loc The source location of the construct that requires the |
5847 | /// conversion. |
5848 | /// |
5849 | /// \param From The expression we're converting from. |
5850 | /// |
5851 | /// \param Converter Used to control and diagnose the conversion process. |
5852 | /// |
5853 | /// \returns The expression, converted to an integral or enumeration type if |
5854 | /// successful. |
5855 | ExprResult Sema::PerformContextualImplicitConversion( |
5856 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { |
5857 | // We can't perform any more checking for type-dependent expressions. |
5858 | if (From->isTypeDependent()) |
5859 | return From; |
5860 | |
5861 | // Process placeholders immediately. |
5862 | if (From->hasPlaceholderType()) { |
5863 | ExprResult result = CheckPlaceholderExpr(From); |
5864 | if (result.isInvalid()) |
5865 | return result; |
5866 | From = result.get(); |
5867 | } |
5868 | |
5869 | // If the expression already has a matching type, we're golden. |
5870 | QualType T = From->getType(); |
5871 | if (Converter.match(T)) |
5872 | return DefaultLvalueConversion(From); |
5873 | |
5874 | // FIXME: Check for missing '()' if T is a function type? |
5875 | |
5876 | // We can only perform contextual implicit conversions on objects of class |
5877 | // type. |
5878 | const RecordType *RecordTy = T->getAs<RecordType>(); |
5879 | if (!RecordTy || !getLangOpts().CPlusPlus) { |
5880 | if (!Converter.Suppress) |
5881 | Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); |
5882 | return From; |
5883 | } |
5884 | |
5885 | // We must have a complete class type. |
5886 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { |
5887 | ContextualImplicitConverter &Converter; |
5888 | Expr *From; |
5889 | |
5890 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) |
5891 | : Converter(Converter), From(From) {} |
5892 | |
5893 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
5894 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); |
5895 | } |
5896 | } IncompleteDiagnoser(Converter, From); |
5897 | |
5898 | if (Converter.Suppress ? !isCompleteType(Loc, T) |
5899 | : RequireCompleteType(Loc, T, IncompleteDiagnoser)) |
5900 | return From; |
5901 | |
5902 | // Look for a conversion to an integral or enumeration type. |
5903 | UnresolvedSet<4> |
5904 | ViableConversions; // These are *potentially* viable in C++1y. |
5905 | UnresolvedSet<4> ExplicitConversions; |
5906 | const auto &Conversions = |
5907 | cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); |
5908 | |
5909 | bool HadMultipleCandidates = |
5910 | (std::distance(Conversions.begin(), Conversions.end()) > 1); |
5911 | |
5912 | // To check that there is only one target type, in C++1y: |
5913 | QualType ToType; |
5914 | bool HasUniqueTargetType = true; |
5915 | |
5916 | // Collect explicit or viable (potentially in C++1y) conversions. |
5917 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
5918 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
5919 | CXXConversionDecl *Conversion; |
5920 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); |
5921 | if (ConvTemplate) { |
5922 | if (getLangOpts().CPlusPlus14) |
5923 | Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
5924 | else |
5925 | continue; // C++11 does not consider conversion operator templates(?). |
5926 | } else |
5927 | Conversion = cast<CXXConversionDecl>(D); |
5928 | |
5929 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5931, __PRETTY_FUNCTION__)) |
5930 | "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5931, __PRETTY_FUNCTION__)) |
5931 | "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 5931, __PRETTY_FUNCTION__)); |
5932 | |
5933 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); |
5934 | if (Converter.match(CurToType) || ConvTemplate) { |
5935 | |
5936 | if (Conversion->isExplicit()) { |
5937 | // FIXME: For C++1y, do we need this restriction? |
5938 | // cf. diagnoseNoViableConversion() |
5939 | if (!ConvTemplate) |
5940 | ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); |
5941 | } else { |
5942 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { |
5943 | if (ToType.isNull()) |
5944 | ToType = CurToType.getUnqualifiedType(); |
5945 | else if (HasUniqueTargetType && |
5946 | (CurToType.getUnqualifiedType() != ToType)) |
5947 | HasUniqueTargetType = false; |
5948 | } |
5949 | ViableConversions.addDecl(I.getDecl(), I.getAccess()); |
5950 | } |
5951 | } |
5952 | } |
5953 | |
5954 | if (getLangOpts().CPlusPlus14) { |
5955 | // C++1y [conv]p6: |
5956 | // ... An expression e of class type E appearing in such a context |
5957 | // is said to be contextually implicitly converted to a specified |
5958 | // type T and is well-formed if and only if e can be implicitly |
5959 | // converted to a type T that is determined as follows: E is searched |
5960 | // for conversion functions whose return type is cv T or reference to |
5961 | // cv T such that T is allowed by the context. There shall be |
5962 | // exactly one such T. |
5963 | |
5964 | // If no unique T is found: |
5965 | if (ToType.isNull()) { |
5966 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
5967 | HadMultipleCandidates, |
5968 | ExplicitConversions)) |
5969 | return ExprError(); |
5970 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
5971 | } |
5972 | |
5973 | // If more than one unique Ts are found: |
5974 | if (!HasUniqueTargetType) |
5975 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
5976 | ViableConversions); |
5977 | |
5978 | // If one unique T is found: |
5979 | // First, build a candidate set from the previously recorded |
5980 | // potentially viable conversions. |
5981 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
5982 | collectViableConversionCandidates(*this, From, ToType, ViableConversions, |
5983 | CandidateSet); |
5984 | |
5985 | // Then, perform overload resolution over the candidate set. |
5986 | OverloadCandidateSet::iterator Best; |
5987 | switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { |
5988 | case OR_Success: { |
5989 | // Apply this conversion. |
5990 | DeclAccessPair Found = |
5991 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); |
5992 | if (recordConversion(*this, Loc, From, Converter, T, |
5993 | HadMultipleCandidates, Found)) |
5994 | return ExprError(); |
5995 | break; |
5996 | } |
5997 | case OR_Ambiguous: |
5998 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
5999 | ViableConversions); |
6000 | case OR_No_Viable_Function: |
6001 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6002 | HadMultipleCandidates, |
6003 | ExplicitConversions)) |
6004 | return ExprError(); |
6005 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
6006 | case OR_Deleted: |
6007 | // We'll complain below about a non-integral condition type. |
6008 | break; |
6009 | } |
6010 | } else { |
6011 | switch (ViableConversions.size()) { |
6012 | case 0: { |
6013 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6014 | HadMultipleCandidates, |
6015 | ExplicitConversions)) |
6016 | return ExprError(); |
6017 | |
6018 | // We'll complain below about a non-integral condition type. |
6019 | break; |
6020 | } |
6021 | case 1: { |
6022 | // Apply this conversion. |
6023 | DeclAccessPair Found = ViableConversions[0]; |
6024 | if (recordConversion(*this, Loc, From, Converter, T, |
6025 | HadMultipleCandidates, Found)) |
6026 | return ExprError(); |
6027 | break; |
6028 | } |
6029 | default: |
6030 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6031 | ViableConversions); |
6032 | } |
6033 | } |
6034 | |
6035 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
6036 | } |
6037 | |
6038 | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is |
6039 | /// an acceptable non-member overloaded operator for a call whose |
6040 | /// arguments have types T1 (and, if non-empty, T2). This routine |
6041 | /// implements the check in C++ [over.match.oper]p3b2 concerning |
6042 | /// enumeration types. |
6043 | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, |
6044 | FunctionDecl *Fn, |
6045 | ArrayRef<Expr *> Args) { |
6046 | QualType T1 = Args[0]->getType(); |
6047 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); |
6048 | |
6049 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) |
6050 | return true; |
6051 | |
6052 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) |
6053 | return true; |
6054 | |
6055 | const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); |
6056 | if (Proto->getNumParams() < 1) |
6057 | return false; |
6058 | |
6059 | if (T1->isEnumeralType()) { |
6060 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); |
6061 | if (Context.hasSameUnqualifiedType(T1, ArgType)) |
6062 | return true; |
6063 | } |
6064 | |
6065 | if (Proto->getNumParams() < 2) |
6066 | return false; |
6067 | |
6068 | if (!T2.isNull() && T2->isEnumeralType()) { |
6069 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); |
6070 | if (Context.hasSameUnqualifiedType(T2, ArgType)) |
6071 | return true; |
6072 | } |
6073 | |
6074 | return false; |
6075 | } |
6076 | |
6077 | /// AddOverloadCandidate - Adds the given function to the set of |
6078 | /// candidate functions, using the given function call arguments. If |
6079 | /// @p SuppressUserConversions, then don't allow user-defined |
6080 | /// conversions via constructors or conversion operators. |
6081 | /// |
6082 | /// \param PartialOverloading true if we are performing "partial" overloading |
6083 | /// based on an incomplete set of function arguments. This feature is used by |
6084 | /// code completion. |
6085 | void Sema::AddOverloadCandidate( |
6086 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, |
6087 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6088 | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, |
6089 | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, |
6090 | OverloadCandidateParamOrder PO) { |
6091 | const FunctionProtoType *Proto |
6092 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); |
6093 | assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded" ) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6093, __PRETTY_FUNCTION__)); |
6094 | assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates" ) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6095, __PRETTY_FUNCTION__)) |
6095 | "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates" ) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6095, __PRETTY_FUNCTION__)); |
6096 | |
6097 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { |
6098 | if (!isa<CXXConstructorDecl>(Method)) { |
6099 | // If we get here, it's because we're calling a member function |
6100 | // that is named without a member access expression (e.g., |
6101 | // "this->f") that was either written explicitly or created |
6102 | // implicitly. This can happen with a qualified call to a member |
6103 | // function, e.g., X::f(). We use an empty type for the implied |
6104 | // object argument (C++ [over.call.func]p3), and the acting context |
6105 | // is irrelevant. |
6106 | AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), |
6107 | Expr::Classification::makeSimpleLValue(), Args, |
6108 | CandidateSet, SuppressUserConversions, |
6109 | PartialOverloading, EarlyConversions, PO); |
6110 | return; |
6111 | } |
6112 | // We treat a constructor like a non-member function, since its object |
6113 | // argument doesn't participate in overload resolution. |
6114 | } |
6115 | |
6116 | if (!CandidateSet.isNewCandidate(Function, PO)) |
6117 | return; |
6118 | |
6119 | // C++11 [class.copy]p11: [DR1402] |
6120 | // A defaulted move constructor that is defined as deleted is ignored by |
6121 | // overload resolution. |
6122 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); |
6123 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && |
6124 | Constructor->isMoveConstructor()) |
6125 | return; |
6126 | |
6127 | // Overload resolution is always an unevaluated context. |
6128 | EnterExpressionEvaluationContext Unevaluated( |
6129 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6130 | |
6131 | // C++ [over.match.oper]p3: |
6132 | // if no operand has a class type, only those non-member functions in the |
6133 | // lookup set that have a first parameter of type T1 or "reference to |
6134 | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there |
6135 | // is a right operand) a second parameter of type T2 or "reference to |
6136 | // (possibly cv-qualified) T2", when T2 is an enumeration type, are |
6137 | // candidate functions. |
6138 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && |
6139 | !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) |
6140 | return; |
6141 | |
6142 | // Add this candidate |
6143 | OverloadCandidate &Candidate = |
6144 | CandidateSet.addCandidate(Args.size(), EarlyConversions); |
6145 | Candidate.FoundDecl = FoundDecl; |
6146 | Candidate.Function = Function; |
6147 | Candidate.Viable = true; |
6148 | Candidate.RewriteKind = |
6149 | CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); |
6150 | Candidate.IsSurrogate = false; |
6151 | Candidate.IsADLCandidate = IsADLCandidate; |
6152 | Candidate.IgnoreObjectArgument = false; |
6153 | Candidate.ExplicitCallArguments = Args.size(); |
6154 | |
6155 | if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && |
6156 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) { |
6157 | Candidate.Viable = false; |
6158 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
6159 | return; |
6160 | } |
6161 | |
6162 | if (Constructor) { |
6163 | // C++ [class.copy]p3: |
6164 | // A member function template is never instantiated to perform the copy |
6165 | // of a class object to an object of its class type. |
6166 | QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); |
6167 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && |
6168 | (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || |
6169 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), |
6170 | ClassType))) { |
6171 | Candidate.Viable = false; |
6172 | Candidate.FailureKind = ovl_fail_illegal_constructor; |
6173 | return; |
6174 | } |
6175 | |
6176 | // C++ [over.match.funcs]p8: (proposed DR resolution) |
6177 | // A constructor inherited from class type C that has a first parameter |
6178 | // of type "reference to P" (including such a constructor instantiated |
6179 | // from a template) is excluded from the set of candidate functions when |
6180 | // constructing an object of type cv D if the argument list has exactly |
6181 | // one argument and D is reference-related to P and P is reference-related |
6182 | // to C. |
6183 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); |
6184 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && |
6185 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { |
6186 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); |
6187 | QualType C = Context.getRecordType(Constructor->getParent()); |
6188 | QualType D = Context.getRecordType(Shadow->getParent()); |
6189 | SourceLocation Loc = Args.front()->getExprLoc(); |
6190 | if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && |
6191 | (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { |
6192 | Candidate.Viable = false; |
6193 | Candidate.FailureKind = ovl_fail_inhctor_slice; |
6194 | return; |
6195 | } |
6196 | } |
6197 | |
6198 | // Check that the constructor is capable of constructing an object in the |
6199 | // destination address space. |
6200 | if (!Qualifiers::isAddressSpaceSupersetOf( |
6201 | Constructor->getMethodQualifiers().getAddressSpace(), |
6202 | CandidateSet.getDestAS())) { |
6203 | Candidate.Viable = false; |
6204 | Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; |
6205 | } |
6206 | } |
6207 | |
6208 | unsigned NumParams = Proto->getNumParams(); |
6209 | |
6210 | // (C++ 13.3.2p2): A candidate function having fewer than m |
6211 | // parameters is viable only if it has an ellipsis in its parameter |
6212 | // list (8.3.5). |
6213 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
6214 | !Proto->isVariadic()) { |
6215 | Candidate.Viable = false; |
6216 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
6217 | return; |
6218 | } |
6219 | |
6220 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
6221 | // is viable only if the (m+1)st parameter has a default argument |
6222 | // (8.3.6). For the purposes of overload resolution, the |
6223 | // parameter list is truncated on the right, so that there are |
6224 | // exactly m parameters. |
6225 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); |
6226 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
6227 | // Not enough arguments. |
6228 | Candidate.Viable = false; |
6229 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
6230 | return; |
6231 | } |
6232 | |
6233 | // (CUDA B.1): Check for invalid calls between targets. |
6234 | if (getLangOpts().CUDA) |
6235 | if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) |
6236 | // Skip the check for callers that are implicit members, because in this |
6237 | // case we may not yet know what the member's target is; the target is |
6238 | // inferred for the member automatically, based on the bases and fields of |
6239 | // the class. |
6240 | if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { |
6241 | Candidate.Viable = false; |
6242 | Candidate.FailureKind = ovl_fail_bad_target; |
6243 | return; |
6244 | } |
6245 | |
6246 | // Determine the implicit conversion sequences for each of the |
6247 | // arguments. |
6248 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
6249 | unsigned ConvIdx = |
6250 | PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; |
6251 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
6252 | // We already formed a conversion sequence for this parameter during |
6253 | // template argument deduction. |
6254 | } else if (ArgIdx < NumParams) { |
6255 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
6256 | // exist for each argument an implicit conversion sequence |
6257 | // (13.3.3.1) that converts that argument to the corresponding |
6258 | // parameter of F. |
6259 | QualType ParamType = Proto->getParamType(ArgIdx); |
6260 | Candidate.Conversions[ConvIdx] = TryCopyInitialization( |
6261 | *this, Args[ArgIdx], ParamType, SuppressUserConversions, |
6262 | /*InOverloadResolution=*/true, |
6263 | /*AllowObjCWritebackConversion=*/ |
6264 | getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); |
6265 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6266 | Candidate.Viable = false; |
6267 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6268 | return; |
6269 | } |
6270 | } else { |
6271 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
6272 | // argument for which there is no corresponding parameter is |
6273 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
6274 | Candidate.Conversions[ConvIdx].setEllipsis(); |
6275 | } |
6276 | } |
6277 | |
6278 | if (!AllowExplicit) { |
6279 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); |
6280 | if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { |
6281 | Candidate.Viable = false; |
6282 | Candidate.FailureKind = ovl_fail_explicit_resolved; |
6283 | return; |
6284 | } |
6285 | } |
6286 | |
6287 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { |
6288 | Candidate.Viable = false; |
6289 | Candidate.FailureKind = ovl_fail_enable_if; |
6290 | Candidate.DeductionFailure.Data = FailedAttr; |
6291 | return; |
6292 | } |
6293 | |
6294 | if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { |
6295 | Candidate.Viable = false; |
6296 | Candidate.FailureKind = ovl_fail_ext_disabled; |
6297 | return; |
6298 | } |
6299 | } |
6300 | |
6301 | ObjCMethodDecl * |
6302 | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, |
6303 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { |
6304 | if (Methods.size() <= 1) |
6305 | return nullptr; |
6306 | |
6307 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
6308 | bool Match = true; |
6309 | ObjCMethodDecl *Method = Methods[b]; |
6310 | unsigned NumNamedArgs = Sel.getNumArgs(); |
6311 | // Method might have more arguments than selector indicates. This is due |
6312 | // to addition of c-style arguments in method. |
6313 | if (Method->param_size() > NumNamedArgs) |
6314 | NumNamedArgs = Method->param_size(); |
6315 | if (Args.size() < NumNamedArgs) |
6316 | continue; |
6317 | |
6318 | for (unsigned i = 0; i < NumNamedArgs; i++) { |
6319 | // We can't do any type-checking on a type-dependent argument. |
6320 | if (Args[i]->isTypeDependent()) { |
6321 | Match = false; |
6322 | break; |
6323 | } |
6324 | |
6325 | ParmVarDecl *param = Method->parameters()[i]; |
6326 | Expr *argExpr = Args[i]; |
6327 | assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6327, __PRETTY_FUNCTION__)); |
6328 | |
6329 | // Strip the unbridged-cast placeholder expression off unless it's |
6330 | // a consumed argument. |
6331 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && |
6332 | !param->hasAttr<CFConsumedAttr>()) |
6333 | argExpr = stripARCUnbridgedCast(argExpr); |
6334 | |
6335 | // If the parameter is __unknown_anytype, move on to the next method. |
6336 | if (param->getType() == Context.UnknownAnyTy) { |
6337 | Match = false; |
6338 | break; |
6339 | } |
6340 | |
6341 | ImplicitConversionSequence ConversionState |
6342 | = TryCopyInitialization(*this, argExpr, param->getType(), |
6343 | /*SuppressUserConversions*/false, |
6344 | /*InOverloadResolution=*/true, |
6345 | /*AllowObjCWritebackConversion=*/ |
6346 | getLangOpts().ObjCAutoRefCount, |
6347 | /*AllowExplicit*/false); |
6348 | // This function looks for a reasonably-exact match, so we consider |
6349 | // incompatible pointer conversions to be a failure here. |
6350 | if (ConversionState.isBad() || |
6351 | (ConversionState.isStandard() && |
6352 | ConversionState.Standard.Second == |
6353 | ICK_Incompatible_Pointer_Conversion)) { |
6354 | Match = false; |
6355 | break; |
6356 | } |
6357 | } |
6358 | // Promote additional arguments to variadic methods. |
6359 | if (Match && Method->isVariadic()) { |
6360 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { |
6361 | if (Args[i]->isTypeDependent()) { |
6362 | Match = false; |
6363 | break; |
6364 | } |
6365 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
6366 | nullptr); |
6367 | if (Arg.isInvalid()) { |
6368 | Match = false; |
6369 | break; |
6370 | } |
6371 | } |
6372 | } else { |
6373 | // Check for extra arguments to non-variadic methods. |
6374 | if (Args.size() != NumNamedArgs) |
6375 | Match = false; |
6376 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { |
6377 | // Special case when selectors have no argument. In this case, select |
6378 | // one with the most general result type of 'id'. |
6379 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
6380 | QualType ReturnT = Methods[b]->getReturnType(); |
6381 | if (ReturnT->isObjCIdType()) |
6382 | return Methods[b]; |
6383 | } |
6384 | } |
6385 | } |
6386 | |
6387 | if (Match) |
6388 | return Method; |
6389 | } |
6390 | return nullptr; |
6391 | } |
6392 | |
6393 | static bool |
6394 | convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, |
6395 | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, |
6396 | bool MissingImplicitThis, Expr *&ConvertedThis, |
6397 | SmallVectorImpl<Expr *> &ConvertedArgs) { |
6398 | if (ThisArg) { |
6399 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); |
6400 | assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6401, __PRETTY_FUNCTION__)) |
6401 | "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6401, __PRETTY_FUNCTION__)); |
6402 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!" ) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6402, __PRETTY_FUNCTION__)); |
6403 | ExprResult R = S.PerformObjectArgumentInitialization( |
6404 | ThisArg, /*Qualifier=*/nullptr, Method, Method); |
6405 | if (R.isInvalid()) |
6406 | return false; |
6407 | ConvertedThis = R.get(); |
6408 | } else { |
6409 | if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { |
6410 | (void)MD; |
6411 | assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6413, __PRETTY_FUNCTION__)) |
6412 | isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6413, __PRETTY_FUNCTION__)) |
6413 | "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6413, __PRETTY_FUNCTION__)); |
6414 | } |
6415 | ConvertedThis = nullptr; |
6416 | } |
6417 | |
6418 | // Ignore any variadic arguments. Converting them is pointless, since the |
6419 | // user can't refer to them in the function condition. |
6420 | unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); |
6421 | |
6422 | // Convert the arguments. |
6423 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { |
6424 | ExprResult R; |
6425 | R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
6426 | S.Context, Function->getParamDecl(I)), |
6427 | SourceLocation(), Args[I]); |
6428 | |
6429 | if (R.isInvalid()) |
6430 | return false; |
6431 | |
6432 | ConvertedArgs.push_back(R.get()); |
6433 | } |
6434 | |
6435 | if (Trap.hasErrorOccurred()) |
6436 | return false; |
6437 | |
6438 | // Push default arguments if needed. |
6439 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { |
6440 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { |
6441 | ParmVarDecl *P = Function->getParamDecl(i); |
6442 | Expr *DefArg = P->hasUninstantiatedDefaultArg() |
6443 | ? P->getUninstantiatedDefaultArg() |
6444 | : P->getDefaultArg(); |
6445 | // This can only happen in code completion, i.e. when PartialOverloading |
6446 | // is true. |
6447 | if (!DefArg) |
6448 | return false; |
6449 | ExprResult R = |
6450 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
6451 | S.Context, Function->getParamDecl(i)), |
6452 | SourceLocation(), DefArg); |
6453 | if (R.isInvalid()) |
6454 | return false; |
6455 | ConvertedArgs.push_back(R.get()); |
6456 | } |
6457 | |
6458 | if (Trap.hasErrorOccurred()) |
6459 | return false; |
6460 | } |
6461 | return true; |
6462 | } |
6463 | |
6464 | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, |
6465 | bool MissingImplicitThis) { |
6466 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); |
6467 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) |
6468 | return nullptr; |
6469 | |
6470 | SFINAETrap Trap(*this); |
6471 | SmallVector<Expr *, 16> ConvertedArgs; |
6472 | // FIXME: We should look into making enable_if late-parsed. |
6473 | Expr *DiscardedThis; |
6474 | if (!convertArgsForAvailabilityChecks( |
6475 | *this, Function, /*ThisArg=*/nullptr, Args, Trap, |
6476 | /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) |
6477 | return *EnableIfAttrs.begin(); |
6478 | |
6479 | for (auto *EIA : EnableIfAttrs) { |
6480 | APValue Result; |
6481 | // FIXME: This doesn't consider value-dependent cases, because doing so is |
6482 | // very difficult. Ideally, we should handle them more gracefully. |
6483 | if (EIA->getCond()->isValueDependent() || |
6484 | !EIA->getCond()->EvaluateWithSubstitution( |
6485 | Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) |
6486 | return EIA; |
6487 | |
6488 | if (!Result.isInt() || !Result.getInt().getBoolValue()) |
6489 | return EIA; |
6490 | } |
6491 | return nullptr; |
6492 | } |
6493 | |
6494 | template <typename CheckFn> |
6495 | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, |
6496 | bool ArgDependent, SourceLocation Loc, |
6497 | CheckFn &&IsSuccessful) { |
6498 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; |
6499 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { |
6500 | if (ArgDependent == DIA->getArgDependent()) |
6501 | Attrs.push_back(DIA); |
6502 | } |
6503 | |
6504 | // Common case: No diagnose_if attributes, so we can quit early. |
6505 | if (Attrs.empty()) |
6506 | return false; |
6507 | |
6508 | auto WarningBegin = std::stable_partition( |
6509 | Attrs.begin(), Attrs.end(), |
6510 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); |
6511 | |
6512 | // Note that diagnose_if attributes are late-parsed, so they appear in the |
6513 | // correct order (unlike enable_if attributes). |
6514 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), |
6515 | IsSuccessful); |
6516 | if (ErrAttr != WarningBegin) { |
6517 | const DiagnoseIfAttr *DIA = *ErrAttr; |
6518 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); |
6519 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
6520 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
6521 | return true; |
6522 | } |
6523 | |
6524 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) |
6525 | if (IsSuccessful(DIA)) { |
6526 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); |
6527 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
6528 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
6529 | } |
6530 | |
6531 | return false; |
6532 | } |
6533 | |
6534 | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
6535 | const Expr *ThisArg, |
6536 | ArrayRef<const Expr *> Args, |
6537 | SourceLocation Loc) { |
6538 | return diagnoseDiagnoseIfAttrsWith( |
6539 | *this, Function, /*ArgDependent=*/true, Loc, |
6540 | [&](const DiagnoseIfAttr *DIA) { |
6541 | APValue Result; |
6542 | // It's sane to use the same Args for any redecl of this function, since |
6543 | // EvaluateWithSubstitution only cares about the position of each |
6544 | // argument in the arg list, not the ParmVarDecl* it maps to. |
6545 | if (!DIA->getCond()->EvaluateWithSubstitution( |
6546 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) |
6547 | return false; |
6548 | return Result.isInt() && Result.getInt().getBoolValue(); |
6549 | }); |
6550 | } |
6551 | |
6552 | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
6553 | SourceLocation Loc) { |
6554 | return diagnoseDiagnoseIfAttrsWith( |
6555 | *this, ND, /*ArgDependent=*/false, Loc, |
6556 | [&](const DiagnoseIfAttr *DIA) { |
6557 | bool Result; |
6558 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && |
6559 | Result; |
6560 | }); |
6561 | } |
6562 | |
6563 | /// Add all of the function declarations in the given function set to |
6564 | /// the overload candidate set. |
6565 | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, |
6566 | ArrayRef<Expr *> Args, |
6567 | OverloadCandidateSet &CandidateSet, |
6568 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
6569 | bool SuppressUserConversions, |
6570 | bool PartialOverloading, |
6571 | bool FirstArgumentIsBase) { |
6572 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
6573 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
6574 | ArrayRef<Expr *> FunctionArgs = Args; |
6575 | |
6576 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
6577 | FunctionDecl *FD = |
6578 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
6579 | |
6580 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { |
6581 | QualType ObjectType; |
6582 | Expr::Classification ObjectClassification; |
6583 | if (Args.size() > 0) { |
6584 | if (Expr *E = Args[0]) { |
6585 | // Use the explicit base to restrict the lookup: |
6586 | ObjectType = E->getType(); |
6587 | // Pointers in the object arguments are implicitly dereferenced, so we |
6588 | // always classify them as l-values. |
6589 | if (!ObjectType.isNull() && ObjectType->isPointerType()) |
6590 | ObjectClassification = Expr::Classification::makeSimpleLValue(); |
6591 | else |
6592 | ObjectClassification = E->Classify(Context); |
6593 | } // .. else there is an implicit base. |
6594 | FunctionArgs = Args.slice(1); |
6595 | } |
6596 | if (FunTmpl) { |
6597 | AddMethodTemplateCandidate( |
6598 | FunTmpl, F.getPair(), |
6599 | cast<CXXRecordDecl>(FunTmpl->getDeclContext()), |
6600 | ExplicitTemplateArgs, ObjectType, ObjectClassification, |
6601 | FunctionArgs, CandidateSet, SuppressUserConversions, |
6602 | PartialOverloading); |
6603 | } else { |
6604 | AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), |
6605 | cast<CXXMethodDecl>(FD)->getParent(), ObjectType, |
6606 | ObjectClassification, FunctionArgs, CandidateSet, |
6607 | SuppressUserConversions, PartialOverloading); |
6608 | } |
6609 | } else { |
6610 | // This branch handles both standalone functions and static methods. |
6611 | |
6612 | // Slice the first argument (which is the base) when we access |
6613 | // static method as non-static. |
6614 | if (Args.size() > 0 && |
6615 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && |
6616 | !isa<CXXConstructorDecl>(FD)))) { |
6617 | assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast <void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6617, __PRETTY_FUNCTION__)); |
6618 | FunctionArgs = Args.slice(1); |
6619 | } |
6620 | if (FunTmpl) { |
6621 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), |
6622 | ExplicitTemplateArgs, FunctionArgs, |
6623 | CandidateSet, SuppressUserConversions, |
6624 | PartialOverloading); |
6625 | } else { |
6626 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, |
6627 | SuppressUserConversions, PartialOverloading); |
6628 | } |
6629 | } |
6630 | } |
6631 | } |
6632 | |
6633 | /// AddMethodCandidate - Adds a named decl (which is some kind of |
6634 | /// method) as a method candidate to the given overload set. |
6635 | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, |
6636 | Expr::Classification ObjectClassification, |
6637 | ArrayRef<Expr *> Args, |
6638 | OverloadCandidateSet &CandidateSet, |
6639 | bool SuppressUserConversions, |
6640 | OverloadCandidateParamOrder PO) { |
6641 | NamedDecl *Decl = FoundDecl.getDecl(); |
6642 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); |
6643 | |
6644 | if (isa<UsingShadowDecl>(Decl)) |
6645 | Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); |
6646 | |
6647 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { |
6648 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) && "Expected a member function template") ? static_cast<void > (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6649, __PRETTY_FUNCTION__)) |
6649 | "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) && "Expected a member function template") ? static_cast<void > (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6649, __PRETTY_FUNCTION__)); |
6650 | AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, |
6651 | /*ExplicitArgs*/ nullptr, ObjectType, |
6652 | ObjectClassification, Args, CandidateSet, |
6653 | SuppressUserConversions, false, PO); |
6654 | } else { |
6655 | AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, |
6656 | ObjectType, ObjectClassification, Args, CandidateSet, |
6657 | SuppressUserConversions, false, None, PO); |
6658 | } |
6659 | } |
6660 | |
6661 | /// AddMethodCandidate - Adds the given C++ member function to the set |
6662 | /// of candidate functions, using the given function call arguments |
6663 | /// and the object argument (@c Object). For example, in a call |
6664 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain |
6665 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't |
6666 | /// allow user-defined conversions via constructors or conversion |
6667 | /// operators. |
6668 | void |
6669 | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, |
6670 | CXXRecordDecl *ActingContext, QualType ObjectType, |
6671 | Expr::Classification ObjectClassification, |
6672 | ArrayRef<Expr *> Args, |
6673 | OverloadCandidateSet &CandidateSet, |
6674 | bool SuppressUserConversions, |
6675 | bool PartialOverloading, |
6676 | ConversionSequenceList EarlyConversions, |
6677 | OverloadCandidateParamOrder PO) { |
6678 | const FunctionProtoType *Proto |
6679 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); |
6680 | assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded" ) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6680, __PRETTY_FUNCTION__)); |
6681 | assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6682, __PRETTY_FUNCTION__)) |
6682 | "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6682, __PRETTY_FUNCTION__)); |
6683 | |
6684 | if (!CandidateSet.isNewCandidate(Method, PO)) |
6685 | return; |
6686 | |
6687 | // C++11 [class.copy]p23: [DR1402] |
6688 | // A defaulted move assignment operator that is defined as deleted is |
6689 | // ignored by overload resolution. |
6690 | if (Method->isDefaulted() && Method->isDeleted() && |
6691 | Method->isMoveAssignmentOperator()) |
6692 | return; |
6693 | |
6694 | // Overload resolution is always an unevaluated context. |
6695 | EnterExpressionEvaluationContext Unevaluated( |
6696 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6697 | |
6698 | // Add this candidate |
6699 | OverloadCandidate &Candidate = |
6700 | CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); |
6701 | Candidate.FoundDecl = FoundDecl; |
6702 | Candidate.Function = Method; |
6703 | Candidate.RewriteKind = |
6704 | CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); |
6705 | Candidate.IsSurrogate = false; |
6706 | Candidate.IgnoreObjectArgument = false; |
6707 | Candidate.ExplicitCallArguments = Args.size(); |
6708 | |
6709 | unsigned NumParams = Proto->getNumParams(); |
6710 | |
6711 | // (C++ 13.3.2p2): A candidate function having fewer than m |
6712 | // parameters is viable only if it has an ellipsis in its parameter |
6713 | // list (8.3.5). |
6714 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
6715 | !Proto->isVariadic()) { |
6716 | Candidate.Viable = false; |
6717 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
6718 | return; |
6719 | } |
6720 | |
6721 | // (C++ 13.3.2p2): A candidate function having more than m parameters |
6722 | // is viable only if the (m+1)st parameter has a default argument |
6723 | // (8.3.6). For the purposes of overload resolution, the |
6724 | // parameter list is truncated on the right, so that there are |
6725 | // exactly m parameters. |
6726 | unsigned MinRequiredArgs = Method->getMinRequiredArguments(); |
6727 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
6728 | // Not enough arguments. |
6729 | Candidate.Viable = false; |
6730 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
6731 | return; |
6732 | } |
6733 | |
6734 | Candidate.Viable = true; |
6735 | |
6736 | if (Method->isStatic() || ObjectType.isNull()) |
6737 | // The implicit object argument is ignored. |
6738 | Candidate.IgnoreObjectArgument = true; |
6739 | else { |
6740 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
6741 | // Determine the implicit conversion sequence for the object |
6742 | // parameter. |
6743 | Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( |
6744 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
6745 | Method, ActingContext); |
6746 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6747 | Candidate.Viable = false; |
6748 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6749 | return; |
6750 | } |
6751 | } |
6752 | |
6753 | // (CUDA B.1): Check for invalid calls between targets. |
6754 | if (getLangOpts().CUDA) |
6755 | if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) |
6756 | if (!IsAllowedCUDACall(Caller, Method)) { |
6757 | Candidate.Viable = false; |
6758 | Candidate.FailureKind = ovl_fail_bad_target; |
6759 | return; |
6760 | } |
6761 | |
6762 | // Determine the implicit conversion sequences for each of the |
6763 | // arguments. |
6764 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
6765 | unsigned ConvIdx = |
6766 | PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); |
6767 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
6768 | // We already formed a conversion sequence for this parameter during |
6769 | // template argument deduction. |
6770 | } else if (ArgIdx < NumParams) { |
6771 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
6772 | // exist for each argument an implicit conversion sequence |
6773 | // (13.3.3.1) that converts that argument to the corresponding |
6774 | // parameter of F. |
6775 | QualType ParamType = Proto->getParamType(ArgIdx); |
6776 | Candidate.Conversions[ConvIdx] |
6777 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
6778 | SuppressUserConversions, |
6779 | /*InOverloadResolution=*/true, |
6780 | /*AllowObjCWritebackConversion=*/ |
6781 | getLangOpts().ObjCAutoRefCount); |
6782 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6783 | Candidate.Viable = false; |
6784 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6785 | return; |
6786 | } |
6787 | } else { |
6788 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
6789 | // argument for which there is no corresponding parameter is |
6790 | // considered to "match the ellipsis" (C+ 13.3.3.1.3). |
6791 | Candidate.Conversions[ConvIdx].setEllipsis(); |
6792 | } |
6793 | } |
6794 | |
6795 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { |
6796 | Candidate.Viable = false; |
6797 | Candidate.FailureKind = ovl_fail_enable_if; |
6798 | Candidate.DeductionFailure.Data = FailedAttr; |
6799 | return; |
6800 | } |
6801 | |
6802 | if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && |
6803 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) { |
6804 | Candidate.Viable = false; |
6805 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
6806 | } |
6807 | } |
6808 | |
6809 | /// Add a C++ member function template as a candidate to the candidate |
6810 | /// set, using template argument deduction to produce an appropriate member |
6811 | /// function template specialization. |
6812 | void Sema::AddMethodTemplateCandidate( |
6813 | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, |
6814 | CXXRecordDecl *ActingContext, |
6815 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, |
6816 | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, |
6817 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6818 | bool PartialOverloading, OverloadCandidateParamOrder PO) { |
6819 | if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) |
6820 | return; |
6821 | |
6822 | // C++ [over.match.funcs]p7: |
6823 | // In each case where a candidate is a function template, candidate |
6824 | // function template specializations are generated using template argument |
6825 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
6826 | // candidate functions in the usual way.113) A given name can refer to one |
6827 | // or more function templates and also to a set of overloaded non-template |
6828 | // functions. In such a case, the candidate functions generated from each |
6829 | // function template are combined with the set of non-template candidate |
6830 | // functions. |
6831 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
6832 | FunctionDecl *Specialization = nullptr; |
6833 | ConversionSequenceList Conversions; |
6834 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
6835 | MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, |
6836 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { |
6837 | return CheckNonDependentConversions( |
6838 | MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, |
6839 | SuppressUserConversions, ActingContext, ObjectType, |
6840 | ObjectClassification, PO); |
6841 | })) { |
6842 | OverloadCandidate &Candidate = |
6843 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
6844 | Candidate.FoundDecl = FoundDecl; |
6845 | Candidate.Function = MethodTmpl->getTemplatedDecl(); |
6846 | Candidate.Viable = false; |
6847 | Candidate.RewriteKind = |
6848 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
6849 | Candidate.IsSurrogate = false; |
6850 | Candidate.IgnoreObjectArgument = |
6851 | cast<CXXMethodDecl>(Candidate.Function)->isStatic() || |
6852 | ObjectType.isNull(); |
6853 | Candidate.ExplicitCallArguments = Args.size(); |
6854 | if (Result == TDK_NonDependentConversionFailure) |
6855 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6856 | else { |
6857 | Candidate.FailureKind = ovl_fail_bad_deduction; |
6858 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
6859 | Info); |
6860 | } |
6861 | return; |
6862 | } |
6863 | |
6864 | // Add the function template specialization produced by template argument |
6865 | // deduction as a candidate. |
6866 | assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6866, __PRETTY_FUNCTION__)); |
6867 | assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6868, __PRETTY_FUNCTION__)) |
6868 | "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6868, __PRETTY_FUNCTION__)); |
6869 | AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, |
6870 | ActingContext, ObjectType, ObjectClassification, Args, |
6871 | CandidateSet, SuppressUserConversions, PartialOverloading, |
6872 | Conversions, PO); |
6873 | } |
6874 | |
6875 | /// Add a C++ function template specialization as a candidate |
6876 | /// in the candidate set, using template argument deduction to produce |
6877 | /// an appropriate function template specialization. |
6878 | void Sema::AddTemplateOverloadCandidate( |
6879 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
6880 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
6881 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6882 | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, |
6883 | OverloadCandidateParamOrder PO) { |
6884 | if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) |
6885 | return; |
6886 | |
6887 | // C++ [over.match.funcs]p7: |
6888 | // In each case where a candidate is a function template, candidate |
6889 | // function template specializations are generated using template argument |
6890 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
6891 | // candidate functions in the usual way.113) A given name can refer to one |
6892 | // or more function templates and also to a set of overloaded non-template |
6893 | // functions. In such a case, the candidate functions generated from each |
6894 | // function template are combined with the set of non-template candidate |
6895 | // functions. |
6896 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
6897 | FunctionDecl *Specialization = nullptr; |
6898 | ConversionSequenceList Conversions; |
6899 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
6900 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, |
6901 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { |
6902 | return CheckNonDependentConversions( |
6903 | FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, |
6904 | SuppressUserConversions, nullptr, QualType(), {}, PO); |
6905 | })) { |
6906 | OverloadCandidate &Candidate = |
6907 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
6908 | Candidate.FoundDecl = FoundDecl; |
6909 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
6910 | Candidate.Viable = false; |
6911 | Candidate.RewriteKind = |
6912 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
6913 | Candidate.IsSurrogate = false; |
6914 | Candidate.IsADLCandidate = IsADLCandidate; |
6915 | // Ignore the object argument if there is one, since we don't have an object |
6916 | // type. |
6917 | Candidate.IgnoreObjectArgument = |
6918 | isa<CXXMethodDecl>(Candidate.Function) && |
6919 | !isa<CXXConstructorDecl>(Candidate.Function); |
6920 | Candidate.ExplicitCallArguments = Args.size(); |
6921 | if (Result == TDK_NonDependentConversionFailure) |
6922 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6923 | else { |
6924 | Candidate.FailureKind = ovl_fail_bad_deduction; |
6925 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
6926 | Info); |
6927 | } |
6928 | return; |
6929 | } |
6930 | |
6931 | // Add the function template specialization produced by template argument |
6932 | // deduction as a candidate. |
6933 | assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 6933, __PRETTY_FUNCTION__)); |
6934 | AddOverloadCandidate( |
6935 | Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, |
6936 | PartialOverloading, AllowExplicit, |
6937 | /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); |
6938 | } |
6939 | |
6940 | /// Check that implicit conversion sequences can be formed for each argument |
6941 | /// whose corresponding parameter has a non-dependent type, per DR1391's |
6942 | /// [temp.deduct.call]p10. |
6943 | bool Sema::CheckNonDependentConversions( |
6944 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, |
6945 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, |
6946 | ConversionSequenceList &Conversions, bool SuppressUserConversions, |
6947 | CXXRecordDecl *ActingContext, QualType ObjectType, |
6948 | Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { |
6949 | // FIXME: The cases in which we allow explicit conversions for constructor |
6950 | // arguments never consider calling a constructor template. It's not clear |
6951 | // that is correct. |
6952 | const bool AllowExplicit = false; |
6953 | |
6954 | auto *FD = FunctionTemplate->getTemplatedDecl(); |
6955 | auto *Method = dyn_cast<CXXMethodDecl>(FD); |
6956 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); |
6957 | unsigned ThisConversions = HasThisConversion ? 1 : 0; |
6958 | |
6959 | Conversions = |
6960 | CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); |
6961 | |
6962 | // Overload resolution is always an unevaluated context. |
6963 | EnterExpressionEvaluationContext Unevaluated( |
6964 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6965 | |
6966 | // For a method call, check the 'this' conversion here too. DR1391 doesn't |
6967 | // require that, but this check should never result in a hard error, and |
6968 | // overload resolution is permitted to sidestep instantiations. |
6969 | if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && |
6970 | !ObjectType.isNull()) { |
6971 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
6972 | Conversions[ConvIdx] = TryObjectArgumentInitialization( |
6973 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
6974 | Method, ActingContext); |
6975 | if (Conversions[ConvIdx].isBad()) |
6976 | return true; |
6977 | } |
6978 | |
6979 | for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; |
6980 | ++I) { |
6981 | QualType ParamType = ParamTypes[I]; |
6982 | if (!ParamType->isDependentType()) { |
6983 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed |
6984 | ? 0 |
6985 | : (ThisConversions + I); |
6986 | Conversions[ConvIdx] |
6987 | = TryCopyInitialization(*this, Args[I], ParamType, |
6988 | SuppressUserConversions, |
6989 | /*InOverloadResolution=*/true, |
6990 | /*AllowObjCWritebackConversion=*/ |
6991 | getLangOpts().ObjCAutoRefCount, |
6992 | AllowExplicit); |
6993 | if (Conversions[ConvIdx].isBad()) |
6994 | return true; |
6995 | } |
6996 | } |
6997 | |
6998 | return false; |
6999 | } |
7000 | |
7001 | /// Determine whether this is an allowable conversion from the result |
7002 | /// of an explicit conversion operator to the expected type, per C++ |
7003 | /// [over.match.conv]p1 and [over.match.ref]p1. |
7004 | /// |
7005 | /// \param ConvType The return type of the conversion function. |
7006 | /// |
7007 | /// \param ToType The type we are converting to. |
7008 | /// |
7009 | /// \param AllowObjCPointerConversion Allow a conversion from one |
7010 | /// Objective-C pointer to another. |
7011 | /// |
7012 | /// \returns true if the conversion is allowable, false otherwise. |
7013 | static bool isAllowableExplicitConversion(Sema &S, |
7014 | QualType ConvType, QualType ToType, |
7015 | bool AllowObjCPointerConversion) { |
7016 | QualType ToNonRefType = ToType.getNonReferenceType(); |
7017 | |
7018 | // Easy case: the types are the same. |
7019 | if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) |
7020 | return true; |
7021 | |
7022 | // Allow qualification conversions. |
7023 | bool ObjCLifetimeConversion; |
7024 | if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, |
7025 | ObjCLifetimeConversion)) |
7026 | return true; |
7027 | |
7028 | // If we're not allowed to consider Objective-C pointer conversions, |
7029 | // we're done. |
7030 | if (!AllowObjCPointerConversion) |
7031 | return false; |
7032 | |
7033 | // Is this an Objective-C pointer conversion? |
7034 | bool IncompatibleObjC = false; |
7035 | QualType ConvertedType; |
7036 | return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, |
7037 | IncompatibleObjC); |
7038 | } |
7039 | |
7040 | /// AddConversionCandidate - Add a C++ conversion function as a |
7041 | /// candidate in the candidate set (C++ [over.match.conv], |
7042 | /// C++ [over.match.copy]). From is the expression we're converting from, |
7043 | /// and ToType is the type that we're eventually trying to convert to |
7044 | /// (which may or may not be the same type as the type that the |
7045 | /// conversion function produces). |
7046 | void Sema::AddConversionCandidate( |
7047 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
7048 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
7049 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7050 | bool AllowExplicit, bool AllowResultConversion) { |
7051 | assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate" ) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7052, __PRETTY_FUNCTION__)) |
7052 | "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate" ) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7052, __PRETTY_FUNCTION__)); |
7053 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); |
7054 | if (!CandidateSet.isNewCandidate(Conversion)) |
7055 | return; |
7056 | |
7057 | // If the conversion function has an undeduced return type, trigger its |
7058 | // deduction now. |
7059 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { |
7060 | if (DeduceReturnType(Conversion, From->getExprLoc())) |
7061 | return; |
7062 | ConvType = Conversion->getConversionType().getNonReferenceType(); |
7063 | } |
7064 | |
7065 | // If we don't allow any conversion of the result type, ignore conversion |
7066 | // functions that don't convert to exactly (possibly cv-qualified) T. |
7067 | if (!AllowResultConversion && |
7068 | !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) |
7069 | return; |
7070 | |
7071 | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion |
7072 | // operator is only a candidate if its return type is the target type or |
7073 | // can be converted to the target type with a qualification conversion. |
7074 | if (Conversion->isExplicit() && |
7075 | !isAllowableExplicitConversion(*this, ConvType, ToType, |
7076 | AllowObjCConversionOnExplicit)) |
7077 | return; |
7078 | |
7079 | // Overload resolution is always an unevaluated context. |
7080 | EnterExpressionEvaluationContext Unevaluated( |
7081 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7082 | |
7083 | // Add this candidate |
7084 | OverloadCandidate &Candidate = CandidateSet.addCandidate(1); |
7085 | Candidate.FoundDecl = FoundDecl; |
7086 | Candidate.Function = Conversion; |
7087 | Candidate.IsSurrogate = false; |
7088 | Candidate.IgnoreObjectArgument = false; |
7089 | Candidate.FinalConversion.setAsIdentityConversion(); |
7090 | Candidate.FinalConversion.setFromType(ConvType); |
7091 | Candidate.FinalConversion.setAllToTypes(ToType); |
7092 | Candidate.Viable = true; |
7093 | Candidate.ExplicitCallArguments = 1; |
7094 | |
7095 | // C++ [over.match.funcs]p4: |
7096 | // For conversion functions, the function is considered to be a member of |
7097 | // the class of the implicit implied object argument for the purpose of |
7098 | // defining the type of the implicit object parameter. |
7099 | // |
7100 | // Determine the implicit conversion sequence for the implicit |
7101 | // object parameter. |
7102 | QualType ImplicitParamType = From->getType(); |
7103 | if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) |
7104 | ImplicitParamType = FromPtrType->getPointeeType(); |
7105 | CXXRecordDecl *ConversionContext |
7106 | = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); |
7107 | |
7108 | Candidate.Conversions[0] = TryObjectArgumentInitialization( |
7109 | *this, CandidateSet.getLocation(), From->getType(), |
7110 | From->Classify(Context), Conversion, ConversionContext); |
7111 | |
7112 | if (Candidate.Conversions[0].isBad()) { |
7113 | Candidate.Viable = false; |
7114 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7115 | return; |
7116 | } |
7117 | |
7118 | // We won't go through a user-defined type conversion function to convert a |
7119 | // derived to base as such conversions are given Conversion Rank. They only |
7120 | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] |
7121 | QualType FromCanon |
7122 | = Context.getCanonicalType(From->getType().getUnqualifiedType()); |
7123 | QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); |
7124 | if (FromCanon == ToCanon || |
7125 | IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { |
7126 | Candidate.Viable = false; |
7127 | Candidate.FailureKind = ovl_fail_trivial_conversion; |
7128 | return; |
7129 | } |
7130 | |
7131 | // To determine what the conversion from the result of calling the |
7132 | // conversion function to the type we're eventually trying to |
7133 | // convert to (ToType), we need to synthesize a call to the |
7134 | // conversion function and attempt copy initialization from it. This |
7135 | // makes sure that we get the right semantics with respect to |
7136 | // lvalues/rvalues and the type. Fortunately, we can allocate this |
7137 | // call on the stack and we don't need its arguments to be |
7138 | // well-formed. |
7139 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), |
7140 | VK_LValue, From->getBeginLoc()); |
7141 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, |
7142 | Context.getPointerType(Conversion->getType()), |
7143 | CK_FunctionToPointerDecay, |
7144 | &ConversionRef, VK_RValue); |
7145 | |
7146 | QualType ConversionType = Conversion->getConversionType(); |
7147 | if (!isCompleteType(From->getBeginLoc(), ConversionType)) { |
7148 | Candidate.Viable = false; |
7149 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7150 | return; |
7151 | } |
7152 | |
7153 | ExprValueKind VK = Expr::getValueKindForType(ConversionType); |
7154 | |
7155 | // Note that it is safe to allocate CallExpr on the stack here because |
7156 | // there are 0 arguments (i.e., nothing is allocated using ASTContext's |
7157 | // allocator). |
7158 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); |
7159 | |
7160 | alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
7161 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( |
7162 | Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); |
7163 | |
7164 | ImplicitConversionSequence ICS = |
7165 | TryCopyInitialization(*this, TheTemporaryCall, ToType, |
7166 | /*SuppressUserConversions=*/true, |
7167 | /*InOverloadResolution=*/false, |
7168 | /*AllowObjCWritebackConversion=*/false); |
7169 | |
7170 | switch (ICS.getKind()) { |
7171 | case ImplicitConversionSequence::StandardConversion: |
7172 | Candidate.FinalConversion = ICS.Standard; |
7173 | |
7174 | // C++ [over.ics.user]p3: |
7175 | // If the user-defined conversion is specified by a specialization of a |
7176 | // conversion function template, the second standard conversion sequence |
7177 | // shall have exact match rank. |
7178 | if (Conversion->getPrimaryTemplate() && |
7179 | GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { |
7180 | Candidate.Viable = false; |
7181 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; |
7182 | return; |
7183 | } |
7184 | |
7185 | // C++0x [dcl.init.ref]p5: |
7186 | // In the second case, if the reference is an rvalue reference and |
7187 | // the second standard conversion sequence of the user-defined |
7188 | // conversion sequence includes an lvalue-to-rvalue conversion, the |
7189 | // program is ill-formed. |
7190 | if (ToType->isRValueReferenceType() && |
7191 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
7192 | Candidate.Viable = false; |
7193 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7194 | return; |
7195 | } |
7196 | break; |
7197 | |
7198 | case ImplicitConversionSequence::BadConversion: |
7199 | Candidate.Viable = false; |
7200 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7201 | return; |
7202 | |
7203 | default: |
7204 | llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7205) |
7205 | "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" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7205); |
7206 | } |
7207 | |
7208 | if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != |
7209 | ExplicitSpecKind::ResolvedFalse) { |
7210 | Candidate.Viable = false; |
7211 | Candidate.FailureKind = ovl_fail_explicit_resolved; |
7212 | return; |
7213 | } |
7214 | |
7215 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { |
7216 | Candidate.Viable = false; |
7217 | Candidate.FailureKind = ovl_fail_enable_if; |
7218 | Candidate.DeductionFailure.Data = FailedAttr; |
7219 | return; |
7220 | } |
7221 | |
7222 | if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && |
7223 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { |
7224 | Candidate.Viable = false; |
7225 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7226 | } |
7227 | } |
7228 | |
7229 | /// Adds a conversion function template specialization |
7230 | /// candidate to the overload set, using template argument deduction |
7231 | /// to deduce the template arguments of the conversion function |
7232 | /// template from the type that we are converting to (C++ |
7233 | /// [temp.deduct.conv]). |
7234 | void Sema::AddTemplateConversionCandidate( |
7235 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
7236 | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, |
7237 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7238 | bool AllowExplicit, bool AllowResultConversion) { |
7239 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl ()) && "Only conversion function templates permitted here" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7240, __PRETTY_FUNCTION__)) |
7240 | "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl ()) && "Only conversion function templates permitted here" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7240, __PRETTY_FUNCTION__)); |
7241 | |
7242 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) |
7243 | return; |
7244 | |
7245 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7246 | CXXConversionDecl *Specialization = nullptr; |
7247 | if (TemplateDeductionResult Result |
7248 | = DeduceTemplateArguments(FunctionTemplate, ToType, |
7249 | Specialization, Info)) { |
7250 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7251 | Candidate.FoundDecl = FoundDecl; |
7252 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7253 | Candidate.Viable = false; |
7254 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7255 | Candidate.IsSurrogate = false; |
7256 | Candidate.IgnoreObjectArgument = false; |
7257 | Candidate.ExplicitCallArguments = 1; |
7258 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7259 | Info); |
7260 | return; |
7261 | } |
7262 | |
7263 | // Add the conversion function template specialization produced by |
7264 | // template argument deduction as a candidate. |
7265 | assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7265, __PRETTY_FUNCTION__)); |
7266 | AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, |
7267 | CandidateSet, AllowObjCConversionOnExplicit, |
7268 | AllowExplicit, AllowResultConversion); |
7269 | } |
7270 | |
7271 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that |
7272 | /// converts the given @c Object to a function pointer via the |
7273 | /// conversion function @c Conversion, and then attempts to call it |
7274 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is |
7275 | /// the type of function that we'll eventually be calling. |
7276 | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, |
7277 | DeclAccessPair FoundDecl, |
7278 | CXXRecordDecl *ActingContext, |
7279 | const FunctionProtoType *Proto, |
7280 | Expr *Object, |
7281 | ArrayRef<Expr *> Args, |
7282 | OverloadCandidateSet& CandidateSet) { |
7283 | if (!CandidateSet.isNewCandidate(Conversion)) |
7284 | return; |
7285 | |
7286 | // Overload resolution is always an unevaluated context. |
7287 | EnterExpressionEvaluationContext Unevaluated( |
7288 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7289 | |
7290 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); |
7291 | Candidate.FoundDecl = FoundDecl; |
7292 | Candidate.Function = nullptr; |
7293 | Candidate.Surrogate = Conversion; |
7294 | Candidate.Viable = true; |
7295 | Candidate.IsSurrogate = true; |
7296 | Candidate.IgnoreObjectArgument = false; |
7297 | Candidate.ExplicitCallArguments = Args.size(); |
7298 | |
7299 | // Determine the implicit conversion sequence for the implicit |
7300 | // object parameter. |
7301 | ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( |
7302 | *this, CandidateSet.getLocation(), Object->getType(), |
7303 | Object->Classify(Context), Conversion, ActingContext); |
7304 | if (ObjectInit.isBad()) { |
7305 | Candidate.Viable = false; |
7306 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7307 | Candidate.Conversions[0] = ObjectInit; |
7308 | return; |
7309 | } |
7310 | |
7311 | // The first conversion is actually a user-defined conversion whose |
7312 | // first conversion is ObjectInit's standard conversion (which is |
7313 | // effectively a reference binding). Record it as such. |
7314 | Candidate.Conversions[0].setUserDefined(); |
7315 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; |
7316 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; |
7317 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; |
7318 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; |
7319 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; |
7320 | Candidate.Conversions[0].UserDefined.After |
7321 | = Candidate.Conversions[0].UserDefined.Before; |
7322 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); |
7323 | |
7324 | // Find the |
7325 | unsigned NumParams = Proto->getNumParams(); |
7326 | |
7327 | // (C++ 13.3.2p2): A candidate function having fewer than m |
7328 | // parameters is viable only if it has an ellipsis in its parameter |
7329 | // list (8.3.5). |
7330 | if (Args.size() > NumParams && !Proto->isVariadic()) { |
7331 | Candidate.Viable = false; |
7332 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
7333 | return; |
7334 | } |
7335 | |
7336 | // Function types don't have any default arguments, so just check if |
7337 | // we have enough arguments. |
7338 | if (Args.size() < NumParams) { |
7339 | // Not enough arguments. |
7340 | Candidate.Viable = false; |
7341 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
7342 | return; |
7343 | } |
7344 | |
7345 | // Determine the implicit conversion sequences for each of the |
7346 | // arguments. |
7347 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
7348 | if (ArgIdx < NumParams) { |
7349 | // (C++ 13.3.2p3): for F to be a viable function, there shall |
7350 | // exist for each argument an implicit conversion sequence |
7351 | // (13.3.3.1) that converts that argument to the corresponding |
7352 | // parameter of F. |
7353 | QualType ParamType = Proto->getParamType(ArgIdx); |
7354 | Candidate.Conversions[ArgIdx + 1] |
7355 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
7356 | /*SuppressUserConversions=*/false, |
7357 | /*InOverloadResolution=*/false, |
7358 | /*AllowObjCWritebackConversion=*/ |
7359 | getLangOpts().ObjCAutoRefCount); |
7360 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { |
7361 | Candidate.Viable = false; |
7362 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7363 | return; |
7364 | } |
7365 | } else { |
7366 | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
7367 | // argument for which there is no corresponding parameter is |
7368 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
7369 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); |
7370 | } |
7371 | } |
7372 | |
7373 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { |
7374 | Candidate.Viable = false; |
7375 | Candidate.FailureKind = ovl_fail_enable_if; |
7376 | Candidate.DeductionFailure.Data = FailedAttr; |
7377 | return; |
7378 | } |
7379 | } |
7380 | |
7381 | /// Add all of the non-member operator function declarations in the given |
7382 | /// function set to the overload candidate set. |
7383 | void Sema::AddNonMemberOperatorCandidates( |
7384 | const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, |
7385 | OverloadCandidateSet &CandidateSet, |
7386 | TemplateArgumentListInfo *ExplicitTemplateArgs) { |
7387 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
7388 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
7389 | ArrayRef<Expr *> FunctionArgs = Args; |
7390 | |
7391 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
7392 | FunctionDecl *FD = |
7393 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
7394 | |
7395 | // Don't consider rewritten functions if we're not rewriting. |
7396 | if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) |
7397 | continue; |
7398 | |
7399 | assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7400, __PRETTY_FUNCTION__)) |
7400 | "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7400, __PRETTY_FUNCTION__)); |
7401 | |
7402 | if (FunTmpl) { |
7403 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, |
7404 | FunctionArgs, CandidateSet); |
7405 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) |
7406 | AddTemplateOverloadCandidate( |
7407 | FunTmpl, F.getPair(), ExplicitTemplateArgs, |
7408 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, |
7409 | true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); |
7410 | } else { |
7411 | if (ExplicitTemplateArgs) |
7412 | continue; |
7413 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); |
7414 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) |
7415 | AddOverloadCandidate(FD, F.getPair(), |
7416 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, |
7417 | false, false, true, false, ADLCallKind::NotADL, |
7418 | None, OverloadCandidateParamOrder::Reversed); |
7419 | } |
7420 | } |
7421 | } |
7422 | |
7423 | /// Add overload candidates for overloaded operators that are |
7424 | /// member functions. |
7425 | /// |
7426 | /// Add the overloaded operator candidates that are member functions |
7427 | /// for the operator Op that was used in an operator expression such |
7428 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and |
7429 | /// CandidateSet will store the added overload candidates. (C++ |
7430 | /// [over.match.oper]). |
7431 | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
7432 | SourceLocation OpLoc, |
7433 | ArrayRef<Expr *> Args, |
7434 | OverloadCandidateSet &CandidateSet, |
7435 | OverloadCandidateParamOrder PO) { |
7436 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
7437 | |
7438 | // C++ [over.match.oper]p3: |
7439 | // For a unary operator @ with an operand of a type whose |
7440 | // cv-unqualified version is T1, and for a binary operator @ with |
7441 | // a left operand of a type whose cv-unqualified version is T1 and |
7442 | // a right operand of a type whose cv-unqualified version is T2, |
7443 | // three sets of candidate functions, designated member |
7444 | // candidates, non-member candidates and built-in candidates, are |
7445 | // constructed as follows: |
7446 | QualType T1 = Args[0]->getType(); |
7447 | |
7448 | // -- If T1 is a complete class type or a class currently being |
7449 | // defined, the set of member candidates is the result of the |
7450 | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, |
7451 | // the set of member candidates is empty. |
7452 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { |
7453 | // Complete the type if it can be completed. |
7454 | if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) |
7455 | return; |
7456 | // If the type is neither complete nor being defined, bail out now. |
7457 | if (!T1Rec->getDecl()->getDefinition()) |
7458 | return; |
7459 | |
7460 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); |
7461 | LookupQualifiedName(Operators, T1Rec->getDecl()); |
7462 | Operators.suppressDiagnostics(); |
7463 | |
7464 | for (LookupResult::iterator Oper = Operators.begin(), |
7465 | OperEnd = Operators.end(); |
7466 | Oper != OperEnd; |
7467 | ++Oper) |
7468 | AddMethodCandidate(Oper.getPair(), Args[0]->getType(), |
7469 | Args[0]->Classify(Context), Args.slice(1), |
7470 | CandidateSet, /*SuppressUserConversion=*/false, PO); |
7471 | } |
7472 | } |
7473 | |
7474 | /// AddBuiltinCandidate - Add a candidate for a built-in |
7475 | /// operator. ResultTy and ParamTys are the result and parameter types |
7476 | /// of the built-in candidate, respectively. Args and NumArgs are the |
7477 | /// arguments being passed to the candidate. IsAssignmentOperator |
7478 | /// should be true when this built-in candidate is an assignment |
7479 | /// operator. NumContextualBoolArguments is the number of arguments |
7480 | /// (at the beginning of the argument list) that will be contextually |
7481 | /// converted to bool. |
7482 | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
7483 | OverloadCandidateSet& CandidateSet, |
7484 | bool IsAssignmentOperator, |
7485 | unsigned NumContextualBoolArguments) { |
7486 | // Overload resolution is always an unevaluated context. |
7487 | EnterExpressionEvaluationContext Unevaluated( |
7488 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7489 | |
7490 | // Add this candidate |
7491 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); |
7492 | Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); |
7493 | Candidate.Function = nullptr; |
7494 | Candidate.IsSurrogate = false; |
7495 | Candidate.IgnoreObjectArgument = false; |
7496 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); |
7497 | |
7498 | // Determine the implicit conversion sequences for each of the |
7499 | // arguments. |
7500 | Candidate.Viable = true; |
7501 | Candidate.ExplicitCallArguments = Args.size(); |
7502 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
7503 | // C++ [over.match.oper]p4: |
7504 | // For the built-in assignment operators, conversions of the |
7505 | // left operand are restricted as follows: |
7506 | // -- no temporaries are introduced to hold the left operand, and |
7507 | // -- no user-defined conversions are applied to the left |
7508 | // operand to achieve a type match with the left-most |
7509 | // parameter of a built-in candidate. |
7510 | // |
7511 | // We block these conversions by turning off user-defined |
7512 | // conversions, since that is the only way that initialization of |
7513 | // a reference to a non-class type can occur from something that |
7514 | // is not of the same type. |
7515 | if (ArgIdx < NumContextualBoolArguments) { |
7516 | assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7517, __PRETTY_FUNCTION__)) |
7517 | "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7517, __PRETTY_FUNCTION__)); |
7518 | Candidate.Conversions[ArgIdx] |
7519 | = TryContextuallyConvertToBool(*this, Args[ArgIdx]); |
7520 | } else { |
7521 | Candidate.Conversions[ArgIdx] |
7522 | = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], |
7523 | ArgIdx == 0 && IsAssignmentOperator, |
7524 | /*InOverloadResolution=*/false, |
7525 | /*AllowObjCWritebackConversion=*/ |
7526 | getLangOpts().ObjCAutoRefCount); |
7527 | } |
7528 | if (Candidate.Conversions[ArgIdx].isBad()) { |
7529 | Candidate.Viable = false; |
7530 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7531 | break; |
7532 | } |
7533 | } |
7534 | } |
7535 | |
7536 | namespace { |
7537 | |
7538 | /// BuiltinCandidateTypeSet - A set of types that will be used for the |
7539 | /// candidate operator functions for built-in operators (C++ |
7540 | /// [over.built]). The types are separated into pointer types and |
7541 | /// enumeration types. |
7542 | class BuiltinCandidateTypeSet { |
7543 | /// TypeSet - A set of types. |
7544 | typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, |
7545 | llvm::SmallPtrSet<QualType, 8>> TypeSet; |
7546 | |
7547 | /// PointerTypes - The set of pointer types that will be used in the |
7548 | /// built-in candidates. |
7549 | TypeSet PointerTypes; |
7550 | |
7551 | /// MemberPointerTypes - The set of member pointer types that will be |
7552 | /// used in the built-in candidates. |
7553 | TypeSet MemberPointerTypes; |
7554 | |
7555 | /// EnumerationTypes - The set of enumeration types that will be |
7556 | /// used in the built-in candidates. |
7557 | TypeSet EnumerationTypes; |
7558 | |
7559 | /// The set of vector types that will be used in the built-in |
7560 | /// candidates. |
7561 | TypeSet VectorTypes; |
7562 | |
7563 | /// A flag indicating non-record types are viable candidates |
7564 | bool HasNonRecordTypes; |
7565 | |
7566 | /// A flag indicating whether either arithmetic or enumeration types |
7567 | /// were present in the candidate set. |
7568 | bool HasArithmeticOrEnumeralTypes; |
7569 | |
7570 | /// A flag indicating whether the nullptr type was present in the |
7571 | /// candidate set. |
7572 | bool HasNullPtrType; |
7573 | |
7574 | /// Sema - The semantic analysis instance where we are building the |
7575 | /// candidate type set. |
7576 | Sema &SemaRef; |
7577 | |
7578 | /// Context - The AST context in which we will build the type sets. |
7579 | ASTContext &Context; |
7580 | |
7581 | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
7582 | const Qualifiers &VisibleQuals); |
7583 | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); |
7584 | |
7585 | public: |
7586 | /// iterator - Iterates through the types that are part of the set. |
7587 | typedef TypeSet::iterator iterator; |
7588 | |
7589 | BuiltinCandidateTypeSet(Sema &SemaRef) |
7590 | : HasNonRecordTypes(false), |
7591 | HasArithmeticOrEnumeralTypes(false), |
7592 | HasNullPtrType(false), |
7593 | SemaRef(SemaRef), |
7594 | Context(SemaRef.Context) { } |
7595 | |
7596 | void AddTypesConvertedFrom(QualType Ty, |
7597 | SourceLocation Loc, |
7598 | bool AllowUserConversions, |
7599 | bool AllowExplicitConversions, |
7600 | const Qualifiers &VisibleTypeConversionsQuals); |
7601 | |
7602 | /// pointer_begin - First pointer type found; |
7603 | iterator pointer_begin() { return PointerTypes.begin(); } |
7604 | |
7605 | /// pointer_end - Past the last pointer type found; |
7606 | iterator pointer_end() { return PointerTypes.end(); } |
7607 | |
7608 | /// member_pointer_begin - First member pointer type found; |
7609 | iterator member_pointer_begin() { return MemberPointerTypes.begin(); } |
7610 | |
7611 | /// member_pointer_end - Past the last member pointer type found; |
7612 | iterator member_pointer_end() { return MemberPointerTypes.end(); } |
7613 | |
7614 | /// enumeration_begin - First enumeration type found; |
7615 | iterator enumeration_begin() { return EnumerationTypes.begin(); } |
7616 | |
7617 | /// enumeration_end - Past the last enumeration type found; |
7618 | iterator enumeration_end() { return EnumerationTypes.end(); } |
7619 | |
7620 | iterator vector_begin() { return VectorTypes.begin(); } |
7621 | iterator vector_end() { return VectorTypes.end(); } |
7622 | |
7623 | bool hasNonRecordTypes() { return HasNonRecordTypes; } |
7624 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } |
7625 | bool hasNullPtrType() const { return HasNullPtrType; } |
7626 | }; |
7627 | |
7628 | } // end anonymous namespace |
7629 | |
7630 | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to |
7631 | /// the set of pointer types along with any more-qualified variants of |
7632 | /// that type. For example, if @p Ty is "int const *", this routine |
7633 | /// will add "int const *", "int const volatile *", "int const |
7634 | /// restrict *", and "int const volatile restrict *" to the set of |
7635 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
7636 | /// false otherwise. |
7637 | /// |
7638 | /// FIXME: what to do about extended qualifiers? |
7639 | bool |
7640 | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
7641 | const Qualifiers &VisibleQuals) { |
7642 | |
7643 | // Insert this type. |
7644 | if (!PointerTypes.insert(Ty)) |
7645 | return false; |
7646 | |
7647 | QualType PointeeTy; |
7648 | const PointerType *PointerTy = Ty->getAs<PointerType>(); |
7649 | bool buildObjCPtr = false; |
7650 | if (!PointerTy) { |
7651 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); |
7652 | PointeeTy = PTy->getPointeeType(); |
7653 | buildObjCPtr = true; |
7654 | } else { |
7655 | PointeeTy = PointerTy->getPointeeType(); |
7656 | } |
7657 | |
7658 | // Don't add qualified variants of arrays. For one, they're not allowed |
7659 | // (the qualifier would sink to the element type), and for another, the |
7660 | // only overload situation where it matters is subscript or pointer +- int, |
7661 | // and those shouldn't have qualifier variants anyway. |
7662 | if (PointeeTy->isArrayType()) |
7663 | return true; |
7664 | |
7665 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
7666 | bool hasVolatile = VisibleQuals.hasVolatile(); |
7667 | bool hasRestrict = VisibleQuals.hasRestrict(); |
7668 | |
7669 | // Iterate through all strict supersets of BaseCVR. |
7670 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
7671 | if ((CVR | BaseCVR) != CVR) continue; |
7672 | // Skip over volatile if no volatile found anywhere in the types. |
7673 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; |
7674 | |
7675 | // Skip over restrict if no restrict found anywhere in the types, or if |
7676 | // the type cannot be restrict-qualified. |
7677 | if ((CVR & Qualifiers::Restrict) && |
7678 | (!hasRestrict || |
7679 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) |
7680 | continue; |
7681 | |
7682 | // Build qualified pointee type. |
7683 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
7684 | |
7685 | // Build qualified pointer type. |
7686 | QualType QPointerTy; |
7687 | if (!buildObjCPtr) |
7688 | QPointerTy = Context.getPointerType(QPointeeTy); |
7689 | else |
7690 | QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); |
7691 | |
7692 | // Insert qualified pointer type. |
7693 | PointerTypes.insert(QPointerTy); |
7694 | } |
7695 | |
7696 | return true; |
7697 | } |
7698 | |
7699 | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty |
7700 | /// to the set of pointer types along with any more-qualified variants of |
7701 | /// that type. For example, if @p Ty is "int const *", this routine |
7702 | /// will add "int const *", "int const volatile *", "int const |
7703 | /// restrict *", and "int const volatile restrict *" to the set of |
7704 | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
7705 | /// false otherwise. |
7706 | /// |
7707 | /// FIXME: what to do about extended qualifiers? |
7708 | bool |
7709 | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( |
7710 | QualType Ty) { |
7711 | // Insert this type. |
7712 | if (!MemberPointerTypes.insert(Ty)) |
7713 | return false; |
7714 | |
7715 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); |
7716 | assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!") ? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7716, __PRETTY_FUNCTION__)); |
7717 | |
7718 | QualType PointeeTy = PointerTy->getPointeeType(); |
7719 | // Don't add qualified variants of arrays. For one, they're not allowed |
7720 | // (the qualifier would sink to the element type), and for another, the |
7721 | // only overload situation where it matters is subscript or pointer +- int, |
7722 | // and those shouldn't have qualifier variants anyway. |
7723 | if (PointeeTy->isArrayType()) |
7724 | return true; |
7725 | const Type *ClassTy = PointerTy->getClass(); |
7726 | |
7727 | // Iterate through all strict supersets of the pointee type's CVR |
7728 | // qualifiers. |
7729 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
7730 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
7731 | if ((CVR | BaseCVR) != CVR) continue; |
7732 | |
7733 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
7734 | MemberPointerTypes.insert( |
7735 | Context.getMemberPointerType(QPointeeTy, ClassTy)); |
7736 | } |
7737 | |
7738 | return true; |
7739 | } |
7740 | |
7741 | /// AddTypesConvertedFrom - Add each of the types to which the type @p |
7742 | /// Ty can be implicit converted to the given set of @p Types. We're |
7743 | /// primarily interested in pointer types and enumeration types. We also |
7744 | /// take member pointer types, for the conditional operator. |
7745 | /// AllowUserConversions is true if we should look at the conversion |
7746 | /// functions of a class type, and AllowExplicitConversions if we |
7747 | /// should also include the explicit conversion functions of a class |
7748 | /// type. |
7749 | void |
7750 | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, |
7751 | SourceLocation Loc, |
7752 | bool AllowUserConversions, |
7753 | bool AllowExplicitConversions, |
7754 | const Qualifiers &VisibleQuals) { |
7755 | // Only deal with canonical types. |
7756 | Ty = Context.getCanonicalType(Ty); |
7757 | |
7758 | // Look through reference types; they aren't part of the type of an |
7759 | // expression for the purposes of conversions. |
7760 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) |
7761 | Ty = RefTy->getPointeeType(); |
7762 | |
7763 | // If we're dealing with an array type, decay to the pointer. |
7764 | if (Ty->isArrayType()) |
7765 | Ty = SemaRef.Context.getArrayDecayedType(Ty); |
7766 | |
7767 | // Otherwise, we don't care about qualifiers on the type. |
7768 | Ty = Ty.getLocalUnqualifiedType(); |
7769 | |
7770 | // Flag if we ever add a non-record type. |
7771 | const RecordType *TyRec = Ty->getAs<RecordType>(); |
7772 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; |
7773 | |
7774 | // Flag if we encounter an arithmetic type. |
7775 | HasArithmeticOrEnumeralTypes = |
7776 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); |
7777 | |
7778 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) |
7779 | PointerTypes.insert(Ty); |
7780 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { |
7781 | // Insert our type, and its more-qualified variants, into the set |
7782 | // of types. |
7783 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) |
7784 | return; |
7785 | } else if (Ty->isMemberPointerType()) { |
7786 | // Member pointers are far easier, since the pointee can't be converted. |
7787 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) |
7788 | return; |
7789 | } else if (Ty->isEnumeralType()) { |
7790 | HasArithmeticOrEnumeralTypes = true; |
7791 | EnumerationTypes.insert(Ty); |
7792 | } else if (Ty->isVectorType()) { |
7793 | // We treat vector types as arithmetic types in many contexts as an |
7794 | // extension. |
7795 | HasArithmeticOrEnumeralTypes = true; |
7796 | VectorTypes.insert(Ty); |
7797 | } else if (Ty->isNullPtrType()) { |
7798 | HasNullPtrType = true; |
7799 | } else if (AllowUserConversions && TyRec) { |
7800 | // No conversion functions in incomplete types. |
7801 | if (!SemaRef.isCompleteType(Loc, Ty)) |
7802 | return; |
7803 | |
7804 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
7805 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
7806 | if (isa<UsingShadowDecl>(D)) |
7807 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
7808 | |
7809 | // Skip conversion function templates; they don't tell us anything |
7810 | // about which builtin types we can convert to. |
7811 | if (isa<FunctionTemplateDecl>(D)) |
7812 | continue; |
7813 | |
7814 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
7815 | if (AllowExplicitConversions || !Conv->isExplicit()) { |
7816 | AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, |
7817 | VisibleQuals); |
7818 | } |
7819 | } |
7820 | } |
7821 | } |
7822 | /// Helper function for adjusting address spaces for the pointer or reference |
7823 | /// operands of builtin operators depending on the argument. |
7824 | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, |
7825 | Expr *Arg) { |
7826 | return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); |
7827 | } |
7828 | |
7829 | /// Helper function for AddBuiltinOperatorCandidates() that adds |
7830 | /// the volatile- and non-volatile-qualified assignment operators for the |
7831 | /// given type to the candidate set. |
7832 | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, |
7833 | QualType T, |
7834 | ArrayRef<Expr *> Args, |
7835 | OverloadCandidateSet &CandidateSet) { |
7836 | QualType ParamTypes[2]; |
7837 | |
7838 | // T& operator=(T&, T) |
7839 | ParamTypes[0] = S.Context.getLValueReferenceType( |
7840 | AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); |
7841 | ParamTypes[1] = T; |
7842 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
7843 | /*IsAssignmentOperator=*/true); |
7844 | |
7845 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { |
7846 | // volatile T& operator=(volatile T&, T) |
7847 | ParamTypes[0] = S.Context.getLValueReferenceType( |
7848 | AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), |
7849 | Args[0])); |
7850 | ParamTypes[1] = T; |
7851 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
7852 | /*IsAssignmentOperator=*/true); |
7853 | } |
7854 | } |
7855 | |
7856 | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, |
7857 | /// if any, found in visible type conversion functions found in ArgExpr's type. |
7858 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { |
7859 | Qualifiers VRQuals; |
7860 | const RecordType *TyRec; |
7861 | if (const MemberPointerType *RHSMPType = |
7862 | ArgExpr->getType()->getAs<MemberPointerType>()) |
7863 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); |
7864 | else |
7865 | TyRec = ArgExpr->getType()->getAs<RecordType>(); |
7866 | if (!TyRec) { |
7867 | // Just to be safe, assume the worst case. |
7868 | VRQuals.addVolatile(); |
7869 | VRQuals.addRestrict(); |
7870 | return VRQuals; |
7871 | } |
7872 | |
7873 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
7874 | if (!ClassDecl->hasDefinition()) |
7875 | return VRQuals; |
7876 | |
7877 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
7878 | if (isa<UsingShadowDecl>(D)) |
7879 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
7880 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { |
7881 | QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); |
7882 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) |
7883 | CanTy = ResTypeRef->getPointeeType(); |
7884 | // Need to go down the pointer/mempointer chain and add qualifiers |
7885 | // as see them. |
7886 | bool done = false; |
7887 | while (!done) { |
7888 | if (CanTy.isRestrictQualified()) |
7889 | VRQuals.addRestrict(); |
7890 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) |
7891 | CanTy = ResTypePtr->getPointeeType(); |
7892 | else if (const MemberPointerType *ResTypeMPtr = |
7893 | CanTy->getAs<MemberPointerType>()) |
7894 | CanTy = ResTypeMPtr->getPointeeType(); |
7895 | else |
7896 | done = true; |
7897 | if (CanTy.isVolatileQualified()) |
7898 | VRQuals.addVolatile(); |
7899 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) |
7900 | return VRQuals; |
7901 | } |
7902 | } |
7903 | } |
7904 | return VRQuals; |
7905 | } |
7906 | |
7907 | namespace { |
7908 | |
7909 | /// Helper class to manage the addition of builtin operator overload |
7910 | /// candidates. It provides shared state and utility methods used throughout |
7911 | /// the process, as well as a helper method to add each group of builtin |
7912 | /// operator overloads from the standard to a candidate set. |
7913 | class BuiltinOperatorOverloadBuilder { |
7914 | // Common instance state available to all overload candidate addition methods. |
7915 | Sema &S; |
7916 | ArrayRef<Expr *> Args; |
7917 | Qualifiers VisibleTypeConversionsQuals; |
7918 | bool HasArithmeticOrEnumeralCandidateType; |
7919 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; |
7920 | OverloadCandidateSet &CandidateSet; |
7921 | |
7922 | static constexpr int ArithmeticTypesCap = 24; |
7923 | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; |
7924 | |
7925 | // Define some indices used to iterate over the arithmetic types in |
7926 | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic |
7927 | // types are that preserved by promotion (C++ [over.built]p2). |
7928 | unsigned FirstIntegralType, |
7929 | LastIntegralType; |
7930 | unsigned FirstPromotedIntegralType, |
7931 | LastPromotedIntegralType; |
7932 | unsigned FirstPromotedArithmeticType, |
7933 | LastPromotedArithmeticType; |
7934 | unsigned NumArithmeticTypes; |
7935 | |
7936 | void InitArithmeticTypes() { |
7937 | // Start of promoted types. |
7938 | FirstPromotedArithmeticType = 0; |
7939 | ArithmeticTypes.push_back(S.Context.FloatTy); |
7940 | ArithmeticTypes.push_back(S.Context.DoubleTy); |
7941 | ArithmeticTypes.push_back(S.Context.LongDoubleTy); |
7942 | if (S.Context.getTargetInfo().hasFloat128Type()) |
7943 | ArithmeticTypes.push_back(S.Context.Float128Ty); |
7944 | |
7945 | // Start of integral types. |
7946 | FirstIntegralType = ArithmeticTypes.size(); |
7947 | FirstPromotedIntegralType = ArithmeticTypes.size(); |
7948 | ArithmeticTypes.push_back(S.Context.IntTy); |
7949 | ArithmeticTypes.push_back(S.Context.LongTy); |
7950 | ArithmeticTypes.push_back(S.Context.LongLongTy); |
7951 | if (S.Context.getTargetInfo().hasInt128Type()) |
7952 | ArithmeticTypes.push_back(S.Context.Int128Ty); |
7953 | ArithmeticTypes.push_back(S.Context.UnsignedIntTy); |
7954 | ArithmeticTypes.push_back(S.Context.UnsignedLongTy); |
7955 | ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); |
7956 | if (S.Context.getTargetInfo().hasInt128Type()) |
7957 | ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); |
7958 | LastPromotedIntegralType = ArithmeticTypes.size(); |
7959 | LastPromotedArithmeticType = ArithmeticTypes.size(); |
7960 | // End of promoted types. |
7961 | |
7962 | ArithmeticTypes.push_back(S.Context.BoolTy); |
7963 | ArithmeticTypes.push_back(S.Context.CharTy); |
7964 | ArithmeticTypes.push_back(S.Context.WCharTy); |
7965 | if (S.Context.getLangOpts().Char8) |
7966 | ArithmeticTypes.push_back(S.Context.Char8Ty); |
7967 | ArithmeticTypes.push_back(S.Context.Char16Ty); |
7968 | ArithmeticTypes.push_back(S.Context.Char32Ty); |
7969 | ArithmeticTypes.push_back(S.Context.SignedCharTy); |
7970 | ArithmeticTypes.push_back(S.Context.ShortTy); |
7971 | ArithmeticTypes.push_back(S.Context.UnsignedCharTy); |
7972 | ArithmeticTypes.push_back(S.Context.UnsignedShortTy); |
7973 | LastIntegralType = ArithmeticTypes.size(); |
7974 | NumArithmeticTypes = ArithmeticTypes.size(); |
7975 | // End of integral types. |
7976 | // FIXME: What about complex? What about half? |
7977 | |
7978 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7979, __PRETTY_FUNCTION__)) |
7979 | "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 7979, __PRETTY_FUNCTION__)); |
7980 | } |
7981 | |
7982 | /// Helper method to factor out the common pattern of adding overloads |
7983 | /// for '++' and '--' builtin operators. |
7984 | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, |
7985 | bool HasVolatile, |
7986 | bool HasRestrict) { |
7987 | QualType ParamTypes[2] = { |
7988 | S.Context.getLValueReferenceType(CandidateTy), |
7989 | S.Context.IntTy |
7990 | }; |
7991 | |
7992 | // Non-volatile version. |
7993 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
7994 | |
7995 | // Use a heuristic to reduce number of builtin candidates in the set: |
7996 | // add volatile version only if there are conversions to a volatile type. |
7997 | if (HasVolatile) { |
7998 | ParamTypes[0] = |
7999 | S.Context.getLValueReferenceType( |
8000 | S.Context.getVolatileType(CandidateTy)); |
8001 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8002 | } |
8003 | |
8004 | // Add restrict version only if there are conversions to a restrict type |
8005 | // and our candidate type is a non-restrict-qualified pointer. |
8006 | if (HasRestrict && CandidateTy->isAnyPointerType() && |
8007 | !CandidateTy.isRestrictQualified()) { |
8008 | ParamTypes[0] |
8009 | = S.Context.getLValueReferenceType( |
8010 | S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); |
8011 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8012 | |
8013 | if (HasVolatile) { |
8014 | ParamTypes[0] |
8015 | = S.Context.getLValueReferenceType( |
8016 | S.Context.getCVRQualifiedType(CandidateTy, |
8017 | (Qualifiers::Volatile | |
8018 | Qualifiers::Restrict))); |
8019 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8020 | } |
8021 | } |
8022 | |
8023 | } |
8024 | |
8025 | public: |
8026 | BuiltinOperatorOverloadBuilder( |
8027 | Sema &S, ArrayRef<Expr *> Args, |
8028 | Qualifiers VisibleTypeConversionsQuals, |
8029 | bool HasArithmeticOrEnumeralCandidateType, |
8030 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, |
8031 | OverloadCandidateSet &CandidateSet) |
8032 | : S(S), Args(Args), |
8033 | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), |
8034 | HasArithmeticOrEnumeralCandidateType( |
8035 | HasArithmeticOrEnumeralCandidateType), |
8036 | CandidateTypes(CandidateTypes), |
8037 | CandidateSet(CandidateSet) { |
8038 | |
8039 | InitArithmeticTypes(); |
8040 | } |
8041 | |
8042 | // Increment is deprecated for bool since C++17. |
8043 | // |
8044 | // C++ [over.built]p3: |
8045 | // |
8046 | // For every pair (T, VQ), where T is an arithmetic type other |
8047 | // than bool, and VQ is either volatile or empty, there exist |
8048 | // candidate operator functions of the form |
8049 | // |
8050 | // VQ T& operator++(VQ T&); |
8051 | // T operator++(VQ T&, int); |
8052 | // |
8053 | // C++ [over.built]p4: |
8054 | // |
8055 | // For every pair (T, VQ), where T is an arithmetic type other |
8056 | // than bool, and VQ is either volatile or empty, there exist |
8057 | // candidate operator functions of the form |
8058 | // |
8059 | // VQ T& operator--(VQ T&); |
8060 | // T operator--(VQ T&, int); |
8061 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { |
8062 | if (!HasArithmeticOrEnumeralCandidateType) |
8063 | return; |
8064 | |
8065 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { |
8066 | const auto TypeOfT = ArithmeticTypes[Arith]; |
8067 | if (TypeOfT == S.Context.BoolTy) { |
8068 | if (Op == OO_MinusMinus) |
8069 | continue; |
8070 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) |
8071 | continue; |
8072 | } |
8073 | addPlusPlusMinusMinusStyleOverloads( |
8074 | TypeOfT, |
8075 | VisibleTypeConversionsQuals.hasVolatile(), |
8076 | VisibleTypeConversionsQuals.hasRestrict()); |
8077 | } |
8078 | } |
8079 | |
8080 | // C++ [over.built]p5: |
8081 | // |
8082 | // For every pair (T, VQ), where T is a cv-qualified or |
8083 | // cv-unqualified object type, and VQ is either volatile or |
8084 | // empty, there exist candidate operator functions of the form |
8085 | // |
8086 | // T*VQ& operator++(T*VQ&); |
8087 | // T*VQ& operator--(T*VQ&); |
8088 | // T* operator++(T*VQ&, int); |
8089 | // T* operator--(T*VQ&, int); |
8090 | void addPlusPlusMinusMinusPointerOverloads() { |
8091 | for (BuiltinCandidateTypeSet::iterator |
8092 | Ptr = CandidateTypes[0].pointer_begin(), |
8093 | PtrEnd = CandidateTypes[0].pointer_end(); |
8094 | Ptr != PtrEnd; ++Ptr) { |
8095 | // Skip pointer types that aren't pointers to object types. |
8096 | if (!(*Ptr)->getPointeeType()->isObjectType()) |
8097 | continue; |
8098 | |
8099 | addPlusPlusMinusMinusStyleOverloads(*Ptr, |
8100 | (!(*Ptr).isVolatileQualified() && |
8101 | VisibleTypeConversionsQuals.hasVolatile()), |
8102 | (!(*Ptr).isRestrictQualified() && |
8103 | VisibleTypeConversionsQuals.hasRestrict())); |
8104 | } |
8105 | } |
8106 | |
8107 | // C++ [over.built]p6: |
8108 | // For every cv-qualified or cv-unqualified object type T, there |
8109 | // exist candidate operator functions of the form |
8110 | // |
8111 | // T& operator*(T*); |
8112 | // |
8113 | // C++ [over.built]p7: |
8114 | // For every function type T that does not have cv-qualifiers or a |
8115 | // ref-qualifier, there exist candidate operator functions of the form |
8116 | // T& operator*(T*); |
8117 | void addUnaryStarPointerOverloads() { |
8118 | for (BuiltinCandidateTypeSet::iterator |
8119 | Ptr = CandidateTypes[0].pointer_begin(), |
8120 | PtrEnd = CandidateTypes[0].pointer_end(); |
8121 | Ptr != PtrEnd; ++Ptr) { |
8122 | QualType ParamTy = *Ptr; |
8123 | QualType PointeeTy = ParamTy->getPointeeType(); |
8124 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) |
8125 | continue; |
8126 | |
8127 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) |
8128 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) |
8129 | continue; |
8130 | |
8131 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
8132 | } |
8133 | } |
8134 | |
8135 | // C++ [over.built]p9: |
8136 | // For every promoted arithmetic type T, there exist candidate |
8137 | // operator functions of the form |
8138 | // |
8139 | // T operator+(T); |
8140 | // T operator-(T); |
8141 | void addUnaryPlusOrMinusArithmeticOverloads() { |
8142 | if (!HasArithmeticOrEnumeralCandidateType) |
8143 | return; |
8144 | |
8145 | for (unsigned Arith = FirstPromotedArithmeticType; |
8146 | Arith < LastPromotedArithmeticType; ++Arith) { |
8147 | QualType ArithTy = ArithmeticTypes[Arith]; |
8148 | S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); |
8149 | } |
8150 | |
8151 | // Extension: We also add these operators for vector types. |
8152 | for (BuiltinCandidateTypeSet::iterator |
8153 | Vec = CandidateTypes[0].vector_begin(), |
8154 | VecEnd = CandidateTypes[0].vector_end(); |
8155 | Vec != VecEnd; ++Vec) { |
8156 | QualType VecTy = *Vec; |
8157 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
8158 | } |
8159 | } |
8160 | |
8161 | // C++ [over.built]p8: |
8162 | // For every type T, there exist candidate operator functions of |
8163 | // the form |
8164 | // |
8165 | // T* operator+(T*); |
8166 | void addUnaryPlusPointerOverloads() { |
8167 | for (BuiltinCandidateTypeSet::iterator |
8168 | Ptr = CandidateTypes[0].pointer_begin(), |
8169 | PtrEnd = CandidateTypes[0].pointer_end(); |
8170 | Ptr != PtrEnd; ++Ptr) { |
8171 | QualType ParamTy = *Ptr; |
8172 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
8173 | } |
8174 | } |
8175 | |
8176 | // C++ [over.built]p10: |
8177 | // For every promoted integral type T, there exist candidate |
8178 | // operator functions of the form |
8179 | // |
8180 | // T operator~(T); |
8181 | void addUnaryTildePromotedIntegralOverloads() { |
8182 | if (!HasArithmeticOrEnumeralCandidateType) |
8183 | return; |
8184 | |
8185 | for (unsigned Int = FirstPromotedIntegralType; |
8186 | Int < LastPromotedIntegralType; ++Int) { |
8187 | QualType IntTy = ArithmeticTypes[Int]; |
8188 | S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); |
8189 | } |
8190 | |
8191 | // Extension: We also add this operator for vector types. |
8192 | for (BuiltinCandidateTypeSet::iterator |
8193 | Vec = CandidateTypes[0].vector_begin(), |
8194 | VecEnd = CandidateTypes[0].vector_end(); |
8195 | Vec != VecEnd; ++Vec) { |
8196 | QualType VecTy = *Vec; |
8197 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
8198 | } |
8199 | } |
8200 | |
8201 | // C++ [over.match.oper]p16: |
8202 | // For every pointer to member type T or type std::nullptr_t, there |
8203 | // exist candidate operator functions of the form |
8204 | // |
8205 | // bool operator==(T,T); |
8206 | // bool operator!=(T,T); |
8207 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { |
8208 | /// Set of (canonical) types that we've already handled. |
8209 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8210 | |
8211 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8212 | for (BuiltinCandidateTypeSet::iterator |
8213 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), |
8214 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); |
8215 | MemPtr != MemPtrEnd; |
8216 | ++MemPtr) { |
8217 | // Don't add the same builtin candidate twice. |
8218 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) |
8219 | continue; |
8220 | |
8221 | QualType ParamTypes[2] = { *MemPtr, *MemPtr }; |
8222 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8223 | } |
8224 | |
8225 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { |
8226 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); |
8227 | if (AddedTypes.insert(NullPtrTy).second) { |
8228 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; |
8229 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8230 | } |
8231 | } |
8232 | } |
8233 | } |
8234 | |
8235 | // C++ [over.built]p15: |
8236 | // |
8237 | // For every T, where T is an enumeration type or a pointer type, |
8238 | // there exist candidate operator functions of the form |
8239 | // |
8240 | // bool operator<(T, T); |
8241 | // bool operator>(T, T); |
8242 | // bool operator<=(T, T); |
8243 | // bool operator>=(T, T); |
8244 | // bool operator==(T, T); |
8245 | // bool operator!=(T, T); |
8246 | // R operator<=>(T, T) |
8247 | void addGenericBinaryPointerOrEnumeralOverloads() { |
8248 | // C++ [over.match.oper]p3: |
8249 | // [...]the built-in candidates include all of the candidate operator |
8250 | // functions defined in 13.6 that, compared to the given operator, [...] |
8251 | // do not have the same parameter-type-list as any non-template non-member |
8252 | // candidate. |
8253 | // |
8254 | // Note that in practice, this only affects enumeration types because there |
8255 | // aren't any built-in candidates of record type, and a user-defined operator |
8256 | // must have an operand of record or enumeration type. Also, the only other |
8257 | // overloaded operator with enumeration arguments, operator=, |
8258 | // cannot be overloaded for enumeration types, so this is the only place |
8259 | // where we must suppress candidates like this. |
8260 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > |
8261 | UserDefinedBinaryOperators; |
8262 | |
8263 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8264 | if (CandidateTypes[ArgIdx].enumeration_begin() != |
8265 | CandidateTypes[ArgIdx].enumeration_end()) { |
8266 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), |
8267 | CEnd = CandidateSet.end(); |
8268 | C != CEnd; ++C) { |
8269 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) |
8270 | continue; |
8271 | |
8272 | if (C->Function->isFunctionTemplateSpecialization()) |
8273 | continue; |
8274 | |
8275 | // We interpret "same parameter-type-list" as applying to the |
8276 | // "synthesized candidate, with the order of the two parameters |
8277 | // reversed", not to the original function. |
8278 | bool Reversed = C->RewriteKind & CRK_Reversed; |
8279 | QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) |
8280 | ->getType() |
8281 | .getUnqualifiedType(); |
8282 | QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) |
8283 | ->getType() |
8284 | .getUnqualifiedType(); |
8285 | |
8286 | // Skip if either parameter isn't of enumeral type. |
8287 | if (!FirstParamType->isEnumeralType() || |
8288 | !SecondParamType->isEnumeralType()) |
8289 | continue; |
8290 | |
8291 | // Add this operator to the set of known user-defined operators. |
8292 | UserDefinedBinaryOperators.insert( |
8293 | std::make_pair(S.Context.getCanonicalType(FirstParamType), |
8294 | S.Context.getCanonicalType(SecondParamType))); |
8295 | } |
8296 | } |
8297 | } |
8298 | |
8299 | /// Set of (canonical) types that we've already handled. |
8300 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8301 | |
8302 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8303 | for (BuiltinCandidateTypeSet::iterator |
8304 | Ptr = CandidateTypes[ArgIdx].pointer_begin(), |
8305 | PtrEnd = CandidateTypes[ArgIdx].pointer_end(); |
8306 | Ptr != PtrEnd; ++Ptr) { |
8307 | // Don't add the same builtin candidate twice. |
8308 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) |
8309 | continue; |
8310 | |
8311 | QualType ParamTypes[2] = { *Ptr, *Ptr }; |
8312 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8313 | } |
8314 | for (BuiltinCandidateTypeSet::iterator |
8315 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), |
8316 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); |
8317 | Enum != EnumEnd; ++Enum) { |
8318 | CanQualType CanonType = S.Context.getCanonicalType(*Enum); |
8319 | |
8320 | // Don't add the same builtin candidate twice, or if a user defined |
8321 | // candidate exists. |
8322 | if (!AddedTypes.insert(CanonType).second || |
8323 | UserDefinedBinaryOperators.count(std::make_pair(CanonType, |
8324 | CanonType))) |
8325 | continue; |
8326 | QualType ParamTypes[2] = { *Enum, *Enum }; |
8327 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8328 | } |
8329 | } |
8330 | } |
8331 | |
8332 | // C++ [over.built]p13: |
8333 | // |
8334 | // For every cv-qualified or cv-unqualified object type T |
8335 | // there exist candidate operator functions of the form |
8336 | // |
8337 | // T* operator+(T*, ptrdiff_t); |
8338 | // T& operator[](T*, ptrdiff_t); [BELOW] |
8339 | // T* operator-(T*, ptrdiff_t); |
8340 | // T* operator+(ptrdiff_t, T*); |
8341 | // T& operator[](ptrdiff_t, T*); [BELOW] |
8342 | // |
8343 | // C++ [over.built]p14: |
8344 | // |
8345 | // For every T, where T is a pointer to object type, there |
8346 | // exist candidate operator functions of the form |
8347 | // |
8348 | // ptrdiff_t operator-(T, T); |
8349 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { |
8350 | /// Set of (canonical) types that we've already handled. |
8351 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8352 | |
8353 | for (int Arg = 0; Arg < 2; ++Arg) { |
8354 | QualType AsymmetricParamTypes[2] = { |
8355 | S.Context.getPointerDiffType(), |
8356 | S.Context.getPointerDiffType(), |
8357 | }; |
8358 | for (BuiltinCandidateTypeSet::iterator |
8359 | Ptr = CandidateTypes[Arg].pointer_begin(), |
8360 | PtrEnd = CandidateTypes[Arg].pointer_end(); |
8361 | Ptr != PtrEnd; ++Ptr) { |
8362 | QualType PointeeTy = (*Ptr)->getPointeeType(); |
8363 | if (!PointeeTy->isObjectType()) |
8364 | continue; |
8365 | |
8366 | AsymmetricParamTypes[Arg] = *Ptr; |
8367 | if (Arg == 0 || Op == OO_Plus) { |
8368 | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) |
8369 | // T* operator+(ptrdiff_t, T*); |
8370 | S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); |
8371 | } |
8372 | if (Op == OO_Minus) { |
8373 | // ptrdiff_t operator-(T, T); |
8374 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) |
8375 | continue; |
8376 | |
8377 | QualType ParamTypes[2] = { *Ptr, *Ptr }; |
8378 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8379 | } |
8380 | } |
8381 | } |
8382 | } |
8383 | |
8384 | // C++ [over.built]p12: |
8385 | // |
8386 | // For every pair of promoted arithmetic types L and R, there |
8387 | // exist candidate operator functions of the form |
8388 | // |
8389 | // LR operator*(L, R); |
8390 | // LR operator/(L, R); |
8391 | // LR operator+(L, R); |
8392 | // LR operator-(L, R); |
8393 | // bool operator<(L, R); |
8394 | // bool operator>(L, R); |
8395 | // bool operator<=(L, R); |
8396 | // bool operator>=(L, R); |
8397 | // bool operator==(L, R); |
8398 | // bool operator!=(L, R); |
8399 | // |
8400 | // where LR is the result of the usual arithmetic conversions |
8401 | // between types L and R. |
8402 | // |
8403 | // C++ [over.built]p24: |
8404 | // |
8405 | // For every pair of promoted arithmetic types L and R, there exist |
8406 | // candidate operator functions of the form |
8407 | // |
8408 | // LR operator?(bool, L, R); |
8409 | // |
8410 | // where LR is the result of the usual arithmetic conversions |
8411 | // between types L and R. |
8412 | // Our candidates ignore the first parameter. |
8413 | void addGenericBinaryArithmeticOverloads() { |
8414 | if (!HasArithmeticOrEnumeralCandidateType) |
8415 | return; |
8416 | |
8417 | for (unsigned Left = FirstPromotedArithmeticType; |
8418 | Left < LastPromotedArithmeticType; ++Left) { |
8419 | for (unsigned Right = FirstPromotedArithmeticType; |
8420 | Right < LastPromotedArithmeticType; ++Right) { |
8421 | QualType LandR[2] = { ArithmeticTypes[Left], |
8422 | ArithmeticTypes[Right] }; |
8423 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8424 | } |
8425 | } |
8426 | |
8427 | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the |
8428 | // conditional operator for vector types. |
8429 | for (BuiltinCandidateTypeSet::iterator |
8430 | Vec1 = CandidateTypes[0].vector_begin(), |
8431 | Vec1End = CandidateTypes[0].vector_end(); |
8432 | Vec1 != Vec1End; ++Vec1) { |
8433 | for (BuiltinCandidateTypeSet::iterator |
8434 | Vec2 = CandidateTypes[1].vector_begin(), |
8435 | Vec2End = CandidateTypes[1].vector_end(); |
8436 | Vec2 != Vec2End; ++Vec2) { |
8437 | QualType LandR[2] = { *Vec1, *Vec2 }; |
8438 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8439 | } |
8440 | } |
8441 | } |
8442 | |
8443 | // C++2a [over.built]p14: |
8444 | // |
8445 | // For every integral type T there exists a candidate operator function |
8446 | // of the form |
8447 | // |
8448 | // std::strong_ordering operator<=>(T, T) |
8449 | // |
8450 | // C++2a [over.built]p15: |
8451 | // |
8452 | // For every pair of floating-point types L and R, there exists a candidate |
8453 | // operator function of the form |
8454 | // |
8455 | // std::partial_ordering operator<=>(L, R); |
8456 | // |
8457 | // FIXME: The current specification for integral types doesn't play nice with |
8458 | // the direction of p0946r0, which allows mixed integral and unscoped-enum |
8459 | // comparisons. Under the current spec this can lead to ambiguity during |
8460 | // overload resolution. For example: |
8461 | // |
8462 | // enum A : int {a}; |
8463 | // auto x = (a <=> (long)42); |
8464 | // |
8465 | // error: call is ambiguous for arguments 'A' and 'long'. |
8466 | // note: candidate operator<=>(int, int) |
8467 | // note: candidate operator<=>(long, long) |
8468 | // |
8469 | // To avoid this error, this function deviates from the specification and adds |
8470 | // the mixed overloads `operator<=>(L, R)` where L and R are promoted |
8471 | // arithmetic types (the same as the generic relational overloads). |
8472 | // |
8473 | // For now this function acts as a placeholder. |
8474 | void addThreeWayArithmeticOverloads() { |
8475 | addGenericBinaryArithmeticOverloads(); |
8476 | } |
8477 | |
8478 | // C++ [over.built]p17: |
8479 | // |
8480 | // For every pair of promoted integral types L and R, there |
8481 | // exist candidate operator functions of the form |
8482 | // |
8483 | // LR operator%(L, R); |
8484 | // LR operator&(L, R); |
8485 | // LR operator^(L, R); |
8486 | // LR operator|(L, R); |
8487 | // L operator<<(L, R); |
8488 | // L operator>>(L, R); |
8489 | // |
8490 | // where LR is the result of the usual arithmetic conversions |
8491 | // between types L and R. |
8492 | void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { |
8493 | if (!HasArithmeticOrEnumeralCandidateType) |
8494 | return; |
8495 | |
8496 | for (unsigned Left = FirstPromotedIntegralType; |
8497 | Left < LastPromotedIntegralType; ++Left) { |
8498 | for (unsigned Right = FirstPromotedIntegralType; |
8499 | Right < LastPromotedIntegralType; ++Right) { |
8500 | QualType LandR[2] = { ArithmeticTypes[Left], |
8501 | ArithmeticTypes[Right] }; |
8502 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8503 | } |
8504 | } |
8505 | } |
8506 | |
8507 | // C++ [over.built]p20: |
8508 | // |
8509 | // For every pair (T, VQ), where T is an enumeration or |
8510 | // pointer to member type and VQ is either volatile or |
8511 | // empty, there exist candidate operator functions of the form |
8512 | // |
8513 | // VQ T& operator=(VQ T&, T); |
8514 | void addAssignmentMemberPointerOrEnumeralOverloads() { |
8515 | /// Set of (canonical) types that we've already handled. |
8516 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8517 | |
8518 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
8519 | for (BuiltinCandidateTypeSet::iterator |
8520 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), |
8521 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); |
8522 | Enum != EnumEnd; ++Enum) { |
8523 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) |
8524 | continue; |
8525 | |
8526 | AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); |
8527 | } |
8528 | |
8529 | for (BuiltinCandidateTypeSet::iterator |
8530 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), |
8531 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); |
8532 | MemPtr != MemPtrEnd; ++MemPtr) { |
8533 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) |
8534 | continue; |
8535 | |
8536 | AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); |
8537 | } |
8538 | } |
8539 | } |
8540 | |
8541 | // C++ [over.built]p19: |
8542 | // |
8543 | // For every pair (T, VQ), where T is any type and VQ is either |
8544 | // volatile or empty, there exist candidate operator functions |
8545 | // of the form |
8546 | // |
8547 | // T*VQ& operator=(T*VQ&, T*); |
8548 | // |
8549 | // C++ [over.built]p21: |
8550 | // |
8551 | // For every pair (T, VQ), where T is a cv-qualified or |
8552 | // cv-unqualified object type and VQ is either volatile or |
8553 | // empty, there exist candidate operator functions of the form |
8554 | // |
8555 | // T*VQ& operator+=(T*VQ&, ptrdiff_t); |
8556 | // T*VQ& operator-=(T*VQ&, ptrdiff_t); |
8557 | void addAssignmentPointerOverloads(bool isEqualOp) { |
8558 | /// Set of (canonical) types that we've already handled. |
8559 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8560 | |
8561 | for (BuiltinCandidateTypeSet::iterator |
8562 | Ptr = CandidateTypes[0].pointer_begin(), |
8563 | PtrEnd = CandidateTypes[0].pointer_end(); |
8564 | Ptr != PtrEnd; ++Ptr) { |
8565 | // If this is operator=, keep track of the builtin candidates we added. |
8566 | if (isEqualOp) |
8567 | AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); |
8568 | else if (!(*Ptr)->getPointeeType()->isObjectType()) |
8569 | continue; |
8570 | |
8571 | // non-volatile version |
8572 | QualType ParamTypes[2] = { |
8573 | S.Context.getLValueReferenceType(*Ptr), |
8574 | isEqualOp ? *Ptr : S.Context.getPointerDiffType(), |
8575 | }; |
8576 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8577 | /*IsAssignmentOperator=*/ isEqualOp); |
8578 | |
8579 | bool NeedVolatile = !(*Ptr).isVolatileQualified() && |
8580 | VisibleTypeConversionsQuals.hasVolatile(); |
8581 | if (NeedVolatile) { |
8582 | // volatile version |
8583 | ParamTypes[0] = |
8584 | S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); |
8585 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8586 | /*IsAssignmentOperator=*/isEqualOp); |
8587 | } |
8588 | |
8589 | if (!(*Ptr).isRestrictQualified() && |
8590 | VisibleTypeConversionsQuals.hasRestrict()) { |
8591 | // restrict version |
8592 | ParamTypes[0] |
8593 | = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); |
8594 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8595 | /*IsAssignmentOperator=*/isEqualOp); |
8596 | |
8597 | if (NeedVolatile) { |
8598 | // volatile restrict version |
8599 | ParamTypes[0] |
8600 | = S.Context.getLValueReferenceType( |
8601 | S.Context.getCVRQualifiedType(*Ptr, |
8602 | (Qualifiers::Volatile | |
8603 | Qualifiers::Restrict))); |
8604 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8605 | /*IsAssignmentOperator=*/isEqualOp); |
8606 | } |
8607 | } |
8608 | } |
8609 | |
8610 | if (isEqualOp) { |
8611 | for (BuiltinCandidateTypeSet::iterator |
8612 | Ptr = CandidateTypes[1].pointer_begin(), |
8613 | PtrEnd = CandidateTypes[1].pointer_end(); |
8614 | Ptr != PtrEnd; ++Ptr) { |
8615 | // Make sure we don't add the same candidate twice. |
8616 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) |
8617 | continue; |
8618 | |
8619 | QualType ParamTypes[2] = { |
8620 | S.Context.getLValueReferenceType(*Ptr), |
8621 | *Ptr, |
8622 | }; |
8623 | |
8624 | // non-volatile version |
8625 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8626 | /*IsAssignmentOperator=*/true); |
8627 | |
8628 | bool NeedVolatile = !(*Ptr).isVolatileQualified() && |
8629 | VisibleTypeConversionsQuals.hasVolatile(); |
8630 | if (NeedVolatile) { |
8631 | // volatile version |
8632 | ParamTypes[0] = |
8633 | S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); |
8634 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8635 | /*IsAssignmentOperator=*/true); |
8636 | } |
8637 | |
8638 | if (!(*Ptr).isRestrictQualified() && |
8639 | VisibleTypeConversionsQuals.hasRestrict()) { |
8640 | // restrict version |
8641 | ParamTypes[0] |
8642 | = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); |
8643 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8644 | /*IsAssignmentOperator=*/true); |
8645 | |
8646 | if (NeedVolatile) { |
8647 | // volatile restrict version |
8648 | ParamTypes[0] |
8649 | = S.Context.getLValueReferenceType( |
8650 | S.Context.getCVRQualifiedType(*Ptr, |
8651 | (Qualifiers::Volatile | |
8652 | Qualifiers::Restrict))); |
8653 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8654 | /*IsAssignmentOperator=*/true); |
8655 | } |
8656 | } |
8657 | } |
8658 | } |
8659 | } |
8660 | |
8661 | // C++ [over.built]p18: |
8662 | // |
8663 | // For every triple (L, VQ, R), where L is an arithmetic type, |
8664 | // VQ is either volatile or empty, and R is a promoted |
8665 | // arithmetic type, there exist candidate operator functions of |
8666 | // the form |
8667 | // |
8668 | // VQ L& operator=(VQ L&, R); |
8669 | // VQ L& operator*=(VQ L&, R); |
8670 | // VQ L& operator/=(VQ L&, R); |
8671 | // VQ L& operator+=(VQ L&, R); |
8672 | // VQ L& operator-=(VQ L&, R); |
8673 | void addAssignmentArithmeticOverloads(bool isEqualOp) { |
8674 | if (!HasArithmeticOrEnumeralCandidateType) |
8675 | return; |
8676 | |
8677 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { |
8678 | for (unsigned Right = FirstPromotedArithmeticType; |
8679 | Right < LastPromotedArithmeticType; ++Right) { |
8680 | QualType ParamTypes[2]; |
8681 | ParamTypes[1] = ArithmeticTypes[Right]; |
8682 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
8683 | S, ArithmeticTypes[Left], Args[0]); |
8684 | // Add this built-in operator as a candidate (VQ is empty). |
8685 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); |
8686 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8687 | /*IsAssignmentOperator=*/isEqualOp); |
8688 | |
8689 | // Add this built-in operator as a candidate (VQ is 'volatile'). |
8690 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
8691 | ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); |
8692 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); |
8693 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8694 | /*IsAssignmentOperator=*/isEqualOp); |
8695 | } |
8696 | } |
8697 | } |
8698 | |
8699 | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. |
8700 | for (BuiltinCandidateTypeSet::iterator |
8701 | Vec1 = CandidateTypes[0].vector_begin(), |
8702 | Vec1End = CandidateTypes[0].vector_end(); |
8703 | Vec1 != Vec1End; ++Vec1) { |
8704 | for (BuiltinCandidateTypeSet::iterator |
8705 | Vec2 = CandidateTypes[1].vector_begin(), |
8706 | Vec2End = CandidateTypes[1].vector_end(); |
8707 | Vec2 != Vec2End; ++Vec2) { |
8708 | QualType ParamTypes[2]; |
8709 | ParamTypes[1] = *Vec2; |
8710 | // Add this built-in operator as a candidate (VQ is empty). |
8711 | ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); |
8712 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8713 | /*IsAssignmentOperator=*/isEqualOp); |
8714 | |
8715 | // Add this built-in operator as a candidate (VQ is 'volatile'). |
8716 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
8717 | ParamTypes[0] = S.Context.getVolatileType(*Vec1); |
8718 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); |
8719 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8720 | /*IsAssignmentOperator=*/isEqualOp); |
8721 | } |
8722 | } |
8723 | } |
8724 | } |
8725 | |
8726 | // C++ [over.built]p22: |
8727 | // |
8728 | // For every triple (L, VQ, R), where L is an integral type, VQ |
8729 | // is either volatile or empty, and R is a promoted integral |
8730 | // type, there exist candidate operator functions of the form |
8731 | // |
8732 | // VQ L& operator%=(VQ L&, R); |
8733 | // VQ L& operator<<=(VQ L&, R); |
8734 | // VQ L& operator>>=(VQ L&, R); |
8735 | // VQ L& operator&=(VQ L&, R); |
8736 | // VQ L& operator^=(VQ L&, R); |
8737 | // VQ L& operator|=(VQ L&, R); |
8738 | void addAssignmentIntegralOverloads() { |
8739 | if (!HasArithmeticOrEnumeralCandidateType) |
8740 | return; |
8741 | |
8742 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { |
8743 | for (unsigned Right = FirstPromotedIntegralType; |
8744 | Right < LastPromotedIntegralType; ++Right) { |
8745 | QualType ParamTypes[2]; |
8746 | ParamTypes[1] = ArithmeticTypes[Right]; |
8747 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
8748 | S, ArithmeticTypes[Left], Args[0]); |
8749 | // Add this built-in operator as a candidate (VQ is empty). |
8750 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); |
8751 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8752 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
8753 | // Add this built-in operator as a candidate (VQ is 'volatile'). |
8754 | ParamTypes[0] = LeftBaseTy; |
8755 | ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); |
8756 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); |
8757 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8758 | } |
8759 | } |
8760 | } |
8761 | } |
8762 | |
8763 | // C++ [over.operator]p23: |
8764 | // |
8765 | // There also exist candidate operator functions of the form |
8766 | // |
8767 | // bool operator!(bool); |
8768 | // bool operator&&(bool, bool); |
8769 | // bool operator||(bool, bool); |
8770 | void addExclaimOverload() { |
8771 | QualType ParamTy = S.Context.BoolTy; |
8772 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, |
8773 | /*IsAssignmentOperator=*/false, |
8774 | /*NumContextualBoolArguments=*/1); |
8775 | } |
8776 | void addAmpAmpOrPipePipeOverload() { |
8777 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; |
8778 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8779 | /*IsAssignmentOperator=*/false, |
8780 | /*NumContextualBoolArguments=*/2); |
8781 | } |
8782 | |
8783 | // C++ [over.built]p13: |
8784 | // |
8785 | // For every cv-qualified or cv-unqualified object type T there |
8786 | // exist candidate operator functions of the form |
8787 | // |
8788 | // T* operator+(T*, ptrdiff_t); [ABOVE] |
8789 | // T& operator[](T*, ptrdiff_t); |
8790 | // T* operator-(T*, ptrdiff_t); [ABOVE] |
8791 | // T* operator+(ptrdiff_t, T*); [ABOVE] |
8792 | // T& operator[](ptrdiff_t, T*); |
8793 | void addSubscriptOverloads() { |
8794 | for (BuiltinCandidateTypeSet::iterator |
8795 | Ptr = CandidateTypes[0].pointer_begin(), |
8796 | PtrEnd = CandidateTypes[0].pointer_end(); |
8797 | Ptr != PtrEnd; ++Ptr) { |
8798 | QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; |
8799 | QualType PointeeType = (*Ptr)->getPointeeType(); |
8800 | if (!PointeeType->isObjectType()) |
8801 | continue; |
8802 | |
8803 | // T& operator[](T*, ptrdiff_t) |
8804 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8805 | } |
8806 | |
8807 | for (BuiltinCandidateTypeSet::iterator |
8808 | Ptr = CandidateTypes[1].pointer_begin(), |
8809 | PtrEnd = CandidateTypes[1].pointer_end(); |
8810 | Ptr != PtrEnd; ++Ptr) { |
8811 | QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; |
8812 | QualType PointeeType = (*Ptr)->getPointeeType(); |
8813 | if (!PointeeType->isObjectType()) |
8814 | continue; |
8815 | |
8816 | // T& operator[](ptrdiff_t, T*) |
8817 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8818 | } |
8819 | } |
8820 | |
8821 | // C++ [over.built]p11: |
8822 | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, |
8823 | // C1 is the same type as C2 or is a derived class of C2, T is an object |
8824 | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, |
8825 | // there exist candidate operator functions of the form |
8826 | // |
8827 | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); |
8828 | // |
8829 | // where CV12 is the union of CV1 and CV2. |
8830 | void addArrowStarOverloads() { |
8831 | for (BuiltinCandidateTypeSet::iterator |
8832 | Ptr = CandidateTypes[0].pointer_begin(), |
8833 | PtrEnd = CandidateTypes[0].pointer_end(); |
8834 | Ptr != PtrEnd; ++Ptr) { |
8835 | QualType C1Ty = (*Ptr); |
8836 | QualType C1; |
8837 | QualifierCollector Q1; |
8838 | C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); |
8839 | if (!isa<RecordType>(C1)) |
8840 | continue; |
8841 | // heuristic to reduce number of builtin candidates in the set. |
8842 | // Add volatile/restrict version only if there are conversions to a |
8843 | // volatile/restrict type. |
8844 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) |
8845 | continue; |
8846 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) |
8847 | continue; |
8848 | for (BuiltinCandidateTypeSet::iterator |
8849 | MemPtr = CandidateTypes[1].member_pointer_begin(), |
8850 | MemPtrEnd = CandidateTypes[1].member_pointer_end(); |
8851 | MemPtr != MemPtrEnd; ++MemPtr) { |
8852 | const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); |
8853 | QualType C2 = QualType(mptr->getClass(), 0); |
8854 | C2 = C2.getUnqualifiedType(); |
8855 | if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) |
8856 | break; |
8857 | QualType ParamTypes[2] = { *Ptr, *MemPtr }; |
8858 | // build CV12 T& |
8859 | QualType T = mptr->getPointeeType(); |
8860 | if (!VisibleTypeConversionsQuals.hasVolatile() && |
8861 | T.isVolatileQualified()) |
8862 | continue; |
8863 | if (!VisibleTypeConversionsQuals.hasRestrict() && |
8864 | T.isRestrictQualified()) |
8865 | continue; |
8866 | T = Q1.apply(S.Context, T); |
8867 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8868 | } |
8869 | } |
8870 | } |
8871 | |
8872 | // Note that we don't consider the first argument, since it has been |
8873 | // contextually converted to bool long ago. The candidates below are |
8874 | // therefore added as binary. |
8875 | // |
8876 | // C++ [over.built]p25: |
8877 | // For every type T, where T is a pointer, pointer-to-member, or scoped |
8878 | // enumeration type, there exist candidate operator functions of the form |
8879 | // |
8880 | // T operator?(bool, T, T); |
8881 | // |
8882 | void addConditionalOperatorOverloads() { |
8883 | /// Set of (canonical) types that we've already handled. |
8884 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
8885 | |
8886 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
8887 | for (BuiltinCandidateTypeSet::iterator |
8888 | Ptr = CandidateTypes[ArgIdx].pointer_begin(), |
8889 | PtrEnd = CandidateTypes[ArgIdx].pointer_end(); |
8890 | Ptr != PtrEnd; ++Ptr) { |
8891 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) |
8892 | continue; |
8893 | |
8894 | QualType ParamTypes[2] = { *Ptr, *Ptr }; |
8895 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8896 | } |
8897 | |
8898 | for (BuiltinCandidateTypeSet::iterator |
8899 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), |
8900 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); |
8901 | MemPtr != MemPtrEnd; ++MemPtr) { |
8902 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) |
8903 | continue; |
8904 | |
8905 | QualType ParamTypes[2] = { *MemPtr, *MemPtr }; |
8906 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8907 | } |
8908 | |
8909 | if (S.getLangOpts().CPlusPlus11) { |
8910 | for (BuiltinCandidateTypeSet::iterator |
8911 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), |
8912 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); |
8913 | Enum != EnumEnd; ++Enum) { |
8914 | if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) |
8915 | continue; |
8916 | |
8917 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) |
8918 | continue; |
8919 | |
8920 | QualType ParamTypes[2] = { *Enum, *Enum }; |
8921 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8922 | } |
8923 | } |
8924 | } |
8925 | } |
8926 | }; |
8927 | |
8928 | } // end anonymous namespace |
8929 | |
8930 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in |
8931 | /// operator overloads to the candidate set (C++ [over.built]), based |
8932 | /// on the operator @p Op and the arguments given. For example, if the |
8933 | /// operator is a binary '+', this routine might add "int |
8934 | /// operator+(int, int)" to cover integer addition. |
8935 | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
8936 | SourceLocation OpLoc, |
8937 | ArrayRef<Expr *> Args, |
8938 | OverloadCandidateSet &CandidateSet) { |
8939 | // Find all of the types that the arguments can convert to, but only |
8940 | // if the operator we're looking at has built-in operator candidates |
8941 | // that make use of these types. Also record whether we encounter non-record |
8942 | // candidate types or either arithmetic or enumeral candidate types. |
8943 | Qualifiers VisibleTypeConversionsQuals; |
8944 | VisibleTypeConversionsQuals.addConst(); |
8945 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) |
8946 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); |
8947 | |
8948 | bool HasNonRecordCandidateType = false; |
8949 | bool HasArithmeticOrEnumeralCandidateType = false; |
8950 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; |
8951 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8952 | CandidateTypes.emplace_back(*this); |
8953 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), |
8954 | OpLoc, |
8955 | true, |
8956 | (Op == OO_Exclaim || |
8957 | Op == OO_AmpAmp || |
8958 | Op == OO_PipePipe), |
8959 | VisibleTypeConversionsQuals); |
8960 | HasNonRecordCandidateType = HasNonRecordCandidateType || |
8961 | CandidateTypes[ArgIdx].hasNonRecordTypes(); |
8962 | HasArithmeticOrEnumeralCandidateType = |
8963 | HasArithmeticOrEnumeralCandidateType || |
8964 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); |
8965 | } |
8966 | |
8967 | // Exit early when no non-record types have been added to the candidate set |
8968 | // for any of the arguments to the operator. |
8969 | // |
8970 | // We can't exit early for !, ||, or &&, since there we have always have |
8971 | // 'bool' overloads. |
8972 | if (!HasNonRecordCandidateType && |
8973 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) |
8974 | return; |
8975 | |
8976 | // Setup an object to manage the common state for building overloads. |
8977 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, |
8978 | VisibleTypeConversionsQuals, |
8979 | HasArithmeticOrEnumeralCandidateType, |
8980 | CandidateTypes, CandidateSet); |
8981 | |
8982 | // Dispatch over the operation to add in only those overloads which apply. |
8983 | switch (Op) { |
8984 | case OO_None: |
8985 | case NUM_OVERLOADED_OPERATORS: |
8986 | llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 8986); |
8987 | |
8988 | case OO_New: |
8989 | case OO_Delete: |
8990 | case OO_Array_New: |
8991 | case OO_Array_Delete: |
8992 | case OO_Call: |
8993 | llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 8994) |
8994 | "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 8994); |
8995 | |
8996 | case OO_Comma: |
8997 | case OO_Arrow: |
8998 | case OO_Coawait: |
8999 | // C++ [over.match.oper]p3: |
9000 | // -- For the operator ',', the unary operator '&', the |
9001 | // operator '->', or the operator 'co_await', the |
9002 | // built-in candidates set is empty. |
9003 | break; |
9004 | |
9005 | case OO_Plus: // '+' is either unary or binary |
9006 | if (Args.size() == 1) |
9007 | OpBuilder.addUnaryPlusPointerOverloads(); |
9008 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
9009 | |
9010 | case OO_Minus: // '-' is either unary or binary |
9011 | if (Args.size() == 1) { |
9012 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); |
9013 | } else { |
9014 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); |
9015 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9016 | } |
9017 | break; |
9018 | |
9019 | case OO_Star: // '*' is either unary or binary |
9020 | if (Args.size() == 1) |
9021 | OpBuilder.addUnaryStarPointerOverloads(); |
9022 | else |
9023 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9024 | break; |
9025 | |
9026 | case OO_Slash: |
9027 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9028 | break; |
9029 | |
9030 | case OO_PlusPlus: |
9031 | case OO_MinusMinus: |
9032 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); |
9033 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); |
9034 | break; |
9035 | |
9036 | case OO_EqualEqual: |
9037 | case OO_ExclaimEqual: |
9038 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); |
9039 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
9040 | |
9041 | case OO_Less: |
9042 | case OO_Greater: |
9043 | case OO_LessEqual: |
9044 | case OO_GreaterEqual: |
9045 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); |
9046 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9047 | break; |
9048 | |
9049 | case OO_Spaceship: |
9050 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); |
9051 | OpBuilder.addThreeWayArithmeticOverloads(); |
9052 | break; |
9053 | |
9054 | case OO_Percent: |
9055 | case OO_Caret: |
9056 | case OO_Pipe: |
9057 | case OO_LessLess: |
9058 | case OO_GreaterGreater: |
9059 | OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); |
9060 | break; |
9061 | |
9062 | case OO_Amp: // '&' is either unary or binary |
9063 | if (Args.size() == 1) |
9064 | // C++ [over.match.oper]p3: |
9065 | // -- For the operator ',', the unary operator '&', or the |
9066 | // operator '->', the built-in candidates set is empty. |
9067 | break; |
9068 | |
9069 | OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); |
9070 | break; |
9071 | |
9072 | case OO_Tilde: |
9073 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); |
9074 | break; |
9075 | |
9076 | case OO_Equal: |
9077 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); |
9078 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
9079 | |
9080 | case OO_PlusEqual: |
9081 | case OO_MinusEqual: |
9082 | OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); |
9083 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
9084 | |
9085 | case OO_StarEqual: |
9086 | case OO_SlashEqual: |
9087 | OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); |
9088 | break; |
9089 | |
9090 | case OO_PercentEqual: |
9091 | case OO_LessLessEqual: |
9092 | case OO_GreaterGreaterEqual: |
9093 | case OO_AmpEqual: |
9094 | case OO_CaretEqual: |
9095 | case OO_PipeEqual: |
9096 | OpBuilder.addAssignmentIntegralOverloads(); |
9097 | break; |
9098 | |
9099 | case OO_Exclaim: |
9100 | OpBuilder.addExclaimOverload(); |
9101 | break; |
9102 | |
9103 | case OO_AmpAmp: |
9104 | case OO_PipePipe: |
9105 | OpBuilder.addAmpAmpOrPipePipeOverload(); |
9106 | break; |
9107 | |
9108 | case OO_Subscript: |
9109 | OpBuilder.addSubscriptOverloads(); |
9110 | break; |
9111 | |
9112 | case OO_ArrowStar: |
9113 | OpBuilder.addArrowStarOverloads(); |
9114 | break; |
9115 | |
9116 | case OO_Conditional: |
9117 | OpBuilder.addConditionalOperatorOverloads(); |
9118 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9119 | break; |
9120 | } |
9121 | } |
9122 | |
9123 | /// Add function candidates found via argument-dependent lookup |
9124 | /// to the set of overloading candidates. |
9125 | /// |
9126 | /// This routine performs argument-dependent name lookup based on the |
9127 | /// given function name (which may also be an operator name) and adds |
9128 | /// all of the overload candidates found by ADL to the overload |
9129 | /// candidate set (C++ [basic.lookup.argdep]). |
9130 | void |
9131 | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, |
9132 | SourceLocation Loc, |
9133 | ArrayRef<Expr *> Args, |
9134 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
9135 | OverloadCandidateSet& CandidateSet, |
9136 | bool PartialOverloading) { |
9137 | ADLResult Fns; |
9138 | |
9139 | // FIXME: This approach for uniquing ADL results (and removing |
9140 | // redundant candidates from the set) relies on pointer-equality, |
9141 | // which means we need to key off the canonical decl. However, |
9142 | // always going back to the canonical decl might not get us the |
9143 | // right set of default arguments. What default arguments are |
9144 | // we supposed to consider on ADL candidates, anyway? |
9145 | |
9146 | // FIXME: Pass in the explicit template arguments? |
9147 | ArgumentDependentLookup(Name, Loc, Args, Fns); |
9148 | |
9149 | // Erase all of the candidates we already knew about. |
9150 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), |
9151 | CandEnd = CandidateSet.end(); |
9152 | Cand != CandEnd; ++Cand) |
9153 | if (Cand->Function) { |
9154 | Fns.erase(Cand->Function); |
9155 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) |
9156 | Fns.erase(FunTmpl); |
9157 | } |
9158 | |
9159 | // For each of the ADL candidates we found, add it to the overload |
9160 | // set. |
9161 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { |
9162 | DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); |
9163 | |
9164 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { |
9165 | if (ExplicitTemplateArgs) |
9166 | continue; |
9167 | |
9168 | AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, |
9169 | /*SuppressUserConversions=*/false, PartialOverloading, |
9170 | /*AllowExplicit*/ true, |
9171 | /*AllowExplicitConversions*/ false, |
9172 | ADLCallKind::UsesADL); |
9173 | } else { |
9174 | AddTemplateOverloadCandidate( |
9175 | cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, |
9176 | CandidateSet, |
9177 | /*SuppressUserConversions=*/false, PartialOverloading, |
9178 | /*AllowExplicit*/true, ADLCallKind::UsesADL); |
9179 | } |
9180 | } |
9181 | } |
9182 | |
9183 | namespace { |
9184 | enum class Comparison { Equal, Better, Worse }; |
9185 | } |
9186 | |
9187 | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of |
9188 | /// overload resolution. |
9189 | /// |
9190 | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff |
9191 | /// Cand1's first N enable_if attributes have precisely the same conditions as |
9192 | /// Cand2's first N enable_if attributes (where N = the number of enable_if |
9193 | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. |
9194 | /// |
9195 | /// Note that you can have a pair of candidates such that Cand1's enable_if |
9196 | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are |
9197 | /// worse than Cand1's. |
9198 | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, |
9199 | const FunctionDecl *Cand2) { |
9200 | // Common case: One (or both) decls don't have enable_if attrs. |
9201 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); |
9202 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); |
9203 | if (!Cand1Attr || !Cand2Attr) { |
9204 | if (Cand1Attr == Cand2Attr) |
9205 | return Comparison::Equal; |
9206 | return Cand1Attr ? Comparison::Better : Comparison::Worse; |
9207 | } |
9208 | |
9209 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); |
9210 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); |
9211 | |
9212 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; |
9213 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { |
9214 | Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); |
9215 | Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); |
9216 | |
9217 | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 |
9218 | // has fewer enable_if attributes than Cand2, and vice versa. |
9219 | if (!Cand1A) |
9220 | return Comparison::Worse; |
9221 | if (!Cand2A) |
9222 | return Comparison::Better; |
9223 | |
9224 | Cand1ID.clear(); |
9225 | Cand2ID.clear(); |
9226 | |
9227 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); |
9228 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); |
9229 | if (Cand1ID != Cand2ID) |
9230 | return Comparison::Worse; |
9231 | } |
9232 | |
9233 | return Comparison::Equal; |
9234 | } |
9235 | |
9236 | static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, |
9237 | const OverloadCandidate &Cand2) { |
9238 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || |
9239 | !Cand2.Function->isMultiVersion()) |
9240 | return false; |
9241 | |
9242 | // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this |
9243 | // is obviously better. |
9244 | if (Cand1.Function->isInvalidDecl()) return false; |
9245 | if (Cand2.Function->isInvalidDecl()) return true; |
9246 | |
9247 | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer |
9248 | // cpu_dispatch, else arbitrarily based on the identifiers. |
9249 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); |
9250 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); |
9251 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); |
9252 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); |
9253 | |
9254 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) |
9255 | return false; |
9256 | |
9257 | if (Cand1CPUDisp && !Cand2CPUDisp) |
9258 | return true; |
9259 | if (Cand2CPUDisp && !Cand1CPUDisp) |
9260 | return false; |
9261 | |
9262 | if (Cand1CPUSpec && Cand2CPUSpec) { |
9263 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) |
9264 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); |
9265 | |
9266 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> |
9267 | FirstDiff = std::mismatch( |
9268 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), |
9269 | Cand2CPUSpec->cpus_begin(), |
9270 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { |
9271 | return LHS->getName() == RHS->getName(); |
9272 | }); |
9273 | |
9274 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <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!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9276, __PRETTY_FUNCTION__)) |
9275 | "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <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!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9276, __PRETTY_FUNCTION__)) |
9276 | "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <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!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9276, __PRETTY_FUNCTION__)); |
9277 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); |
9278 | } |
9279 | 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" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9279); |
9280 | } |
9281 | |
9282 | /// isBetterOverloadCandidate - Determines whether the first overload |
9283 | /// candidate is a better candidate than the second (C++ 13.3.3p1). |
9284 | bool clang::isBetterOverloadCandidate( |
9285 | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, |
9286 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { |
9287 | // Define viable functions to be better candidates than non-viable |
9288 | // functions. |
9289 | if (!Cand2.Viable) |
9290 | return Cand1.Viable; |
9291 | else if (!Cand1.Viable) |
9292 | return false; |
9293 | |
9294 | // C++ [over.match.best]p1: |
9295 | // |
9296 | // -- if F is a static member function, ICS1(F) is defined such |
9297 | // that ICS1(F) is neither better nor worse than ICS1(G) for |
9298 | // any function G, and, symmetrically, ICS1(G) is neither |
9299 | // better nor worse than ICS1(F). |
9300 | unsigned StartArg = 0; |
9301 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) |
9302 | StartArg = 1; |
9303 | |
9304 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { |
9305 | // We don't allow incompatible pointer conversions in C++. |
9306 | if (!S.getLangOpts().CPlusPlus) |
9307 | return ICS.isStandard() && |
9308 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; |
9309 | |
9310 | // The only ill-formed conversion we allow in C++ is the string literal to |
9311 | // char* conversion, which is only considered ill-formed after C++11. |
9312 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
9313 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); |
9314 | }; |
9315 | |
9316 | // Define functions that don't require ill-formed conversions for a given |
9317 | // argument to be better candidates than functions that do. |
9318 | unsigned NumArgs = Cand1.Conversions.size(); |
9319 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch" ) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9319, __PRETTY_FUNCTION__)); |
9320 | bool HasBetterConversion = false; |
9321 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
9322 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); |
9323 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); |
9324 | if (Cand1Bad != Cand2Bad) { |
9325 | if (Cand1Bad) |
9326 | return false; |
9327 | HasBetterConversion = true; |
9328 | } |
9329 | } |
9330 | |
9331 | if (HasBetterConversion) |
9332 | return true; |
9333 | |
9334 | // C++ [over.match.best]p1: |
9335 | // A viable function F1 is defined to be a better function than another |
9336 | // viable function F2 if for all arguments i, ICSi(F1) is not a worse |
9337 | // conversion sequence than ICSi(F2), and then... |
9338 | bool HasWorseConversion = false; |
9339 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
9340 | switch (CompareImplicitConversionSequences(S, Loc, |
9341 | Cand1.Conversions[ArgIdx], |
9342 | Cand2.Conversions[ArgIdx])) { |
9343 | case ImplicitConversionSequence::Better: |
9344 | // Cand1 has a better conversion sequence. |
9345 | HasBetterConversion = true; |
9346 | break; |
9347 | |
9348 | case ImplicitConversionSequence::Worse: |
9349 | if (Cand1.Function && Cand1.Function == Cand2.Function && |
9350 | (Cand2.RewriteKind & CRK_Reversed) != 0) { |
9351 | // Work around large-scale breakage caused by considering reversed |
9352 | // forms of operator== in C++20: |
9353 | // |
9354 | // When comparing a function against its reversed form, if we have a |
9355 | // better conversion for one argument and a worse conversion for the |
9356 | // other, we prefer the non-reversed form. |
9357 | // |
9358 | // This prevents a conversion function from being considered ambiguous |
9359 | // with its own reversed form in various where it's only incidentally |
9360 | // heterogeneous. |
9361 | // |
9362 | // We diagnose this as an extension from CreateOverloadedBinOp. |
9363 | HasWorseConversion = true; |
9364 | break; |
9365 | } |
9366 | |
9367 | // Cand1 can't be better than Cand2. |
9368 | return false; |
9369 | |
9370 | case ImplicitConversionSequence::Indistinguishable: |
9371 | // Do nothing. |
9372 | break; |
9373 | } |
9374 | } |
9375 | |
9376 | // -- for some argument j, ICSj(F1) is a better conversion sequence than |
9377 | // ICSj(F2), or, if not that, |
9378 | if (HasBetterConversion) |
9379 | return true; |
9380 | if (HasWorseConversion) |
9381 | return false; |
9382 | |
9383 | // -- the context is an initialization by user-defined conversion |
9384 | // (see 8.5, 13.3.1.5) and the standard conversion sequence |
9385 | // from the return type of F1 to the destination type (i.e., |
9386 | // the type of the entity being initialized) is a better |
9387 | // conversion sequence than the standard conversion sequence |
9388 | // from the return type of F2 to the destination type. |
9389 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && |
9390 | Cand1.Function && Cand2.Function && |
9391 | isa<CXXConversionDecl>(Cand1.Function) && |
9392 | isa<CXXConversionDecl>(Cand2.Function)) { |
9393 | // First check whether we prefer one of the conversion functions over the |
9394 | // other. This only distinguishes the results in non-standard, extension |
9395 | // cases such as the conversion from a lambda closure type to a function |
9396 | // pointer or block. |
9397 | ImplicitConversionSequence::CompareKind Result = |
9398 | compareConversionFunctions(S, Cand1.Function, Cand2.Function); |
9399 | if (Result == ImplicitConversionSequence::Indistinguishable) |
9400 | Result = CompareStandardConversionSequences(S, Loc, |
9401 | Cand1.FinalConversion, |
9402 | Cand2.FinalConversion); |
9403 | |
9404 | if (Result != ImplicitConversionSequence::Indistinguishable) |
9405 | return Result == ImplicitConversionSequence::Better; |
9406 | |
9407 | // FIXME: Compare kind of reference binding if conversion functions |
9408 | // convert to a reference type used in direct reference binding, per |
9409 | // C++14 [over.match.best]p1 section 2 bullet 3. |
9410 | } |
9411 | |
9412 | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, |
9413 | // as combined with the resolution to CWG issue 243. |
9414 | // |
9415 | // When the context is initialization by constructor ([over.match.ctor] or |
9416 | // either phase of [over.match.list]), a constructor is preferred over |
9417 | // a conversion function. |
9418 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && |
9419 | Cand1.Function && Cand2.Function && |
9420 | isa<CXXConstructorDecl>(Cand1.Function) != |
9421 | isa<CXXConstructorDecl>(Cand2.Function)) |
9422 | return isa<CXXConstructorDecl>(Cand1.Function); |
9423 | |
9424 | // -- F1 is a non-template function and F2 is a function template |
9425 | // specialization, or, if not that, |
9426 | bool Cand1IsSpecialization = Cand1.Function && |
9427 | Cand1.Function->getPrimaryTemplate(); |
9428 | bool Cand2IsSpecialization = Cand2.Function && |
9429 | Cand2.Function->getPrimaryTemplate(); |
9430 | if (Cand1IsSpecialization != Cand2IsSpecialization) |
9431 | return Cand2IsSpecialization; |
9432 | |
9433 | // -- F1 and F2 are function template specializations, and the function |
9434 | // template for F1 is more specialized than the template for F2 |
9435 | // according to the partial ordering rules described in 14.5.5.2, or, |
9436 | // if not that, |
9437 | if (Cand1IsSpecialization && Cand2IsSpecialization) { |
9438 | if (FunctionTemplateDecl *BetterTemplate |
9439 | = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), |
9440 | Cand2.Function->getPrimaryTemplate(), |
9441 | Loc, |
9442 | isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion |
9443 | : TPOC_Call, |
9444 | Cand1.ExplicitCallArguments, |
9445 | Cand2.ExplicitCallArguments)) |
9446 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); |
9447 | } |
9448 | |
9449 | // -- F1 is a constructor for a class D, F2 is a constructor for a base |
9450 | // class B of D, and for all arguments the corresponding parameters of |
9451 | // F1 and F2 have the same type. |
9452 | // FIXME: Implement the "all parameters have the same type" check. |
9453 | bool Cand1IsInherited = |
9454 | dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); |
9455 | bool Cand2IsInherited = |
9456 | dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); |
9457 | if (Cand1IsInherited != Cand2IsInherited) |
9458 | return Cand2IsInherited; |
9459 | else if (Cand1IsInherited) { |
9460 | assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail ("Cand2IsInherited", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9460, __PRETTY_FUNCTION__)); |
9461 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); |
9462 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); |
9463 | if (Cand1Class->isDerivedFrom(Cand2Class)) |
9464 | return true; |
9465 | if (Cand2Class->isDerivedFrom(Cand1Class)) |
9466 | return false; |
9467 | // Inherited from sibling base classes: still ambiguous. |
9468 | } |
9469 | |
9470 | // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not |
9471 | // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate |
9472 | // with reversed order of parameters and F1 is not |
9473 | // |
9474 | // We rank reversed + different operator as worse than just reversed, but |
9475 | // that comparison can never happen, because we only consider reversing for |
9476 | // the maximally-rewritten operator (== or <=>). |
9477 | if (Cand1.RewriteKind != Cand2.RewriteKind) |
9478 | return Cand1.RewriteKind < Cand2.RewriteKind; |
9479 | |
9480 | // Check C++17 tie-breakers for deduction guides. |
9481 | { |
9482 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); |
9483 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); |
9484 | if (Guide1 && Guide2) { |
9485 | // -- F1 is generated from a deduction-guide and F2 is not |
9486 | if (Guide1->isImplicit() != Guide2->isImplicit()) |
9487 | return Guide2->isImplicit(); |
9488 | |
9489 | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not |
9490 | if (Guide1->isCopyDeductionCandidate()) |
9491 | return true; |
9492 | } |
9493 | } |
9494 | |
9495 | // Check for enable_if value-based overload resolution. |
9496 | if (Cand1.Function && Cand2.Function) { |
9497 | Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); |
9498 | if (Cmp != Comparison::Equal) |
9499 | return Cmp == Comparison::Better; |
9500 | } |
9501 | |
9502 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { |
9503 | FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); |
9504 | return S.IdentifyCUDAPreference(Caller, Cand1.Function) > |
9505 | S.IdentifyCUDAPreference(Caller, Cand2.Function); |
9506 | } |
9507 | |
9508 | bool HasPS1 = Cand1.Function != nullptr && |
9509 | functionHasPassObjectSizeParams(Cand1.Function); |
9510 | bool HasPS2 = Cand2.Function != nullptr && |
9511 | functionHasPassObjectSizeParams(Cand2.Function); |
9512 | if (HasPS1 != HasPS2 && HasPS1) |
9513 | return true; |
9514 | |
9515 | return isBetterMultiversionCandidate(Cand1, Cand2); |
9516 | } |
9517 | |
9518 | /// Determine whether two declarations are "equivalent" for the purposes of |
9519 | /// name lookup and overload resolution. This applies when the same internal/no |
9520 | /// linkage entity is defined by two modules (probably by textually including |
9521 | /// the same header). In such a case, we don't consider the declarations to |
9522 | /// declare the same entity, but we also don't want lookups with both |
9523 | /// declarations visible to be ambiguous in some cases (this happens when using |
9524 | /// a modularized libstdc++). |
9525 | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
9526 | const NamedDecl *B) { |
9527 | auto *VA = dyn_cast_or_null<ValueDecl>(A); |
9528 | auto *VB = dyn_cast_or_null<ValueDecl>(B); |
9529 | if (!VA || !VB) |
9530 | return false; |
9531 | |
9532 | // The declarations must be declaring the same name as an internal linkage |
9533 | // entity in different modules. |
9534 | if (!VA->getDeclContext()->getRedeclContext()->Equals( |
9535 | VB->getDeclContext()->getRedeclContext()) || |
9536 | getOwningModule(const_cast<ValueDecl *>(VA)) == |
9537 | getOwningModule(const_cast<ValueDecl *>(VB)) || |
9538 | VA->isExternallyVisible() || VB->isExternallyVisible()) |
9539 | return false; |
9540 | |
9541 | // Check that the declarations appear to be equivalent. |
9542 | // |
9543 | // FIXME: Checking the type isn't really enough to resolve the ambiguity. |
9544 | // For constants and functions, we should check the initializer or body is |
9545 | // the same. For non-constant variables, we shouldn't allow it at all. |
9546 | if (Context.hasSameType(VA->getType(), VB->getType())) |
9547 | return true; |
9548 | |
9549 | // Enum constants within unnamed enumerations will have different types, but |
9550 | // may still be similar enough to be interchangeable for our purposes. |
9551 | if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { |
9552 | if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { |
9553 | // Only handle anonymous enums. If the enumerations were named and |
9554 | // equivalent, they would have been merged to the same type. |
9555 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); |
9556 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); |
9557 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || |
9558 | !Context.hasSameType(EnumA->getIntegerType(), |
9559 | EnumB->getIntegerType())) |
9560 | return false; |
9561 | // Allow this only if the value is the same for both enumerators. |
9562 | return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); |
9563 | } |
9564 | } |
9565 | |
9566 | // Nothing else is sufficiently similar. |
9567 | return false; |
9568 | } |
9569 | |
9570 | void Sema::diagnoseEquivalentInternalLinkageDeclarations( |
9571 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { |
9572 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; |
9573 | |
9574 | Module *M = getOwningModule(const_cast<NamedDecl*>(D)); |
9575 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) |
9576 | << !M << (M ? M->getFullModuleName() : ""); |
9577 | |
9578 | for (auto *E : Equiv) { |
9579 | Module *M = getOwningModule(const_cast<NamedDecl*>(E)); |
9580 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) |
9581 | << !M << (M ? M->getFullModuleName() : ""); |
9582 | } |
9583 | } |
9584 | |
9585 | /// Computes the best viable function (C++ 13.3.3) |
9586 | /// within an overload candidate set. |
9587 | /// |
9588 | /// \param Loc The location of the function name (or operator symbol) for |
9589 | /// which overload resolution occurs. |
9590 | /// |
9591 | /// \param Best If overload resolution was successful or found a deleted |
9592 | /// function, \p Best points to the candidate function found. |
9593 | /// |
9594 | /// \returns The result of overload resolution. |
9595 | OverloadingResult |
9596 | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, |
9597 | iterator &Best) { |
9598 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; |
9599 | std::transform(begin(), end(), std::back_inserter(Candidates), |
9600 | [](OverloadCandidate &Cand) { return &Cand; }); |
9601 | |
9602 | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but |
9603 | // are accepted by both clang and NVCC. However, during a particular |
9604 | // compilation mode only one call variant is viable. We need to |
9605 | // exclude non-viable overload candidates from consideration based |
9606 | // only on their host/device attributes. Specifically, if one |
9607 | // candidate call is WrongSide and the other is SameSide, we ignore |
9608 | // the WrongSide candidate. |
9609 | if (S.getLangOpts().CUDA) { |
9610 | const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); |
9611 | bool ContainsSameSideCandidate = |
9612 | llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { |
9613 | // Check viable function only. |
9614 | return Cand->Viable && Cand->Function && |
9615 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
9616 | Sema::CFP_SameSide; |
9617 | }); |
9618 | if (ContainsSameSideCandidate) { |
9619 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { |
9620 | // Check viable function only to avoid unnecessary data copying/moving. |
9621 | return Cand->Viable && Cand->Function && |
9622 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
9623 | Sema::CFP_WrongSide; |
9624 | }; |
9625 | llvm::erase_if(Candidates, IsWrongSideCandidate); |
9626 | } |
9627 | } |
9628 | |
9629 | // Find the best viable function. |
9630 | Best = end(); |
9631 | for (auto *Cand : Candidates) { |
9632 | Cand->Best = false; |
9633 | if (Cand->Viable) |
9634 | if (Best == end() || |
9635 | isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) |
9636 | Best = Cand; |
9637 | } |
9638 | |
9639 | // If we didn't find any viable functions, abort. |
9640 | if (Best == end()) |
9641 | return OR_No_Viable_Function; |
9642 | |
9643 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; |
9644 | |
9645 | llvm::SmallVector<OverloadCandidate*, 4> PendingBest; |
9646 | PendingBest.push_back(&*Best); |
9647 | Best->Best = true; |
9648 | |
9649 | // Make sure that this function is better than every other viable |
9650 | // function. If not, we have an ambiguity. |
9651 | while (!PendingBest.empty()) { |
9652 | auto *Curr = PendingBest.pop_back_val(); |
9653 | for (auto *Cand : Candidates) { |
9654 | if (Cand->Viable && !Cand->Best && |
9655 | !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { |
9656 | PendingBest.push_back(Cand); |
9657 | Cand->Best = true; |
9658 | |
9659 | if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, |
9660 | Curr->Function)) |
9661 | EquivalentCands.push_back(Cand->Function); |
9662 | else |
9663 | Best = end(); |
9664 | } |
9665 | } |
9666 | } |
9667 | |
9668 | // If we found more than one best candidate, this is ambiguous. |
9669 | if (Best == end()) |
9670 | return OR_Ambiguous; |
9671 | |
9672 | // Best is the best viable function. |
9673 | if (Best->Function && Best->Function->isDeleted()) |
9674 | return OR_Deleted; |
9675 | |
9676 | if (!EquivalentCands.empty()) |
9677 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, |
9678 | EquivalentCands); |
9679 | |
9680 | return OR_Success; |
9681 | } |
9682 | |
9683 | namespace { |
9684 | |
9685 | enum OverloadCandidateKind { |
9686 | oc_function, |
9687 | oc_method, |
9688 | oc_reversed_binary_operator, |
9689 | oc_constructor, |
9690 | oc_implicit_default_constructor, |
9691 | oc_implicit_copy_constructor, |
9692 | oc_implicit_move_constructor, |
9693 | oc_implicit_copy_assignment, |
9694 | oc_implicit_move_assignment, |
9695 | oc_inherited_constructor |
9696 | }; |
9697 | |
9698 | enum OverloadCandidateSelect { |
9699 | ocs_non_template, |
9700 | ocs_template, |
9701 | ocs_described_template, |
9702 | }; |
9703 | |
9704 | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> |
9705 | ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, |
9706 | OverloadCandidateRewriteKind CRK, |
9707 | std::string &Description) { |
9708 | |
9709 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); |
9710 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { |
9711 | isTemplate = true; |
9712 | Description = S.getTemplateArgumentBindingsText( |
9713 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); |
9714 | } |
9715 | |
9716 | OverloadCandidateSelect Select = [&]() { |
9717 | if (!Description.empty()) |
9718 | return ocs_described_template; |
9719 | return isTemplate ? ocs_template : ocs_non_template; |
9720 | }(); |
9721 | |
9722 | OverloadCandidateKind Kind = [&]() { |
9723 | if (CRK & CRK_Reversed) |
9724 | return oc_reversed_binary_operator; |
9725 | |
9726 | if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { |
9727 | if (!Ctor->isImplicit()) { |
9728 | if (isa<ConstructorUsingShadowDecl>(Found)) |
9729 | return oc_inherited_constructor; |
9730 | else |
9731 | return oc_constructor; |
9732 | } |
9733 | |
9734 | if (Ctor->isDefaultConstructor()) |
9735 | return oc_implicit_default_constructor; |
9736 | |
9737 | if (Ctor->isMoveConstructor()) |
9738 | return oc_implicit_move_constructor; |
9739 | |
9740 | assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor" ) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9741, __PRETTY_FUNCTION__)) |
9741 | "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor" ) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9741, __PRETTY_FUNCTION__)); |
9742 | return oc_implicit_copy_constructor; |
9743 | } |
9744 | |
9745 | if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { |
9746 | // This actually gets spelled 'candidate function' for now, but |
9747 | // it doesn't hurt to split it out. |
9748 | if (!Meth->isImplicit()) |
9749 | return oc_method; |
9750 | |
9751 | if (Meth->isMoveAssignmentOperator()) |
9752 | return oc_implicit_move_assignment; |
9753 | |
9754 | if (Meth->isCopyAssignmentOperator()) |
9755 | return oc_implicit_copy_assignment; |
9756 | |
9757 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9757, __PRETTY_FUNCTION__)); |
9758 | return oc_method; |
9759 | } |
9760 | |
9761 | return oc_function; |
9762 | }(); |
9763 | |
9764 | return std::make_pair(Kind, Select); |
9765 | } |
9766 | |
9767 | void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { |
9768 | // FIXME: It'd be nice to only emit a note once per using-decl per overload |
9769 | // set. |
9770 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) |
9771 | S.Diag(FoundDecl->getLocation(), |
9772 | diag::note_ovl_candidate_inherited_constructor) |
9773 | << Shadow->getNominatedBaseClass(); |
9774 | } |
9775 | |
9776 | } // end anonymous namespace |
9777 | |
9778 | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, |
9779 | const FunctionDecl *FD) { |
9780 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { |
9781 | bool AlwaysTrue; |
9782 | if (EnableIf->getCond()->isValueDependent() || |
9783 | !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) |
9784 | return false; |
9785 | if (!AlwaysTrue) |
9786 | return false; |
9787 | } |
9788 | return true; |
9789 | } |
9790 | |
9791 | /// Returns true if we can take the address of the function. |
9792 | /// |
9793 | /// \param Complain - If true, we'll emit a diagnostic |
9794 | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are |
9795 | /// we in overload resolution? |
9796 | /// \param Loc - The location of the statement we're complaining about. Ignored |
9797 | /// if we're not complaining, or if we're in overload resolution. |
9798 | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, |
9799 | bool Complain, |
9800 | bool InOverloadResolution, |
9801 | SourceLocation Loc) { |
9802 | if (!isFunctionAlwaysEnabled(S.Context, FD)) { |
9803 | if (Complain) { |
9804 | if (InOverloadResolution) |
9805 | S.Diag(FD->getBeginLoc(), |
9806 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); |
9807 | else |
9808 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; |
9809 | } |
9810 | return false; |
9811 | } |
9812 | |
9813 | auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { |
9814 | return P->hasAttr<PassObjectSizeAttr>(); |
9815 | }); |
9816 | if (I == FD->param_end()) |
9817 | return true; |
9818 | |
9819 | if (Complain) { |
9820 | // Add one to ParamNo because it's user-facing |
9821 | unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; |
9822 | if (InOverloadResolution) |
9823 | S.Diag(FD->getLocation(), |
9824 | diag::note_ovl_candidate_has_pass_object_size_params) |
9825 | << ParamNo; |
9826 | else |
9827 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) |
9828 | << FD << ParamNo; |
9829 | } |
9830 | return false; |
9831 | } |
9832 | |
9833 | static bool checkAddressOfCandidateIsAvailable(Sema &S, |
9834 | const FunctionDecl *FD) { |
9835 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, |
9836 | /*InOverloadResolution=*/true, |
9837 | /*Loc=*/SourceLocation()); |
9838 | } |
9839 | |
9840 | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
9841 | bool Complain, |
9842 | SourceLocation Loc) { |
9843 | return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, |
9844 | /*InOverloadResolution=*/false, |
9845 | Loc); |
9846 | } |
9847 | |
9848 | // Notes the location of an overload candidate. |
9849 | void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, |
9850 | OverloadCandidateRewriteKind RewriteKind, |
9851 | QualType DestType, bool TakingAddress) { |
9852 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) |
9853 | return; |
9854 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && |
9855 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) |
9856 | return; |
9857 | |
9858 | std::string FnDesc; |
9859 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = |
9860 | ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); |
9861 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) |
9862 | << (unsigned)KSPair.first << (unsigned)KSPair.second |
9863 | << Fn << FnDesc; |
9864 | |
9865 | HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); |
9866 | Diag(Fn->getLocation(), PD); |
9867 | MaybeEmitInheritedConstructorNote(*this, Found); |
9868 | } |
9869 | |
9870 | // Notes the location of all overload candidates designated through |
9871 | // OverloadedExpr |
9872 | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, |
9873 | bool TakingAddress) { |
9874 | assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9874, __PRETTY_FUNCTION__)); |
9875 | |
9876 | OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); |
9877 | OverloadExpr *OvlExpr = Ovl.Expression; |
9878 | |
9879 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
9880 | IEnd = OvlExpr->decls_end(); |
9881 | I != IEnd; ++I) { |
9882 | if (FunctionTemplateDecl *FunTmpl = |
9883 | dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { |
9884 | NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, |
9885 | TakingAddress); |
9886 | } else if (FunctionDecl *Fun |
9887 | = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { |
9888 | NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); |
9889 | } |
9890 | } |
9891 | } |
9892 | |
9893 | /// Diagnoses an ambiguous conversion. The partial diagnostic is the |
9894 | /// "lead" diagnostic; it will be given two arguments, the source and |
9895 | /// target types of the conversion. |
9896 | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( |
9897 | Sema &S, |
9898 | SourceLocation CaretLoc, |
9899 | const PartialDiagnostic &PDiag) const { |
9900 | S.Diag(CaretLoc, PDiag) |
9901 | << Ambiguous.getFromType() << Ambiguous.getToType(); |
9902 | // FIXME: The note limiting machinery is borrowed from |
9903 | // OverloadCandidateSet::NoteCandidates; there's an opportunity for |
9904 | // refactoring here. |
9905 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
9906 | unsigned CandsShown = 0; |
9907 | AmbiguousConversionSequence::const_iterator I, E; |
9908 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { |
9909 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) |
9910 | break; |
9911 | ++CandsShown; |
9912 | S.NoteOverloadCandidate(I->first, I->second); |
9913 | } |
9914 | if (I != E) |
9915 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); |
9916 | } |
9917 | |
9918 | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, |
9919 | unsigned I, bool TakingCandidateAddress) { |
9920 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; |
9921 | assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail ("Conv.isBad()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9921, __PRETTY_FUNCTION__)); |
9922 | assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function" ) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9922, __PRETTY_FUNCTION__)); |
9923 | FunctionDecl *Fn = Cand->Function; |
9924 | |
9925 | // There's a conversion slot for the object argument if this is a |
9926 | // non-constructor method. Note that 'I' corresponds the |
9927 | // conversion-slot index. |
9928 | bool isObjectArgument = false; |
9929 | if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { |
9930 | if (I == 0) |
9931 | isObjectArgument = true; |
9932 | else |
9933 | I--; |
9934 | } |
9935 | |
9936 | std::string FnDesc; |
9937 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
9938 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), |
9939 | FnDesc); |
9940 | |
9941 | Expr *FromExpr = Conv.Bad.FromExpr; |
9942 | QualType FromTy = Conv.Bad.getFromType(); |
9943 | QualType ToTy = Conv.Bad.getToType(); |
9944 | |
9945 | if (FromTy == S.Context.OverloadTy) { |
9946 | assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?" ) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 9946, __PRETTY_FUNCTION__)); |
9947 | Expr *E = FromExpr->IgnoreParens(); |
9948 | if (isa<UnaryOperator>(E)) |
9949 | E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); |
9950 | DeclarationName Name = cast<OverloadExpr>(E)->getName(); |
9951 | |
9952 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) |
9953 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
9954 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy |
9955 | << Name << I + 1; |
9956 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
9957 | return; |
9958 | } |
9959 | |
9960 | // Do some hand-waving analysis to see if the non-viability is due |
9961 | // to a qualifier mismatch. |
9962 | CanQualType CFromTy = S.Context.getCanonicalType(FromTy); |
9963 | CanQualType CToTy = S.Context.getCanonicalType(ToTy); |
9964 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) |
9965 | CToTy = RT->getPointeeType(); |
9966 | else { |
9967 | // TODO: detect and diagnose the full richness of const mismatches. |
9968 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) |
9969 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { |
9970 | CFromTy = FromPT->getPointeeType(); |
9971 | CToTy = ToPT->getPointeeType(); |
9972 | } |
9973 | } |
9974 | |
9975 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && |
9976 | !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { |
9977 | Qualifiers FromQs = CFromTy.getQualifiers(); |
9978 | Qualifiers ToQs = CToTy.getQualifiers(); |
9979 | |
9980 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { |
9981 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) |
9982 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
9983 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
9984 | << ToTy << (unsigned)isObjectArgument << I + 1; |
9985 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
9986 | return; |
9987 | } |
9988 | |
9989 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
9990 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) |
9991 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
9992 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
9993 | << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() |
9994 | << (unsigned)isObjectArgument << I + 1; |
9995 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
9996 | return; |
9997 | } |
9998 | |
9999 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { |
10000 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) |
10001 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10002 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10003 | << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() |
10004 | << (unsigned)isObjectArgument << I + 1; |
10005 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10006 | return; |
10007 | } |
10008 | |
10009 | if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { |
10010 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) |
10011 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10012 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10013 | << FromQs.hasUnaligned() << I + 1; |
10014 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10015 | return; |
10016 | } |
10017 | |
10018 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
10019 | assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast <void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10019, __PRETTY_FUNCTION__)); |
10020 | |
10021 | if (isObjectArgument) { |
10022 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) |
10023 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10024 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10025 | << (CVR - 1); |
10026 | } else { |
10027 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) |
10028 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10029 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10030 | << (CVR - 1) << I + 1; |
10031 | } |
10032 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10033 | return; |
10034 | } |
10035 | |
10036 | // Special diagnostic for failure to convert an initializer list, since |
10037 | // telling the user that it has type void is not useful. |
10038 | if (FromExpr && isa<InitListExpr>(FromExpr)) { |
10039 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) |
10040 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10041 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10042 | << ToTy << (unsigned)isObjectArgument << I + 1; |
10043 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10044 | return; |
10045 | } |
10046 | |
10047 | // Diagnose references or pointers to incomplete types differently, |
10048 | // since it's far from impossible that the incompleteness triggered |
10049 | // the failure. |
10050 | QualType TempFromTy = FromTy.getNonReferenceType(); |
10051 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) |
10052 | TempFromTy = PTy->getPointeeType(); |
10053 | if (TempFromTy->isIncompleteType()) { |
10054 | // Emit the generic diagnostic and, optionally, add the hints to it. |
10055 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) |
10056 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10057 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10058 | << ToTy << (unsigned)isObjectArgument << I + 1 |
10059 | << (unsigned)(Cand->Fix.Kind); |
10060 | |
10061 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10062 | return; |
10063 | } |
10064 | |
10065 | // Diagnose base -> derived pointer conversions. |
10066 | unsigned BaseToDerivedConversion = 0; |
10067 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { |
10068 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { |
10069 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
10070 | FromPtrTy->getPointeeType()) && |
10071 | !FromPtrTy->getPointeeType()->isIncompleteType() && |
10072 | !ToPtrTy->getPointeeType()->isIncompleteType() && |
10073 | S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), |
10074 | FromPtrTy->getPointeeType())) |
10075 | BaseToDerivedConversion = 1; |
10076 | } |
10077 | } else if (const ObjCObjectPointerType *FromPtrTy |
10078 | = FromTy->getAs<ObjCObjectPointerType>()) { |
10079 | if (const ObjCObjectPointerType *ToPtrTy |
10080 | = ToTy->getAs<ObjCObjectPointerType>()) |
10081 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) |
10082 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) |
10083 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
10084 | FromPtrTy->getPointeeType()) && |
10085 | FromIface->isSuperClassOf(ToIface)) |
10086 | BaseToDerivedConversion = 2; |
10087 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { |
10088 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && |
10089 | !FromTy->isIncompleteType() && |
10090 | !ToRefTy->getPointeeType()->isIncompleteType() && |
10091 | S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { |
10092 | BaseToDerivedConversion = 3; |
10093 | } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && |
10094 | ToTy.getNonReferenceType().getCanonicalType() == |
10095 | FromTy.getNonReferenceType().getCanonicalType()) { |
10096 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) |
10097 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10098 | << (unsigned)isObjectArgument << I + 1 |
10099 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); |
10100 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10101 | return; |
10102 | } |
10103 | } |
10104 | |
10105 | if (BaseToDerivedConversion) { |
10106 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) |
10107 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10108 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10109 | << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; |
10110 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10111 | return; |
10112 | } |
10113 | |
10114 | if (isa<ObjCObjectPointerType>(CFromTy) && |
10115 | isa<PointerType>(CToTy)) { |
10116 | Qualifiers FromQs = CFromTy.getQualifiers(); |
10117 | Qualifiers ToQs = CToTy.getQualifiers(); |
10118 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
10119 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) |
10120 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10121 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) |
10122 | << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; |
10123 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10124 | return; |
10125 | } |
10126 | } |
10127 | |
10128 | if (TakingCandidateAddress && |
10129 | !checkAddressOfCandidateIsAvailable(S, Cand->Function)) |
10130 | return; |
10131 | |
10132 | // Emit the generic diagnostic and, optionally, add the hints to it. |
10133 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); |
10134 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10135 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy |
10136 | << ToTy << (unsigned)isObjectArgument << I + 1 |
10137 | << (unsigned)(Cand->Fix.Kind); |
10138 | |
10139 | // If we can fix the conversion, suggest the FixIts. |
10140 | for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), |
10141 | HE = Cand->Fix.Hints.end(); HI != HE; ++HI) |
10142 | FDiag << *HI; |
10143 | S.Diag(Fn->getLocation(), FDiag); |
10144 | |
10145 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10146 | } |
10147 | |
10148 | /// Additional arity mismatch diagnosis specific to a function overload |
10149 | /// candidates. This is not covered by the more general DiagnoseArityMismatch() |
10150 | /// over a candidate in any candidate set. |
10151 | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, |
10152 | unsigned NumArgs) { |
10153 | FunctionDecl *Fn = Cand->Function; |
10154 | unsigned MinParams = Fn->getMinRequiredArguments(); |
10155 | |
10156 | // With invalid overloaded operators, it's possible that we think we |
10157 | // have an arity mismatch when in fact it looks like we have the |
10158 | // right number of arguments, because only overloaded operators have |
10159 | // the weird behavior of overloading member and non-member functions. |
10160 | // Just don't report anything. |
10161 | if (Fn->isInvalidDecl() && |
10162 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) |
10163 | return true; |
10164 | |
10165 | if (NumArgs < MinParams) { |
10166 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10168, __PRETTY_FUNCTION__)) |
10167 | (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10168, __PRETTY_FUNCTION__)) |
10168 | Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10168, __PRETTY_FUNCTION__)); |
10169 | } else { |
10170 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10172, __PRETTY_FUNCTION__)) |
10171 | (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10172, __PRETTY_FUNCTION__)) |
10172 | Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10172, __PRETTY_FUNCTION__)); |
10173 | } |
10174 | |
10175 | return false; |
10176 | } |
10177 | |
10178 | /// General arity mismatch diagnosis over a candidate in a candidate set. |
10179 | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, |
10180 | unsigned NumFormalArgs) { |
10181 | assert(isa<FunctionDecl>(D) &&((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") ? static_cast<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\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10184, __PRETTY_FUNCTION__)) |
10182 | "The templated declaration should at least be a function"((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") ? static_cast<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\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10184, __PRETTY_FUNCTION__)) |
10183 | " when diagnosing bad template argument deduction due to too many"((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") ? static_cast<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\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10184, __PRETTY_FUNCTION__)) |
10184 | " or too few arguments")((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") ? static_cast<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\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10184, __PRETTY_FUNCTION__)); |
10185 | |
10186 | FunctionDecl *Fn = cast<FunctionDecl>(D); |
10187 | |
10188 | // TODO: treat calls to a missing default constructor as a special case |
10189 | const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); |
10190 | unsigned MinParams = Fn->getMinRequiredArguments(); |
10191 | |
10192 | // at least / at most / exactly |
10193 | unsigned mode, modeCount; |
10194 | if (NumFormalArgs < MinParams) { |
10195 | if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || |
10196 | FnTy->isTemplateVariadic()) |
10197 | mode = 0; // "at least" |
10198 | else |
10199 | mode = 2; // "exactly" |
10200 | modeCount = MinParams; |
10201 | } else { |
10202 | if (MinParams != FnTy->getNumParams()) |
10203 | mode = 1; // "at most" |
10204 | else |
10205 | mode = 2; // "exactly" |
10206 | modeCount = FnTy->getNumParams(); |
10207 | } |
10208 | |
10209 | std::string Description; |
10210 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
10211 | ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); |
10212 | |
10213 | if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) |
10214 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) |
10215 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10216 | << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; |
10217 | else |
10218 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) |
10219 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
10220 | << Description << mode << modeCount << NumFormalArgs; |
10221 | |
10222 | MaybeEmitInheritedConstructorNote(S, Found); |
10223 | } |
10224 | |
10225 | /// Arity mismatch diagnosis specific to a function overload candidate. |
10226 | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, |
10227 | unsigned NumFormalArgs) { |
10228 | if (!CheckArityMismatch(S, Cand, NumFormalArgs)) |
10229 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); |
10230 | } |
10231 | |
10232 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { |
10233 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) |
10234 | return TD; |
10235 | llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10236) |
10236 | " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10236); |
10237 | } |
10238 | |
10239 | /// Diagnose a failed template-argument deduction. |
10240 | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, |
10241 | DeductionFailureInfo &DeductionFailure, |
10242 | unsigned NumArgs, |
10243 | bool TakingCandidateAddress) { |
10244 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); |
10245 | NamedDecl *ParamD; |
10246 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || |
10247 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || |
10248 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); |
10249 | switch (DeductionFailure.Result) { |
10250 | case Sema::TDK_Success: |
10251 | llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10251); |
10252 | |
10253 | case Sema::TDK_Incomplete: { |
10254 | assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10254, __PRETTY_FUNCTION__)); |
10255 | S.Diag(Templated->getLocation(), |
10256 | diag::note_ovl_candidate_incomplete_deduction) |
10257 | << ParamD->getDeclName(); |
10258 | MaybeEmitInheritedConstructorNote(S, Found); |
10259 | return; |
10260 | } |
10261 | |
10262 | case Sema::TDK_IncompletePack: { |
10263 | assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10263, __PRETTY_FUNCTION__)); |
10264 | S.Diag(Templated->getLocation(), |
10265 | diag::note_ovl_candidate_incomplete_deduction_pack) |
10266 | << ParamD->getDeclName() |
10267 | << (DeductionFailure.getFirstArg()->pack_size() + 1) |
10268 | << *DeductionFailure.getFirstArg(); |
10269 | MaybeEmitInheritedConstructorNote(S, Found); |
10270 | return; |
10271 | } |
10272 | |
10273 | case Sema::TDK_Underqualified: { |
10274 | assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10274, __PRETTY_FUNCTION__)); |
10275 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); |
10276 | |
10277 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); |
10278 | |
10279 | // Param will have been canonicalized, but it should just be a |
10280 | // qualified version of ParamD, so move the qualifiers to that. |
10281 | QualifierCollector Qs; |
10282 | Qs.strip(Param); |
10283 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); |
10284 | assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast< void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10284, __PRETTY_FUNCTION__)); |
10285 | |
10286 | // Arg has also been canonicalized, but there's nothing we can do |
10287 | // about that. It also doesn't matter as much, because it won't |
10288 | // have any template parameters in it (because deduction isn't |
10289 | // done on dependent types). |
10290 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); |
10291 | |
10292 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) |
10293 | << ParamD->getDeclName() << Arg << NonCanonParam; |
10294 | MaybeEmitInheritedConstructorNote(S, Found); |
10295 | return; |
10296 | } |
10297 | |
10298 | case Sema::TDK_Inconsistent: { |
10299 | assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10299, __PRETTY_FUNCTION__)); |
10300 | int which = 0; |
10301 | if (isa<TemplateTypeParmDecl>(ParamD)) |
10302 | which = 0; |
10303 | else if (isa<NonTypeTemplateParmDecl>(ParamD)) { |
10304 | // Deduction might have failed because we deduced arguments of two |
10305 | // different types for a non-type template parameter. |
10306 | // FIXME: Use a different TDK value for this. |
10307 | QualType T1 = |
10308 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); |
10309 | QualType T2 = |
10310 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); |
10311 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { |
10312 | S.Diag(Templated->getLocation(), |
10313 | diag::note_ovl_candidate_inconsistent_deduction_types) |
10314 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 |
10315 | << *DeductionFailure.getSecondArg() << T2; |
10316 | MaybeEmitInheritedConstructorNote(S, Found); |
10317 | return; |
10318 | } |
10319 | |
10320 | which = 1; |
10321 | } else { |
10322 | which = 2; |
10323 | } |
10324 | |
10325 | S.Diag(Templated->getLocation(), |
10326 | diag::note_ovl_candidate_inconsistent_deduction) |
10327 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() |
10328 | << *DeductionFailure.getSecondArg(); |
10329 | MaybeEmitInheritedConstructorNote(S, Found); |
10330 | return; |
10331 | } |
10332 | |
10333 | case Sema::TDK_InvalidExplicitArguments: |
10334 | assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10334, __PRETTY_FUNCTION__)); |
10335 | if (ParamD->getDeclName()) |
10336 | S.Diag(Templated->getLocation(), |
10337 | diag::note_ovl_candidate_explicit_arg_mismatch_named) |
10338 | << ParamD->getDeclName(); |
10339 | else { |
10340 | int index = 0; |
10341 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) |
10342 | index = TTP->getIndex(); |
10343 | else if (NonTypeTemplateParmDecl *NTTP |
10344 | = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) |
10345 | index = NTTP->getIndex(); |
10346 | else |
10347 | index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); |
10348 | S.Diag(Templated->getLocation(), |
10349 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) |
10350 | << (index + 1); |
10351 | } |
10352 | MaybeEmitInheritedConstructorNote(S, Found); |
10353 | return; |
10354 | |
10355 | case Sema::TDK_TooManyArguments: |
10356 | case Sema::TDK_TooFewArguments: |
10357 | DiagnoseArityMismatch(S, Found, Templated, NumArgs); |
10358 | return; |
10359 | |
10360 | case Sema::TDK_InstantiationDepth: |
10361 | S.Diag(Templated->getLocation(), |
10362 | diag::note_ovl_candidate_instantiation_depth); |
10363 | MaybeEmitInheritedConstructorNote(S, Found); |
10364 | return; |
10365 | |
10366 | case Sema::TDK_SubstitutionFailure: { |
10367 | // Format the template argument list into the argument string. |
10368 | SmallString<128> TemplateArgString; |
10369 | if (TemplateArgumentList *Args = |
10370 | DeductionFailure.getTemplateArgumentList()) { |
10371 | TemplateArgString = " "; |
10372 | TemplateArgString += S.getTemplateArgumentBindingsText( |
10373 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
10374 | } |
10375 | |
10376 | // If this candidate was disabled by enable_if, say so. |
10377 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); |
10378 | if (PDiag && PDiag->second.getDiagID() == |
10379 | diag::err_typename_nested_not_found_enable_if) { |
10380 | // FIXME: Use the source range of the condition, and the fully-qualified |
10381 | // name of the enable_if template. These are both present in PDiag. |
10382 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) |
10383 | << "'enable_if'" << TemplateArgString; |
10384 | return; |
10385 | } |
10386 | |
10387 | // We found a specific requirement that disabled the enable_if. |
10388 | if (PDiag && PDiag->second.getDiagID() == |
10389 | diag::err_typename_nested_not_found_requirement) { |
10390 | S.Diag(Templated->getLocation(), |
10391 | diag::note_ovl_candidate_disabled_by_requirement) |
10392 | << PDiag->second.getStringArg(0) << TemplateArgString; |
10393 | return; |
10394 | } |
10395 | |
10396 | // Format the SFINAE diagnostic into the argument string. |
10397 | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s |
10398 | // formatted message in another diagnostic. |
10399 | SmallString<128> SFINAEArgString; |
10400 | SourceRange R; |
10401 | if (PDiag) { |
10402 | SFINAEArgString = ": "; |
10403 | R = SourceRange(PDiag->first, PDiag->first); |
10404 | PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); |
10405 | } |
10406 | |
10407 | S.Diag(Templated->getLocation(), |
10408 | diag::note_ovl_candidate_substitution_failure) |
10409 | << TemplateArgString << SFINAEArgString << R; |
10410 | MaybeEmitInheritedConstructorNote(S, Found); |
10411 | return; |
10412 | } |
10413 | |
10414 | case Sema::TDK_DeducedMismatch: |
10415 | case Sema::TDK_DeducedMismatchNested: { |
10416 | // Format the template argument list into the argument string. |
10417 | SmallString<128> TemplateArgString; |
10418 | if (TemplateArgumentList *Args = |
10419 | DeductionFailure.getTemplateArgumentList()) { |
10420 | TemplateArgString = " "; |
10421 | TemplateArgString += S.getTemplateArgumentBindingsText( |
10422 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
10423 | } |
10424 | |
10425 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) |
10426 | << (*DeductionFailure.getCallArgIndex() + 1) |
10427 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() |
10428 | << TemplateArgString |
10429 | << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); |
10430 | break; |
10431 | } |
10432 | |
10433 | case Sema::TDK_NonDeducedMismatch: { |
10434 | // FIXME: Provide a source location to indicate what we couldn't match. |
10435 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); |
10436 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); |
10437 | if (FirstTA.getKind() == TemplateArgument::Template && |
10438 | SecondTA.getKind() == TemplateArgument::Template) { |
10439 | TemplateName FirstTN = FirstTA.getAsTemplate(); |
10440 | TemplateName SecondTN = SecondTA.getAsTemplate(); |
10441 | if (FirstTN.getKind() == TemplateName::Template && |
10442 | SecondTN.getKind() == TemplateName::Template) { |
10443 | if (FirstTN.getAsTemplateDecl()->getName() == |
10444 | SecondTN.getAsTemplateDecl()->getName()) { |
10445 | // FIXME: This fixes a bad diagnostic where both templates are named |
10446 | // the same. This particular case is a bit difficult since: |
10447 | // 1) It is passed as a string to the diagnostic printer. |
10448 | // 2) The diagnostic printer only attempts to find a better |
10449 | // name for types, not decls. |
10450 | // Ideally, this should folded into the diagnostic printer. |
10451 | S.Diag(Templated->getLocation(), |
10452 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) |
10453 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); |
10454 | return; |
10455 | } |
10456 | } |
10457 | } |
10458 | |
10459 | if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && |
10460 | !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) |
10461 | return; |
10462 | |
10463 | // FIXME: For generic lambda parameters, check if the function is a lambda |
10464 | // call operator, and if so, emit a prettier and more informative |
10465 | // diagnostic that mentions 'auto' and lambda in addition to |
10466 | // (or instead of?) the canonical template type parameters. |
10467 | S.Diag(Templated->getLocation(), |
10468 | diag::note_ovl_candidate_non_deduced_mismatch) |
10469 | << FirstTA << SecondTA; |
10470 | return; |
10471 | } |
10472 | // TODO: diagnose these individually, then kill off |
10473 | // note_ovl_candidate_bad_deduction, which is uselessly vague. |
10474 | case Sema::TDK_MiscellaneousDeductionFailure: |
10475 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); |
10476 | MaybeEmitInheritedConstructorNote(S, Found); |
10477 | return; |
10478 | case Sema::TDK_CUDATargetMismatch: |
10479 | S.Diag(Templated->getLocation(), |
10480 | diag::note_cuda_ovl_candidate_target_mismatch); |
10481 | return; |
10482 | } |
10483 | } |
10484 | |
10485 | /// Diagnose a failed template-argument deduction, for function calls. |
10486 | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, |
10487 | unsigned NumArgs, |
10488 | bool TakingCandidateAddress) { |
10489 | unsigned TDK = Cand->DeductionFailure.Result; |
10490 | if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { |
10491 | if (CheckArityMismatch(S, Cand, NumArgs)) |
10492 | return; |
10493 | } |
10494 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern |
10495 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); |
10496 | } |
10497 | |
10498 | /// CUDA: diagnose an invalid call across targets. |
10499 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { |
10500 | FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); |
10501 | FunctionDecl *Callee = Cand->Function; |
10502 | |
10503 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), |
10504 | CalleeTarget = S.IdentifyCUDATarget(Callee); |
10505 | |
10506 | std::string FnDesc; |
10507 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
10508 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, |
10509 | Cand->getRewriteKind(), FnDesc); |
10510 | |
10511 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) |
10512 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
10513 | << FnDesc /* Ignored */ |
10514 | << CalleeTarget << CallerTarget; |
10515 | |
10516 | // This could be an implicit constructor for which we could not infer the |
10517 | // target due to a collsion. Diagnose that case. |
10518 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); |
10519 | if (Meth != nullptr && Meth->isImplicit()) { |
10520 | CXXRecordDecl *ParentClass = Meth->getParent(); |
10521 | Sema::CXXSpecialMember CSM; |
10522 | |
10523 | switch (FnKindPair.first) { |
10524 | default: |
10525 | return; |
10526 | case oc_implicit_default_constructor: |
10527 | CSM = Sema::CXXDefaultConstructor; |
10528 | break; |
10529 | case oc_implicit_copy_constructor: |
10530 | CSM = Sema::CXXCopyConstructor; |
10531 | break; |
10532 | case oc_implicit_move_constructor: |
10533 | CSM = Sema::CXXMoveConstructor; |
10534 | break; |
10535 | case oc_implicit_copy_assignment: |
10536 | CSM = Sema::CXXCopyAssignment; |
10537 | break; |
10538 | case oc_implicit_move_assignment: |
10539 | CSM = Sema::CXXMoveAssignment; |
10540 | break; |
10541 | }; |
10542 | |
10543 | bool ConstRHS = false; |
10544 | if (Meth->getNumParams()) { |
10545 | if (const ReferenceType *RT = |
10546 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { |
10547 | ConstRHS = RT->getPointeeType().isConstQualified(); |
10548 | } |
10549 | } |
10550 | |
10551 | S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, |
10552 | /* ConstRHS */ ConstRHS, |
10553 | /* Diagnose */ true); |
10554 | } |
10555 | } |
10556 | |
10557 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { |
10558 | FunctionDecl *Callee = Cand->Function; |
10559 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); |
10560 | |
10561 | S.Diag(Callee->getLocation(), |
10562 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
10563 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
10564 | } |
10565 | |
10566 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { |
10567 | ExplicitSpecifier ES; |
10568 | const char *DeclName; |
10569 | switch (Cand->Function->getDeclKind()) { |
10570 | case Decl::Kind::CXXConstructor: |
10571 | ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); |
10572 | DeclName = "constructor"; |
10573 | break; |
10574 | case Decl::Kind::CXXConversion: |
10575 | ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); |
10576 | DeclName = "conversion operator"; |
10577 | break; |
10578 | case Decl::Kind::CXXDeductionGuide: |
10579 | ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); |
10580 | DeclName = "deductiong guide"; |
10581 | break; |
10582 | default: |
10583 | llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10583); |
10584 | } |
10585 | assert(ES.getExpr() && "null expression should be handled before")((ES.getExpr() && "null expression should be handled before" ) ? static_cast<void> (0) : __assert_fail ("ES.getExpr() && \"null expression should be handled before\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10585, __PRETTY_FUNCTION__)); |
10586 | S.Diag(Cand->Function->getLocation(), |
10587 | diag::note_ovl_candidate_explicit_forbidden) |
10588 | << DeclName; |
10589 | S.Diag(ES.getExpr()->getBeginLoc(), |
10590 | diag::note_explicit_bool_resolved_to_true); |
10591 | } |
10592 | |
10593 | static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { |
10594 | FunctionDecl *Callee = Cand->Function; |
10595 | |
10596 | S.Diag(Callee->getLocation(), |
10597 | diag::note_ovl_candidate_disabled_by_extension) |
10598 | << S.getOpenCLExtensionsFromDeclExtMap(Callee); |
10599 | } |
10600 | |
10601 | /// Generates a 'note' diagnostic for an overload candidate. We've |
10602 | /// already generated a primary error at the call site. |
10603 | /// |
10604 | /// It really does need to be a single diagnostic with its caret |
10605 | /// pointed at the candidate declaration. Yes, this creates some |
10606 | /// major challenges of technical writing. Yes, this makes pointing |
10607 | /// out problems with specific arguments quite awkward. It's still |
10608 | /// better than generating twenty screens of text for every failed |
10609 | /// overload. |
10610 | /// |
10611 | /// It would be great to be able to express per-candidate problems |
10612 | /// more richly for those diagnostic clients that cared, but we'd |
10613 | /// still have to be just as careful with the default diagnostics. |
10614 | /// \param CtorDestAS Addr space of object being constructed (for ctor |
10615 | /// candidates only). |
10616 | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, |
10617 | unsigned NumArgs, |
10618 | bool TakingCandidateAddress, |
10619 | LangAS CtorDestAS = LangAS::Default) { |
10620 | FunctionDecl *Fn = Cand->Function; |
10621 | |
10622 | // Note deleted candidates, but only if they're viable. |
10623 | if (Cand->Viable) { |
10624 | if (Fn->isDeleted()) { |
10625 | std::string FnDesc; |
10626 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
10627 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, |
10628 | Cand->getRewriteKind(), FnDesc); |
10629 | |
10630 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) |
10631 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
10632 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); |
10633 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10634 | return; |
10635 | } |
10636 | |
10637 | // We don't really have anything else to say about viable candidates. |
10638 | S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
10639 | return; |
10640 | } |
10641 | |
10642 | switch (Cand->FailureKind) { |
10643 | case ovl_fail_too_many_arguments: |
10644 | case ovl_fail_too_few_arguments: |
10645 | return DiagnoseArityMismatch(S, Cand, NumArgs); |
10646 | |
10647 | case ovl_fail_bad_deduction: |
10648 | return DiagnoseBadDeduction(S, Cand, NumArgs, |
10649 | TakingCandidateAddress); |
10650 | |
10651 | case ovl_fail_illegal_constructor: { |
10652 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) |
10653 | << (Fn->getPrimaryTemplate() ? 1 : 0); |
10654 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10655 | return; |
10656 | } |
10657 | |
10658 | case ovl_fail_object_addrspace_mismatch: { |
10659 | Qualifiers QualsForPrinting; |
10660 | QualsForPrinting.setAddressSpace(CtorDestAS); |
10661 | S.Diag(Fn->getLocation(), |
10662 | diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) |
10663 | << QualsForPrinting; |
10664 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10665 | return; |
10666 | } |
10667 | |
10668 | case ovl_fail_trivial_conversion: |
10669 | case ovl_fail_bad_final_conversion: |
10670 | case ovl_fail_final_conversion_not_exact: |
10671 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
10672 | |
10673 | case ovl_fail_bad_conversion: { |
10674 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); |
10675 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) |
10676 | if (Cand->Conversions[I].isBad()) |
10677 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); |
10678 | |
10679 | // FIXME: this currently happens when we're called from SemaInit |
10680 | // when user-conversion overload fails. Figure out how to handle |
10681 | // those conditions and diagnose them well. |
10682 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
10683 | } |
10684 | |
10685 | case ovl_fail_bad_target: |
10686 | return DiagnoseBadTarget(S, Cand); |
10687 | |
10688 | case ovl_fail_enable_if: |
10689 | return DiagnoseFailedEnableIfAttr(S, Cand); |
10690 | |
10691 | case ovl_fail_explicit_resolved: |
10692 | return DiagnoseFailedExplicitSpec(S, Cand); |
10693 | |
10694 | case ovl_fail_ext_disabled: |
10695 | return DiagnoseOpenCLExtensionDisabled(S, Cand); |
10696 | |
10697 | case ovl_fail_inhctor_slice: |
10698 | // It's generally not interesting to note copy/move constructors here. |
10699 | if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) |
10700 | return; |
10701 | S.Diag(Fn->getLocation(), |
10702 | diag::note_ovl_candidate_inherited_constructor_slice) |
10703 | << (Fn->getPrimaryTemplate() ? 1 : 0) |
10704 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); |
10705 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
10706 | return; |
10707 | |
10708 | case ovl_fail_addr_not_available: { |
10709 | bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); |
10710 | (void)Available; |
10711 | assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail ( "!Available", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10711, __PRETTY_FUNCTION__)); |
10712 | break; |
10713 | } |
10714 | case ovl_non_default_multiversion_function: |
10715 | // Do nothing, these should simply be ignored. |
10716 | break; |
10717 | } |
10718 | } |
10719 | |
10720 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { |
10721 | // Desugar the type of the surrogate down to a function type, |
10722 | // retaining as many typedefs as possible while still showing |
10723 | // the function type (and, therefore, its parameter types). |
10724 | QualType FnType = Cand->Surrogate->getConversionType(); |
10725 | bool isLValueReference = false; |
10726 | bool isRValueReference = false; |
10727 | bool isPointer = false; |
10728 | if (const LValueReferenceType *FnTypeRef = |
10729 | FnType->getAs<LValueReferenceType>()) { |
10730 | FnType = FnTypeRef->getPointeeType(); |
10731 | isLValueReference = true; |
10732 | } else if (const RValueReferenceType *FnTypeRef = |
10733 | FnType->getAs<RValueReferenceType>()) { |
10734 | FnType = FnTypeRef->getPointeeType(); |
10735 | isRValueReference = true; |
10736 | } |
10737 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { |
10738 | FnType = FnTypePtr->getPointeeType(); |
10739 | isPointer = true; |
10740 | } |
10741 | // Desugar down to a function type. |
10742 | FnType = QualType(FnType->getAs<FunctionType>(), 0); |
10743 | // Reconstruct the pointer/reference as appropriate. |
10744 | if (isPointer) FnType = S.Context.getPointerType(FnType); |
10745 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); |
10746 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); |
10747 | |
10748 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) |
10749 | << FnType; |
10750 | } |
10751 | |
10752 | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, |
10753 | SourceLocation OpLoc, |
10754 | OverloadCandidate *Cand) { |
10755 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary" ) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10755, __PRETTY_FUNCTION__)); |
10756 | std::string TypeStr("operator"); |
10757 | TypeStr += Opc; |
10758 | TypeStr += "("; |
10759 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); |
10760 | if (Cand->Conversions.size() == 1) { |
10761 | TypeStr += ")"; |
10762 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
10763 | } else { |
10764 | TypeStr += ", "; |
10765 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); |
10766 | TypeStr += ")"; |
10767 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
10768 | } |
10769 | } |
10770 | |
10771 | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, |
10772 | OverloadCandidate *Cand) { |
10773 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { |
10774 | if (ICS.isBad()) break; // all meaningless after first invalid |
10775 | if (!ICS.isAmbiguous()) continue; |
10776 | |
10777 | ICS.DiagnoseAmbiguousConversion( |
10778 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); |
10779 | } |
10780 | } |
10781 | |
10782 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { |
10783 | if (Cand->Function) |
10784 | return Cand->Function->getLocation(); |
10785 | if (Cand->IsSurrogate) |
10786 | return Cand->Surrogate->getLocation(); |
10787 | return SourceLocation(); |
10788 | } |
10789 | |
10790 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { |
10791 | switch ((Sema::TemplateDeductionResult)DFI.Result) { |
10792 | case Sema::TDK_Success: |
10793 | case Sema::TDK_NonDependentConversionFailure: |
10794 | llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10794); |
10795 | |
10796 | case Sema::TDK_Invalid: |
10797 | case Sema::TDK_Incomplete: |
10798 | case Sema::TDK_IncompletePack: |
10799 | return 1; |
10800 | |
10801 | case Sema::TDK_Underqualified: |
10802 | case Sema::TDK_Inconsistent: |
10803 | return 2; |
10804 | |
10805 | case Sema::TDK_SubstitutionFailure: |
10806 | case Sema::TDK_DeducedMismatch: |
10807 | case Sema::TDK_DeducedMismatchNested: |
10808 | case Sema::TDK_NonDeducedMismatch: |
10809 | case Sema::TDK_MiscellaneousDeductionFailure: |
10810 | case Sema::TDK_CUDATargetMismatch: |
10811 | return 3; |
10812 | |
10813 | case Sema::TDK_InstantiationDepth: |
10814 | return 4; |
10815 | |
10816 | case Sema::TDK_InvalidExplicitArguments: |
10817 | return 5; |
10818 | |
10819 | case Sema::TDK_TooManyArguments: |
10820 | case Sema::TDK_TooFewArguments: |
10821 | return 6; |
10822 | } |
10823 | llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10823); |
10824 | } |
10825 | |
10826 | namespace { |
10827 | struct CompareOverloadCandidatesForDisplay { |
10828 | Sema &S; |
10829 | SourceLocation Loc; |
10830 | size_t NumArgs; |
10831 | OverloadCandidateSet::CandidateSetKind CSK; |
10832 | |
10833 | CompareOverloadCandidatesForDisplay( |
10834 | Sema &S, SourceLocation Loc, size_t NArgs, |
10835 | OverloadCandidateSet::CandidateSetKind CSK) |
10836 | : S(S), NumArgs(NArgs), CSK(CSK) {} |
10837 | |
10838 | bool operator()(const OverloadCandidate *L, |
10839 | const OverloadCandidate *R) { |
10840 | // Fast-path this check. |
10841 | if (L == R) return false; |
10842 | |
10843 | // Order first by viability. |
10844 | if (L->Viable) { |
10845 | if (!R->Viable) return true; |
10846 | |
10847 | // TODO: introduce a tri-valued comparison for overload |
10848 | // candidates. Would be more worthwhile if we had a sort |
10849 | // that could exploit it. |
10850 | if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) |
10851 | return true; |
10852 | if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) |
10853 | return false; |
10854 | } else if (R->Viable) |
10855 | return false; |
10856 | |
10857 | assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0) : __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10857, __PRETTY_FUNCTION__)); |
10858 | |
10859 | // Criteria by which we can sort non-viable candidates: |
10860 | if (!L->Viable) { |
10861 | // 1. Arity mismatches come after other candidates. |
10862 | if (L->FailureKind == ovl_fail_too_many_arguments || |
10863 | L->FailureKind == ovl_fail_too_few_arguments) { |
10864 | if (R->FailureKind == ovl_fail_too_many_arguments || |
10865 | R->FailureKind == ovl_fail_too_few_arguments) { |
10866 | int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); |
10867 | int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); |
10868 | if (LDist == RDist) { |
10869 | if (L->FailureKind == R->FailureKind) |
10870 | // Sort non-surrogates before surrogates. |
10871 | return !L->IsSurrogate && R->IsSurrogate; |
10872 | // Sort candidates requiring fewer parameters than there were |
10873 | // arguments given after candidates requiring more parameters |
10874 | // than there were arguments given. |
10875 | return L->FailureKind == ovl_fail_too_many_arguments; |
10876 | } |
10877 | return LDist < RDist; |
10878 | } |
10879 | return false; |
10880 | } |
10881 | if (R->FailureKind == ovl_fail_too_many_arguments || |
10882 | R->FailureKind == ovl_fail_too_few_arguments) |
10883 | return true; |
10884 | |
10885 | // 2. Bad conversions come first and are ordered by the number |
10886 | // of bad conversions and quality of good conversions. |
10887 | if (L->FailureKind == ovl_fail_bad_conversion) { |
10888 | if (R->FailureKind != ovl_fail_bad_conversion) |
10889 | return true; |
10890 | |
10891 | // The conversion that can be fixed with a smaller number of changes, |
10892 | // comes first. |
10893 | unsigned numLFixes = L->Fix.NumConversionsFixed; |
10894 | unsigned numRFixes = R->Fix.NumConversionsFixed; |
10895 | numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; |
10896 | numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; |
10897 | if (numLFixes != numRFixes) { |
10898 | return numLFixes < numRFixes; |
10899 | } |
10900 | |
10901 | // If there's any ordering between the defined conversions... |
10902 | // FIXME: this might not be transitive. |
10903 | assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast <void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10903, __PRETTY_FUNCTION__)); |
10904 | |
10905 | int leftBetter = 0; |
10906 | unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); |
10907 | for (unsigned E = L->Conversions.size(); I != E; ++I) { |
10908 | switch (CompareImplicitConversionSequences(S, Loc, |
10909 | L->Conversions[I], |
10910 | R->Conversions[I])) { |
10911 | case ImplicitConversionSequence::Better: |
10912 | leftBetter++; |
10913 | break; |
10914 | |
10915 | case ImplicitConversionSequence::Worse: |
10916 | leftBetter--; |
10917 | break; |
10918 | |
10919 | case ImplicitConversionSequence::Indistinguishable: |
10920 | break; |
10921 | } |
10922 | } |
10923 | if (leftBetter > 0) return true; |
10924 | if (leftBetter < 0) return false; |
10925 | |
10926 | } else if (R->FailureKind == ovl_fail_bad_conversion) |
10927 | return false; |
10928 | |
10929 | if (L->FailureKind == ovl_fail_bad_deduction) { |
10930 | if (R->FailureKind != ovl_fail_bad_deduction) |
10931 | return true; |
10932 | |
10933 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
10934 | return RankDeductionFailure(L->DeductionFailure) |
10935 | < RankDeductionFailure(R->DeductionFailure); |
10936 | } else if (R->FailureKind == ovl_fail_bad_deduction) |
10937 | return false; |
10938 | |
10939 | // TODO: others? |
10940 | } |
10941 | |
10942 | // Sort everything else by location. |
10943 | SourceLocation LLoc = GetLocationForCandidate(L); |
10944 | SourceLocation RLoc = GetLocationForCandidate(R); |
10945 | |
10946 | // Put candidates without locations (e.g. builtins) at the end. |
10947 | if (LLoc.isInvalid()) return false; |
10948 | if (RLoc.isInvalid()) return true; |
10949 | |
10950 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
10951 | } |
10952 | }; |
10953 | } |
10954 | |
10955 | /// CompleteNonViableCandidate - Normally, overload resolution only |
10956 | /// computes up to the first bad conversion. Produces the FixIt set if |
10957 | /// possible. |
10958 | static void |
10959 | CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, |
10960 | ArrayRef<Expr *> Args, |
10961 | OverloadCandidateSet::CandidateSetKind CSK) { |
10962 | assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail ("!Cand->Viable", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10962, __PRETTY_FUNCTION__)); |
10963 | |
10964 | // Don't do anything on failures other than bad conversion. |
10965 | if (Cand->FailureKind != ovl_fail_bad_conversion) return; |
10966 | |
10967 | // We only want the FixIts if all the arguments can be corrected. |
10968 | bool Unfixable = false; |
10969 | // Use a implicit copy initialization to check conversion fixes. |
10970 | Cand->Fix.setConversionChecker(TryCopyInitialization); |
10971 | |
10972 | // Attempt to fix the bad conversion. |
10973 | unsigned ConvCount = Cand->Conversions.size(); |
10974 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; |
10975 | ++ConvIdx) { |
10976 | assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate" ) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 10976, __PRETTY_FUNCTION__)); |
10977 | if (Cand->Conversions[ConvIdx].isInitialized() && |
10978 | Cand->Conversions[ConvIdx].isBad()) { |
10979 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
10980 | break; |
10981 | } |
10982 | } |
10983 | |
10984 | // FIXME: this should probably be preserved from the overload |
10985 | // operation somehow. |
10986 | bool SuppressUserConversions = false; |
10987 | |
10988 | unsigned ConvIdx = 0; |
10989 | unsigned ArgIdx = 0; |
10990 | ArrayRef<QualType> ParamTypes; |
10991 | |
10992 | if (Cand->IsSurrogate) { |
10993 | QualType ConvType |
10994 | = Cand->Surrogate->getConversionType().getNonReferenceType(); |
10995 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
10996 | ConvType = ConvPtrType->getPointeeType(); |
10997 | ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); |
10998 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
10999 | ConvIdx = 1; |
11000 | } else if (Cand->Function) { |
11001 | ParamTypes = |
11002 | Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); |
11003 | if (isa<CXXMethodDecl>(Cand->Function) && |
11004 | !isa<CXXConstructorDecl>(Cand->Function)) { |
11005 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
11006 | ConvIdx = 1; |
11007 | if (CSK == OverloadCandidateSet::CSK_Operator && |
11008 | Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) |
11009 | // Argument 0 is 'this', which doesn't have a corresponding parameter. |
11010 | ArgIdx = 1; |
11011 | } |
11012 | } else { |
11013 | // Builtin operator. |
11014 | assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail ("ConvCount <= 3", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11014, __PRETTY_FUNCTION__)); |
11015 | ParamTypes = Cand->BuiltinParamTypes; |
11016 | } |
11017 | |
11018 | // Fill in the rest of the conversions. |
11019 | bool Reversed = Cand->RewriteKind & CRK_Reversed; |
11020 | for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; |
11021 | ConvIdx != ConvCount; |
11022 | ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { |
11023 | assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion" ) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11023, __PRETTY_FUNCTION__)); |
11024 | if (Cand->Conversions[ConvIdx].isInitialized()) { |
11025 | // We've already checked this conversion. |
11026 | } else if (ParamIdx < ParamTypes.size()) { |
11027 | if (ParamTypes[ParamIdx]->isDependentType()) |
11028 | Cand->Conversions[ConvIdx].setAsIdentityConversion( |
11029 | Args[ArgIdx]->getType()); |
11030 | else { |
11031 | Cand->Conversions[ConvIdx] = |
11032 | TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], |
11033 | SuppressUserConversions, |
11034 | /*InOverloadResolution=*/true, |
11035 | /*AllowObjCWritebackConversion=*/ |
11036 | S.getLangOpts().ObjCAutoRefCount); |
11037 | // Store the FixIt in the candidate if it exists. |
11038 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) |
11039 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
11040 | } |
11041 | } else |
11042 | Cand->Conversions[ConvIdx].setEllipsis(); |
11043 | } |
11044 | } |
11045 | |
11046 | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( |
11047 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
11048 | SourceLocation OpLoc, |
11049 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
11050 | // Sort the candidates by viability and position. Sorting directly would |
11051 | // be prohibitive, so we make a set of pointers and sort those. |
11052 | SmallVector<OverloadCandidate*, 32> Cands; |
11053 | if (OCD == OCD_AllCandidates) Cands.reserve(size()); |
11054 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
11055 | if (!Filter(*Cand)) |
11056 | continue; |
11057 | switch (OCD) { |
11058 | case OCD_AllCandidates: |
11059 | if (!Cand->Viable) { |
11060 | if (!Cand->Function && !Cand->IsSurrogate) { |
11061 | // This a non-viable builtin candidate. We do not, in general, |
11062 | // want to list every possible builtin candidate. |
11063 | continue; |
11064 | } |
11065 | CompleteNonViableCandidate(S, Cand, Args, Kind); |
11066 | } |
11067 | break; |
11068 | |
11069 | case OCD_ViableCandidates: |
11070 | if (!Cand->Viable) |
11071 | continue; |
11072 | break; |
11073 | |
11074 | case OCD_AmbiguousCandidates: |
11075 | if (!Cand->Best) |
11076 | continue; |
11077 | break; |
11078 | } |
11079 | |
11080 | Cands.push_back(Cand); |
11081 | } |
11082 | |
11083 | llvm::stable_sort( |
11084 | Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); |
11085 | |
11086 | return Cands; |
11087 | } |
11088 | |
11089 | /// When overload resolution fails, prints diagnostic messages containing the |
11090 | /// candidates in the candidate set. |
11091 | void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, |
11092 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
11093 | StringRef Opc, SourceLocation OpLoc, |
11094 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
11095 | |
11096 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); |
11097 | |
11098 | S.Diag(PD.first, PD.second); |
11099 | |
11100 | NoteCandidates(S, Args, Cands, Opc, OpLoc); |
11101 | } |
11102 | |
11103 | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, |
11104 | ArrayRef<OverloadCandidate *> Cands, |
11105 | StringRef Opc, SourceLocation OpLoc) { |
11106 | bool ReportedAmbiguousConversions = false; |
11107 | |
11108 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
11109 | unsigned CandsShown = 0; |
11110 | auto I = Cands.begin(), E = Cands.end(); |
11111 | for (; I != E; ++I) { |
11112 | OverloadCandidate *Cand = *I; |
11113 | |
11114 | // Set an arbitrary limit on the number of candidate functions we'll spam |
11115 | // the user with. FIXME: This limit should depend on details of the |
11116 | // candidate list. |
11117 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { |
11118 | break; |
11119 | } |
11120 | ++CandsShown; |
11121 | |
11122 | if (Cand->Function) |
11123 | NoteFunctionCandidate(S, Cand, Args.size(), |
11124 | /*TakingCandidateAddress=*/false, DestAS); |
11125 | else if (Cand->IsSurrogate) |
11126 | NoteSurrogateCandidate(S, Cand); |
11127 | else { |
11128 | assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11129, __PRETTY_FUNCTION__)) |
11129 | "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11129, __PRETTY_FUNCTION__)); |
11130 | // Generally we only see ambiguities including viable builtin |
11131 | // operators if overload resolution got screwed up by an |
11132 | // ambiguous user-defined conversion. |
11133 | // |
11134 | // FIXME: It's quite possible for different conversions to see |
11135 | // different ambiguities, though. |
11136 | if (!ReportedAmbiguousConversions) { |
11137 | NoteAmbiguousUserConversions(S, OpLoc, Cand); |
11138 | ReportedAmbiguousConversions = true; |
11139 | } |
11140 | |
11141 | // If this is a viable builtin, print it. |
11142 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); |
11143 | } |
11144 | } |
11145 | |
11146 | if (I != E) |
11147 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); |
11148 | } |
11149 | |
11150 | static SourceLocation |
11151 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { |
11152 | return Cand->Specialization ? Cand->Specialization->getLocation() |
11153 | : SourceLocation(); |
11154 | } |
11155 | |
11156 | namespace { |
11157 | struct CompareTemplateSpecCandidatesForDisplay { |
11158 | Sema &S; |
11159 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} |
11160 | |
11161 | bool operator()(const TemplateSpecCandidate *L, |
11162 | const TemplateSpecCandidate *R) { |
11163 | // Fast-path this check. |
11164 | if (L == R) |
11165 | return false; |
11166 | |
11167 | // Assuming that both candidates are not matches... |
11168 | |
11169 | // Sort by the ranking of deduction failures. |
11170 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
11171 | return RankDeductionFailure(L->DeductionFailure) < |
11172 | RankDeductionFailure(R->DeductionFailure); |
11173 | |
11174 | // Sort everything else by location. |
11175 | SourceLocation LLoc = GetLocationForCandidate(L); |
11176 | SourceLocation RLoc = GetLocationForCandidate(R); |
11177 | |
11178 | // Put candidates without locations (e.g. builtins) at the end. |
11179 | if (LLoc.isInvalid()) |
11180 | return false; |
11181 | if (RLoc.isInvalid()) |
11182 | return true; |
11183 | |
11184 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
11185 | } |
11186 | }; |
11187 | } |
11188 | |
11189 | /// Diagnose a template argument deduction failure. |
11190 | /// We are treating these failures as overload failures due to bad |
11191 | /// deductions. |
11192 | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, |
11193 | bool ForTakingAddress) { |
11194 | DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern |
11195 | DeductionFailure, /*NumArgs=*/0, ForTakingAddress); |
11196 | } |
11197 | |
11198 | void TemplateSpecCandidateSet::destroyCandidates() { |
11199 | for (iterator i = begin(), e = end(); i != e; ++i) { |
11200 | i->DeductionFailure.Destroy(); |
11201 | } |
11202 | } |
11203 | |
11204 | void TemplateSpecCandidateSet::clear() { |
11205 | destroyCandidates(); |
11206 | Candidates.clear(); |
11207 | } |
11208 | |
11209 | /// NoteCandidates - When no template specialization match is found, prints |
11210 | /// diagnostic messages containing the non-matching specializations that form |
11211 | /// the candidate set. |
11212 | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with |
11213 | /// OCD == OCD_AllCandidates and Cand->Viable == false. |
11214 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { |
11215 | // Sort the candidates by position (assuming no candidate is a match). |
11216 | // Sorting directly would be prohibitive, so we make a set of pointers |
11217 | // and sort those. |
11218 | SmallVector<TemplateSpecCandidate *, 32> Cands; |
11219 | Cands.reserve(size()); |
11220 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
11221 | if (Cand->Specialization) |
11222 | Cands.push_back(Cand); |
11223 | // Otherwise, this is a non-matching builtin candidate. We do not, |
11224 | // in general, want to list every possible builtin candidate. |
11225 | } |
11226 | |
11227 | llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); |
11228 | |
11229 | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() |
11230 | // for generalization purposes (?). |
11231 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
11232 | |
11233 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; |
11234 | unsigned CandsShown = 0; |
11235 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
11236 | TemplateSpecCandidate *Cand = *I; |
11237 | |
11238 | // Set an arbitrary limit on the number of candidates we'll spam |
11239 | // the user with. FIXME: This limit should depend on details of the |
11240 | // candidate list. |
11241 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) |
11242 | break; |
11243 | ++CandsShown; |
11244 | |
11245 | assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11246, __PRETTY_FUNCTION__)) |
11246 | "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11246, __PRETTY_FUNCTION__)); |
11247 | Cand->NoteDeductionFailure(S, ForTakingAddress); |
11248 | } |
11249 | |
11250 | if (I != E) |
11251 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); |
11252 | } |
11253 | |
11254 | // [PossiblyAFunctionType] --> [Return] |
11255 | // NonFunctionType --> NonFunctionType |
11256 | // R (A) --> R(A) |
11257 | // R (*)(A) --> R (A) |
11258 | // R (&)(A) --> R (A) |
11259 | // R (S::*)(A) --> R (A) |
11260 | QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { |
11261 | QualType Ret = PossiblyAFunctionType; |
11262 | if (const PointerType *ToTypePtr = |
11263 | PossiblyAFunctionType->getAs<PointerType>()) |
11264 | Ret = ToTypePtr->getPointeeType(); |
11265 | else if (const ReferenceType *ToTypeRef = |
11266 | PossiblyAFunctionType->getAs<ReferenceType>()) |
11267 | Ret = ToTypeRef->getPointeeType(); |
11268 | else if (const MemberPointerType *MemTypePtr = |
11269 | PossiblyAFunctionType->getAs<MemberPointerType>()) |
11270 | Ret = MemTypePtr->getPointeeType(); |
11271 | Ret = |
11272 | Context.getCanonicalType(Ret).getUnqualifiedType(); |
11273 | return Ret; |
11274 | } |
11275 | |
11276 | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, |
11277 | bool Complain = true) { |
11278 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
11279 | S.DeduceReturnType(FD, Loc, Complain)) |
11280 | return true; |
11281 | |
11282 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
11283 | if (S.getLangOpts().CPlusPlus17 && |
11284 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && |
11285 | !S.ResolveExceptionSpec(Loc, FPT)) |
11286 | return true; |
11287 | |
11288 | return false; |
11289 | } |
11290 | |
11291 | namespace { |
11292 | // A helper class to help with address of function resolution |
11293 | // - allows us to avoid passing around all those ugly parameters |
11294 | class AddressOfFunctionResolver { |
11295 | Sema& S; |
11296 | Expr* SourceExpr; |
11297 | const QualType& TargetType; |
11298 | QualType TargetFunctionType; // Extracted function type from target type |
11299 | |
11300 | bool Complain; |
11301 | //DeclAccessPair& ResultFunctionAccessPair; |
11302 | ASTContext& Context; |
11303 | |
11304 | bool TargetTypeIsNonStaticMemberFunction; |
11305 | bool FoundNonTemplateFunction; |
11306 | bool StaticMemberFunctionFromBoundPointer; |
11307 | bool HasComplained; |
11308 | |
11309 | OverloadExpr::FindResult OvlExprInfo; |
11310 | OverloadExpr *OvlExpr; |
11311 | TemplateArgumentListInfo OvlExplicitTemplateArgs; |
11312 | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; |
11313 | TemplateSpecCandidateSet FailedCandidates; |
11314 | |
11315 | public: |
11316 | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, |
11317 | const QualType &TargetType, bool Complain) |
11318 | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), |
11319 | Complain(Complain), Context(S.getASTContext()), |
11320 | TargetTypeIsNonStaticMemberFunction( |
11321 | !!TargetType->getAs<MemberPointerType>()), |
11322 | FoundNonTemplateFunction(false), |
11323 | StaticMemberFunctionFromBoundPointer(false), |
11324 | HasComplained(false), |
11325 | OvlExprInfo(OverloadExpr::find(SourceExpr)), |
11326 | OvlExpr(OvlExprInfo.Expression), |
11327 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { |
11328 | ExtractUnqualifiedFunctionTypeFromTargetType(); |
11329 | |
11330 | if (TargetFunctionType->isFunctionType()) { |
11331 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) |
11332 | if (!UME->isImplicitAccess() && |
11333 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) |
11334 | StaticMemberFunctionFromBoundPointer = true; |
11335 | } else if (OvlExpr->hasExplicitTemplateArgs()) { |
11336 | DeclAccessPair dap; |
11337 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( |
11338 | OvlExpr, false, &dap)) { |
11339 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) |
11340 | if (!Method->isStatic()) { |
11341 | // If the target type is a non-function type and the function found |
11342 | // is a non-static member function, pretend as if that was the |
11343 | // target, it's the only possible type to end up with. |
11344 | TargetTypeIsNonStaticMemberFunction = true; |
11345 | |
11346 | // And skip adding the function if its not in the proper form. |
11347 | // We'll diagnose this due to an empty set of functions. |
11348 | if (!OvlExprInfo.HasFormOfMemberPointer) |
11349 | return; |
11350 | } |
11351 | |
11352 | Matches.push_back(std::make_pair(dap, Fn)); |
11353 | } |
11354 | return; |
11355 | } |
11356 | |
11357 | if (OvlExpr->hasExplicitTemplateArgs()) |
11358 | OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); |
11359 | |
11360 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { |
11361 | // C++ [over.over]p4: |
11362 | // If more than one function is selected, [...] |
11363 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { |
11364 | if (FoundNonTemplateFunction) |
11365 | EliminateAllTemplateMatches(); |
11366 | else |
11367 | EliminateAllExceptMostSpecializedTemplate(); |
11368 | } |
11369 | } |
11370 | |
11371 | if (S.getLangOpts().CUDA && Matches.size() > 1) |
11372 | EliminateSuboptimalCudaMatches(); |
11373 | } |
11374 | |
11375 | bool hasComplained() const { return HasComplained; } |
11376 | |
11377 | private: |
11378 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { |
11379 | QualType Discard; |
11380 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || |
11381 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); |
11382 | } |
11383 | |
11384 | /// \return true if A is considered a better overload candidate for the |
11385 | /// desired type than B. |
11386 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { |
11387 | // If A doesn't have exactly the correct type, we don't want to classify it |
11388 | // as "better" than anything else. This way, the user is required to |
11389 | // disambiguate for us if there are multiple candidates and no exact match. |
11390 | return candidateHasExactlyCorrectType(A) && |
11391 | (!candidateHasExactlyCorrectType(B) || |
11392 | compareEnableIfAttrs(S, A, B) == Comparison::Better); |
11393 | } |
11394 | |
11395 | /// \return true if we were able to eliminate all but one overload candidate, |
11396 | /// false otherwise. |
11397 | bool eliminiateSuboptimalOverloadCandidates() { |
11398 | // Same algorithm as overload resolution -- one pass to pick the "best", |
11399 | // another pass to be sure that nothing is better than the best. |
11400 | auto Best = Matches.begin(); |
11401 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) |
11402 | if (isBetterCandidate(I->second, Best->second)) |
11403 | Best = I; |
11404 | |
11405 | const FunctionDecl *BestFn = Best->second; |
11406 | auto IsBestOrInferiorToBest = [this, BestFn]( |
11407 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { |
11408 | return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); |
11409 | }; |
11410 | |
11411 | // Note: We explicitly leave Matches unmodified if there isn't a clear best |
11412 | // option, so we can potentially give the user a better error |
11413 | if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) |
11414 | return false; |
11415 | Matches[0] = *Best; |
11416 | Matches.resize(1); |
11417 | return true; |
11418 | } |
11419 | |
11420 | bool isTargetTypeAFunction() const { |
11421 | return TargetFunctionType->isFunctionType(); |
11422 | } |
11423 | |
11424 | // [ToType] [Return] |
11425 | |
11426 | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false |
11427 | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false |
11428 | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true |
11429 | void inline ExtractUnqualifiedFunctionTypeFromTargetType() { |
11430 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); |
11431 | } |
11432 | |
11433 | // return true if any matching specializations were found |
11434 | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, |
11435 | const DeclAccessPair& CurAccessFunPair) { |
11436 | if (CXXMethodDecl *Method |
11437 | = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { |
11438 | // Skip non-static function templates when converting to pointer, and |
11439 | // static when converting to member pointer. |
11440 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) |
11441 | return false; |
11442 | } |
11443 | else if (TargetTypeIsNonStaticMemberFunction) |
11444 | return false; |
11445 | |
11446 | // C++ [over.over]p2: |
11447 | // If the name is a function template, template argument deduction is |
11448 | // done (14.8.2.2), and if the argument deduction succeeds, the |
11449 | // resulting template argument list is used to generate a single |
11450 | // function template specialization, which is added to the set of |
11451 | // overloaded functions considered. |
11452 | FunctionDecl *Specialization = nullptr; |
11453 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
11454 | if (Sema::TemplateDeductionResult Result |
11455 | = S.DeduceTemplateArguments(FunctionTemplate, |
11456 | &OvlExplicitTemplateArgs, |
11457 | TargetFunctionType, Specialization, |
11458 | Info, /*IsAddressOfFunction*/true)) { |
11459 | // Make a note of the failed deduction for diagnostics. |
11460 | FailedCandidates.addCandidate() |
11461 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), |
11462 | MakeDeductionFailureInfo(Context, Result, Info)); |
11463 | return false; |
11464 | } |
11465 | |
11466 | // Template argument deduction ensures that we have an exact match or |
11467 | // compatible pointer-to-function arguments that would be adjusted by ICS. |
11468 | // This function template specicalization works. |
11469 | assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11471, __PRETTY_FUNCTION__)) |
11470 | Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11471, __PRETTY_FUNCTION__)) |
11471 | Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11471, __PRETTY_FUNCTION__)); |
11472 | |
11473 | if (!S.checkAddressOfFunctionIsAvailable(Specialization)) |
11474 | return false; |
11475 | |
11476 | Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); |
11477 | return true; |
11478 | } |
11479 | |
11480 | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, |
11481 | const DeclAccessPair& CurAccessFunPair) { |
11482 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
11483 | // Skip non-static functions when converting to pointer, and static |
11484 | // when converting to member pointer. |
11485 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) |
11486 | return false; |
11487 | } |
11488 | else if (TargetTypeIsNonStaticMemberFunction) |
11489 | return false; |
11490 | |
11491 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { |
11492 | if (S.getLangOpts().CUDA) |
11493 | if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) |
11494 | if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) |
11495 | return false; |
11496 | if (FunDecl->isMultiVersion()) { |
11497 | const auto *TA = FunDecl->getAttr<TargetAttr>(); |
11498 | if (TA && !TA->isDefaultVersion()) |
11499 | return false; |
11500 | } |
11501 | |
11502 | // If any candidate has a placeholder return type, trigger its deduction |
11503 | // now. |
11504 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), |
11505 | Complain)) { |
11506 | HasComplained |= Complain; |
11507 | return false; |
11508 | } |
11509 | |
11510 | if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) |
11511 | return false; |
11512 | |
11513 | // If we're in C, we need to support types that aren't exactly identical. |
11514 | if (!S.getLangOpts().CPlusPlus || |
11515 | candidateHasExactlyCorrectType(FunDecl)) { |
11516 | Matches.push_back(std::make_pair( |
11517 | CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); |
11518 | FoundNonTemplateFunction = true; |
11519 | return true; |
11520 | } |
11521 | } |
11522 | |
11523 | return false; |
11524 | } |
11525 | |
11526 | bool FindAllFunctionsThatMatchTargetTypeExactly() { |
11527 | bool Ret = false; |
11528 | |
11529 | // If the overload expression doesn't have the form of a pointer to |
11530 | // member, don't try to convert it to a pointer-to-member type. |
11531 | if (IsInvalidFormOfPointerToMemberFunction()) |
11532 | return false; |
11533 | |
11534 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
11535 | E = OvlExpr->decls_end(); |
11536 | I != E; ++I) { |
11537 | // Look through any using declarations to find the underlying function. |
11538 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); |
11539 | |
11540 | // C++ [over.over]p3: |
11541 | // Non-member functions and static member functions match |
11542 | // targets of type "pointer-to-function" or "reference-to-function." |
11543 | // Nonstatic member functions match targets of |
11544 | // type "pointer-to-member-function." |
11545 | // Note that according to DR 247, the containing class does not matter. |
11546 | if (FunctionTemplateDecl *FunctionTemplate |
11547 | = dyn_cast<FunctionTemplateDecl>(Fn)) { |
11548 | if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) |
11549 | Ret = true; |
11550 | } |
11551 | // If we have explicit template arguments supplied, skip non-templates. |
11552 | else if (!OvlExpr->hasExplicitTemplateArgs() && |
11553 | AddMatchingNonTemplateFunction(Fn, I.getPair())) |
11554 | Ret = true; |
11555 | } |
11556 | assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail ("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11556, __PRETTY_FUNCTION__)); |
11557 | return Ret; |
11558 | } |
11559 | |
11560 | void EliminateAllExceptMostSpecializedTemplate() { |
11561 | // [...] and any given function template specialization F1 is |
11562 | // eliminated if the set contains a second function template |
11563 | // specialization whose function template is more specialized |
11564 | // than the function template of F1 according to the partial |
11565 | // ordering rules of 14.5.5.2. |
11566 | |
11567 | // The algorithm specified above is quadratic. We instead use a |
11568 | // two-pass algorithm (similar to the one used to identify the |
11569 | // best viable function in an overload set) that identifies the |
11570 | // best function template (if it exists). |
11571 | |
11572 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! |
11573 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) |
11574 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); |
11575 | |
11576 | // TODO: It looks like FailedCandidates does not serve much purpose |
11577 | // here, since the no_viable diagnostic has index 0. |
11578 | UnresolvedSetIterator Result = S.getMostSpecialized( |
11579 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, |
11580 | SourceExpr->getBeginLoc(), S.PDiag(), |
11581 | S.PDiag(diag::err_addr_ovl_ambiguous) |
11582 | << Matches[0].second->getDeclName(), |
11583 | S.PDiag(diag::note_ovl_candidate) |
11584 | << (unsigned)oc_function << (unsigned)ocs_described_template, |
11585 | Complain, TargetFunctionType); |
11586 | |
11587 | if (Result != MatchesCopy.end()) { |
11588 | // Make it the first and only element |
11589 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; |
11590 | Matches[0].second = cast<FunctionDecl>(*Result); |
11591 | Matches.resize(1); |
11592 | } else |
11593 | HasComplained |= Complain; |
11594 | } |
11595 | |
11596 | void EliminateAllTemplateMatches() { |
11597 | // [...] any function template specializations in the set are |
11598 | // eliminated if the set also contains a non-template function, [...] |
11599 | for (unsigned I = 0, N = Matches.size(); I != N; ) { |
11600 | if (Matches[I].second->getPrimaryTemplate() == nullptr) |
11601 | ++I; |
11602 | else { |
11603 | Matches[I] = Matches[--N]; |
11604 | Matches.resize(N); |
11605 | } |
11606 | } |
11607 | } |
11608 | |
11609 | void EliminateSuboptimalCudaMatches() { |
11610 | S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); |
11611 | } |
11612 | |
11613 | public: |
11614 | void ComplainNoMatchesFound() const { |
11615 | assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail ("Matches.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11615, __PRETTY_FUNCTION__)); |
11616 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) |
11617 | << OvlExpr->getName() << TargetFunctionType |
11618 | << OvlExpr->getSourceRange(); |
11619 | if (FailedCandidates.empty()) |
11620 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
11621 | /*TakingAddress=*/true); |
11622 | else { |
11623 | // We have some deduction failure messages. Use them to diagnose |
11624 | // the function templates, and diagnose the non-template candidates |
11625 | // normally. |
11626 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
11627 | IEnd = OvlExpr->decls_end(); |
11628 | I != IEnd; ++I) |
11629 | if (FunctionDecl *Fun = |
11630 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) |
11631 | if (!functionHasPassObjectSizeParams(Fun)) |
11632 | S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, |
11633 | /*TakingAddress=*/true); |
11634 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); |
11635 | } |
11636 | } |
11637 | |
11638 | bool IsInvalidFormOfPointerToMemberFunction() const { |
11639 | return TargetTypeIsNonStaticMemberFunction && |
11640 | !OvlExprInfo.HasFormOfMemberPointer; |
11641 | } |
11642 | |
11643 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { |
11644 | // TODO: Should we condition this on whether any functions might |
11645 | // have matched, or is it more appropriate to do that in callers? |
11646 | // TODO: a fixit wouldn't hurt. |
11647 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) |
11648 | << TargetType << OvlExpr->getSourceRange(); |
11649 | } |
11650 | |
11651 | bool IsStaticMemberFunctionFromBoundPointer() const { |
11652 | return StaticMemberFunctionFromBoundPointer; |
11653 | } |
11654 | |
11655 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { |
11656 | S.Diag(OvlExpr->getBeginLoc(), |
11657 | diag::err_invalid_form_pointer_member_function) |
11658 | << OvlExpr->getSourceRange(); |
11659 | } |
11660 | |
11661 | void ComplainOfInvalidConversion() const { |
11662 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) |
11663 | << OvlExpr->getName() << TargetType; |
11664 | } |
11665 | |
11666 | void ComplainMultipleMatchesFound() const { |
11667 | assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail ("Matches.size() > 1", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11667, __PRETTY_FUNCTION__)); |
11668 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) |
11669 | << OvlExpr->getName() << OvlExpr->getSourceRange(); |
11670 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
11671 | /*TakingAddress=*/true); |
11672 | } |
11673 | |
11674 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } |
11675 | |
11676 | int getNumMatches() const { return Matches.size(); } |
11677 | |
11678 | FunctionDecl* getMatchingFunctionDecl() const { |
11679 | if (Matches.size() != 1) return nullptr; |
11680 | return Matches[0].second; |
11681 | } |
11682 | |
11683 | const DeclAccessPair* getMatchingFunctionAccessPair() const { |
11684 | if (Matches.size() != 1) return nullptr; |
11685 | return &Matches[0].first; |
11686 | } |
11687 | }; |
11688 | } |
11689 | |
11690 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of |
11691 | /// an overloaded function (C++ [over.over]), where @p From is an |
11692 | /// expression with overloaded function type and @p ToType is the type |
11693 | /// we're trying to resolve to. For example: |
11694 | /// |
11695 | /// @code |
11696 | /// int f(double); |
11697 | /// int f(int); |
11698 | /// |
11699 | /// int (*pfd)(double) = f; // selects f(double) |
11700 | /// @endcode |
11701 | /// |
11702 | /// This routine returns the resulting FunctionDecl if it could be |
11703 | /// resolved, and NULL otherwise. When @p Complain is true, this |
11704 | /// routine will emit diagnostics if there is an error. |
11705 | FunctionDecl * |
11706 | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
11707 | QualType TargetType, |
11708 | bool Complain, |
11709 | DeclAccessPair &FoundResult, |
11710 | bool *pHadMultipleCandidates) { |
11711 | assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11711, __PRETTY_FUNCTION__)); |
11712 | |
11713 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, |
11714 | Complain); |
11715 | int NumMatches = Resolver.getNumMatches(); |
11716 | FunctionDecl *Fn = nullptr; |
11717 | bool ShouldComplain = Complain && !Resolver.hasComplained(); |
11718 | if (NumMatches == 0 && ShouldComplain) { |
11719 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) |
11720 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); |
11721 | else |
11722 | Resolver.ComplainNoMatchesFound(); |
11723 | } |
11724 | else if (NumMatches > 1 && ShouldComplain) |
11725 | Resolver.ComplainMultipleMatchesFound(); |
11726 | else if (NumMatches == 1) { |
11727 | Fn = Resolver.getMatchingFunctionDecl(); |
11728 | assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11728, __PRETTY_FUNCTION__)); |
11729 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
11730 | ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); |
11731 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); |
11732 | if (Complain) { |
11733 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) |
11734 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); |
11735 | else |
11736 | CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); |
11737 | } |
11738 | } |
11739 | |
11740 | if (pHadMultipleCandidates) |
11741 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); |
11742 | return Fn; |
11743 | } |
11744 | |
11745 | /// Given an expression that refers to an overloaded function, try to |
11746 | /// resolve that function to a single function that can have its address taken. |
11747 | /// This will modify `Pair` iff it returns non-null. |
11748 | /// |
11749 | /// This routine can only realistically succeed if all but one candidates in the |
11750 | /// overload set for SrcExpr cannot have their addresses taken. |
11751 | FunctionDecl * |
11752 | Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, |
11753 | DeclAccessPair &Pair) { |
11754 | OverloadExpr::FindResult R = OverloadExpr::find(E); |
11755 | OverloadExpr *Ovl = R.Expression; |
11756 | FunctionDecl *Result = nullptr; |
11757 | DeclAccessPair DAP; |
11758 | // Don't use the AddressOfResolver because we're specifically looking for |
11759 | // cases where we have one overload candidate that lacks |
11760 | // enable_if/pass_object_size/... |
11761 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { |
11762 | auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); |
11763 | if (!FD) |
11764 | return nullptr; |
11765 | |
11766 | if (!checkAddressOfFunctionIsAvailable(FD)) |
11767 | continue; |
11768 | |
11769 | // We have more than one result; quit. |
11770 | if (Result) |
11771 | return nullptr; |
11772 | DAP = I.getPair(); |
11773 | Result = FD; |
11774 | } |
11775 | |
11776 | if (Result) |
11777 | Pair = DAP; |
11778 | return Result; |
11779 | } |
11780 | |
11781 | /// Given an overloaded function, tries to turn it into a non-overloaded |
11782 | /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This |
11783 | /// will perform access checks, diagnose the use of the resultant decl, and, if |
11784 | /// requested, potentially perform a function-to-pointer decay. |
11785 | /// |
11786 | /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. |
11787 | /// Otherwise, returns true. This may emit diagnostics and return true. |
11788 | bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( |
11789 | ExprResult &SrcExpr, bool DoFunctionPointerConverion) { |
11790 | Expr *E = SrcExpr.get(); |
11791 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload" ) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11791, __PRETTY_FUNCTION__)); |
11792 | |
11793 | DeclAccessPair DAP; |
11794 | FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); |
11795 | if (!Found || Found->isCPUDispatchMultiVersion() || |
11796 | Found->isCPUSpecificMultiVersion()) |
11797 | return false; |
11798 | |
11799 | // Emitting multiple diagnostics for a function that is both inaccessible and |
11800 | // unavailable is consistent with our behavior elsewhere. So, always check |
11801 | // for both. |
11802 | DiagnoseUseOfDecl(Found, E->getExprLoc()); |
11803 | CheckAddressOfMemberAccess(E, DAP); |
11804 | Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); |
11805 | if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) |
11806 | SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); |
11807 | else |
11808 | SrcExpr = Fixed; |
11809 | return true; |
11810 | } |
11811 | |
11812 | /// Given an expression that refers to an overloaded function, try to |
11813 | /// resolve that overloaded function expression down to a single function. |
11814 | /// |
11815 | /// This routine can only resolve template-ids that refer to a single function |
11816 | /// template, where that template-id refers to a single template whose template |
11817 | /// arguments are either provided by the template-id or have defaults, |
11818 | /// as described in C++0x [temp.arg.explicit]p3. |
11819 | /// |
11820 | /// If no template-ids are found, no diagnostics are emitted and NULL is |
11821 | /// returned. |
11822 | FunctionDecl * |
11823 | Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, |
11824 | bool Complain, |
11825 | DeclAccessPair *FoundResult) { |
11826 | // C++ [over.over]p1: |
11827 | // [...] [Note: any redundant set of parentheses surrounding the |
11828 | // overloaded function name is ignored (5.1). ] |
11829 | // C++ [over.over]p1: |
11830 | // [...] The overloaded function name can be preceded by the & |
11831 | // operator. |
11832 | |
11833 | // If we didn't actually find any template-ids, we're done. |
11834 | if (!ovl->hasExplicitTemplateArgs()) |
11835 | return nullptr; |
11836 | |
11837 | TemplateArgumentListInfo ExplicitTemplateArgs; |
11838 | ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); |
11839 | TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); |
11840 | |
11841 | // Look through all of the overloaded functions, searching for one |
11842 | // whose type matches exactly. |
11843 | FunctionDecl *Matched = nullptr; |
11844 | for (UnresolvedSetIterator I = ovl->decls_begin(), |
11845 | E = ovl->decls_end(); I != E; ++I) { |
11846 | // C++0x [temp.arg.explicit]p3: |
11847 | // [...] In contexts where deduction is done and fails, or in contexts |
11848 | // where deduction is not done, if a template argument list is |
11849 | // specified and it, along with any default template arguments, |
11850 | // identifies a single function template specialization, then the |
11851 | // template-id is an lvalue for the function template specialization. |
11852 | FunctionTemplateDecl *FunctionTemplate |
11853 | = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); |
11854 | |
11855 | // C++ [over.over]p2: |
11856 | // If the name is a function template, template argument deduction is |
11857 | // done (14.8.2.2), and if the argument deduction succeeds, the |
11858 | // resulting template argument list is used to generate a single |
11859 | // function template specialization, which is added to the set of |
11860 | // overloaded functions considered. |
11861 | FunctionDecl *Specialization = nullptr; |
11862 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
11863 | if (TemplateDeductionResult Result |
11864 | = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, |
11865 | Specialization, Info, |
11866 | /*IsAddressOfFunction*/true)) { |
11867 | // Make a note of the failed deduction for diagnostics. |
11868 | // TODO: Actually use the failed-deduction info? |
11869 | FailedCandidates.addCandidate() |
11870 | .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), |
11871 | MakeDeductionFailureInfo(Context, Result, Info)); |
11872 | continue; |
11873 | } |
11874 | |
11875 | assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11875, __PRETTY_FUNCTION__)); |
11876 | |
11877 | // Multiple matches; we can't resolve to a single declaration. |
11878 | if (Matched) { |
11879 | if (Complain) { |
11880 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) |
11881 | << ovl->getName(); |
11882 | NoteAllOverloadCandidates(ovl); |
11883 | } |
11884 | return nullptr; |
11885 | } |
11886 | |
11887 | Matched = Specialization; |
11888 | if (FoundResult) *FoundResult = I.getPair(); |
11889 | } |
11890 | |
11891 | if (Matched && |
11892 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) |
11893 | return nullptr; |
11894 | |
11895 | return Matched; |
11896 | } |
11897 | |
11898 | // Resolve and fix an overloaded expression that can be resolved |
11899 | // because it identifies a single function template specialization. |
11900 | // |
11901 | // Last three arguments should only be supplied if Complain = true |
11902 | // |
11903 | // Return true if it was logically possible to so resolve the |
11904 | // expression, regardless of whether or not it succeeded. Always |
11905 | // returns true if 'complain' is set. |
11906 | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( |
11907 | ExprResult &SrcExpr, bool doFunctionPointerConverion, |
11908 | bool complain, SourceRange OpRangeForComplaining, |
11909 | QualType DestTypeForComplaining, |
11910 | unsigned DiagIDForComplaining) { |
11911 | assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11911, __PRETTY_FUNCTION__)); |
11912 | |
11913 | OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); |
11914 | |
11915 | DeclAccessPair found; |
11916 | ExprResult SingleFunctionExpression; |
11917 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( |
11918 | ovl.Expression, /*complain*/ false, &found)) { |
11919 | if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { |
11920 | SrcExpr = ExprError(); |
11921 | return true; |
11922 | } |
11923 | |
11924 | // It is only correct to resolve to an instance method if we're |
11925 | // resolving a form that's permitted to be a pointer to member. |
11926 | // Otherwise we'll end up making a bound member expression, which |
11927 | // is illegal in all the contexts we resolve like this. |
11928 | if (!ovl.HasFormOfMemberPointer && |
11929 | isa<CXXMethodDecl>(fn) && |
11930 | cast<CXXMethodDecl>(fn)->isInstance()) { |
11931 | if (!complain) return false; |
11932 | |
11933 | Diag(ovl.Expression->getExprLoc(), |
11934 | diag::err_bound_member_function) |
11935 | << 0 << ovl.Expression->getSourceRange(); |
11936 | |
11937 | // TODO: I believe we only end up here if there's a mix of |
11938 | // static and non-static candidates (otherwise the expression |
11939 | // would have 'bound member' type, not 'overload' type). |
11940 | // Ideally we would note which candidate was chosen and why |
11941 | // the static candidates were rejected. |
11942 | SrcExpr = ExprError(); |
11943 | return true; |
11944 | } |
11945 | |
11946 | // Fix the expression to refer to 'fn'. |
11947 | SingleFunctionExpression = |
11948 | FixOverloadedFunctionReference(SrcExpr.get(), found, fn); |
11949 | |
11950 | // If desired, do function-to-pointer decay. |
11951 | if (doFunctionPointerConverion) { |
11952 | SingleFunctionExpression = |
11953 | DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); |
11954 | if (SingleFunctionExpression.isInvalid()) { |
11955 | SrcExpr = ExprError(); |
11956 | return true; |
11957 | } |
11958 | } |
11959 | } |
11960 | |
11961 | if (!SingleFunctionExpression.isUsable()) { |
11962 | if (complain) { |
11963 | Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) |
11964 | << ovl.Expression->getName() |
11965 | << DestTypeForComplaining |
11966 | << OpRangeForComplaining |
11967 | << ovl.Expression->getQualifierLoc().getSourceRange(); |
11968 | NoteAllOverloadCandidates(SrcExpr.get()); |
11969 | |
11970 | SrcExpr = ExprError(); |
11971 | return true; |
11972 | } |
11973 | |
11974 | return false; |
11975 | } |
11976 | |
11977 | SrcExpr = SingleFunctionExpression; |
11978 | return true; |
11979 | } |
11980 | |
11981 | /// Add a single candidate to the overload set. |
11982 | static void AddOverloadedCallCandidate(Sema &S, |
11983 | DeclAccessPair FoundDecl, |
11984 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
11985 | ArrayRef<Expr *> Args, |
11986 | OverloadCandidateSet &CandidateSet, |
11987 | bool PartialOverloading, |
11988 | bool KnownValid) { |
11989 | NamedDecl *Callee = FoundDecl.getDecl(); |
11990 | if (isa<UsingShadowDecl>(Callee)) |
11991 | Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); |
11992 | |
11993 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { |
11994 | if (ExplicitTemplateArgs) { |
11995 | assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast <void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 11995, __PRETTY_FUNCTION__)); |
11996 | return; |
11997 | } |
11998 | // Prevent ill-formed function decls to be added as overload candidates. |
11999 | if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) |
12000 | return; |
12001 | |
12002 | S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, |
12003 | /*SuppressUserConversions=*/false, |
12004 | PartialOverloading); |
12005 | return; |
12006 | } |
12007 | |
12008 | if (FunctionTemplateDecl *FuncTemplate |
12009 | = dyn_cast<FunctionTemplateDecl>(Callee)) { |
12010 | S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, |
12011 | ExplicitTemplateArgs, Args, CandidateSet, |
12012 | /*SuppressUserConversions=*/false, |
12013 | PartialOverloading); |
12014 | return; |
12015 | } |
12016 | |
12017 | assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate" ) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12017, __PRETTY_FUNCTION__)); |
12018 | } |
12019 | |
12020 | /// Add the overload candidates named by callee and/or found by argument |
12021 | /// dependent lookup to the given overload set. |
12022 | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
12023 | ArrayRef<Expr *> Args, |
12024 | OverloadCandidateSet &CandidateSet, |
12025 | bool PartialOverloading) { |
12026 | |
12027 | #ifndef NDEBUG |
12028 | // Verify that ArgumentDependentLookup is consistent with the rules |
12029 | // in C++0x [basic.lookup.argdep]p3: |
12030 | // |
12031 | // Let X be the lookup set produced by unqualified lookup (3.4.1) |
12032 | // and let Y be the lookup set produced by argument dependent |
12033 | // lookup (defined as follows). If X contains |
12034 | // |
12035 | // -- a declaration of a class member, or |
12036 | // |
12037 | // -- a block-scope function declaration that is not a |
12038 | // using-declaration, or |
12039 | // |
12040 | // -- a declaration that is neither a function or a function |
12041 | // template |
12042 | // |
12043 | // then Y is empty. |
12044 | |
12045 | if (ULE->requiresADL()) { |
12046 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
12047 | E = ULE->decls_end(); I != E; ++I) { |
12048 | assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast< void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12048, __PRETTY_FUNCTION__)); |
12049 | assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext( )->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12050, __PRETTY_FUNCTION__)) |
12050 | !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext( )->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12050, __PRETTY_FUNCTION__)); |
12051 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate ()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12051, __PRETTY_FUNCTION__)); |
12052 | } |
12053 | } |
12054 | #endif |
12055 | |
12056 | // It would be nice to avoid this copy. |
12057 | TemplateArgumentListInfo TABuffer; |
12058 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
12059 | if (ULE->hasExplicitTemplateArgs()) { |
12060 | ULE->copyTemplateArgumentsInto(TABuffer); |
12061 | ExplicitTemplateArgs = &TABuffer; |
12062 | } |
12063 | |
12064 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
12065 | E = ULE->decls_end(); I != E; ++I) |
12066 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, |
12067 | CandidateSet, PartialOverloading, |
12068 | /*KnownValid*/ true); |
12069 | |
12070 | if (ULE->requiresADL()) |
12071 | AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), |
12072 | Args, ExplicitTemplateArgs, |
12073 | CandidateSet, PartialOverloading); |
12074 | } |
12075 | |
12076 | /// Determine whether a declaration with the specified name could be moved into |
12077 | /// a different namespace. |
12078 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { |
12079 | switch (Name.getCXXOverloadedOperator()) { |
12080 | case OO_New: case OO_Array_New: |
12081 | case OO_Delete: case OO_Array_Delete: |
12082 | return false; |
12083 | |
12084 | default: |
12085 | return true; |
12086 | } |
12087 | } |
12088 | |
12089 | /// Attempt to recover from an ill-formed use of a non-dependent name in a |
12090 | /// template, where the non-dependent name was declared after the template |
12091 | /// was defined. This is common in code written for a compilers which do not |
12092 | /// correctly implement two-stage name lookup. |
12093 | /// |
12094 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
12095 | static bool |
12096 | DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, |
12097 | const CXXScopeSpec &SS, LookupResult &R, |
12098 | OverloadCandidateSet::CandidateSetKind CSK, |
12099 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
12100 | ArrayRef<Expr *> Args, |
12101 | bool *DoDiagnoseEmptyLookup = nullptr) { |
12102 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) |
12103 | return false; |
12104 | |
12105 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { |
12106 | if (DC->isTransparentContext()) |
12107 | continue; |
12108 | |
12109 | SemaRef.LookupQualifiedName(R, DC); |
12110 | |
12111 | if (!R.empty()) { |
12112 | R.suppressDiagnostics(); |
12113 | |
12114 | if (isa<CXXRecordDecl>(DC)) { |
12115 | // Don't diagnose names we find in classes; we get much better |
12116 | // diagnostics for these from DiagnoseEmptyLookup. |
12117 | R.clear(); |
12118 | if (DoDiagnoseEmptyLookup) |
12119 | *DoDiagnoseEmptyLookup = true; |
12120 | return false; |
12121 | } |
12122 | |
12123 | OverloadCandidateSet Candidates(FnLoc, CSK); |
12124 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) |
12125 | AddOverloadedCallCandidate(SemaRef, I.getPair(), |
12126 | ExplicitTemplateArgs, Args, |
12127 | Candidates, false, /*KnownValid*/ false); |
12128 | |
12129 | OverloadCandidateSet::iterator Best; |
12130 | if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { |
12131 | // No viable functions. Don't bother the user with notes for functions |
12132 | // which don't work and shouldn't be found anyway. |
12133 | R.clear(); |
12134 | return false; |
12135 | } |
12136 | |
12137 | // Find the namespaces where ADL would have looked, and suggest |
12138 | // declaring the function there instead. |
12139 | Sema::AssociatedNamespaceSet AssociatedNamespaces; |
12140 | Sema::AssociatedClassSet AssociatedClasses; |
12141 | SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, |
12142 | AssociatedNamespaces, |
12143 | AssociatedClasses); |
12144 | Sema::AssociatedNamespaceSet SuggestedNamespaces; |
12145 | if (canBeDeclaredInNamespace(R.getLookupName())) { |
12146 | DeclContext *Std = SemaRef.getStdNamespace(); |
12147 | for (Sema::AssociatedNamespaceSet::iterator |
12148 | it = AssociatedNamespaces.begin(), |
12149 | end = AssociatedNamespaces.end(); it != end; ++it) { |
12150 | // Never suggest declaring a function within namespace 'std'. |
12151 | if (Std && Std->Encloses(*it)) |
12152 | continue; |
12153 | |
12154 | // Never suggest declaring a function within a namespace with a |
12155 | // reserved name, like __gnu_cxx. |
12156 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); |
12157 | if (NS && |
12158 | NS->getQualifiedNameAsString().find("__") != std::string::npos) |
12159 | continue; |
12160 | |
12161 | SuggestedNamespaces.insert(*it); |
12162 | } |
12163 | } |
12164 | |
12165 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) |
12166 | << R.getLookupName(); |
12167 | if (SuggestedNamespaces.empty()) { |
12168 | SemaRef.Diag(Best->Function->getLocation(), |
12169 | diag::note_not_found_by_two_phase_lookup) |
12170 | << R.getLookupName() << 0; |
12171 | } else if (SuggestedNamespaces.size() == 1) { |
12172 | SemaRef.Diag(Best->Function->getLocation(), |
12173 | diag::note_not_found_by_two_phase_lookup) |
12174 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); |
12175 | } else { |
12176 | // FIXME: It would be useful to list the associated namespaces here, |
12177 | // but the diagnostics infrastructure doesn't provide a way to produce |
12178 | // a localized representation of a list of items. |
12179 | SemaRef.Diag(Best->Function->getLocation(), |
12180 | diag::note_not_found_by_two_phase_lookup) |
12181 | << R.getLookupName() << 2; |
12182 | } |
12183 | |
12184 | // Try to recover by calling this function. |
12185 | return true; |
12186 | } |
12187 | |
12188 | R.clear(); |
12189 | } |
12190 | |
12191 | return false; |
12192 | } |
12193 | |
12194 | /// Attempt to recover from ill-formed use of a non-dependent operator in a |
12195 | /// template, where the non-dependent operator was declared after the template |
12196 | /// was defined. |
12197 | /// |
12198 | /// Returns true if a viable candidate was found and a diagnostic was issued. |
12199 | static bool |
12200 | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, |
12201 | SourceLocation OpLoc, |
12202 | ArrayRef<Expr *> Args) { |
12203 | DeclarationName OpName = |
12204 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); |
12205 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); |
12206 | return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, |
12207 | OverloadCandidateSet::CSK_Operator, |
12208 | /*ExplicitTemplateArgs=*/nullptr, Args); |
12209 | } |
12210 | |
12211 | namespace { |
12212 | class BuildRecoveryCallExprRAII { |
12213 | Sema &SemaRef; |
12214 | public: |
12215 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { |
12216 | assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast< void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12216, __PRETTY_FUNCTION__)); |
12217 | SemaRef.IsBuildingRecoveryCallExpr = true; |
12218 | } |
12219 | |
12220 | ~BuildRecoveryCallExprRAII() { |
12221 | SemaRef.IsBuildingRecoveryCallExpr = false; |
12222 | } |
12223 | }; |
12224 | |
12225 | } |
12226 | |
12227 | /// Attempts to recover from a call where no functions were found. |
12228 | /// |
12229 | /// Returns true if new candidates were found. |
12230 | static ExprResult |
12231 | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
12232 | UnresolvedLookupExpr *ULE, |
12233 | SourceLocation LParenLoc, |
12234 | MutableArrayRef<Expr *> Args, |
12235 | SourceLocation RParenLoc, |
12236 | bool EmptyLookup, bool AllowTypoCorrection) { |
12237 | // Do not try to recover if it is already building a recovery call. |
12238 | // This stops infinite loops for template instantiations like |
12239 | // |
12240 | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} |
12241 | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} |
12242 | // |
12243 | if (SemaRef.IsBuildingRecoveryCallExpr) |
12244 | return ExprError(); |
12245 | BuildRecoveryCallExprRAII RCE(SemaRef); |
12246 | |
12247 | CXXScopeSpec SS; |
12248 | SS.Adopt(ULE->getQualifierLoc()); |
12249 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); |
12250 | |
12251 | TemplateArgumentListInfo TABuffer; |
12252 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
12253 | if (ULE->hasExplicitTemplateArgs()) { |
12254 | ULE->copyTemplateArgumentsInto(TABuffer); |
12255 | ExplicitTemplateArgs = &TABuffer; |
12256 | } |
12257 | |
12258 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), |
12259 | Sema::LookupOrdinaryName); |
12260 | bool DoDiagnoseEmptyLookup = EmptyLookup; |
12261 | if (!DiagnoseTwoPhaseLookup( |
12262 | SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, |
12263 | ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { |
12264 | NoTypoCorrectionCCC NoTypoValidator{}; |
12265 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), |
12266 | ExplicitTemplateArgs != nullptr, |
12267 | dyn_cast<MemberExpr>(Fn)); |
12268 | CorrectionCandidateCallback &Validator = |
12269 | AllowTypoCorrection |
12270 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) |
12271 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); |
12272 | if (!DoDiagnoseEmptyLookup || |
12273 | SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, |
12274 | Args)) |
12275 | return ExprError(); |
12276 | } |
12277 | |
12278 | assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12278, __PRETTY_FUNCTION__)); |
12279 | |
12280 | // If recovery created an ambiguity, just bail out. |
12281 | if (R.isAmbiguous()) { |
12282 | R.suppressDiagnostics(); |
12283 | return ExprError(); |
12284 | } |
12285 | |
12286 | // Build an implicit member call if appropriate. Just drop the |
12287 | // casts and such from the call, we don't really care. |
12288 | ExprResult NewFn = ExprError(); |
12289 | if ((*R.begin())->isCXXClassMember()) |
12290 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, |
12291 | ExplicitTemplateArgs, S); |
12292 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) |
12293 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, |
12294 | ExplicitTemplateArgs); |
12295 | else |
12296 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); |
12297 | |
12298 | if (NewFn.isInvalid()) |
12299 | return ExprError(); |
12300 | |
12301 | // This shouldn't cause an infinite loop because we're giving it |
12302 | // an expression with viable lookup results, which should never |
12303 | // end up here. |
12304 | return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, |
12305 | MultiExprArg(Args.data(), Args.size()), |
12306 | RParenLoc); |
12307 | } |
12308 | |
12309 | /// Constructs and populates an OverloadedCandidateSet from |
12310 | /// the given function. |
12311 | /// \returns true when an the ExprResult output parameter has been set. |
12312 | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, |
12313 | UnresolvedLookupExpr *ULE, |
12314 | MultiExprArg Args, |
12315 | SourceLocation RParenLoc, |
12316 | OverloadCandidateSet *CandidateSet, |
12317 | ExprResult *Result) { |
12318 | #ifndef NDEBUG |
12319 | if (ULE->requiresADL()) { |
12320 | // To do ADL, we must have found an unqualified name. |
12321 | assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL" ) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12321, __PRETTY_FUNCTION__)); |
12322 | |
12323 | // We don't perform ADL for implicit declarations of builtins. |
12324 | // Verify that this was correctly set up. |
12325 | FunctionDecl *F; |
12326 | if (ULE->decls_begin() != ULE->decls_end() && |
12327 | ULE->decls_begin() + 1 == ULE->decls_end() && |
12328 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && |
12329 | F->getBuiltinID() && F->isImplicit()) |
12330 | llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12330); |
12331 | |
12332 | // We don't perform ADL in C. |
12333 | assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast <void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12333, __PRETTY_FUNCTION__)); |
12334 | } |
12335 | #endif |
12336 | |
12337 | UnbridgedCastsSet UnbridgedCasts; |
12338 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { |
12339 | *Result = ExprError(); |
12340 | return true; |
12341 | } |
12342 | |
12343 | // Add the functions denoted by the callee to the set of candidate |
12344 | // functions, including those from argument-dependent lookup. |
12345 | AddOverloadedCallCandidates(ULE, Args, *CandidateSet); |
12346 | |
12347 | if (getLangOpts().MSVCCompat && |
12348 | CurContext->isDependentContext() && !isSFINAEContext() && |
12349 | (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { |
12350 | |
12351 | OverloadCandidateSet::iterator Best; |
12352 | if (CandidateSet->empty() || |
12353 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == |
12354 | OR_No_Viable_Function) { |
12355 | // In Microsoft mode, if we are inside a template class member function |
12356 | // then create a type dependent CallExpr. The goal is to postpone name |
12357 | // lookup to instantiation time to be able to search into type dependent |
12358 | // base classes. |
12359 | CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, |
12360 | VK_RValue, RParenLoc); |
12361 | CE->setTypeDependent(true); |
12362 | CE->setValueDependent(true); |
12363 | CE->setInstantiationDependent(true); |
12364 | *Result = CE; |
12365 | return true; |
12366 | } |
12367 | } |
12368 | |
12369 | if (CandidateSet->empty()) |
12370 | return false; |
12371 | |
12372 | UnbridgedCasts.restore(); |
12373 | return false; |
12374 | } |
12375 | |
12376 | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns |
12377 | /// the completed call expression. If overload resolution fails, emits |
12378 | /// diagnostics and returns ExprError() |
12379 | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
12380 | UnresolvedLookupExpr *ULE, |
12381 | SourceLocation LParenLoc, |
12382 | MultiExprArg Args, |
12383 | SourceLocation RParenLoc, |
12384 | Expr *ExecConfig, |
12385 | OverloadCandidateSet *CandidateSet, |
12386 | OverloadCandidateSet::iterator *Best, |
12387 | OverloadingResult OverloadResult, |
12388 | bool AllowTypoCorrection) { |
12389 | if (CandidateSet->empty()) |
12390 | return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, |
12391 | RParenLoc, /*EmptyLookup=*/true, |
12392 | AllowTypoCorrection); |
12393 | |
12394 | switch (OverloadResult) { |
12395 | case OR_Success: { |
12396 | FunctionDecl *FDecl = (*Best)->Function; |
12397 | SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); |
12398 | if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) |
12399 | return ExprError(); |
12400 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
12401 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, |
12402 | ExecConfig, /*IsExecConfig=*/false, |
12403 | (*Best)->IsADLCandidate); |
12404 | } |
12405 | |
12406 | case OR_No_Viable_Function: { |
12407 | // Try to recover by looking for viable functions which the user might |
12408 | // have meant to call. |
12409 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, |
12410 | Args, RParenLoc, |
12411 | /*EmptyLookup=*/false, |
12412 | AllowTypoCorrection); |
12413 | if (!Recovery.isInvalid()) |
12414 | return Recovery; |
12415 | |
12416 | // If the user passes in a function that we can't take the address of, we |
12417 | // generally end up emitting really bad error messages. Here, we attempt to |
12418 | // emit better ones. |
12419 | for (const Expr *Arg : Args) { |
12420 | if (!Arg->getType()->isFunctionType()) |
12421 | continue; |
12422 | if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { |
12423 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); |
12424 | if (FD && |
12425 | !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, |
12426 | Arg->getExprLoc())) |
12427 | return ExprError(); |
12428 | } |
12429 | } |
12430 | |
12431 | CandidateSet->NoteCandidates( |
12432 | PartialDiagnosticAt( |
12433 | Fn->getBeginLoc(), |
12434 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) |
12435 | << ULE->getName() << Fn->getSourceRange()), |
12436 | SemaRef, OCD_AllCandidates, Args); |
12437 | break; |
12438 | } |
12439 | |
12440 | case OR_Ambiguous: |
12441 | CandidateSet->NoteCandidates( |
12442 | PartialDiagnosticAt(Fn->getBeginLoc(), |
12443 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) |
12444 | << ULE->getName() << Fn->getSourceRange()), |
12445 | SemaRef, OCD_AmbiguousCandidates, Args); |
12446 | break; |
12447 | |
12448 | case OR_Deleted: { |
12449 | CandidateSet->NoteCandidates( |
12450 | PartialDiagnosticAt(Fn->getBeginLoc(), |
12451 | SemaRef.PDiag(diag::err_ovl_deleted_call) |
12452 | << ULE->getName() << Fn->getSourceRange()), |
12453 | SemaRef, OCD_AllCandidates, Args); |
12454 | |
12455 | // We emitted an error for the unavailable/deleted function call but keep |
12456 | // the call in the AST. |
12457 | FunctionDecl *FDecl = (*Best)->Function; |
12458 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
12459 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, |
12460 | ExecConfig, /*IsExecConfig=*/false, |
12461 | (*Best)->IsADLCandidate); |
12462 | } |
12463 | } |
12464 | |
12465 | // Overload resolution failed. |
12466 | return ExprError(); |
12467 | } |
12468 | |
12469 | static void markUnaddressableCandidatesUnviable(Sema &S, |
12470 | OverloadCandidateSet &CS) { |
12471 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { |
12472 | if (I->Viable && |
12473 | !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { |
12474 | I->Viable = false; |
12475 | I->FailureKind = ovl_fail_addr_not_available; |
12476 | } |
12477 | } |
12478 | } |
12479 | |
12480 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn |
12481 | /// (which eventually refers to the declaration Func) and the call |
12482 | /// arguments Args/NumArgs, attempt to resolve the function call down |
12483 | /// to a specific function. If overload resolution succeeds, returns |
12484 | /// the call expression produced by overload resolution. |
12485 | /// Otherwise, emits diagnostics and returns ExprError. |
12486 | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
12487 | UnresolvedLookupExpr *ULE, |
12488 | SourceLocation LParenLoc, |
12489 | MultiExprArg Args, |
12490 | SourceLocation RParenLoc, |
12491 | Expr *ExecConfig, |
12492 | bool AllowTypoCorrection, |
12493 | bool CalleesAddressIsTaken) { |
12494 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), |
12495 | OverloadCandidateSet::CSK_Normal); |
12496 | ExprResult result; |
12497 | |
12498 | if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, |
12499 | &result)) |
12500 | return result; |
12501 | |
12502 | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that |
12503 | // functions that aren't addressible are considered unviable. |
12504 | if (CalleesAddressIsTaken) |
12505 | markUnaddressableCandidatesUnviable(*this, CandidateSet); |
12506 | |
12507 | OverloadCandidateSet::iterator Best; |
12508 | OverloadingResult OverloadResult = |
12509 | CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); |
12510 | |
12511 | return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, |
12512 | ExecConfig, &CandidateSet, &Best, |
12513 | OverloadResult, AllowTypoCorrection); |
12514 | } |
12515 | |
12516 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { |
12517 | return Functions.size() > 1 || |
12518 | (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); |
12519 | } |
12520 | |
12521 | /// Create a unary operation that may resolve to an overloaded |
12522 | /// operator. |
12523 | /// |
12524 | /// \param OpLoc The location of the operator itself (e.g., '*'). |
12525 | /// |
12526 | /// \param Opc The UnaryOperatorKind that describes this operator. |
12527 | /// |
12528 | /// \param Fns The set of non-member functions that will be |
12529 | /// considered by overload resolution. The caller needs to build this |
12530 | /// set based on the context using, e.g., |
12531 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
12532 | /// set should not contain any member functions; those will be added |
12533 | /// by CreateOverloadedUnaryOp(). |
12534 | /// |
12535 | /// \param Input The input argument. |
12536 | ExprResult |
12537 | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
12538 | const UnresolvedSetImpl &Fns, |
12539 | Expr *Input, bool PerformADL) { |
12540 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); |
12541 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator" ) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12541, __PRETTY_FUNCTION__)); |
12542 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
12543 | // TODO: provide better source location info. |
12544 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
12545 | |
12546 | if (checkPlaceholderForOverload(*this, Input)) |
12547 | return ExprError(); |
12548 | |
12549 | Expr *Args[2] = { Input, nullptr }; |
12550 | unsigned NumArgs = 1; |
12551 | |
12552 | // For post-increment and post-decrement, add the implicit '0' as |
12553 | // the second argument, so that we know this is a post-increment or |
12554 | // post-decrement. |
12555 | if (Opc == UO_PostInc || Opc == UO_PostDec) { |
12556 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
12557 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, |
12558 | SourceLocation()); |
12559 | NumArgs = 2; |
12560 | } |
12561 | |
12562 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); |
12563 | |
12564 | if (Input->isTypeDependent()) { |
12565 | if (Fns.empty()) |
12566 | return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, |
12567 | VK_RValue, OK_Ordinary, OpLoc, false); |
12568 | |
12569 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
12570 | UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( |
12571 | Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, |
12572 | /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); |
12573 | return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, |
12574 | Context.DependentTy, VK_RValue, OpLoc, |
12575 | FPOptions()); |
12576 | } |
12577 | |
12578 | // Build an empty overload set. |
12579 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); |
12580 | |
12581 | // Add the candidates from the given function set. |
12582 | AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); |
12583 | |
12584 | // Add operator candidates that are member functions. |
12585 | AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
12586 | |
12587 | // Add candidates from ADL. |
12588 | if (PerformADL) { |
12589 | AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, |
12590 | /*ExplicitTemplateArgs*/nullptr, |
12591 | CandidateSet); |
12592 | } |
12593 | |
12594 | // Add builtin operator candidates. |
12595 | AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
12596 | |
12597 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
12598 | |
12599 | // Perform overload resolution. |
12600 | OverloadCandidateSet::iterator Best; |
12601 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
12602 | case OR_Success: { |
12603 | // We found a built-in operator or an overloaded operator. |
12604 | FunctionDecl *FnDecl = Best->Function; |
12605 | |
12606 | if (FnDecl) { |
12607 | Expr *Base = nullptr; |
12608 | // We matched an overloaded operator. Build a call to that |
12609 | // operator. |
12610 | |
12611 | // Convert the arguments. |
12612 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
12613 | CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); |
12614 | |
12615 | ExprResult InputRes = |
12616 | PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, |
12617 | Best->FoundDecl, Method); |
12618 | if (InputRes.isInvalid()) |
12619 | return ExprError(); |
12620 | Base = Input = InputRes.get(); |
12621 | } else { |
12622 | // Convert the arguments. |
12623 | ExprResult InputInit |
12624 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( |
12625 | Context, |
12626 | FnDecl->getParamDecl(0)), |
12627 | SourceLocation(), |
12628 | Input); |
12629 | if (InputInit.isInvalid()) |
12630 | return ExprError(); |
12631 | Input = InputInit.get(); |
12632 | } |
12633 | |
12634 | // Build the actual expression node. |
12635 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, |
12636 | Base, HadMultipleCandidates, |
12637 | OpLoc); |
12638 | if (FnExpr.isInvalid()) |
12639 | return ExprError(); |
12640 | |
12641 | // Determine the result type. |
12642 | QualType ResultTy = FnDecl->getReturnType(); |
12643 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
12644 | ResultTy = ResultTy.getNonLValueExprType(Context); |
12645 | |
12646 | Args[0] = Input; |
12647 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
12648 | Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, |
12649 | FPOptions(), Best->IsADLCandidate); |
12650 | |
12651 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) |
12652 | return ExprError(); |
12653 | |
12654 | if (CheckFunctionCall(FnDecl, TheCall, |
12655 | FnDecl->getType()->castAs<FunctionProtoType>())) |
12656 | return ExprError(); |
12657 | |
12658 | return MaybeBindToTemporary(TheCall); |
12659 | } else { |
12660 | // We matched a built-in operator. Convert the arguments, then |
12661 | // break out so that we will build the appropriate built-in |
12662 | // operator node. |
12663 | ExprResult InputRes = PerformImplicitConversion( |
12664 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, |
12665 | CCK_ForBuiltinOverloadedOp); |
12666 | if (InputRes.isInvalid()) |
12667 | return ExprError(); |
12668 | Input = InputRes.get(); |
12669 | break; |
12670 | } |
12671 | } |
12672 | |
12673 | case OR_No_Viable_Function: |
12674 | // This is an erroneous use of an operator which can be overloaded by |
12675 | // a non-member function. Check for non-member operators which were |
12676 | // defined too late to be candidates. |
12677 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) |
12678 | // FIXME: Recover by calling the found function. |
12679 | return ExprError(); |
12680 | |
12681 | // No viable function; fall through to handling this as a |
12682 | // built-in operator, which will produce an error message for us. |
12683 | break; |
12684 | |
12685 | case OR_Ambiguous: |
12686 | CandidateSet.NoteCandidates( |
12687 | PartialDiagnosticAt(OpLoc, |
12688 | PDiag(diag::err_ovl_ambiguous_oper_unary) |
12689 | << UnaryOperator::getOpcodeStr(Opc) |
12690 | << Input->getType() << Input->getSourceRange()), |
12691 | *this, OCD_AmbiguousCandidates, ArgsArray, |
12692 | UnaryOperator::getOpcodeStr(Opc), OpLoc); |
12693 | return ExprError(); |
12694 | |
12695 | case OR_Deleted: |
12696 | CandidateSet.NoteCandidates( |
12697 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
12698 | << UnaryOperator::getOpcodeStr(Opc) |
12699 | << Input->getSourceRange()), |
12700 | *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), |
12701 | OpLoc); |
12702 | return ExprError(); |
12703 | } |
12704 | |
12705 | // Either we found no viable overloaded operator or we matched a |
12706 | // built-in operator. In either case, fall through to trying to |
12707 | // build a built-in operation. |
12708 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
12709 | } |
12710 | |
12711 | /// Create a binary operation that may resolve to an overloaded |
12712 | /// operator. |
12713 | /// |
12714 | /// \param OpLoc The location of the operator itself (e.g., '+'). |
12715 | /// |
12716 | /// \param Opc The BinaryOperatorKind that describes this operator. |
12717 | /// |
12718 | /// \param Fns The set of non-member functions that will be |
12719 | /// considered by overload resolution. The caller needs to build this |
12720 | /// set based on the context using, e.g., |
12721 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
12722 | /// set should not contain any member functions; those will be added |
12723 | /// by CreateOverloadedBinOp(). |
12724 | /// |
12725 | /// \param LHS Left-hand argument. |
12726 | /// \param RHS Right-hand argument. |
12727 | ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, |
12728 | BinaryOperatorKind Opc, |
12729 | const UnresolvedSetImpl &Fns, Expr *LHS, |
12730 | Expr *RHS, bool PerformADL, |
12731 | bool AllowRewrittenCandidates) { |
12732 | Expr *Args[2] = { LHS, RHS }; |
12733 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple |
12734 | |
12735 | if (!getLangOpts().CPlusPlus2a) |
12736 | AllowRewrittenCandidates = false; |
12737 | |
12738 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); |
12739 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
12740 | |
12741 | // If either side is type-dependent, create an appropriate dependent |
12742 | // expression. |
12743 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { |
12744 | if (Fns.empty()) { |
12745 | // If there are no functions to store, just build a dependent |
12746 | // BinaryOperator or CompoundAssignment. |
12747 | if (Opc <= BO_Assign || Opc > BO_OrAssign) |
12748 | return new (Context) BinaryOperator( |
12749 | Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, |
12750 | OpLoc, FPFeatures); |
12751 | |
12752 | return new (Context) CompoundAssignOperator( |
12753 | Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, |
12754 | Context.DependentTy, Context.DependentTy, OpLoc, |
12755 | FPFeatures); |
12756 | } |
12757 | |
12758 | // FIXME: save results of ADL from here? |
12759 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
12760 | // TODO: provide better source location info in DNLoc component. |
12761 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
12762 | UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( |
12763 | Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, |
12764 | /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); |
12765 | return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, |
12766 | Context.DependentTy, VK_RValue, OpLoc, |
12767 | FPFeatures); |
12768 | } |
12769 | |
12770 | // Always do placeholder-like conversions on the RHS. |
12771 | if (checkPlaceholderForOverload(*this, Args[1])) |
12772 | return ExprError(); |
12773 | |
12774 | // Do placeholder-like conversion on the LHS; note that we should |
12775 | // not get here with a PseudoObject LHS. |
12776 | assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast <void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12776, __PRETTY_FUNCTION__)); |
12777 | if (checkPlaceholderForOverload(*this, Args[0])) |
12778 | return ExprError(); |
12779 | |
12780 | // If this is the assignment operator, we only perform overload resolution |
12781 | // if the left-hand side is a class or enumeration type. This is actually |
12782 | // a hack. The standard requires that we do overload resolution between the |
12783 | // various built-in candidates, but as DR507 points out, this can lead to |
12784 | // problems. So we do it this way, which pretty much follows what GCC does. |
12785 | // Note that we go the traditional code path for compound assignment forms. |
12786 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) |
12787 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
12788 | |
12789 | // If this is the .* operator, which is not overloadable, just |
12790 | // create a built-in binary operator. |
12791 | if (Opc == BO_PtrMemD) |
12792 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
12793 | |
12794 | // Build an empty overload set. |
12795 | OverloadCandidateSet CandidateSet( |
12796 | OpLoc, OverloadCandidateSet::CSK_Operator, |
12797 | OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); |
12798 | |
12799 | OverloadedOperatorKind ExtraOp = |
12800 | AllowRewrittenCandidates ? getRewrittenOverloadedOperator(Op) : OO_None; |
12801 | |
12802 | // Add the candidates from the given function set. This also adds the |
12803 | // rewritten candidates using these functions if necessary. |
12804 | AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); |
12805 | |
12806 | // Add operator candidates that are member functions. |
12807 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
12808 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) |
12809 | AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, |
12810 | OverloadCandidateParamOrder::Reversed); |
12811 | |
12812 | // In C++20, also add any rewritten member candidates. |
12813 | if (ExtraOp) { |
12814 | AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); |
12815 | if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) |
12816 | AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, |
12817 | CandidateSet, |
12818 | OverloadCandidateParamOrder::Reversed); |
12819 | } |
12820 | |
12821 | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not |
12822 | // performed for an assignment operator (nor for operator[] nor operator->, |
12823 | // which don't get here). |
12824 | if (Opc != BO_Assign && PerformADL) { |
12825 | AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, |
12826 | /*ExplicitTemplateArgs*/ nullptr, |
12827 | CandidateSet); |
12828 | if (ExtraOp) { |
12829 | DeclarationName ExtraOpName = |
12830 | Context.DeclarationNames.getCXXOperatorName(ExtraOp); |
12831 | AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, |
12832 | /*ExplicitTemplateArgs*/ nullptr, |
12833 | CandidateSet); |
12834 | } |
12835 | } |
12836 | |
12837 | // Add builtin operator candidates. |
12838 | // |
12839 | // FIXME: We don't add any rewritten candidates here. This is strictly |
12840 | // incorrect; a builtin candidate could be hidden by a non-viable candidate, |
12841 | // resulting in our selecting a rewritten builtin candidate. For example: |
12842 | // |
12843 | // enum class E { e }; |
12844 | // bool operator!=(E, E) requires false; |
12845 | // bool k = E::e != E::e; |
12846 | // |
12847 | // ... should select the rewritten builtin candidate 'operator==(E, E)'. But |
12848 | // it seems unreasonable to consider rewritten builtin candidates. A core |
12849 | // issue has been filed proposing to removed this requirement. |
12850 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
12851 | |
12852 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
12853 | |
12854 | // Perform overload resolution. |
12855 | OverloadCandidateSet::iterator Best; |
12856 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
12857 | case OR_Success: { |
12858 | // We found a built-in operator or an overloaded operator. |
12859 | FunctionDecl *FnDecl = Best->Function; |
12860 | |
12861 | bool IsReversed = (Best->RewriteKind & CRK_Reversed); |
12862 | if (IsReversed) |
12863 | std::swap(Args[0], Args[1]); |
12864 | |
12865 | if (FnDecl) { |
12866 | Expr *Base = nullptr; |
12867 | // We matched an overloaded operator. Build a call to that |
12868 | // operator. |
12869 | |
12870 | OverloadedOperatorKind ChosenOp = |
12871 | FnDecl->getDeclName().getCXXOverloadedOperator(); |
12872 | |
12873 | // C++2a [over.match.oper]p9: |
12874 | // If a rewritten operator== candidate is selected by overload |
12875 | // resolution for an operator@, its return type shall be cv bool |
12876 | if (Best->RewriteKind && ChosenOp == OO_EqualEqual && |
12877 | !FnDecl->getReturnType()->isBooleanType()) { |
12878 | Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) |
12879 | << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) |
12880 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
12881 | Diag(FnDecl->getLocation(), diag::note_declared_at); |
12882 | return ExprError(); |
12883 | } |
12884 | |
12885 | if (AllowRewrittenCandidates && !IsReversed && |
12886 | CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { |
12887 | // We could have reversed this operator, but didn't. Check if the |
12888 | // reversed form was a viable candidate, and if so, if it had a |
12889 | // better conversion for either parameter. If so, this call is |
12890 | // formally ambiguous, and allowing it is an extension. |
12891 | for (OverloadCandidate &Cand : CandidateSet) { |
12892 | if (Cand.Viable && Cand.Function == FnDecl && |
12893 | Cand.RewriteKind & CRK_Reversed) { |
12894 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
12895 | if (CompareImplicitConversionSequences( |
12896 | *this, OpLoc, Cand.Conversions[ArgIdx], |
12897 | Best->Conversions[ArgIdx]) == |
12898 | ImplicitConversionSequence::Better) { |
12899 | Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) |
12900 | << BinaryOperator::getOpcodeStr(Opc) |
12901 | << Args[0]->getType() << Args[1]->getType() |
12902 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
12903 | Diag(FnDecl->getLocation(), |
12904 | diag::note_ovl_ambiguous_oper_binary_reversed_candidate); |
12905 | } |
12906 | } |
12907 | break; |
12908 | } |
12909 | } |
12910 | } |
12911 | |
12912 | // Convert the arguments. |
12913 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
12914 | // Best->Access is only meaningful for class members. |
12915 | CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); |
12916 | |
12917 | ExprResult Arg1 = |
12918 | PerformCopyInitialization( |
12919 | InitializedEntity::InitializeParameter(Context, |
12920 | FnDecl->getParamDecl(0)), |
12921 | SourceLocation(), Args[1]); |
12922 | if (Arg1.isInvalid()) |
12923 | return ExprError(); |
12924 | |
12925 | ExprResult Arg0 = |
12926 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, |
12927 | Best->FoundDecl, Method); |
12928 | if (Arg0.isInvalid()) |
12929 | return ExprError(); |
12930 | Base = Args[0] = Arg0.getAs<Expr>(); |
12931 | Args[1] = RHS = Arg1.getAs<Expr>(); |
12932 | } else { |
12933 | // Convert the arguments. |
12934 | ExprResult Arg0 = PerformCopyInitialization( |
12935 | InitializedEntity::InitializeParameter(Context, |
12936 | FnDecl->getParamDecl(0)), |
12937 | SourceLocation(), Args[0]); |
12938 | if (Arg0.isInvalid()) |
12939 | return ExprError(); |
12940 | |
12941 | ExprResult Arg1 = |
12942 | PerformCopyInitialization( |
12943 | InitializedEntity::InitializeParameter(Context, |
12944 | FnDecl->getParamDecl(1)), |
12945 | SourceLocation(), Args[1]); |
12946 | if (Arg1.isInvalid()) |
12947 | return ExprError(); |
12948 | Args[0] = LHS = Arg0.getAs<Expr>(); |
12949 | Args[1] = RHS = Arg1.getAs<Expr>(); |
Although the value stored to 'RHS' is used in the enclosing expression, the value is never actually read from 'RHS' | |
12950 | } |
12951 | |
12952 | // Build the actual expression node. |
12953 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, |
12954 | Best->FoundDecl, Base, |
12955 | HadMultipleCandidates, OpLoc); |
12956 | if (FnExpr.isInvalid()) |
12957 | return ExprError(); |
12958 | |
12959 | // Determine the result type. |
12960 | QualType ResultTy = FnDecl->getReturnType(); |
12961 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
12962 | ResultTy = ResultTy.getNonLValueExprType(Context); |
12963 | |
12964 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( |
12965 | Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, |
12966 | FPFeatures, Best->IsADLCandidate); |
12967 | |
12968 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, |
12969 | FnDecl)) |
12970 | return ExprError(); |
12971 | |
12972 | ArrayRef<const Expr *> ArgsArray(Args, 2); |
12973 | const Expr *ImplicitThis = nullptr; |
12974 | // Cut off the implicit 'this'. |
12975 | if (isa<CXXMethodDecl>(FnDecl)) { |
12976 | ImplicitThis = ArgsArray[0]; |
12977 | ArgsArray = ArgsArray.slice(1); |
12978 | } |
12979 | |
12980 | // Check for a self move. |
12981 | if (Op == OO_Equal) |
12982 | DiagnoseSelfMove(Args[0], Args[1], OpLoc); |
12983 | |
12984 | checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, |
12985 | isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), |
12986 | VariadicDoesNotApply); |
12987 | |
12988 | ExprResult R = MaybeBindToTemporary(TheCall); |
12989 | if (R.isInvalid()) |
12990 | return ExprError(); |
12991 | |
12992 | // For a rewritten candidate, we've already reversed the arguments |
12993 | // if needed. Perform the rest of the rewrite now. |
12994 | if ((Best->RewriteKind & CRK_DifferentOperator) || |
12995 | (Op == OO_Spaceship && IsReversed)) { |
12996 | if (Op == OO_ExclaimEqual) { |
12997 | assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name" ) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 12997, __PRETTY_FUNCTION__)); |
12998 | R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); |
12999 | } else { |
13000 | assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name" ) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13000, __PRETTY_FUNCTION__)); |
13001 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
13002 | Expr *ZeroLiteral = |
13003 | IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); |
13004 | |
13005 | Sema::CodeSynthesisContext Ctx; |
13006 | Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; |
13007 | Ctx.Entity = FnDecl; |
13008 | pushCodeSynthesisContext(Ctx); |
13009 | |
13010 | R = CreateOverloadedBinOp( |
13011 | OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), |
13012 | IsReversed ? R.get() : ZeroLiteral, PerformADL, |
13013 | /*AllowRewrittenCandidates=*/false); |
13014 | |
13015 | popCodeSynthesisContext(); |
13016 | } |
13017 | if (R.isInvalid()) |
13018 | return ExprError(); |
13019 | } else { |
13020 | assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast <void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13020, __PRETTY_FUNCTION__)); |
13021 | } |
13022 | |
13023 | // Make a note in the AST if we did any rewriting. |
13024 | if (Best->RewriteKind != CRK_None) |
13025 | R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); |
13026 | |
13027 | return R; |
13028 | } else { |
13029 | // We matched a built-in operator. Convert the arguments, then |
13030 | // break out so that we will build the appropriate built-in |
13031 | // operator node. |
13032 | ExprResult ArgsRes0 = PerformImplicitConversion( |
13033 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
13034 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
13035 | if (ArgsRes0.isInvalid()) |
13036 | return ExprError(); |
13037 | Args[0] = ArgsRes0.get(); |
13038 | |
13039 | ExprResult ArgsRes1 = PerformImplicitConversion( |
13040 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
13041 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
13042 | if (ArgsRes1.isInvalid()) |
13043 | return ExprError(); |
13044 | Args[1] = ArgsRes1.get(); |
13045 | break; |
13046 | } |
13047 | } |
13048 | |
13049 | case OR_No_Viable_Function: { |
13050 | // C++ [over.match.oper]p9: |
13051 | // If the operator is the operator , [...] and there are no |
13052 | // viable functions, then the operator is assumed to be the |
13053 | // built-in operator and interpreted according to clause 5. |
13054 | if (Opc == BO_Comma) |
13055 | break; |
13056 | |
13057 | // For class as left operand for assignment or compound assignment |
13058 | // operator do not fall through to handling in built-in, but report that |
13059 | // no overloaded assignment operator found |
13060 | ExprResult Result = ExprError(); |
13061 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); |
13062 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, |
13063 | Args, OpLoc); |
13064 | if (Args[0]->getType()->isRecordType() && |
13065 | Opc >= BO_Assign && Opc <= BO_OrAssign) { |
13066 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
13067 | << BinaryOperator::getOpcodeStr(Opc) |
13068 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
13069 | if (Args[0]->getType()->isIncompleteType()) { |
13070 | Diag(OpLoc, diag::note_assign_lhs_incomplete) |
13071 | << Args[0]->getType() |
13072 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
13073 | } |
13074 | } else { |
13075 | // This is an erroneous use of an operator which can be overloaded by |
13076 | // a non-member function. Check for non-member operators which were |
13077 | // defined too late to be candidates. |
13078 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) |
13079 | // FIXME: Recover by calling the found function. |
13080 | return ExprError(); |
13081 | |
13082 | // No viable function; try to create a built-in operation, which will |
13083 | // produce an error. Then, show the non-viable candidates. |
13084 | Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
13085 | } |
13086 | assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13087, __PRETTY_FUNCTION__)) |
13087 | "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13087, __PRETTY_FUNCTION__)); |
13088 | CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); |
13089 | return Result; |
13090 | } |
13091 | |
13092 | case OR_Ambiguous: |
13093 | CandidateSet.NoteCandidates( |
13094 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
13095 | << BinaryOperator::getOpcodeStr(Opc) |
13096 | << Args[0]->getType() |
13097 | << Args[1]->getType() |
13098 | << Args[0]->getSourceRange() |
13099 | << Args[1]->getSourceRange()), |
13100 | *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
13101 | OpLoc); |
13102 | return ExprError(); |
13103 | |
13104 | case OR_Deleted: |
13105 | if (isImplicitlyDeleted(Best->Function)) { |
13106 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
13107 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) |
13108 | << Context.getRecordType(Method->getParent()) |
13109 | << getSpecialMember(Method); |
13110 | |
13111 | // The user probably meant to call this special member. Just |
13112 | // explain why it's deleted. |
13113 | NoteDeletedFunction(Method); |
13114 | return ExprError(); |
13115 | } |
13116 | CandidateSet.NoteCandidates( |
13117 | PartialDiagnosticAt( |
13118 | OpLoc, PDiag(diag::err_ovl_deleted_oper) |
13119 | << getOperatorSpelling(Best->Function->getDeclName() |
13120 | .getCXXOverloadedOperator()) |
13121 | << Args[0]->getSourceRange() |
13122 | << Args[1]->getSourceRange()), |
13123 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
13124 | OpLoc); |
13125 | return ExprError(); |
13126 | } |
13127 | |
13128 | // We matched a built-in operator; build it. |
13129 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
13130 | } |
13131 | |
13132 | ExprResult |
13133 | Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
13134 | SourceLocation RLoc, |
13135 | Expr *Base, Expr *Idx) { |
13136 | Expr *Args[2] = { Base, Idx }; |
13137 | DeclarationName OpName = |
13138 | Context.DeclarationNames.getCXXOperatorName(OO_Subscript); |
13139 | |
13140 | // If either side is type-dependent, create an appropriate dependent |
13141 | // expression. |
13142 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { |
13143 | |
13144 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
13145 | // CHECKME: no 'operator' keyword? |
13146 | DeclarationNameInfo OpNameInfo(OpName, LLoc); |
13147 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
13148 | UnresolvedLookupExpr *Fn |
13149 | = UnresolvedLookupExpr::Create(Context, NamingClass, |
13150 | NestedNameSpecifierLoc(), OpNameInfo, |
13151 | /*ADL*/ true, /*Overloaded*/ false, |
13152 | UnresolvedSetIterator(), |
13153 | UnresolvedSetIterator()); |
13154 | // Can't add any actual overloads yet |
13155 | |
13156 | return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, |
13157 | Context.DependentTy, VK_RValue, RLoc, |
13158 | FPOptions()); |
13159 | } |
13160 | |
13161 | // Handle placeholders on both operands. |
13162 | if (checkPlaceholderForOverload(*this, Args[0])) |
13163 | return ExprError(); |
13164 | if (checkPlaceholderForOverload(*this, Args[1])) |
13165 | return ExprError(); |
13166 | |
13167 | // Build an empty overload set. |
13168 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); |
13169 | |
13170 | // Subscript can only be overloaded as a member function. |
13171 | |
13172 | // Add operator candidates that are member functions. |
13173 | AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
13174 | |
13175 | // Add builtin operator candidates. |
13176 | AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
13177 | |
13178 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
13179 | |
13180 | // Perform overload resolution. |
13181 | OverloadCandidateSet::iterator Best; |
13182 | switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { |
13183 | case OR_Success: { |
13184 | // We found a built-in operator or an overloaded operator. |
13185 | FunctionDecl *FnDecl = Best->Function; |
13186 | |
13187 | if (FnDecl) { |
13188 | // We matched an overloaded operator. Build a call to that |
13189 | // operator. |
13190 | |
13191 | CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); |
13192 | |
13193 | // Convert the arguments. |
13194 | CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); |
13195 | ExprResult Arg0 = |
13196 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, |
13197 | Best->FoundDecl, Method); |
13198 | if (Arg0.isInvalid()) |
13199 | return ExprError(); |
13200 | Args[0] = Arg0.get(); |
13201 | |
13202 | // Convert the arguments. |
13203 | ExprResult InputInit |
13204 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( |
13205 | Context, |
13206 | FnDecl->getParamDecl(0)), |
13207 | SourceLocation(), |
13208 | Args[1]); |
13209 | if (InputInit.isInvalid()) |
13210 | return ExprError(); |
13211 | |
13212 | Args[1] = InputInit.getAs<Expr>(); |
13213 | |
13214 | // Build the actual expression node. |
13215 | DeclarationNameInfo OpLocInfo(OpName, LLoc); |
13216 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
13217 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, |
13218 | Best->FoundDecl, |
13219 | Base, |
13220 | HadMultipleCandidates, |
13221 | OpLocInfo.getLoc(), |
13222 | OpLocInfo.getInfo()); |
13223 | if (FnExpr.isInvalid()) |
13224 | return ExprError(); |
13225 | |
13226 | // Determine the result type |
13227 | QualType ResultTy = FnDecl->getReturnType(); |
13228 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
13229 | ResultTy = ResultTy.getNonLValueExprType(Context); |
13230 | |
13231 | CXXOperatorCallExpr *TheCall = |
13232 | CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), |
13233 | Args, ResultTy, VK, RLoc, FPOptions()); |
13234 | |
13235 | if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) |
13236 | return ExprError(); |
13237 | |
13238 | if (CheckFunctionCall(Method, TheCall, |
13239 | Method->getType()->castAs<FunctionProtoType>())) |
13240 | return ExprError(); |
13241 | |
13242 | return MaybeBindToTemporary(TheCall); |
13243 | } else { |
13244 | // We matched a built-in operator. Convert the arguments, then |
13245 | // break out so that we will build the appropriate built-in |
13246 | // operator node. |
13247 | ExprResult ArgsRes0 = PerformImplicitConversion( |
13248 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
13249 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
13250 | if (ArgsRes0.isInvalid()) |
13251 | return ExprError(); |
13252 | Args[0] = ArgsRes0.get(); |
13253 | |
13254 | ExprResult ArgsRes1 = PerformImplicitConversion( |
13255 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
13256 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
13257 | if (ArgsRes1.isInvalid()) |
13258 | return ExprError(); |
13259 | Args[1] = ArgsRes1.get(); |
13260 | |
13261 | break; |
13262 | } |
13263 | } |
13264 | |
13265 | case OR_No_Viable_Function: { |
13266 | PartialDiagnostic PD = CandidateSet.empty() |
13267 | ? (PDiag(diag::err_ovl_no_oper) |
13268 | << Args[0]->getType() << /*subscript*/ 0 |
13269 | << Args[0]->getSourceRange() << Args[1]->getSourceRange()) |
13270 | : (PDiag(diag::err_ovl_no_viable_subscript) |
13271 | << Args[0]->getType() << Args[0]->getSourceRange() |
13272 | << Args[1]->getSourceRange()); |
13273 | CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, |
13274 | OCD_AllCandidates, Args, "[]", LLoc); |
13275 | return ExprError(); |
13276 | } |
13277 | |
13278 | case OR_Ambiguous: |
13279 | CandidateSet.NoteCandidates( |
13280 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
13281 | << "[]" << Args[0]->getType() |
13282 | << Args[1]->getType() |
13283 | << Args[0]->getSourceRange() |
13284 | << Args[1]->getSourceRange()), |
13285 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); |
13286 | return ExprError(); |
13287 | |
13288 | case OR_Deleted: |
13289 | CandidateSet.NoteCandidates( |
13290 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) |
13291 | << "[]" << Args[0]->getSourceRange() |
13292 | << Args[1]->getSourceRange()), |
13293 | *this, OCD_AllCandidates, Args, "[]", LLoc); |
13294 | return ExprError(); |
13295 | } |
13296 | |
13297 | // We matched a built-in operator; build it. |
13298 | return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); |
13299 | } |
13300 | |
13301 | /// BuildCallToMemberFunction - Build a call to a member |
13302 | /// function. MemExpr is the expression that refers to the member |
13303 | /// function (and includes the object parameter), Args/NumArgs are the |
13304 | /// arguments to the function call (not including the object |
13305 | /// parameter). The caller needs to validate that the member |
13306 | /// expression refers to a non-static member function or an overloaded |
13307 | /// member function. |
13308 | ExprResult |
13309 | Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, |
13310 | SourceLocation LParenLoc, |
13311 | MultiExprArg Args, |
13312 | SourceLocation RParenLoc) { |
13313 | assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE ->getType() == Context.OverloadTy) ? static_cast<void> (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13314, __PRETTY_FUNCTION__)) |
13314 | MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE ->getType() == Context.OverloadTy) ? static_cast<void> (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13314, __PRETTY_FUNCTION__)); |
13315 | |
13316 | // Dig out the member expression. This holds both the object |
13317 | // argument and the member function we're referring to. |
13318 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); |
13319 | |
13320 | // Determine whether this is a call to a pointer-to-member function. |
13321 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { |
13322 | assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast< void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13322, __PRETTY_FUNCTION__)); |
13323 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI ) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13323, __PRETTY_FUNCTION__)); |
13324 | |
13325 | QualType fnType = |
13326 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); |
13327 | |
13328 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); |
13329 | QualType resultType = proto->getCallResultType(Context); |
13330 | ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); |
13331 | |
13332 | // Check that the object type isn't more qualified than the |
13333 | // member function we're calling. |
13334 | Qualifiers funcQuals = proto->getMethodQuals(); |
13335 | |
13336 | QualType objectType = op->getLHS()->getType(); |
13337 | if (op->getOpcode() == BO_PtrMemI) |
13338 | objectType = objectType->castAs<PointerType>()->getPointeeType(); |
13339 | Qualifiers objectQuals = objectType.getQualifiers(); |
13340 | |
13341 | Qualifiers difference = objectQuals - funcQuals; |
13342 | difference.removeObjCGCAttr(); |
13343 | difference.removeAddressSpace(); |
13344 | if (difference) { |
13345 | std::string qualsString = difference.getAsString(); |
13346 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) |
13347 | << fnType.getUnqualifiedType() |
13348 | << qualsString |
13349 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); |
13350 | } |
13351 | |
13352 | CXXMemberCallExpr *call = |
13353 | CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, |
13354 | valueKind, RParenLoc, proto->getNumParams()); |
13355 | |
13356 | if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), |
13357 | call, nullptr)) |
13358 | return ExprError(); |
13359 | |
13360 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) |
13361 | return ExprError(); |
13362 | |
13363 | if (CheckOtherCall(call, proto)) |
13364 | return ExprError(); |
13365 | |
13366 | return MaybeBindToTemporary(call); |
13367 | } |
13368 | |
13369 | if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) |
13370 | return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, |
13371 | RParenLoc); |
13372 | |
13373 | UnbridgedCastsSet UnbridgedCasts; |
13374 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
13375 | return ExprError(); |
13376 | |
13377 | MemberExpr *MemExpr; |
13378 | CXXMethodDecl *Method = nullptr; |
13379 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); |
13380 | NestedNameSpecifier *Qualifier = nullptr; |
13381 | if (isa<MemberExpr>(NakedMemExpr)) { |
13382 | MemExpr = cast<MemberExpr>(NakedMemExpr); |
13383 | Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); |
13384 | FoundDecl = MemExpr->getFoundDecl(); |
13385 | Qualifier = MemExpr->getQualifier(); |
13386 | UnbridgedCasts.restore(); |
13387 | } else { |
13388 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); |
13389 | Qualifier = UnresExpr->getQualifier(); |
13390 | |
13391 | QualType ObjectType = UnresExpr->getBaseType(); |
13392 | Expr::Classification ObjectClassification |
13393 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() |
13394 | : UnresExpr->getBase()->Classify(Context); |
13395 | |
13396 | // Add overload candidates |
13397 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), |
13398 | OverloadCandidateSet::CSK_Normal); |
13399 | |
13400 | // FIXME: avoid copy. |
13401 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
13402 | if (UnresExpr->hasExplicitTemplateArgs()) { |
13403 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
13404 | TemplateArgs = &TemplateArgsBuffer; |
13405 | } |
13406 | |
13407 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), |
13408 | E = UnresExpr->decls_end(); I != E; ++I) { |
13409 | |
13410 | NamedDecl *Func = *I; |
13411 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); |
13412 | if (isa<UsingShadowDecl>(Func)) |
13413 | Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); |
13414 | |
13415 | |
13416 | // Microsoft supports direct constructor calls. |
13417 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { |
13418 | AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, |
13419 | CandidateSet, |
13420 | /*SuppressUserConversions*/ false); |
13421 | } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { |
13422 | // If explicit template arguments were provided, we can't call a |
13423 | // non-template member function. |
13424 | if (TemplateArgs) |
13425 | continue; |
13426 | |
13427 | AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, |
13428 | ObjectClassification, Args, CandidateSet, |
13429 | /*SuppressUserConversions=*/false); |
13430 | } else { |
13431 | AddMethodTemplateCandidate( |
13432 | cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, |
13433 | TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, |
13434 | /*SuppressUserConversions=*/false); |
13435 | } |
13436 | } |
13437 | |
13438 | DeclarationName DeclName = UnresExpr->getMemberName(); |
13439 | |
13440 | UnbridgedCasts.restore(); |
13441 | |
13442 | OverloadCandidateSet::iterator Best; |
13443 | switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), |
13444 | Best)) { |
13445 | case OR_Success: |
13446 | Method = cast<CXXMethodDecl>(Best->Function); |
13447 | FoundDecl = Best->FoundDecl; |
13448 | CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); |
13449 | if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) |
13450 | return ExprError(); |
13451 | // If FoundDecl is different from Method (such as if one is a template |
13452 | // and the other a specialization), make sure DiagnoseUseOfDecl is |
13453 | // called on both. |
13454 | // FIXME: This would be more comprehensively addressed by modifying |
13455 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
13456 | // being used. |
13457 | if (Method != FoundDecl.getDecl() && |
13458 | DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) |
13459 | return ExprError(); |
13460 | break; |
13461 | |
13462 | case OR_No_Viable_Function: |
13463 | CandidateSet.NoteCandidates( |
13464 | PartialDiagnosticAt( |
13465 | UnresExpr->getMemberLoc(), |
13466 | PDiag(diag::err_ovl_no_viable_member_function_in_call) |
13467 | << DeclName << MemExprE->getSourceRange()), |
13468 | *this, OCD_AllCandidates, Args); |
13469 | // FIXME: Leaking incoming expressions! |
13470 | return ExprError(); |
13471 | |
13472 | case OR_Ambiguous: |
13473 | CandidateSet.NoteCandidates( |
13474 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
13475 | PDiag(diag::err_ovl_ambiguous_member_call) |
13476 | << DeclName << MemExprE->getSourceRange()), |
13477 | *this, OCD_AmbiguousCandidates, Args); |
13478 | // FIXME: Leaking incoming expressions! |
13479 | return ExprError(); |
13480 | |
13481 | case OR_Deleted: |
13482 | CandidateSet.NoteCandidates( |
13483 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
13484 | PDiag(diag::err_ovl_deleted_member_call) |
13485 | << DeclName << MemExprE->getSourceRange()), |
13486 | *this, OCD_AllCandidates, Args); |
13487 | // FIXME: Leaking incoming expressions! |
13488 | return ExprError(); |
13489 | } |
13490 | |
13491 | MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); |
13492 | |
13493 | // If overload resolution picked a static member, build a |
13494 | // non-member call based on that function. |
13495 | if (Method->isStatic()) { |
13496 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, |
13497 | RParenLoc); |
13498 | } |
13499 | |
13500 | MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); |
13501 | } |
13502 | |
13503 | QualType ResultType = Method->getReturnType(); |
13504 | ExprValueKind VK = Expr::getValueKindForType(ResultType); |
13505 | ResultType = ResultType.getNonLValueExprType(Context); |
13506 | |
13507 | assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?" ) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13507, __PRETTY_FUNCTION__)); |
13508 | const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); |
13509 | CXXMemberCallExpr *TheCall = |
13510 | CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, |
13511 | RParenLoc, Proto->getNumParams()); |
13512 | |
13513 | // Check for a valid return type. |
13514 | if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), |
13515 | TheCall, Method)) |
13516 | return ExprError(); |
13517 | |
13518 | // Convert the object argument (for a non-static member function call). |
13519 | // We only need to do this if there was actually an overload; otherwise |
13520 | // it was done at lookup. |
13521 | if (!Method->isStatic()) { |
13522 | ExprResult ObjectArg = |
13523 | PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, |
13524 | FoundDecl, Method); |
13525 | if (ObjectArg.isInvalid()) |
13526 | return ExprError(); |
13527 | MemExpr->setBase(ObjectArg.get()); |
13528 | } |
13529 | |
13530 | // Convert the rest of the arguments |
13531 | if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, |
13532 | RParenLoc)) |
13533 | return ExprError(); |
13534 | |
13535 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
13536 | |
13537 | if (CheckFunctionCall(Method, TheCall, Proto)) |
13538 | return ExprError(); |
13539 | |
13540 | // In the case the method to call was not selected by the overloading |
13541 | // resolution process, we still need to handle the enable_if attribute. Do |
13542 | // that here, so it will not hide previous -- and more relevant -- errors. |
13543 | if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { |
13544 | if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { |
13545 | Diag(MemE->getMemberLoc(), |
13546 | diag::err_ovl_no_viable_member_function_in_call) |
13547 | << Method << Method->getSourceRange(); |
13548 | Diag(Method->getLocation(), |
13549 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
13550 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
13551 | return ExprError(); |
13552 | } |
13553 | } |
13554 | |
13555 | if ((isa<CXXConstructorDecl>(CurContext) || |
13556 | isa<CXXDestructorDecl>(CurContext)) && |
13557 | TheCall->getMethodDecl()->isPure()) { |
13558 | const CXXMethodDecl *MD = TheCall->getMethodDecl(); |
13559 | |
13560 | if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && |
13561 | MemExpr->performsVirtualDispatch(getLangOpts())) { |
13562 | Diag(MemExpr->getBeginLoc(), |
13563 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) |
13564 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) |
13565 | << MD->getParent()->getDeclName(); |
13566 | |
13567 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); |
13568 | if (getLangOpts().AppleKext) |
13569 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) |
13570 | << MD->getParent()->getDeclName() << MD->getDeclName(); |
13571 | } |
13572 | } |
13573 | |
13574 | if (CXXDestructorDecl *DD = |
13575 | dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { |
13576 | // a->A::f() doesn't go through the vtable, except in AppleKext mode. |
13577 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; |
13578 | CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, |
13579 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, |
13580 | MemExpr->getMemberLoc()); |
13581 | } |
13582 | |
13583 | return MaybeBindToTemporary(TheCall); |
13584 | } |
13585 | |
13586 | /// BuildCallToObjectOfClassType - Build a call to an object of class |
13587 | /// type (C++ [over.call.object]), which can end up invoking an |
13588 | /// overloaded function call operator (@c operator()) or performing a |
13589 | /// user-defined conversion on the object argument. |
13590 | ExprResult |
13591 | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, |
13592 | SourceLocation LParenLoc, |
13593 | MultiExprArg Args, |
13594 | SourceLocation RParenLoc) { |
13595 | if (checkPlaceholderForOverload(*this, Obj)) |
13596 | return ExprError(); |
13597 | ExprResult Object = Obj; |
13598 | |
13599 | UnbridgedCastsSet UnbridgedCasts; |
13600 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
13601 | return ExprError(); |
13602 | |
13603 | assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument" ) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13604, __PRETTY_FUNCTION__)) |
13604 | "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument" ) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13604, __PRETTY_FUNCTION__)); |
13605 | const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); |
13606 | |
13607 | // C++ [over.call.object]p1: |
13608 | // If the primary-expression E in the function call syntax |
13609 | // evaluates to a class object of type "cv T", then the set of |
13610 | // candidate functions includes at least the function call |
13611 | // operators of T. The function call operators of T are obtained by |
13612 | // ordinary lookup of the name operator() in the context of |
13613 | // (E).operator(). |
13614 | OverloadCandidateSet CandidateSet(LParenLoc, |
13615 | OverloadCandidateSet::CSK_Operator); |
13616 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); |
13617 | |
13618 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), |
13619 | diag::err_incomplete_object_call, Object.get())) |
13620 | return true; |
13621 | |
13622 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); |
13623 | LookupQualifiedName(R, Record->getDecl()); |
13624 | R.suppressDiagnostics(); |
13625 | |
13626 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
13627 | Oper != OperEnd; ++Oper) { |
13628 | AddMethodCandidate(Oper.getPair(), Object.get()->getType(), |
13629 | Object.get()->Classify(Context), Args, CandidateSet, |
13630 | /*SuppressUserConversion=*/false); |
13631 | } |
13632 | |
13633 | // C++ [over.call.object]p2: |
13634 | // In addition, for each (non-explicit in C++0x) conversion function |
13635 | // declared in T of the form |
13636 | // |
13637 | // operator conversion-type-id () cv-qualifier; |
13638 | // |
13639 | // where cv-qualifier is the same cv-qualification as, or a |
13640 | // greater cv-qualification than, cv, and where conversion-type-id |
13641 | // denotes the type "pointer to function of (P1,...,Pn) returning |
13642 | // R", or the type "reference to pointer to function of |
13643 | // (P1,...,Pn) returning R", or the type "reference to function |
13644 | // of (P1,...,Pn) returning R", a surrogate call function [...] |
13645 | // is also considered as a candidate function. Similarly, |
13646 | // surrogate call functions are added to the set of candidate |
13647 | // functions for each conversion function declared in an |
13648 | // accessible base class provided the function is not hidden |
13649 | // within T by another intervening declaration. |
13650 | const auto &Conversions = |
13651 | cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); |
13652 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
13653 | NamedDecl *D = *I; |
13654 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
13655 | if (isa<UsingShadowDecl>(D)) |
13656 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
13657 | |
13658 | // Skip over templated conversion functions; they aren't |
13659 | // surrogates. |
13660 | if (isa<FunctionTemplateDecl>(D)) |
13661 | continue; |
13662 | |
13663 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
13664 | if (!Conv->isExplicit()) { |
13665 | // Strip the reference type (if any) and then the pointer type (if |
13666 | // any) to get down to what might be a function type. |
13667 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); |
13668 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
13669 | ConvType = ConvPtrType->getPointeeType(); |
13670 | |
13671 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) |
13672 | { |
13673 | AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, |
13674 | Object.get(), Args, CandidateSet); |
13675 | } |
13676 | } |
13677 | } |
13678 | |
13679 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
13680 | |
13681 | // Perform overload resolution. |
13682 | OverloadCandidateSet::iterator Best; |
13683 | switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), |
13684 | Best)) { |
13685 | case OR_Success: |
13686 | // Overload resolution succeeded; we'll build the appropriate call |
13687 | // below. |
13688 | break; |
13689 | |
13690 | case OR_No_Viable_Function: { |
13691 | PartialDiagnostic PD = |
13692 | CandidateSet.empty() |
13693 | ? (PDiag(diag::err_ovl_no_oper) |
13694 | << Object.get()->getType() << /*call*/ 1 |
13695 | << Object.get()->getSourceRange()) |
13696 | : (PDiag(diag::err_ovl_no_viable_object_call) |
13697 | << Object.get()->getType() << Object.get()->getSourceRange()); |
13698 | CandidateSet.NoteCandidates( |
13699 | PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, |
13700 | OCD_AllCandidates, Args); |
13701 | break; |
13702 | } |
13703 | case OR_Ambiguous: |
13704 | CandidateSet.NoteCandidates( |
13705 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
13706 | PDiag(diag::err_ovl_ambiguous_object_call) |
13707 | << Object.get()->getType() |
13708 | << Object.get()->getSourceRange()), |
13709 | *this, OCD_AmbiguousCandidates, Args); |
13710 | break; |
13711 | |
13712 | case OR_Deleted: |
13713 | CandidateSet.NoteCandidates( |
13714 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
13715 | PDiag(diag::err_ovl_deleted_object_call) |
13716 | << Object.get()->getType() |
13717 | << Object.get()->getSourceRange()), |
13718 | *this, OCD_AllCandidates, Args); |
13719 | break; |
13720 | } |
13721 | |
13722 | if (Best == CandidateSet.end()) |
13723 | return true; |
13724 | |
13725 | UnbridgedCasts.restore(); |
13726 | |
13727 | if (Best->Function == nullptr) { |
13728 | // Since there is no function declaration, this is one of the |
13729 | // surrogate candidates. Dig out the conversion function. |
13730 | CXXConversionDecl *Conv |
13731 | = cast<CXXConversionDecl>( |
13732 | Best->Conversions[0].UserDefined.ConversionFunction); |
13733 | |
13734 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, |
13735 | Best->FoundDecl); |
13736 | if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) |
13737 | return ExprError(); |
13738 | assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13739, __PRETTY_FUNCTION__)) |
13739 | "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13739, __PRETTY_FUNCTION__)); |
13740 | // We selected one of the surrogate functions that converts the |
13741 | // object parameter to a function pointer. Perform the conversion |
13742 | // on the object argument, then let BuildCallExpr finish the job. |
13743 | |
13744 | // Create an implicit member expr to refer to the conversion operator. |
13745 | // and then call it. |
13746 | ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, |
13747 | Conv, HadMultipleCandidates); |
13748 | if (Call.isInvalid()) |
13749 | return ExprError(); |
13750 | // Record usage of conversion in an implicit cast. |
13751 | Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), |
13752 | CK_UserDefinedConversion, Call.get(), |
13753 | nullptr, VK_RValue); |
13754 | |
13755 | return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); |
13756 | } |
13757 | |
13758 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); |
13759 | |
13760 | // We found an overloaded operator(). Build a CXXOperatorCallExpr |
13761 | // that calls this method, using Object for the implicit object |
13762 | // parameter and passing along the remaining arguments. |
13763 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
13764 | |
13765 | // An error diagnostic has already been printed when parsing the declaration. |
13766 | if (Method->isInvalidDecl()) |
13767 | return ExprError(); |
13768 | |
13769 | const FunctionProtoType *Proto = |
13770 | Method->getType()->getAs<FunctionProtoType>(); |
13771 | |
13772 | unsigned NumParams = Proto->getNumParams(); |
13773 | |
13774 | DeclarationNameInfo OpLocInfo( |
13775 | Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); |
13776 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); |
13777 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
13778 | Obj, HadMultipleCandidates, |
13779 | OpLocInfo.getLoc(), |
13780 | OpLocInfo.getInfo()); |
13781 | if (NewFn.isInvalid()) |
13782 | return true; |
13783 | |
13784 | // The number of argument slots to allocate in the call. If we have default |
13785 | // arguments we need to allocate space for them as well. We additionally |
13786 | // need one more slot for the object parameter. |
13787 | unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); |
13788 | |
13789 | // Build the full argument list for the method call (the implicit object |
13790 | // parameter is placed at the beginning of the list). |
13791 | SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); |
13792 | |
13793 | bool IsError = false; |
13794 | |
13795 | // Initialize the implicit object parameter. |
13796 | ExprResult ObjRes = |
13797 | PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, |
13798 | Best->FoundDecl, Method); |
13799 | if (ObjRes.isInvalid()) |
13800 | IsError = true; |
13801 | else |
13802 | Object = ObjRes; |
13803 | MethodArgs[0] = Object.get(); |
13804 | |
13805 | // Check the argument types. |
13806 | for (unsigned i = 0; i != NumParams; i++) { |
13807 | Expr *Arg; |
13808 | if (i < Args.size()) { |
13809 | Arg = Args[i]; |
13810 | |
13811 | // Pass the argument. |
13812 | |
13813 | ExprResult InputInit |
13814 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( |
13815 | Context, |
13816 | Method->getParamDecl(i)), |
13817 | SourceLocation(), Arg); |
13818 | |
13819 | IsError |= InputInit.isInvalid(); |
13820 | Arg = InputInit.getAs<Expr>(); |
13821 | } else { |
13822 | ExprResult DefArg |
13823 | = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); |
13824 | if (DefArg.isInvalid()) { |
13825 | IsError = true; |
13826 | break; |
13827 | } |
13828 | |
13829 | Arg = DefArg.getAs<Expr>(); |
13830 | } |
13831 | |
13832 | MethodArgs[i + 1] = Arg; |
13833 | } |
13834 | |
13835 | // If this is a variadic call, handle args passed through "...". |
13836 | if (Proto->isVariadic()) { |
13837 | // Promote the arguments (C99 6.5.2.2p7). |
13838 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { |
13839 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
13840 | nullptr); |
13841 | IsError |= Arg.isInvalid(); |
13842 | MethodArgs[i + 1] = Arg.get(); |
13843 | } |
13844 | } |
13845 | |
13846 | if (IsError) |
13847 | return true; |
13848 | |
13849 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
13850 | |
13851 | // Once we've built TheCall, all of the expressions are properly owned. |
13852 | QualType ResultTy = Method->getReturnType(); |
13853 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
13854 | ResultTy = ResultTy.getNonLValueExprType(Context); |
13855 | |
13856 | CXXOperatorCallExpr *TheCall = |
13857 | CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, |
13858 | ResultTy, VK, RParenLoc, FPOptions()); |
13859 | |
13860 | if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) |
13861 | return true; |
13862 | |
13863 | if (CheckFunctionCall(Method, TheCall, Proto)) |
13864 | return true; |
13865 | |
13866 | return MaybeBindToTemporary(TheCall); |
13867 | } |
13868 | |
13869 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> |
13870 | /// (if one exists), where @c Base is an expression of class type and |
13871 | /// @c Member is the name of the member we're trying to find. |
13872 | ExprResult |
13873 | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, |
13874 | bool *NoArrowOperatorFound) { |
13875 | assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type" ) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13876, __PRETTY_FUNCTION__)) |
13876 | "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type" ) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 13876, __PRETTY_FUNCTION__)); |
13877 | |
13878 | if (checkPlaceholderForOverload(*this, Base)) |
13879 | return ExprError(); |
13880 | |
13881 | SourceLocation Loc = Base->getExprLoc(); |
13882 | |
13883 | // C++ [over.ref]p1: |
13884 | // |
13885 | // [...] An expression x->m is interpreted as (x.operator->())->m |
13886 | // for a class object x of type T if T::operator->() exists and if |
13887 | // the operator is selected as the best match function by the |
13888 | // overload resolution mechanism (13.3). |
13889 | DeclarationName OpName = |
13890 | Context.DeclarationNames.getCXXOperatorName(OO_Arrow); |
13891 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); |
13892 | const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); |
13893 | |
13894 | if (RequireCompleteType(Loc, Base->getType(), |
13895 | diag::err_typecheck_incomplete_tag, Base)) |
13896 | return ExprError(); |
13897 | |
13898 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); |
13899 | LookupQualifiedName(R, BaseRecord->getDecl()); |
13900 | R.suppressDiagnostics(); |
13901 | |
13902 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
13903 | Oper != OperEnd; ++Oper) { |
13904 | AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), |
13905 | None, CandidateSet, /*SuppressUserConversion=*/false); |
13906 | } |
13907 | |
13908 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
13909 | |
13910 | // Perform overload resolution. |
13911 | OverloadCandidateSet::iterator Best; |
13912 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
13913 | case OR_Success: |
13914 | // Overload resolution succeeded; we'll build the call below. |
13915 | break; |
13916 | |
13917 | case OR_No_Viable_Function: { |
13918 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); |
13919 | if (CandidateSet.empty()) { |
13920 | QualType BaseType = Base->getType(); |
13921 | if (NoArrowOperatorFound) { |
13922 | // Report this specific error to the caller instead of emitting a |
13923 | // diagnostic, as requested. |
13924 | *NoArrowOperatorFound = true; |
13925 | return ExprError(); |
13926 | } |
13927 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
13928 | << BaseType << Base->getSourceRange(); |
13929 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { |
13930 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) |
13931 | << FixItHint::CreateReplacement(OpLoc, "."); |
13932 | } |
13933 | } else |
13934 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
13935 | << "operator->" << Base->getSourceRange(); |
13936 | CandidateSet.NoteCandidates(*this, Base, Cands); |
13937 | return ExprError(); |
13938 | } |
13939 | case OR_Ambiguous: |
13940 | CandidateSet.NoteCandidates( |
13941 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) |
13942 | << "->" << Base->getType() |
13943 | << Base->getSourceRange()), |
13944 | *this, OCD_AmbiguousCandidates, Base); |
13945 | return ExprError(); |
13946 | |
13947 | case OR_Deleted: |
13948 | CandidateSet.NoteCandidates( |
13949 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
13950 | << "->" << Base->getSourceRange()), |
13951 | *this, OCD_AllCandidates, Base); |
13952 | return ExprError(); |
13953 | } |
13954 | |
13955 | CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); |
13956 | |
13957 | // Convert the object parameter. |
13958 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
13959 | ExprResult BaseResult = |
13960 | PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, |
13961 | Best->FoundDecl, Method); |
13962 | if (BaseResult.isInvalid()) |
13963 | return ExprError(); |
13964 | Base = BaseResult.get(); |
13965 | |
13966 | // Build the operator call. |
13967 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
13968 | Base, HadMultipleCandidates, OpLoc); |
13969 | if (FnExpr.isInvalid()) |
13970 | return ExprError(); |
13971 | |
13972 | QualType ResultTy = Method->getReturnType(); |
13973 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
13974 | ResultTy = ResultTy.getNonLValueExprType(Context); |
13975 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( |
13976 | Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); |
13977 | |
13978 | if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) |
13979 | return ExprError(); |
13980 | |
13981 | if (CheckFunctionCall(Method, TheCall, |
13982 | Method->getType()->castAs<FunctionProtoType>())) |
13983 | return ExprError(); |
13984 | |
13985 | return MaybeBindToTemporary(TheCall); |
13986 | } |
13987 | |
13988 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to |
13989 | /// a literal operator described by the provided lookup results. |
13990 | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, |
13991 | DeclarationNameInfo &SuffixInfo, |
13992 | ArrayRef<Expr*> Args, |
13993 | SourceLocation LitEndLoc, |
13994 | TemplateArgumentListInfo *TemplateArgs) { |
13995 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); |
13996 | |
13997 | OverloadCandidateSet CandidateSet(UDSuffixLoc, |
13998 | OverloadCandidateSet::CSK_Normal); |
13999 | AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, |
14000 | TemplateArgs); |
14001 | |
14002 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14003 | |
14004 | // Perform overload resolution. This will usually be trivial, but might need |
14005 | // to perform substitutions for a literal operator template. |
14006 | OverloadCandidateSet::iterator Best; |
14007 | switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { |
14008 | case OR_Success: |
14009 | case OR_Deleted: |
14010 | break; |
14011 | |
14012 | case OR_No_Viable_Function: |
14013 | CandidateSet.NoteCandidates( |
14014 | PartialDiagnosticAt(UDSuffixLoc, |
14015 | PDiag(diag::err_ovl_no_viable_function_in_call) |
14016 | << R.getLookupName()), |
14017 | *this, OCD_AllCandidates, Args); |
14018 | return ExprError(); |
14019 | |
14020 | case OR_Ambiguous: |
14021 | CandidateSet.NoteCandidates( |
14022 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) |
14023 | << R.getLookupName()), |
14024 | *this, OCD_AmbiguousCandidates, Args); |
14025 | return ExprError(); |
14026 | } |
14027 | |
14028 | FunctionDecl *FD = Best->Function; |
14029 | ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, |
14030 | nullptr, HadMultipleCandidates, |
14031 | SuffixInfo.getLoc(), |
14032 | SuffixInfo.getInfo()); |
14033 | if (Fn.isInvalid()) |
14034 | return true; |
14035 | |
14036 | // Check the argument types. This should almost always be a no-op, except |
14037 | // that array-to-pointer decay is applied to string literals. |
14038 | Expr *ConvArgs[2]; |
14039 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
14040 | ExprResult InputInit = PerformCopyInitialization( |
14041 | InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), |
14042 | SourceLocation(), Args[ArgIdx]); |
14043 | if (InputInit.isInvalid()) |
14044 | return true; |
14045 | ConvArgs[ArgIdx] = InputInit.get(); |
14046 | } |
14047 | |
14048 | QualType ResultTy = FD->getReturnType(); |
14049 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
14050 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14051 | |
14052 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( |
14053 | Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, |
14054 | VK, LitEndLoc, UDSuffixLoc); |
14055 | |
14056 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) |
14057 | return ExprError(); |
14058 | |
14059 | if (CheckFunctionCall(FD, UDL, nullptr)) |
14060 | return ExprError(); |
14061 | |
14062 | return MaybeBindToTemporary(UDL); |
14063 | } |
14064 | |
14065 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the |
14066 | /// given LookupResult is non-empty, it is assumed to describe a member which |
14067 | /// will be invoked. Otherwise, the function will be found via argument |
14068 | /// dependent lookup. |
14069 | /// CallExpr is set to a valid expression and FRS_Success returned on success, |
14070 | /// otherwise CallExpr is set to ExprError() and some non-success value |
14071 | /// is returned. |
14072 | Sema::ForRangeStatus |
14073 | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, |
14074 | SourceLocation RangeLoc, |
14075 | const DeclarationNameInfo &NameInfo, |
14076 | LookupResult &MemberLookup, |
14077 | OverloadCandidateSet *CandidateSet, |
14078 | Expr *Range, ExprResult *CallExpr) { |
14079 | Scope *S = nullptr; |
14080 | |
14081 | CandidateSet->clear(OverloadCandidateSet::CSK_Normal); |
14082 | if (!MemberLookup.empty()) { |
14083 | ExprResult MemberRef = |
14084 | BuildMemberReferenceExpr(Range, Range->getType(), Loc, |
14085 | /*IsPtr=*/false, CXXScopeSpec(), |
14086 | /*TemplateKWLoc=*/SourceLocation(), |
14087 | /*FirstQualifierInScope=*/nullptr, |
14088 | MemberLookup, |
14089 | /*TemplateArgs=*/nullptr, S); |
14090 | if (MemberRef.isInvalid()) { |
14091 | *CallExpr = ExprError(); |
14092 | return FRS_DiagnosticIssued; |
14093 | } |
14094 | *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); |
14095 | if (CallExpr->isInvalid()) { |
14096 | *CallExpr = ExprError(); |
14097 | return FRS_DiagnosticIssued; |
14098 | } |
14099 | } else { |
14100 | UnresolvedSet<0> FoundNames; |
14101 | UnresolvedLookupExpr *Fn = |
14102 | UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, |
14103 | NestedNameSpecifierLoc(), NameInfo, |
14104 | /*NeedsADL=*/true, /*Overloaded=*/false, |
14105 | FoundNames.begin(), FoundNames.end()); |
14106 | |
14107 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, |
14108 | CandidateSet, CallExpr); |
14109 | if (CandidateSet->empty() || CandidateSetError) { |
14110 | *CallExpr = ExprError(); |
14111 | return FRS_NoViableFunction; |
14112 | } |
14113 | OverloadCandidateSet::iterator Best; |
14114 | OverloadingResult OverloadResult = |
14115 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); |
14116 | |
14117 | if (OverloadResult == OR_No_Viable_Function) { |
14118 | *CallExpr = ExprError(); |
14119 | return FRS_NoViableFunction; |
14120 | } |
14121 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, |
14122 | Loc, nullptr, CandidateSet, &Best, |
14123 | OverloadResult, |
14124 | /*AllowTypoCorrection=*/false); |
14125 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { |
14126 | *CallExpr = ExprError(); |
14127 | return FRS_DiagnosticIssued; |
14128 | } |
14129 | } |
14130 | return FRS_Success; |
14131 | } |
14132 | |
14133 | |
14134 | /// FixOverloadedFunctionReference - E is an expression that refers to |
14135 | /// a C++ overloaded function (possibly with some parentheses and |
14136 | /// perhaps a '&' around it). We have resolved the overloaded function |
14137 | /// to the function declaration Fn, so patch up the expression E to |
14138 | /// refer (possibly indirectly) to Fn. Returns the new expr. |
14139 | Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, |
14140 | FunctionDecl *Fn) { |
14141 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { |
14142 | Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), |
14143 | Found, Fn); |
14144 | if (SubExpr == PE->getSubExpr()) |
14145 | return PE; |
14146 | |
14147 | return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); |
14148 | } |
14149 | |
14150 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { |
14151 | Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), |
14152 | Found, Fn); |
14153 | assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14155, __PRETTY_FUNCTION__)) |
14154 | SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14155, __PRETTY_FUNCTION__)) |
14155 | "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14155, __PRETTY_FUNCTION__)); |
14156 | assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?" ) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14156, __PRETTY_FUNCTION__)); |
14157 | if (SubExpr == ICE->getSubExpr()) |
14158 | return ICE; |
14159 | |
14160 | return ImplicitCastExpr::Create(Context, ICE->getType(), |
14161 | ICE->getCastKind(), |
14162 | SubExpr, nullptr, |
14163 | ICE->getValueKind()); |
14164 | } |
14165 | |
14166 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { |
14167 | if (!GSE->isResultDependent()) { |
14168 | Expr *SubExpr = |
14169 | FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); |
14170 | if (SubExpr == GSE->getResultExpr()) |
14171 | return GSE; |
14172 | |
14173 | // Replace the resulting type information before rebuilding the generic |
14174 | // selection expression. |
14175 | ArrayRef<Expr *> A = GSE->getAssocExprs(); |
14176 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); |
14177 | unsigned ResultIdx = GSE->getResultIndex(); |
14178 | AssocExprs[ResultIdx] = SubExpr; |
14179 | |
14180 | return GenericSelectionExpr::Create( |
14181 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), |
14182 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
14183 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
14184 | ResultIdx); |
14185 | } |
14186 | // Rather than fall through to the unreachable, return the original generic |
14187 | // selection expression. |
14188 | return GSE; |
14189 | } |
14190 | |
14191 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { |
14192 | assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function" ) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14193, __PRETTY_FUNCTION__)) |
14193 | "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function" ) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14193, __PRETTY_FUNCTION__)); |
14194 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
14195 | if (Method->isStatic()) { |
14196 | // Do nothing: static member functions aren't any different |
14197 | // from non-member functions. |
14198 | } else { |
14199 | // Fix the subexpression, which really has to be an |
14200 | // UnresolvedLookupExpr holding an overloaded member function |
14201 | // or template. |
14202 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), |
14203 | Found, Fn); |
14204 | if (SubExpr == UnOp->getSubExpr()) |
14205 | return UnOp; |
14206 | |
14207 | assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref" ) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14208, __PRETTY_FUNCTION__)) |
14208 | && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref" ) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14208, __PRETTY_FUNCTION__)); |
14209 | assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() && "fixed to a member ref with no nested name qualifier") ? static_cast <void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14210, __PRETTY_FUNCTION__)) |
14210 | && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() && "fixed to a member ref with no nested name qualifier") ? static_cast <void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14210, __PRETTY_FUNCTION__)); |
14211 | |
14212 | // We have taken the address of a pointer to member |
14213 | // function. Perform the computation here so that we get the |
14214 | // appropriate pointer to member type. |
14215 | QualType ClassType |
14216 | = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); |
14217 | QualType MemPtrType |
14218 | = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); |
14219 | // Under the MS ABI, lock down the inheritance model now. |
14220 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
14221 | (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); |
14222 | |
14223 | return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, |
14224 | VK_RValue, OK_Ordinary, |
14225 | UnOp->getOperatorLoc(), false); |
14226 | } |
14227 | } |
14228 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), |
14229 | Found, Fn); |
14230 | if (SubExpr == UnOp->getSubExpr()) |
14231 | return UnOp; |
14232 | |
14233 | return new (Context) UnaryOperator(SubExpr, UO_AddrOf, |
14234 | Context.getPointerType(SubExpr->getType()), |
14235 | VK_RValue, OK_Ordinary, |
14236 | UnOp->getOperatorLoc(), false); |
14237 | } |
14238 | |
14239 | // C++ [except.spec]p17: |
14240 | // An exception-specification is considered to be needed when: |
14241 | // - in an expression the function is the unique lookup result or the |
14242 | // selected member of a set of overloaded functions |
14243 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
14244 | ResolveExceptionSpec(E->getExprLoc(), FPT); |
14245 | |
14246 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { |
14247 | // FIXME: avoid copy. |
14248 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
14249 | if (ULE->hasExplicitTemplateArgs()) { |
14250 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); |
14251 | TemplateArgs = &TemplateArgsBuffer; |
14252 | } |
14253 | |
14254 | DeclRefExpr *DRE = |
14255 | BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), |
14256 | ULE->getQualifierLoc(), Found.getDecl(), |
14257 | ULE->getTemplateKeywordLoc(), TemplateArgs); |
14258 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); |
14259 | return DRE; |
14260 | } |
14261 | |
14262 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { |
14263 | // FIXME: avoid copy. |
14264 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
14265 | if (MemExpr->hasExplicitTemplateArgs()) { |
14266 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
14267 | TemplateArgs = &TemplateArgsBuffer; |
14268 | } |
14269 | |
14270 | Expr *Base; |
14271 | |
14272 | // If we're filling in a static method where we used to have an |
14273 | // implicit member access, rewrite to a simple decl ref. |
14274 | if (MemExpr->isImplicitAccess()) { |
14275 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
14276 | DeclRefExpr *DRE = BuildDeclRefExpr( |
14277 | Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), |
14278 | MemExpr->getQualifierLoc(), Found.getDecl(), |
14279 | MemExpr->getTemplateKeywordLoc(), TemplateArgs); |
14280 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); |
14281 | return DRE; |
14282 | } else { |
14283 | SourceLocation Loc = MemExpr->getMemberLoc(); |
14284 | if (MemExpr->getQualifier()) |
14285 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); |
14286 | Base = |
14287 | BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); |
14288 | } |
14289 | } else |
14290 | Base = MemExpr->getBase(); |
14291 | |
14292 | ExprValueKind valueKind; |
14293 | QualType type; |
14294 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
14295 | valueKind = VK_LValue; |
14296 | type = Fn->getType(); |
14297 | } else { |
14298 | valueKind = VK_RValue; |
14299 | type = Context.BoundMemberTy; |
14300 | } |
14301 | |
14302 | return BuildMemberExpr( |
14303 | Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), |
14304 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, |
14305 | /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), |
14306 | type, valueKind, OK_Ordinary, TemplateArgs); |
14307 | } |
14308 | |
14309 | llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOverload.cpp" , 14309); |
14310 | } |
14311 | |
14312 | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, |
14313 | DeclAccessPair Found, |
14314 | FunctionDecl *Fn) { |
14315 | return FixOverloadedFunctionReference(E.get(), Found, Fn); |
14316 | } |