Bug Summary

File:clang/lib/Sema/SemaOverload.cpp
Warning:line 3309, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp
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
38using namespace clang;
39using namespace sema;
40
41static 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.
48static ExprResult
49CreateFunctionRefExpr(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 DeclRefExpr *DRE = new (S.Context)
64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
67
68 S.MarkDeclRefReferenced(DRE, Base);
69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71 S.ResolveExceptionSpec(Loc, FPT);
72 DRE->setType(Fn->getType());
73 }
74 }
75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76 CK_FunctionToPointerDecay);
77}
78
79static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle,
83 bool AllowObjCWritebackConversion);
84
85static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86 QualType &ToType,
87 bool InOverloadResolution,
88 StandardConversionSequence &SCS,
89 bool CStyle);
90static OverloadingResult
91IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92 UserDefinedConversionSequence& User,
93 OverloadCandidateSet& Conversions,
94 bool AllowExplicit,
95 bool AllowObjCConversionOnExplicit);
96
97
98static ImplicitConversionSequence::CompareKind
99CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100 const StandardConversionSequence& SCS1,
101 const StandardConversionSequence& SCS2);
102
103static ImplicitConversionSequence::CompareKind
104CompareQualificationConversions(Sema &S,
105 const StandardConversionSequence& SCS1,
106 const StandardConversionSequence& SCS2);
107
108static ImplicitConversionSequence::CompareKind
109CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110 const StandardConversionSequence& SCS1,
111 const StandardConversionSequence& SCS2);
112
113/// GetConversionRank - Retrieve the implicit conversion rank
114/// corresponding to the given implicit conversion kind.
115ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116 static const ImplicitConversionRank
117 Rank[(int)ICK_Num_Conversion_Kinds] = {
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Promotion,
125 ICR_Promotion,
126 ICR_Promotion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_OCL_Scalar_Widening,
138 ICR_Complex_Real_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Writeback_Conversion,
142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143 // it was omitted by the patch that added
144 // ICK_Zero_Event_Conversion
145 ICR_C_Conversion,
146 ICR_C_Conversion_Extension
147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
159 "Function pointer conversion",
160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
163 "Complex promotion",
164 "Integral conversion",
165 "Floating conversion",
166 "Complex conversion",
167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
170 "Boolean conversion",
171 "Compatible-types conversion",
172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion",
178 "Writeback conversion",
179 "OpenCL Zero Event Conversion",
180 "C specific type conversion",
181 "Incompatible pointer conversion"
182 };
183 return Name[Kind];
184}
185
186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
192 DeprecatedStringLiteralToCharPtr = false;
193 QualificationIncludesObjCLifetime = false;
194 ReferenceBinding = false;
195 DirectBinding = false;
196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
200 ObjCLifetimeConversionBinding = false;
201 CopyConstructor = nullptr;
202}
203
204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
220/// used as part of the ranking of standard conversion sequences
221/// (C++ 13.3.3.2p4).
222bool StandardConversionSequence::isPointerConversionToBool() const {
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
227 if (getToType(1)->isBooleanType() &&
228 (getFromType()->isPointerType() ||
229 getFromType()->isMemberPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
232 getFromType()->isNullPtrType() ||
233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
243bool
244StandardConversionSequence::
245isPointerConversionToVoidPointer(ASTContext& Context) const {
246 QualType FromType = getFromType();
247 QualType ToType = getToType(1);
248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265 const Expr *Converted) {
266 // We can have cleanups wrapping the converted expression; these need to be
267 // preserved so that destructors run if necessary.
268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269 Expr *Inner =
270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272 EWC->getObjects());
273 }
274
275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276 switch (ICE->getCastKind()) {
277 case CK_NoOp:
278 case CK_IntegralCast:
279 case CK_IntegralToBoolean:
280 case CK_IntegralToFloating:
281 case CK_BooleanToSignedIntegral:
282 case CK_FloatingToIntegral:
283 case CK_FloatingToBoolean:
284 case CK_FloatingCast:
285 Converted = ICE->getSubExpr();
286 continue;
287
288 default:
289 return Converted;
290 }
291 }
292
293 return Converted;
294}
295
296/// Check if this standard conversion sequence represents a narrowing
297/// conversion, according to C++11 [dcl.init.list]p7.
298///
299/// \param Ctx The AST context.
300/// \param Converted The result of applying this standard conversion sequence.
301/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
302/// value of the expression prior to the narrowing conversion.
303/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
304/// type of the expression prior to the narrowing conversion.
305/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306/// from floating point types to integral types should be ignored.
307NarrowingKind StandardConversionSequence::getNarrowingKind(
308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 310, __PRETTY_FUNCTION__))
;
311
312 // C++11 [dcl.init.list]p7:
313 // A narrowing conversion is an implicit conversion ...
314 QualType FromType = getToType(0);
315 QualType ToType = getToType(1);
316
317 // A conversion to an enumeration type is narrowing if the conversion to
318 // the underlying type is narrowing. This only arises for expressions of
319 // the form 'Enum{init}'.
320 if (auto *ET = ToType->getAs<EnumType>())
321 ToType = ET->getDecl()->getIntegerType();
322
323 switch (Second) {
324 // 'bool' is an integral type; dispatch to the right place to handle it.
325 case ICK_Boolean_Conversion:
326 if (FromType->isRealFloatingType())
327 goto FloatingIntegralConversion;
328 if (FromType->isIntegralOrUnscopedEnumerationType())
329 goto IntegralConversion;
330 // Boolean conversions can be from pointers and pointers to members
331 // [conv.bool], and those aren't considered narrowing conversions.
332 return NK_Not_Narrowing;
333
334 // -- from a floating-point type to an integer type, or
335 //
336 // -- from an integer type or unscoped enumeration type to a floating-point
337 // type, except where the source is a constant expression and the actual
338 // value after conversion will fit into the target type and will produce
339 // the original value when converted back to the original type, or
340 case ICK_Floating_Integral:
341 FloatingIntegralConversion:
342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343 return NK_Type_Narrowing;
344 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345 ToType->isRealFloatingType()) {
346 if (IgnoreFloatToIntegralConversion)
347 return NK_Not_Narrowing;
348 llvm::APSInt IntConstantValue;
349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 350, __PRETTY_FUNCTION__))
;
351
352 // If it's value-dependent, we can't tell whether it's narrowing.
353 if (Initializer->isValueDependent())
354 return NK_Dependent_Narrowing;
355
356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357 // Convert the integer to the floating type.
358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360 llvm::APFloat::rmNearestTiesToEven);
361 // And back.
362 llvm::APSInt ConvertedValue = IntConstantValue;
363 bool ignored;
364 Result.convertToInteger(ConvertedValue,
365 llvm::APFloat::rmTowardZero, &ignored);
366 // If the resulting value is different, this was a narrowing conversion.
367 if (IntConstantValue != ConvertedValue) {
368 ConstantValue = APValue(IntConstantValue);
369 ConstantType = Initializer->getType();
370 return NK_Constant_Narrowing;
371 }
372 } else {
373 // Variables are always narrowings.
374 return NK_Variable_Narrowing;
375 }
376 }
377 return NK_Not_Narrowing;
378
379 // -- from long double to double or float, or from double to float, except
380 // where the source is a constant expression and the actual value after
381 // conversion is within the range of values that can be represented (even
382 // if it cannot be represented exactly), or
383 case ICK_Floating_Conversion:
384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386 // FromType is larger than ToType.
387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388
389 // If it's value-dependent, we can't tell whether it's narrowing.
390 if (Initializer->isValueDependent())
391 return NK_Dependent_Narrowing;
392
393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394 // Constant!
395 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 llvm::APFloat FloatVal = ConstantValue.getFloat();
397 // Convert the source value into the target type.
398 bool ignored;
399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400 Ctx.getFloatTypeSemantics(ToType),
401 llvm::APFloat::rmNearestTiesToEven, &ignored);
402 // If there was no overflow, the source value is within the range of
403 // values that can be represented.
404 if (ConvertStatus & llvm::APFloat::opOverflow) {
405 ConstantType = Initializer->getType();
406 return NK_Constant_Narrowing;
407 }
408 } else {
409 return NK_Variable_Narrowing;
410 }
411 }
412 return NK_Not_Narrowing;
413
414 // -- from an integer type or unscoped enumeration type to an integer type
415 // that cannot represent all the values of the original type, except where
416 // the source is a constant expression and the actual value after
417 // conversion will fit into the target type and will produce the original
418 // value when converted back to the original type.
419 case ICK_Integral_Conversion:
420 IntegralConversion: {
421 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 421, __PRETTY_FUNCTION__))
;
422 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424 const unsigned FromWidth = Ctx.getIntWidth(FromType);
425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426 const unsigned ToWidth = Ctx.getIntWidth(ToType);
427
428 if (FromWidth > ToWidth ||
429 (FromWidth == ToWidth && FromSigned != ToSigned) ||
430 (FromSigned && !ToSigned)) {
431 // Not all values of FromType can be represented in ToType.
432 llvm::APSInt InitializerValue;
433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434
435 // If it's value-dependent, we can't tell whether it's narrowing.
436 if (Initializer->isValueDependent())
437 return NK_Dependent_Narrowing;
438
439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440 // Such conversions on variables are always narrowing.
441 return NK_Variable_Narrowing;
442 }
443 bool Narrowing = false;
444 if (FromWidth < ToWidth) {
445 // Negative -> unsigned is narrowing. Otherwise, more bits is never
446 // narrowing.
447 if (InitializerValue.isSigned() && InitializerValue.isNegative())
448 Narrowing = true;
449 } else {
450 // Add a bit to the InitializerValue so we don't have to worry about
451 // signed vs. unsigned comparisons.
452 InitializerValue = InitializerValue.extend(
453 InitializerValue.getBitWidth() + 1);
454 // Convert the initializer to and from the target width and signed-ness.
455 llvm::APSInt ConvertedValue = InitializerValue;
456 ConvertedValue = ConvertedValue.trunc(ToWidth);
457 ConvertedValue.setIsSigned(ToSigned);
458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459 ConvertedValue.setIsSigned(InitializerValue.isSigned());
460 // If the result is different, this was a narrowing conversion.
461 if (ConvertedValue != InitializerValue)
462 Narrowing = true;
463 }
464 if (Narrowing) {
465 ConstantType = Initializer->getType();
466 ConstantValue = APValue(InitializerValue);
467 return NK_Constant_Narrowing;
468 }
469 }
470 return NK_Not_Narrowing;
471 }
472
473 default:
474 // Other kinds of conversions are not narrowings.
475 return NK_Not_Narrowing;
476 }
477}
478
479/// dump - Print this standard conversion sequence to standard
480/// error. Useful for debugging overloading issues.
481LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
482 raw_ostream &OS = llvm::errs();
483 bool PrintedSomething = false;
484 if (First != ICK_Identity) {
485 OS << GetImplicitConversionName(First);
486 PrintedSomething = true;
487 }
488
489 if (Second != ICK_Identity) {
490 if (PrintedSomething) {
491 OS << " -> ";
492 }
493 OS << GetImplicitConversionName(Second);
494
495 if (CopyConstructor) {
496 OS << " (by copy constructor)";
497 } else if (DirectBinding) {
498 OS << " (direct reference binding)";
499 } else if (ReferenceBinding) {
500 OS << " (reference binding)";
501 }
502 PrintedSomething = true;
503 }
504
505 if (Third != ICK_Identity) {
506 if (PrintedSomething) {
507 OS << " -> ";
508 }
509 OS << GetImplicitConversionName(Third);
510 PrintedSomething = true;
511 }
512
513 if (!PrintedSomething) {
514 OS << "No conversions required";
515 }
516}
517
518/// dump - Print this user-defined conversion sequence to standard
519/// error. Useful for debugging overloading issues.
520void UserDefinedConversionSequence::dump() const {
521 raw_ostream &OS = llvm::errs();
522 if (Before.First || Before.Second || Before.Third) {
523 Before.dump();
524 OS << " -> ";
525 }
526 if (ConversionFunction)
527 OS << '\'' << *ConversionFunction << '\'';
528 else
529 OS << "aggregate initialization";
530 if (After.First || After.Second || After.Third) {
531 OS << " -> ";
532 After.dump();
533 }
534}
535
536/// dump - Print this implicit conversion sequence to standard
537/// error. Useful for debugging overloading issues.
538void ImplicitConversionSequence::dump() const {
539 raw_ostream &OS = llvm::errs();
540 if (isStdInitializerListElement())
541 OS << "Worst std::initializer_list element conversion: ";
542 switch (ConversionKind) {
543 case StandardConversion:
544 OS << "Standard conversion: ";
545 Standard.dump();
546 break;
547 case UserDefinedConversion:
548 OS << "User-defined conversion: ";
549 UserDefined.dump();
550 break;
551 case EllipsisConversion:
552 OS << "Ellipsis conversion";
553 break;
554 case AmbiguousConversion:
555 OS << "Ambiguous conversion";
556 break;
557 case BadConversion:
558 OS << "Bad conversion";
559 break;
560 }
561
562 OS << "\n";
563}
564
565void AmbiguousConversionSequence::construct() {
566 new (&conversions()) ConversionSet();
567}
568
569void AmbiguousConversionSequence::destruct() {
570 conversions().~ConversionSet();
571}
572
573void
574AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575 FromTypePtr = O.FromTypePtr;
576 ToTypePtr = O.ToTypePtr;
577 new (&conversions()) ConversionSet(O.conversions());
578}
579
580namespace {
581 // Structure used by DeductionFailureInfo to store
582 // template argument information.
583 struct DFIArguments {
584 TemplateArgument FirstArg;
585 TemplateArgument SecondArg;
586 };
587 // Structure used by DeductionFailureInfo to store
588 // template parameter and template argument information.
589 struct DFIParamWithArguments : DFIArguments {
590 TemplateParameter Param;
591 };
592 // Structure used by DeductionFailureInfo to store template argument
593 // information and the index of the problematic call argument.
594 struct DFIDeducedMismatchArgs : DFIArguments {
595 TemplateArgumentList *TemplateArgs;
596 unsigned CallArgIndex;
597 };
598 // Structure used by DeductionFailureInfo to store information about
599 // unsatisfied constraints.
600 struct CNSInfo {
601 TemplateArgumentList *TemplateArgs;
602 ConstraintSatisfaction Satisfaction;
603 };
604}
605
606/// Convert from Sema's representation of template deduction information
607/// to the form used in overload-candidate information.
608DeductionFailureInfo
609clang::MakeDeductionFailureInfo(ASTContext &Context,
610 Sema::TemplateDeductionResult TDK,
611 TemplateDeductionInfo &Info) {
612 DeductionFailureInfo Result;
613 Result.Result = static_cast<unsigned>(TDK);
614 Result.HasDiagnostic = false;
615 switch (TDK) {
616 case Sema::TDK_Invalid:
617 case Sema::TDK_InstantiationDepth:
618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
620 case Sema::TDK_MiscellaneousDeductionFailure:
621 case Sema::TDK_CUDATargetMismatch:
622 Result.Data = nullptr;
623 break;
624
625 case Sema::TDK_Incomplete:
626 case Sema::TDK_InvalidExplicitArguments:
627 Result.Data = Info.Param.getOpaqueValue();
628 break;
629
630 case Sema::TDK_DeducedMismatch:
631 case Sema::TDK_DeducedMismatchNested: {
632 // FIXME: Should allocate from normal heap so that we can free this later.
633 auto *Saved = new (Context) DFIDeducedMismatchArgs;
634 Saved->FirstArg = Info.FirstArg;
635 Saved->SecondArg = Info.SecondArg;
636 Saved->TemplateArgs = Info.take();
637 Saved->CallArgIndex = Info.CallArgIndex;
638 Result.Data = Saved;
639 break;
640 }
641
642 case Sema::TDK_NonDeducedMismatch: {
643 // FIXME: Should allocate from normal heap so that we can free this later.
644 DFIArguments *Saved = new (Context) DFIArguments;
645 Saved->FirstArg = Info.FirstArg;
646 Saved->SecondArg = Info.SecondArg;
647 Result.Data = Saved;
648 break;
649 }
650
651 case Sema::TDK_IncompletePack:
652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653 case Sema::TDK_Inconsistent:
654 case Sema::TDK_Underqualified: {
655 // FIXME: Should allocate from normal heap so that we can free this later.
656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657 Saved->Param = Info.Param;
658 Saved->FirstArg = Info.FirstArg;
659 Saved->SecondArg = Info.SecondArg;
660 Result.Data = Saved;
661 break;
662 }
663
664 case Sema::TDK_SubstitutionFailure:
665 Result.Data = Info.take();
666 if (Info.hasSFINAEDiagnostic()) {
667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668 SourceLocation(), PartialDiagnostic::NullDiagnostic());
669 Info.takeSFINAEDiagnostic(*Diag);
670 Result.HasDiagnostic = true;
671 }
672 break;
673
674 case Sema::TDK_ConstraintsNotSatisfied: {
675 CNSInfo *Saved = new (Context) CNSInfo;
676 Saved->TemplateArgs = Info.take();
677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678 Result.Data = Saved;
679 break;
680 }
681
682 case Sema::TDK_Success:
683 case Sema::TDK_NonDependentConversionFailure:
684 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 684)
;
685 }
686
687 return Result;
688}
689
690void DeductionFailureInfo::Destroy() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_Incomplete:
696 case Sema::TDK_TooManyArguments:
697 case Sema::TDK_TooFewArguments:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_CUDATargetMismatch:
700 case Sema::TDK_NonDependentConversionFailure:
701 break;
702
703 case Sema::TDK_IncompletePack:
704 case Sema::TDK_Inconsistent:
705 case Sema::TDK_Underqualified:
706 case Sema::TDK_DeducedMismatch:
707 case Sema::TDK_DeducedMismatchNested:
708 case Sema::TDK_NonDeducedMismatch:
709 // FIXME: Destroy the data?
710 Data = nullptr;
711 break;
712
713 case Sema::TDK_SubstitutionFailure:
714 // FIXME: Destroy the template argument list?
715 Data = nullptr;
716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717 Diag->~PartialDiagnosticAt();
718 HasDiagnostic = false;
719 }
720 break;
721
722 case Sema::TDK_ConstraintsNotSatisfied:
723 // FIXME: Destroy the template argument list?
724 Data = nullptr;
725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726 Diag->~PartialDiagnosticAt();
727 HasDiagnostic = false;
728 }
729 break;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735}
736
737PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738 if (HasDiagnostic)
739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740 return nullptr;
741}
742
743TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
746 case Sema::TDK_Invalid:
747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_TooManyArguments:
749 case Sema::TDK_TooFewArguments:
750 case Sema::TDK_SubstitutionFailure:
751 case Sema::TDK_DeducedMismatch:
752 case Sema::TDK_DeducedMismatchNested:
753 case Sema::TDK_NonDeducedMismatch:
754 case Sema::TDK_CUDATargetMismatch:
755 case Sema::TDK_NonDependentConversionFailure:
756 case Sema::TDK_ConstraintsNotSatisfied:
757 return TemplateParameter();
758
759 case Sema::TDK_Incomplete:
760 case Sema::TDK_InvalidExplicitArguments:
761 return TemplateParameter::getFromOpaqueValue(Data);
762
763 case Sema::TDK_IncompletePack:
764 case Sema::TDK_Inconsistent:
765 case Sema::TDK_Underqualified:
766 return static_cast<DFIParamWithArguments*>(Data)->Param;
767
768 // Unhandled
769 case Sema::TDK_MiscellaneousDeductionFailure:
770 break;
771 }
772
773 return TemplateParameter();
774}
775
776TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778 case Sema::TDK_Success:
779 case Sema::TDK_Invalid:
780 case Sema::TDK_InstantiationDepth:
781 case Sema::TDK_TooManyArguments:
782 case Sema::TDK_TooFewArguments:
783 case Sema::TDK_Incomplete:
784 case Sema::TDK_IncompletePack:
785 case Sema::TDK_InvalidExplicitArguments:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_NonDeducedMismatch:
789 case Sema::TDK_CUDATargetMismatch:
790 case Sema::TDK_NonDependentConversionFailure:
791 return nullptr;
792
793 case Sema::TDK_DeducedMismatch:
794 case Sema::TDK_DeducedMismatchNested:
795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796
797 case Sema::TDK_SubstitutionFailure:
798 return static_cast<TemplateArgumentList*>(Data);
799
800 case Sema::TDK_ConstraintsNotSatisfied:
801 return static_cast<CNSInfo*>(Data)->TemplateArgs;
802
803 // Unhandled
804 case Sema::TDK_MiscellaneousDeductionFailure:
805 break;
806 }
807
808 return nullptr;
809}
810
811const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_Success:
814 case Sema::TDK_Invalid:
815 case Sema::TDK_InstantiationDepth:
816 case Sema::TDK_Incomplete:
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 case Sema::TDK_ConstraintsNotSatisfied:
824 return nullptr;
825
826 case Sema::TDK_IncompletePack:
827 case Sema::TDK_Inconsistent:
828 case Sema::TDK_Underqualified:
829 case Sema::TDK_DeducedMismatch:
830 case Sema::TDK_DeducedMismatchNested:
831 case Sema::TDK_NonDeducedMismatch:
832 return &static_cast<DFIArguments*>(Data)->FirstArg;
833
834 // Unhandled
835 case Sema::TDK_MiscellaneousDeductionFailure:
836 break;
837 }
838
839 return nullptr;
840}
841
842const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844 case Sema::TDK_Success:
845 case Sema::TDK_Invalid:
846 case Sema::TDK_InstantiationDepth:
847 case Sema::TDK_Incomplete:
848 case Sema::TDK_IncompletePack:
849 case Sema::TDK_TooManyArguments:
850 case Sema::TDK_TooFewArguments:
851 case Sema::TDK_InvalidExplicitArguments:
852 case Sema::TDK_SubstitutionFailure:
853 case Sema::TDK_CUDATargetMismatch:
854 case Sema::TDK_NonDependentConversionFailure:
855 case Sema::TDK_ConstraintsNotSatisfied:
856 return nullptr;
857
858 case Sema::TDK_Inconsistent:
859 case Sema::TDK_Underqualified:
860 case Sema::TDK_DeducedMismatch:
861 case Sema::TDK_DeducedMismatchNested:
862 case Sema::TDK_NonDeducedMismatch:
863 return &static_cast<DFIArguments*>(Data)->SecondArg;
864
865 // Unhandled
866 case Sema::TDK_MiscellaneousDeductionFailure:
867 break;
868 }
869
870 return nullptr;
871}
872
873llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875 case Sema::TDK_DeducedMismatch:
876 case Sema::TDK_DeducedMismatchNested:
877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878
879 default:
880 return llvm::None;
881 }
882}
883
884bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885 OverloadedOperatorKind Op) {
886 if (!AllowRewrittenCandidates)
887 return false;
888 return Op == OO_EqualEqual || Op == OO_Spaceship;
889}
890
891bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892 ASTContext &Ctx, const FunctionDecl *FD) {
893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894 return false;
895 // Don't bother adding a reversed candidate that can never be a better
896 // match than the non-reversed version.
897 return FD->getNumParams() != 2 ||
898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899 FD->getParamDecl(1)->getType()) ||
900 FD->hasAttr<EnableIfAttr>();
901}
902
903void OverloadCandidateSet::destroyCandidates() {
904 for (iterator i = begin(), e = end(); i != e; ++i) {
905 for (auto &C : i->Conversions)
906 C.~ImplicitConversionSequence();
907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908 i->DeductionFailure.Destroy();
909 }
910}
911
912void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913 destroyCandidates();
914 SlabAllocator.Reset();
915 NumInlineBytesUsed = 0;
916 Candidates.clear();
917 Functions.clear();
918 Kind = CSK;
919}
920
921namespace {
922 class UnbridgedCastsSet {
923 struct Entry {
924 Expr **Addr;
925 Expr *Saved;
926 };
927 SmallVector<Entry, 2> Entries;
928
929 public:
930 void save(Sema &S, Expr *&E) {
931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 931, __PRETTY_FUNCTION__))
;
932 Entry entry = { &E, E };
933 Entries.push_back(entry);
934 E = S.stripARCUnbridgedCast(E);
935 }
936
937 void restore() {
938 for (SmallVectorImpl<Entry>::iterator
939 i = Entries.begin(), e = Entries.end(); i != e; ++i)
940 *i->Addr = i->Saved;
941 }
942 };
943}
944
945/// checkPlaceholderForOverload - Do any interesting placeholder-like
946/// preprocessing on the given expression.
947///
948/// \param unbridgedCasts a collection to which to add unbridged casts;
949/// without this, they will be immediately diagnosed as errors
950///
951/// Return true on unrecoverable error.
952static bool
953checkPlaceholderForOverload(Sema &S, Expr *&E,
954 UnbridgedCastsSet *unbridgedCasts = nullptr) {
955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
956 // We can't handle overloaded expressions here because overload
957 // resolution might reasonably tweak them.
958 if (placeholder->getKind() == BuiltinType::Overload) return false;
959
960 // If the context potentially accepts unbridged ARC casts, strip
961 // the unbridged cast and add it to the collection for later restoration.
962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963 unbridgedCasts) {
964 unbridgedCasts->save(S, E);
965 return false;
966 }
967
968 // Go ahead and check everything else.
969 ExprResult result = S.CheckPlaceholderExpr(E);
970 if (result.isInvalid())
971 return true;
972
973 E = result.get();
974 return false;
975 }
976
977 // Nothing to do.
978 return false;
979}
980
981/// checkArgPlaceholdersForOverload - Check a set of call operands for
982/// placeholders.
983static bool checkArgPlaceholdersForOverload(Sema &S,
984 MultiExprArg Args,
985 UnbridgedCastsSet &unbridged) {
986 for (unsigned i = 0, e = Args.size(); i != e; ++i)
987 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988 return true;
989
990 return false;
991}
992
993/// Determine whether the given New declaration is an overload of the
994/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995/// New and Old cannot be overloaded, e.g., if New has the same signature as
996/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997/// functions (or function templates) at all. When it does return Ovl_Match or
998/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000/// declaration.
1001///
1002/// Example: Given the following input:
1003///
1004/// void f(int, float); // #1
1005/// void f(int, int); // #2
1006/// int f(int, int); // #3
1007///
1008/// When we process #1, there is no previous declaration of "f", so IsOverload
1009/// will not be used.
1010///
1011/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012/// the parameter types, we see that #1 and #2 are overloaded (since they have
1013/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014/// unchanged.
1015///
1016/// When we process #3, Old is an overload set containing #1 and #2. We compare
1017/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019/// functions are not part of the signature), IsOverload returns Ovl_Match and
1020/// MatchedDecl will be set to point to the FunctionDecl for #2.
1021///
1022/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023/// by a using declaration. The rules for whether to hide shadow declarations
1024/// ignore some properties which otherwise figure into a function template's
1025/// signature.
1026Sema::OverloadKind
1027Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028 NamedDecl *&Match, bool NewIsUsingDecl) {
1029 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030 I != E; ++I) {
1031 NamedDecl *OldD = *I;
1032
1033 bool OldIsUsingDecl = false;
1034 if (isa<UsingShadowDecl>(OldD)) {
1035 OldIsUsingDecl = true;
1036
1037 // We can always introduce two using declarations into the same
1038 // context, even if they have identical signatures.
1039 if (NewIsUsingDecl) continue;
1040
1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042 }
1043
1044 // A using-declaration does not conflict with another declaration
1045 // if one of them is hidden.
1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047 continue;
1048
1049 // If either declaration was introduced by a using declaration,
1050 // we'll need to use slightly different rules for matching.
1051 // Essentially, these rules are the normal rules, except that
1052 // function templates hide function templates with different
1053 // return types or template parameter lists.
1054 bool UseMemberUsingDeclRules =
1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056 !New->getFriendObjectKind();
1057
1058 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062 continue;
1063 }
1064
1065 if (!isa<FunctionTemplateDecl>(OldD) &&
1066 !shouldLinkPossiblyHiddenDecl(*I, New))
1067 continue;
1068
1069 Match = *I;
1070 return Ovl_Match;
1071 }
1072
1073 // Builtins that have custom typechecking or have a reference should
1074 // not be overloadable or redeclarable.
1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076 Match = *I;
1077 return Ovl_NonFunction;
1078 }
1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080 // We can overload with these, which can show up when doing
1081 // redeclaration checks for UsingDecls.
1082 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1082, __PRETTY_FUNCTION__))
;
1083 } else if (isa<TagDecl>(OldD)) {
1084 // We can always overload with tags by hiding them.
1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086 // Optimistically assume that an unresolved using decl will
1087 // overload; if it doesn't, we'll have to diagnose during
1088 // template instantiation.
1089 //
1090 // Exception: if the scope is dependent and this is not a class
1091 // member, the using declaration can only introduce an enumerator.
1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093 Match = *I;
1094 return Ovl_NonFunction;
1095 }
1096 } else {
1097 // (C++ 13p1):
1098 // Only function declarations can be overloaded; object and type
1099 // declarations cannot be overloaded.
1100 Match = *I;
1101 return Ovl_NonFunction;
1102 }
1103 }
1104
1105 // C++ [temp.friend]p1:
1106 // For a friend function declaration that is not a template declaration:
1107 // -- if the name of the friend is a qualified or unqualified template-id,
1108 // [...], otherwise
1109 // -- if the name of the friend is a qualified-id and a matching
1110 // non-template function is found in the specified class or namespace,
1111 // the friend declaration refers to that function, otherwise,
1112 // -- if the name of the friend is a qualified-id and a matching function
1113 // template is found in the specified class or namespace, the friend
1114 // declaration refers to the deduced specialization of that function
1115 // template, otherwise
1116 // -- the name shall be an unqualified-id [...]
1117 // If we get here for a qualified friend declaration, we've just reached the
1118 // third bullet. If the type of the friend is dependent, skip this lookup
1119 // until instantiation.
1120 if (New->getFriendObjectKind() && New->getQualifier() &&
1121 !New->getDescribedFunctionTemplate() &&
1122 !New->getDependentSpecializationInfo() &&
1123 !New->getType()->isDependentType()) {
1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125 TemplateSpecResult.addAllDecls(Old);
1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127 /*QualifiedFriend*/true)) {
1128 New->setInvalidDecl();
1129 return Ovl_Overload;
1130 }
1131
1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133 return Ovl_Match;
1134 }
1135
1136 return Ovl_Overload;
1137}
1138
1139bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141 bool ConsiderRequiresClauses) {
1142 // C++ [basic.start.main]p2: This function shall not be overloaded.
1143 if (New->isMain())
1144 return false;
1145
1146 // MSVCRT user defined entry points cannot be overloaded.
1147 if (New->isMSVCRTEntryPoint())
1148 return false;
1149
1150 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1152
1153 // C++ [temp.fct]p2:
1154 // A function template can be overloaded with other function templates
1155 // and with normal (non-template) functions.
1156 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1157 return true;
1158
1159 // Is the function New an overload of the function Old?
1160 QualType OldQType = Context.getCanonicalType(Old->getType());
1161 QualType NewQType = Context.getCanonicalType(New->getType());
1162
1163 // Compare the signatures (C++ 1.3.10) of the two functions to
1164 // determine whether they are overloads. If we find any mismatch
1165 // in the signature, they are overloads.
1166
1167 // If either of these functions is a K&R-style function (no
1168 // prototype), then we consider them to have matching signatures.
1169 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1171 return false;
1172
1173 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1175
1176 // The signature of a function includes the types of its
1177 // parameters (C++ 1.3.10), which includes the presence or absence
1178 // of the ellipsis; see C++ DR 357).
1179 if (OldQType != NewQType &&
1180 (OldType->getNumParams() != NewType->getNumParams() ||
1181 OldType->isVariadic() != NewType->isVariadic() ||
1182 !FunctionParamTypesAreEqual(OldType, NewType)))
1183 return true;
1184
1185 // C++ [temp.over.link]p4:
1186 // The signature of a function template consists of its function
1187 // signature, its return type and its template parameter list. The names
1188 // of the template parameters are significant only for establishing the
1189 // relationship between the template parameters and the rest of the
1190 // signature.
1191 //
1192 // We check the return type and template parameter lists for function
1193 // templates first; the remaining checks follow.
1194 //
1195 // However, we don't consider either of these when deciding whether
1196 // a member introduced by a shadow declaration is hidden.
1197 if (!UseMemberUsingDeclRules && NewTemplate &&
1198 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199 OldTemplate->getTemplateParameters(),
1200 false, TPL_TemplateMatch) ||
1201 !Context.hasSameType(Old->getDeclaredReturnType(),
1202 New->getDeclaredReturnType())))
1203 return true;
1204
1205 // If the function is a class member, its signature includes the
1206 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1207 //
1208 // As part of this, also check whether one of the member functions
1209 // is static, in which case they are not overloads (C++
1210 // 13.1p2). While not part of the definition of the signature,
1211 // this check is important to determine whether these functions
1212 // can be overloaded.
1213 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215 if (OldMethod && NewMethod &&
1216 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218 if (!UseMemberUsingDeclRules &&
1219 (OldMethod->getRefQualifier() == RQ_None ||
1220 NewMethod->getRefQualifier() == RQ_None)) {
1221 // C++0x [over.load]p2:
1222 // - Member function declarations with the same name and the same
1223 // parameter-type-list as well as member function template
1224 // declarations with the same name, the same parameter-type-list, and
1225 // the same template parameter lists cannot be overloaded if any of
1226 // them, but not all, have a ref-qualifier (8.3.5).
1227 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1230 }
1231 return true;
1232 }
1233
1234 // We may not have applied the implicit const for a constexpr member
1235 // function yet (because we haven't yet resolved whether this is a static
1236 // or non-static member function). Add it now, on the assumption that this
1237 // is a redeclaration of OldMethod.
1238 auto OldQuals = OldMethod->getMethodQualifiers();
1239 auto NewQuals = NewMethod->getMethodQualifiers();
1240 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241 !isa<CXXConstructorDecl>(NewMethod))
1242 NewQuals.addConst();
1243 // We do not allow overloading based off of '__restrict'.
1244 OldQuals.removeRestrict();
1245 NewQuals.removeRestrict();
1246 if (OldQuals != NewQuals)
1247 return true;
1248 }
1249
1250 // Though pass_object_size is placed on parameters and takes an argument, we
1251 // consider it to be a function-level modifier for the sake of function
1252 // identity. Either the function has one or more parameters with
1253 // pass_object_size or it doesn't.
1254 if (functionHasPassObjectSizeParams(New) !=
1255 functionHasPassObjectSizeParams(Old))
1256 return true;
1257
1258 // enable_if attributes are an order-sensitive part of the signature.
1259 for (specific_attr_iterator<EnableIfAttr>
1260 NewI = New->specific_attr_begin<EnableIfAttr>(),
1261 NewE = New->specific_attr_end<EnableIfAttr>(),
1262 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263 OldE = Old->specific_attr_end<EnableIfAttr>();
1264 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265 if (NewI == NewE || OldI == OldE)
1266 return true;
1267 llvm::FoldingSetNodeID NewID, OldID;
1268 NewI->getCond()->Profile(NewID, Context, true);
1269 OldI->getCond()->Profile(OldID, Context, true);
1270 if (NewID != OldID)
1271 return true;
1272 }
1273
1274 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275 // Don't allow overloading of destructors. (In theory we could, but it
1276 // would be a giant change to clang.)
1277 if (!isa<CXXDestructorDecl>(New)) {
1278 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279 OldTarget = IdentifyCUDATarget(Old);
1280 if (NewTarget != CFT_InvalidTarget) {
1281 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
1282 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
;
1283
1284 // Allow overloading of functions with same signature and different CUDA
1285 // target attributes.
1286 if (NewTarget != OldTarget)
1287 return true;
1288 }
1289 }
1290 }
1291
1292 if (ConsiderRequiresClauses) {
1293 Expr *NewRC = New->getTrailingRequiresClause(),
1294 *OldRC = Old->getTrailingRequiresClause();
1295 if ((NewRC != nullptr) != (OldRC != nullptr))
1296 // RC are most certainly different - these are overloads.
1297 return true;
1298
1299 if (NewRC) {
1300 llvm::FoldingSetNodeID NewID, OldID;
1301 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1303 if (NewID != OldID)
1304 // RCs are not equivalent - these are overloads.
1305 return true;
1306 }
1307 }
1308
1309 // The signatures match; this is not an overload.
1310 return false;
1311}
1312
1313/// Tries a user-defined conversion from From to ToType.
1314///
1315/// Produces an implicit conversion sequence for when a standard conversion
1316/// is not an option. See TryImplicitConversion for more information.
1317static ImplicitConversionSequence
1318TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319 bool SuppressUserConversions,
1320 bool AllowExplicit,
1321 bool InOverloadResolution,
1322 bool CStyle,
1323 bool AllowObjCWritebackConversion,
1324 bool AllowObjCConversionOnExplicit) {
1325 ImplicitConversionSequence ICS;
1326
1327 if (SuppressUserConversions) {
1328 // We're not in the case above, so there is no conversion that
1329 // we can perform.
1330 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1331 return ICS;
1332 }
1333
1334 // Attempt user-defined conversion.
1335 OverloadCandidateSet Conversions(From->getExprLoc(),
1336 OverloadCandidateSet::CSK_Normal);
1337 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338 Conversions, AllowExplicit,
1339 AllowObjCConversionOnExplicit)) {
1340 case OR_Success:
1341 case OR_Deleted:
1342 ICS.setUserDefined();
1343 // C++ [over.ics.user]p4:
1344 // A conversion of an expression of class type to the same class
1345 // type is given Exact Match rank, and a conversion of an
1346 // expression of class type to a base class of that type is
1347 // given Conversion rank, in spite of the fact that a copy
1348 // constructor (i.e., a user-defined conversion function) is
1349 // called for those cases.
1350 if (CXXConstructorDecl *Constructor
1351 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1352 QualType FromCanon
1353 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1354 QualType ToCanon
1355 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356 if (Constructor->isCopyConstructor() &&
1357 (FromCanon == ToCanon ||
1358 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359 // Turn this into a "standard" conversion sequence, so that it
1360 // gets ranked with standard conversion sequences.
1361 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1362 ICS.setStandard();
1363 ICS.Standard.setAsIdentityConversion();
1364 ICS.Standard.setFromType(From->getType());
1365 ICS.Standard.setAllToTypes(ToType);
1366 ICS.Standard.CopyConstructor = Constructor;
1367 ICS.Standard.FoundCopyConstructor = Found;
1368 if (ToCanon != FromCanon)
1369 ICS.Standard.Second = ICK_Derived_To_Base;
1370 }
1371 }
1372 break;
1373
1374 case OR_Ambiguous:
1375 ICS.setAmbiguous();
1376 ICS.Ambiguous.setFromType(From->getType());
1377 ICS.Ambiguous.setToType(ToType);
1378 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379 Cand != Conversions.end(); ++Cand)
1380 if (Cand->Best)
1381 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1382 break;
1383
1384 // Fall through.
1385 case OR_No_Viable_Function:
1386 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1387 break;
1388 }
1389
1390 return ICS;
1391}
1392
1393/// TryImplicitConversion - Attempt to perform an implicit conversion
1394/// from the given expression (Expr) to the given type (ToType). This
1395/// function returns an implicit conversion sequence that can be used
1396/// to perform the initialization. Given
1397///
1398/// void f(float f);
1399/// void g(int i) { f(i); }
1400///
1401/// this routine would produce an implicit conversion sequence to
1402/// describe the initialization of f from i, which will be a standard
1403/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1405//
1406/// Note that this routine only determines how the conversion can be
1407/// performed; it does not actually perform the conversion. As such,
1408/// it will not produce any diagnostics if no conversion is available,
1409/// but will instead return an implicit conversion sequence of kind
1410/// "BadConversion".
1411///
1412/// If @p SuppressUserConversions, then user-defined conversions are
1413/// not permitted.
1414/// If @p AllowExplicit, then explicit user-defined conversions are
1415/// permitted.
1416///
1417/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418/// writeback conversion, which allows __autoreleasing id* parameters to
1419/// be initialized with __strong id* or __weak id* arguments.
1420static ImplicitConversionSequence
1421TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422 bool SuppressUserConversions,
1423 bool AllowExplicit,
1424 bool InOverloadResolution,
1425 bool CStyle,
1426 bool AllowObjCWritebackConversion,
1427 bool AllowObjCConversionOnExplicit) {
1428 ImplicitConversionSequence ICS;
1429 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1431 ICS.setStandard();
1432 return ICS;
1433 }
1434
1435 if (!S.getLangOpts().CPlusPlus) {
1436 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1437 return ICS;
1438 }
1439
1440 // C++ [over.ics.user]p4:
1441 // A conversion of an expression of class type to the same class
1442 // type is given Exact Match rank, and a conversion of an
1443 // expression of class type to a base class of that type is
1444 // given Conversion rank, in spite of the fact that a copy/move
1445 // constructor (i.e., a user-defined conversion function) is
1446 // called for those cases.
1447 QualType FromType = From->getType();
1448 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1451 ICS.setStandard();
1452 ICS.Standard.setAsIdentityConversion();
1453 ICS.Standard.setFromType(FromType);
1454 ICS.Standard.setAllToTypes(ToType);
1455
1456 // We don't actually check at this point whether there is a valid
1457 // copy/move constructor, since overloading just assumes that it
1458 // exists. When we actually perform initialization, we'll find the
1459 // appropriate constructor to copy the returned object, if needed.
1460 ICS.Standard.CopyConstructor = nullptr;
1461
1462 // Determine whether this is considered a derived-to-base conversion.
1463 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464 ICS.Standard.Second = ICK_Derived_To_Base;
1465
1466 return ICS;
1467 }
1468
1469 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470 AllowExplicit, InOverloadResolution, CStyle,
1471 AllowObjCWritebackConversion,
1472 AllowObjCConversionOnExplicit);
1473}
1474
1475ImplicitConversionSequence
1476Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477 bool SuppressUserConversions,
1478 bool AllowExplicit,
1479 bool InOverloadResolution,
1480 bool CStyle,
1481 bool AllowObjCWritebackConversion) {
1482 return ::TryImplicitConversion(*this, From, ToType,
1483 SuppressUserConversions, AllowExplicit,
1484 InOverloadResolution, CStyle,
1485 AllowObjCWritebackConversion,
1486 /*AllowObjCConversionOnExplicit=*/false);
1487}
1488
1489/// PerformImplicitConversion - Perform an implicit conversion of the
1490/// expression From to the type ToType. Returns the
1491/// converted expression. Flavor is the kind of conversion we're
1492/// performing, used in the error message. If @p AllowExplicit,
1493/// explicit user-defined conversions are permitted.
1494ExprResult
1495Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496 AssignmentAction Action, bool AllowExplicit) {
1497 ImplicitConversionSequence ICS;
1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499}
1500
1501ExprResult
1502Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503 AssignmentAction Action, bool AllowExplicit,
1504 ImplicitConversionSequence& ICS) {
1505 if (checkPlaceholderForOverload(*this, From))
1506 return ExprError();
1507
1508 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509 bool AllowObjCWritebackConversion
1510 = getLangOpts().ObjCAutoRefCount &&
1511 (Action == AA_Passing || Action == AA_Sending);
1512 if (getLangOpts().ObjC)
1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514 From->getType(), From);
1515 ICS = ::TryImplicitConversion(*this, From, ToType,
1516 /*SuppressUserConversions=*/false,
1517 AllowExplicit,
1518 /*InOverloadResolution=*/false,
1519 /*CStyle=*/false,
1520 AllowObjCWritebackConversion,
1521 /*AllowObjCConversionOnExplicit=*/false);
1522 return PerformImplicitConversion(From, ToType, ICS, Action);
1523}
1524
1525/// Determine whether the conversion from FromType to ToType is a valid
1526/// conversion that strips "noexcept" or "noreturn" off the nested function
1527/// type.
1528bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529 QualType &ResultTy) {
1530 if (Context.hasSameUnqualifiedType(FromType, ToType))
1531 return false;
1532
1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534 // or F(t noexcept) -> F(t)
1535 // where F adds one of the following at most once:
1536 // - a pointer
1537 // - a member pointer
1538 // - a block pointer
1539 // Changes here need matching changes in FindCompositePointerType.
1540 CanQualType CanTo = Context.getCanonicalType(ToType);
1541 CanQualType CanFrom = Context.getCanonicalType(FromType);
1542 Type::TypeClass TyClass = CanTo->getTypeClass();
1543 if (TyClass != CanFrom->getTypeClass()) return false;
1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545 if (TyClass == Type::Pointer) {
1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548 } else if (TyClass == Type::BlockPointer) {
1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551 } else if (TyClass == Type::MemberPointer) {
1552 auto ToMPT = CanTo.castAs<MemberPointerType>();
1553 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554 // A function pointer conversion cannot change the class of the function.
1555 if (ToMPT->getClass() != FromMPT->getClass())
1556 return false;
1557 CanTo = ToMPT->getPointeeType();
1558 CanFrom = FromMPT->getPointeeType();
1559 } else {
1560 return false;
1561 }
1562
1563 TyClass = CanTo->getTypeClass();
1564 if (TyClass != CanFrom->getTypeClass()) return false;
1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566 return false;
1567 }
1568
1569 const auto *FromFn = cast<FunctionType>(CanFrom);
1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571
1572 const auto *ToFn = cast<FunctionType>(CanTo);
1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574
1575 bool Changed = false;
1576
1577 // Drop 'noreturn' if not present in target type.
1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580 Changed = true;
1581 }
1582
1583 // Drop 'noexcept' if not present in target type.
1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587 FromFn = cast<FunctionType>(
1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589 EST_None)
1590 .getTypePtr());
1591 Changed = true;
1592 }
1593
1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595 // only if the ExtParameterInfo lists of the two function prototypes can be
1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598 bool CanUseToFPT, CanUseFromFPT;
1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600 CanUseFromFPT, NewParamInfos) &&
1601 CanUseToFPT && !CanUseFromFPT) {
1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603 ExtInfo.ExtParameterInfos =
1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606 FromFPT->getParamTypes(), ExtInfo);
1607 FromFn = QT->getAs<FunctionType>();
1608 Changed = true;
1609 }
1610 }
1611
1612 if (!Changed)
1613 return false;
1614
1615 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1615, __PRETTY_FUNCTION__))
;
1616 if (QualType(FromFn, 0) != CanTo) return false;
1617
1618 ResultTy = ToType;
1619 return true;
1620}
1621
1622/// Determine whether the conversion from FromType to ToType is a valid
1623/// vector conversion.
1624///
1625/// \param ICK Will be set to the vector conversion kind, if this is a vector
1626/// conversion.
1627static bool IsVectorConversion(Sema &S, QualType FromType,
1628 QualType ToType, ImplicitConversionKind &ICK) {
1629 // We need at least one of these types to be a vector type to have a vector
1630 // conversion.
1631 if (!ToType->isVectorType() && !FromType->isVectorType())
1632 return false;
1633
1634 // Identical types require no conversions.
1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636 return false;
1637
1638 // There are no conversions between extended vector types, only identity.
1639 if (ToType->isExtVectorType()) {
1640 // There are no conversions between extended vector types other than the
1641 // identity conversion.
1642 if (FromType->isExtVectorType())
1643 return false;
1644
1645 // Vector splat from any arithmetic type to a vector.
1646 if (FromType->isArithmeticType()) {
1647 ICK = ICK_Vector_Splat;
1648 return true;
1649 }
1650 }
1651
1652 // We can perform the conversion between vector types in the following cases:
1653 // 1)vector types are equivalent AltiVec and GCC vector types
1654 // 2)lax vector conversions are permitted and the vector types are of the
1655 // same size
1656 if (ToType->isVectorType() && FromType->isVectorType()) {
1657 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1658 S.isLaxVectorConversion(FromType, ToType)) {
1659 ICK = ICK_Vector_Conversion;
1660 return true;
1661 }
1662 }
1663
1664 return false;
1665}
1666
1667static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1670 bool CStyle);
1671
1672/// IsStandardConversion - Determines whether there is a standard
1673/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1674/// expression From to the type ToType. Standard conversion sequences
1675/// only consider non-class types; for conversions that involve class
1676/// types, use TryImplicitConversion. If a conversion exists, SCS will
1677/// contain the standard conversion sequence required to perform this
1678/// conversion and this routine will return true. Otherwise, this
1679/// routine will return false and the value of SCS is unspecified.
1680static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1681 bool InOverloadResolution,
1682 StandardConversionSequence &SCS,
1683 bool CStyle,
1684 bool AllowObjCWritebackConversion) {
1685 QualType FromType = From->getType();
1686
1687 // Standard conversions (C++ [conv])
1688 SCS.setAsIdentityConversion();
1689 SCS.IncompatibleObjC = false;
1690 SCS.setFromType(FromType);
1691 SCS.CopyConstructor = nullptr;
1692
1693 // There are no standard conversions for class types in C++, so
1694 // abort early. When overloading in C, however, we do permit them.
1695 if (S.getLangOpts().CPlusPlus &&
1696 (FromType->isRecordType() || ToType->isRecordType()))
1697 return false;
1698
1699 // The first conversion can be an lvalue-to-rvalue conversion,
1700 // array-to-pointer conversion, or function-to-pointer conversion
1701 // (C++ 4p1).
1702
1703 if (FromType == S.Context.OverloadTy) {
1704 DeclAccessPair AccessPair;
1705 if (FunctionDecl *Fn
1706 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1707 AccessPair)) {
1708 // We were able to resolve the address of the overloaded function,
1709 // so we can convert to the type of that function.
1710 FromType = Fn->getType();
1711 SCS.setFromType(FromType);
1712
1713 // we can sometimes resolve &foo<int> regardless of ToType, so check
1714 // if the type matches (identity) or we are converting to bool
1715 if (!S.Context.hasSameUnqualifiedType(
1716 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1717 QualType resultTy;
1718 // if the function type matches except for [[noreturn]], it's ok
1719 if (!S.IsFunctionConversion(FromType,
1720 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1721 // otherwise, only a boolean conversion is standard
1722 if (!ToType->isBooleanType())
1723 return false;
1724 }
1725
1726 // Check if the "from" expression is taking the address of an overloaded
1727 // function and recompute the FromType accordingly. Take advantage of the
1728 // fact that non-static member functions *must* have such an address-of
1729 // expression.
1730 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1731 if (Method && !Method->isStatic()) {
1732 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
1733 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1735 == 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1736 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
;
1737 const Type *ClassType
1738 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1739 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1740 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1741 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1742 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1743 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
;
1744 FromType = S.Context.getPointerType(FromType);
1745 }
1746
1747 // Check that we've computed the proper type after overload resolution.
1748 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1749 // be calling it from within an NDEBUG block.
1750 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1751 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1752 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
;
1753 } else {
1754 return false;
1755 }
1756 }
1757 // Lvalue-to-rvalue conversion (C++11 4.1):
1758 // A glvalue (3.10) of a non-function, non-array type T can
1759 // be converted to a prvalue.
1760 bool argIsLValue = From->isGLValue();
1761 if (argIsLValue &&
1762 !FromType->isFunctionType() && !FromType->isArrayType() &&
1763 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1764 SCS.First = ICK_Lvalue_To_Rvalue;
1765
1766 // C11 6.3.2.1p2:
1767 // ... if the lvalue has atomic type, the value has the non-atomic version
1768 // of the type of the lvalue ...
1769 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1770 FromType = Atomic->getValueType();
1771
1772 // If T is a non-class type, the type of the rvalue is the
1773 // cv-unqualified version of T. Otherwise, the type of the rvalue
1774 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1775 // just strip the qualifiers because they don't matter.
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (FromType->isArrayType()) {
1778 // Array-to-pointer conversion (C++ 4.2)
1779 SCS.First = ICK_Array_To_Pointer;
1780
1781 // An lvalue or rvalue of type "array of N T" or "array of unknown
1782 // bound of T" can be converted to an rvalue of type "pointer to
1783 // T" (C++ 4.2p1).
1784 FromType = S.Context.getArrayDecayedType(FromType);
1785
1786 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1787 // This conversion is deprecated in C++03 (D.4)
1788 SCS.DeprecatedStringLiteralToCharPtr = true;
1789
1790 // For the purpose of ranking in overload resolution
1791 // (13.3.3.1.1), this conversion is considered an
1792 // array-to-pointer conversion followed by a qualification
1793 // conversion (4.4). (C++ 4.2p2)
1794 SCS.Second = ICK_Identity;
1795 SCS.Third = ICK_Qualification;
1796 SCS.QualificationIncludesObjCLifetime = false;
1797 SCS.setAllToTypes(FromType);
1798 return true;
1799 }
1800 } else if (FromType->isFunctionType() && argIsLValue) {
1801 // Function-to-pointer conversion (C++ 4.3).
1802 SCS.First = ICK_Function_To_Pointer;
1803
1804 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1805 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1806 if (!S.checkAddressOfFunctionIsAvailable(FD))
1807 return false;
1808
1809 // An lvalue of function type T can be converted to an rvalue of
1810 // type "pointer to T." The result is a pointer to the
1811 // function. (C++ 4.3p1).
1812 FromType = S.Context.getPointerType(FromType);
1813 } else {
1814 // We don't require any conversions for the first step.
1815 SCS.First = ICK_Identity;
1816 }
1817 SCS.setToType(0, FromType);
1818
1819 // The second conversion can be an integral promotion, floating
1820 // point promotion, integral conversion, floating point conversion,
1821 // floating-integral conversion, pointer conversion,
1822 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1823 // For overloading in C, this can also be a "compatible-type"
1824 // conversion.
1825 bool IncompatibleObjC = false;
1826 ImplicitConversionKind SecondICK = ICK_Identity;
1827 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1828 // The unqualified versions of the types are the same: there's no
1829 // conversion to do.
1830 SCS.Second = ICK_Identity;
1831 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1832 // Integral promotion (C++ 4.5).
1833 SCS.Second = ICK_Integral_Promotion;
1834 FromType = ToType.getUnqualifiedType();
1835 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1836 // Floating point promotion (C++ 4.6).
1837 SCS.Second = ICK_Floating_Promotion;
1838 FromType = ToType.getUnqualifiedType();
1839 } else if (S.IsComplexPromotion(FromType, ToType)) {
1840 // Complex promotion (Clang extension)
1841 SCS.Second = ICK_Complex_Promotion;
1842 FromType = ToType.getUnqualifiedType();
1843 } else if (ToType->isBooleanType() &&
1844 (FromType->isArithmeticType() ||
1845 FromType->isAnyPointerType() ||
1846 FromType->isBlockPointerType() ||
1847 FromType->isMemberPointerType() ||
1848 FromType->isNullPtrType())) {
1849 // Boolean conversions (C++ 4.12).
1850 SCS.Second = ICK_Boolean_Conversion;
1851 FromType = S.Context.BoolTy;
1852 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1853 ToType->isIntegralType(S.Context)) {
1854 // Integral conversions (C++ 4.7).
1855 SCS.Second = ICK_Integral_Conversion;
1856 FromType = ToType.getUnqualifiedType();
1857 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1858 // Complex conversions (C99 6.3.1.6)
1859 SCS.Second = ICK_Complex_Conversion;
1860 FromType = ToType.getUnqualifiedType();
1861 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1862 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1863 // Complex-real conversions (C99 6.3.1.7)
1864 SCS.Second = ICK_Complex_Real;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1867 // FIXME: disable conversions between long double and __float128 if
1868 // their representation is different until there is back end support
1869 // We of course allow this conversion if long double is really double.
1870 if (&S.Context.getFloatTypeSemantics(FromType) !=
1871 &S.Context.getFloatTypeSemantics(ToType)) {
1872 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1873 ToType == S.Context.LongDoubleTy) ||
1874 (FromType == S.Context.LongDoubleTy &&
1875 ToType == S.Context.Float128Ty));
1876 if (Float128AndLongDouble &&
1877 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1878 &llvm::APFloat::PPCDoubleDouble()))
1879 return false;
1880 }
1881 // Floating point conversions (C++ 4.8).
1882 SCS.Second = ICK_Floating_Conversion;
1883 FromType = ToType.getUnqualifiedType();
1884 } else if ((FromType->isRealFloatingType() &&
1885 ToType->isIntegralType(S.Context)) ||
1886 (FromType->isIntegralOrUnscopedEnumerationType() &&
1887 ToType->isRealFloatingType())) {
1888 // Floating-integral conversions (C++ 4.9).
1889 SCS.Second = ICK_Floating_Integral;
1890 FromType = ToType.getUnqualifiedType();
1891 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1892 SCS.Second = ICK_Block_Pointer_Conversion;
1893 } else if (AllowObjCWritebackConversion &&
1894 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1895 SCS.Second = ICK_Writeback_Conversion;
1896 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1897 FromType, IncompatibleObjC)) {
1898 // Pointer conversions (C++ 4.10).
1899 SCS.Second = ICK_Pointer_Conversion;
1900 SCS.IncompatibleObjC = IncompatibleObjC;
1901 FromType = FromType.getUnqualifiedType();
1902 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1903 InOverloadResolution, FromType)) {
1904 // Pointer to member conversions (4.11).
1905 SCS.Second = ICK_Pointer_Member;
1906 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1907 SCS.Second = SecondICK;
1908 FromType = ToType.getUnqualifiedType();
1909 } else if (!S.getLangOpts().CPlusPlus &&
1910 S.Context.typesAreCompatible(ToType, FromType)) {
1911 // Compatible conversions (Clang extension for C function overloading)
1912 SCS.Second = ICK_Compatible_Conversion;
1913 FromType = ToType.getUnqualifiedType();
1914 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1915 InOverloadResolution,
1916 SCS, CStyle)) {
1917 SCS.Second = ICK_TransparentUnionConversion;
1918 FromType = ToType;
1919 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1920 CStyle)) {
1921 // tryAtomicConversion has updated the standard conversion sequence
1922 // appropriately.
1923 return true;
1924 } else if (ToType->isEventT() &&
1925 From->isIntegerConstantExpr(S.getASTContext()) &&
1926 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1927 SCS.Second = ICK_Zero_Event_Conversion;
1928 FromType = ToType;
1929 } else if (ToType->isQueueT() &&
1930 From->isIntegerConstantExpr(S.getASTContext()) &&
1931 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1932 SCS.Second = ICK_Zero_Queue_Conversion;
1933 FromType = ToType;
1934 } else if (ToType->isSamplerT() &&
1935 From->isIntegerConstantExpr(S.getASTContext())) {
1936 SCS.Second = ICK_Compatible_Conversion;
1937 FromType = ToType;
1938 } else {
1939 // No second conversion required.
1940 SCS.Second = ICK_Identity;
1941 }
1942 SCS.setToType(1, FromType);
1943
1944 // The third conversion can be a function pointer conversion or a
1945 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1946 bool ObjCLifetimeConversion;
1947 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1948 // Function pointer conversions (removing 'noexcept') including removal of
1949 // 'noreturn' (Clang extension).
1950 SCS.Third = ICK_Function_Conversion;
1951 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1952 ObjCLifetimeConversion)) {
1953 SCS.Third = ICK_Qualification;
1954 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1955 FromType = ToType;
1956 } else {
1957 // No conversion required
1958 SCS.Third = ICK_Identity;
1959 }
1960
1961 // C++ [over.best.ics]p6:
1962 // [...] Any difference in top-level cv-qualification is
1963 // subsumed by the initialization itself and does not constitute
1964 // a conversion. [...]
1965 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1966 QualType CanonTo = S.Context.getCanonicalType(ToType);
1967 if (CanonFrom.getLocalUnqualifiedType()
1968 == CanonTo.getLocalUnqualifiedType() &&
1969 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1970 FromType = ToType;
1971 CanonFrom = CanonTo;
1972 }
1973
1974 SCS.setToType(2, FromType);
1975
1976 if (CanonFrom == CanonTo)
1977 return true;
1978
1979 // If we have not converted the argument type to the parameter type,
1980 // this is a bad conversion sequence, unless we're resolving an overload in C.
1981 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1982 return false;
1983
1984 ExprResult ER = ExprResult{From};
1985 Sema::AssignConvertType Conv =
1986 S.CheckSingleAssignmentConstraints(ToType, ER,
1987 /*Diagnose=*/false,
1988 /*DiagnoseCFAudited=*/false,
1989 /*ConvertRHS=*/false);
1990 ImplicitConversionKind SecondConv;
1991 switch (Conv) {
1992 case Sema::Compatible:
1993 SecondConv = ICK_C_Only_Conversion;
1994 break;
1995 // For our purposes, discarding qualifiers is just as bad as using an
1996 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1997 // qualifiers, as well.
1998 case Sema::CompatiblePointerDiscardsQualifiers:
1999 case Sema::IncompatiblePointer:
2000 case Sema::IncompatiblePointerSign:
2001 SecondConv = ICK_Incompatible_Pointer_Conversion;
2002 break;
2003 default:
2004 return false;
2005 }
2006
2007 // First can only be an lvalue conversion, so we pretend that this was the
2008 // second conversion. First should already be valid from earlier in the
2009 // function.
2010 SCS.Second = SecondConv;
2011 SCS.setToType(1, ToType);
2012
2013 // Third is Identity, because Second should rank us worse than any other
2014 // conversion. This could also be ICK_Qualification, but it's simpler to just
2015 // lump everything in with the second conversion, and we don't gain anything
2016 // from making this ICK_Qualification.
2017 SCS.Third = ICK_Identity;
2018 SCS.setToType(2, ToType);
2019 return true;
2020}
2021
2022static bool
2023IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2024 QualType &ToType,
2025 bool InOverloadResolution,
2026 StandardConversionSequence &SCS,
2027 bool CStyle) {
2028
2029 const RecordType *UT = ToType->getAsUnionType();
2030 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2031 return false;
2032 // The field to initialize within the transparent union.
2033 RecordDecl *UD = UT->getDecl();
2034 // It's compatible if the expression matches any of the fields.
2035 for (const auto *it : UD->fields()) {
2036 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2037 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2038 ToType = it->getType();
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045/// IsIntegralPromotion - Determines whether the conversion from the
2046/// expression From (whose potentially-adjusted type is FromType) to
2047/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2048/// sets PromotedType to the promoted type.
2049bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2050 const BuiltinType *To = ToType->getAs<BuiltinType>();
2051 // All integers are built-in.
2052 if (!To) {
2053 return false;
2054 }
2055
2056 // An rvalue of type char, signed char, unsigned char, short int, or
2057 // unsigned short int can be converted to an rvalue of type int if
2058 // int can represent all the values of the source type; otherwise,
2059 // the source rvalue can be converted to an rvalue of type unsigned
2060 // int (C++ 4.5p1).
2061 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2062 !FromType->isEnumeralType()) {
2063 if (// We can promote any signed, promotable integer type to an int
2064 (FromType->isSignedIntegerType() ||
2065 // We can promote any unsigned integer type whose size is
2066 // less than int to an int.
2067 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2068 return To->getKind() == BuiltinType::Int;
2069 }
2070
2071 return To->getKind() == BuiltinType::UInt;
2072 }
2073
2074 // C++11 [conv.prom]p3:
2075 // A prvalue of an unscoped enumeration type whose underlying type is not
2076 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2077 // following types that can represent all the values of the enumeration
2078 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2079 // unsigned int, long int, unsigned long int, long long int, or unsigned
2080 // long long int. If none of the types in that list can represent all the
2081 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2082 // type can be converted to an rvalue a prvalue of the extended integer type
2083 // with lowest integer conversion rank (4.13) greater than the rank of long
2084 // long in which all the values of the enumeration can be represented. If
2085 // there are two such extended types, the signed one is chosen.
2086 // C++11 [conv.prom]p4:
2087 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2088 // can be converted to a prvalue of its underlying type. Moreover, if
2089 // integral promotion can be applied to its underlying type, a prvalue of an
2090 // unscoped enumeration type whose underlying type is fixed can also be
2091 // converted to a prvalue of the promoted underlying type.
2092 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2093 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2094 // provided for a scoped enumeration.
2095 if (FromEnumType->getDecl()->isScoped())
2096 return false;
2097
2098 // We can perform an integral promotion to the underlying type of the enum,
2099 // even if that's not the promoted type. Note that the check for promoting
2100 // the underlying type is based on the type alone, and does not consider
2101 // the bitfield-ness of the actual source expression.
2102 if (FromEnumType->getDecl()->isFixed()) {
2103 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2104 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2105 IsIntegralPromotion(nullptr, Underlying, ToType);
2106 }
2107
2108 // We have already pre-calculated the promotion type, so this is trivial.
2109 if (ToType->isIntegerType() &&
2110 isCompleteType(From->getBeginLoc(), FromType))
2111 return Context.hasSameUnqualifiedType(
2112 ToType, FromEnumType->getDecl()->getPromotionType());
2113
2114 // C++ [conv.prom]p5:
2115 // If the bit-field has an enumerated type, it is treated as any other
2116 // value of that type for promotion purposes.
2117 //
2118 // ... so do not fall through into the bit-field checks below in C++.
2119 if (getLangOpts().CPlusPlus)
2120 return false;
2121 }
2122
2123 // C++0x [conv.prom]p2:
2124 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2125 // to an rvalue a prvalue of the first of the following types that can
2126 // represent all the values of its underlying type: int, unsigned int,
2127 // long int, unsigned long int, long long int, or unsigned long long int.
2128 // If none of the types in that list can represent all the values of its
2129 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2130 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2131 // type.
2132 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2133 ToType->isIntegerType()) {
2134 // Determine whether the type we're converting from is signed or
2135 // unsigned.
2136 bool FromIsSigned = FromType->isSignedIntegerType();
2137 uint64_t FromSize = Context.getTypeSize(FromType);
2138
2139 // The types we'll try to promote to, in the appropriate
2140 // order. Try each of these types.
2141 QualType PromoteTypes[6] = {
2142 Context.IntTy, Context.UnsignedIntTy,
2143 Context.LongTy, Context.UnsignedLongTy ,
2144 Context.LongLongTy, Context.UnsignedLongLongTy
2145 };
2146 for (int Idx = 0; Idx < 6; ++Idx) {
2147 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2148 if (FromSize < ToSize ||
2149 (FromSize == ToSize &&
2150 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2151 // We found the type that we can promote to. If this is the
2152 // type we wanted, we have a promotion. Otherwise, no
2153 // promotion.
2154 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2155 }
2156 }
2157 }
2158
2159 // An rvalue for an integral bit-field (9.6) can be converted to an
2160 // rvalue of type int if int can represent all the values of the
2161 // bit-field; otherwise, it can be converted to unsigned int if
2162 // unsigned int can represent all the values of the bit-field. If
2163 // the bit-field is larger yet, no integral promotion applies to
2164 // it. If the bit-field has an enumerated type, it is treated as any
2165 // other value of that type for promotion purposes (C++ 4.5p3).
2166 // FIXME: We should delay checking of bit-fields until we actually perform the
2167 // conversion.
2168 //
2169 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2170 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2171 // bit-fields and those whose underlying type is larger than int) for GCC
2172 // compatibility.
2173 if (From) {
2174 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2175 llvm::APSInt BitWidth;
2176 if (FromType->isIntegralType(Context) &&
2177 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2178 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2179 ToSize = Context.getTypeSize(ToType);
2180
2181 // Are we promoting to an int from a bitfield that fits in an int?
2182 if (BitWidth < ToSize ||
2183 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2184 return To->getKind() == BuiltinType::Int;
2185 }
2186
2187 // Are we promoting to an unsigned int from an unsigned bitfield
2188 // that fits into an unsigned int?
2189 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2190 return To->getKind() == BuiltinType::UInt;
2191 }
2192
2193 return false;
2194 }
2195 }
2196 }
2197
2198 // An rvalue of type bool can be converted to an rvalue of type int,
2199 // with false becoming zero and true becoming one (C++ 4.5p4).
2200 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2201 return true;
2202 }
2203
2204 return false;
2205}
2206
2207/// IsFloatingPointPromotion - Determines whether the conversion from
2208/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2209/// returns true and sets PromotedType to the promoted type.
2210bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2211 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2212 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2213 /// An rvalue of type float can be converted to an rvalue of type
2214 /// double. (C++ 4.6p1).
2215 if (FromBuiltin->getKind() == BuiltinType::Float &&
2216 ToBuiltin->getKind() == BuiltinType::Double)
2217 return true;
2218
2219 // C99 6.3.1.5p1:
2220 // When a float is promoted to double or long double, or a
2221 // double is promoted to long double [...].
2222 if (!getLangOpts().CPlusPlus &&
2223 (FromBuiltin->getKind() == BuiltinType::Float ||
2224 FromBuiltin->getKind() == BuiltinType::Double) &&
2225 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2226 ToBuiltin->getKind() == BuiltinType::Float128))
2227 return true;
2228
2229 // Half can be promoted to float.
2230 if (!getLangOpts().NativeHalfType &&
2231 FromBuiltin->getKind() == BuiltinType::Half &&
2232 ToBuiltin->getKind() == BuiltinType::Float)
2233 return true;
2234 }
2235
2236 return false;
2237}
2238
2239/// Determine if a conversion is a complex promotion.
2240///
2241/// A complex promotion is defined as a complex -> complex conversion
2242/// where the conversion between the underlying real types is a
2243/// floating-point or integral promotion.
2244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2246 if (!FromComplex)
2247 return false;
2248
2249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2250 if (!ToComplex)
2251 return false;
2252
2253 return IsFloatingPointPromotion(FromComplex->getElementType(),
2254 ToComplex->getElementType()) ||
2255 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2256 ToComplex->getElementType());
2257}
2258
2259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2260/// the pointer type FromPtr to a pointer to type ToPointee, with the
2261/// same type qualifiers as FromPtr has on its pointee type. ToType,
2262/// if non-empty, will be a pointer to ToType that may or may not have
2263/// the right set of qualifiers on its pointee.
2264///
2265static QualType
2266BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2267 QualType ToPointee, QualType ToType,
2268 ASTContext &Context,
2269 bool StripObjCLifetime = false) {
2270 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2271 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2272 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
;
2273
2274 /// Conversions to 'id' subsume cv-qualifier conversions.
2275 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2276 return ToType.getUnqualifiedType();
2277
2278 QualType CanonFromPointee
2279 = Context.getCanonicalType(FromPtr->getPointeeType());
2280 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2281 Qualifiers Quals = CanonFromPointee.getQualifiers();
2282
2283 if (StripObjCLifetime)
2284 Quals.removeObjCLifetime();
2285
2286 // Exact qualifier match -> return the pointer type we're converting to.
2287 if (CanonToPointee.getLocalQualifiers() == Quals) {
2288 // ToType is exactly what we need. Return it.
2289 if (!ToType.isNull())
2290 return ToType.getUnqualifiedType();
2291
2292 // Build a pointer to ToPointee. It has the right qualifiers
2293 // already.
2294 if (isa<ObjCObjectPointerType>(ToType))
2295 return Context.getObjCObjectPointerType(ToPointee);
2296 return Context.getPointerType(ToPointee);
2297 }
2298
2299 // Just build a canonical type that has the right qualifiers.
2300 QualType QualifiedCanonToPointee
2301 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2302
2303 if (isa<ObjCObjectPointerType>(ToType))
2304 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2305 return Context.getPointerType(QualifiedCanonToPointee);
2306}
2307
2308static bool isNullPointerConstantForConversion(Expr *Expr,
2309 bool InOverloadResolution,
2310 ASTContext &Context) {
2311 // Handle value-dependent integral null pointer constants correctly.
2312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2315 return !InOverloadResolution;
2316
2317 return Expr->isNullPointerConstant(Context,
2318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2319 : Expr::NPC_ValueDependentIsNull);
2320}
2321
2322/// IsPointerConversion - Determines whether the conversion of the
2323/// expression From, which has the (possibly adjusted) type FromType,
2324/// can be converted to the type ToType via a pointer conversion (C++
2325/// 4.10). If so, returns true and places the converted type (that
2326/// might differ from ToType in its cv-qualifiers at some level) into
2327/// ConvertedType.
2328///
2329/// This routine also supports conversions to and from block pointers
2330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2331/// pointers to interfaces. FIXME: Once we've determined the
2332/// appropriate overloading rules for Objective-C, we may want to
2333/// split the Objective-C checks into a different routine; however,
2334/// GCC seems to consider all of these conversions to be pointer
2335/// conversions, so for now they live here. IncompatibleObjC will be
2336/// set if the conversion is an allowed Objective-C conversion that
2337/// should result in a warning.
2338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2339 bool InOverloadResolution,
2340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
2342 IncompatibleObjC = false;
2343 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2344 IncompatibleObjC))
2345 return true;
2346
2347 // Conversion from a null pointer constant to any Objective-C pointer type.
2348 if (ToType->isObjCObjectPointerType() &&
2349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2350 ConvertedType = ToType;
2351 return true;
2352 }
2353
2354 // Blocks: Block pointers can be converted to void*.
2355 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2356 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2357 ConvertedType = ToType;
2358 return true;
2359 }
2360 // Blocks: A null pointer constant can be converted to a block
2361 // pointer type.
2362 if (ToType->isBlockPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // If the left-hand-side is nullptr_t, the right side can be a null
2369 // pointer constant.
2370 if (ToType->isNullPtrType() &&
2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372 ConvertedType = ToType;
2373 return true;
2374 }
2375
2376 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2377 if (!ToTypePtr)
2378 return false;
2379
2380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382 ConvertedType = ToType;
2383 return true;
2384 }
2385
2386 // Beyond this point, both types need to be pointers
2387 // , including objective-c pointers.
2388 QualType ToPointeeType = ToTypePtr->getPointeeType();
2389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2390 !getLangOpts().ObjCAutoRefCount) {
2391 ConvertedType = BuildSimilarlyQualifiedPointerType(
2392 FromType->getAs<ObjCObjectPointerType>(),
2393 ToPointeeType,
2394 ToType, Context);
2395 return true;
2396 }
2397 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2398 if (!FromTypePtr)
2399 return false;
2400
2401 QualType FromPointeeType = FromTypePtr->getPointeeType();
2402
2403 // If the unqualified pointee types are the same, this can't be a
2404 // pointer conversion, so don't do all of the work below.
2405 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2406 return false;
2407
2408 // An rvalue of type "pointer to cv T," where T is an object type,
2409 // can be converted to an rvalue of type "pointer to cv void" (C++
2410 // 4.10p2).
2411 if (FromPointeeType->isIncompleteOrObjectType() &&
2412 ToPointeeType->isVoidType()) {
2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2414 ToPointeeType,
2415 ToType, Context,
2416 /*StripObjCLifetime=*/true);
2417 return true;
2418 }
2419
2420 // MSVC allows implicit function to void* type conversion.
2421 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2422 ToPointeeType->isVoidType()) {
2423 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2424 ToPointeeType,
2425 ToType, Context);
2426 return true;
2427 }
2428
2429 // When we're overloading in C, we allow a special kind of pointer
2430 // conversion for compatible-but-not-identical pointee types.
2431 if (!getLangOpts().CPlusPlus &&
2432 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2433 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2434 ToPointeeType,
2435 ToType, Context);
2436 return true;
2437 }
2438
2439 // C++ [conv.ptr]p3:
2440 //
2441 // An rvalue of type "pointer to cv D," where D is a class type,
2442 // can be converted to an rvalue of type "pointer to cv B," where
2443 // B is a base class (clause 10) of D. If B is an inaccessible
2444 // (clause 11) or ambiguous (10.2) base class of D, a program that
2445 // necessitates this conversion is ill-formed. The result of the
2446 // conversion is a pointer to the base class sub-object of the
2447 // derived class object. The null pointer value is converted to
2448 // the null pointer value of the destination type.
2449 //
2450 // Note that we do not check for ambiguity or inaccessibility
2451 // here. That is handled by CheckPointerConversion.
2452 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2453 ToPointeeType->isRecordType() &&
2454 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2455 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2457 ToPointeeType,
2458 ToType, Context);
2459 return true;
2460 }
2461
2462 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2463 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2464 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2465 ToPointeeType,
2466 ToType, Context);
2467 return true;
2468 }
2469
2470 return false;
2471}
2472
2473/// Adopt the given qualifiers for the given type.
2474static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2475 Qualifiers TQs = T.getQualifiers();
2476
2477 // Check whether qualifiers already match.
2478 if (TQs == Qs)
2479 return T;
2480
2481 if (Qs.compatiblyIncludes(TQs))
2482 return Context.getQualifiedType(T, Qs);
2483
2484 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2485}
2486
2487/// isObjCPointerConversion - Determines whether this is an
2488/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2489/// with the same arguments and return values.
2490bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2491 QualType& ConvertedType,
2492 bool &IncompatibleObjC) {
2493 if (!getLangOpts().ObjC)
2494 return false;
2495
2496 // The set of qualifiers on the type we're converting from.
2497 Qualifiers FromQualifiers = FromType.getQualifiers();
2498
2499 // First, we handle all conversions on ObjC object pointer types.
2500 const ObjCObjectPointerType* ToObjCPtr =
2501 ToType->getAs<ObjCObjectPointerType>();
2502 const ObjCObjectPointerType *FromObjCPtr =
2503 FromType->getAs<ObjCObjectPointerType>();
2504
2505 if (ToObjCPtr && FromObjCPtr) {
2506 // If the pointee types are the same (ignoring qualifications),
2507 // then this is not a pointer conversion.
2508 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2509 FromObjCPtr->getPointeeType()))
2510 return false;
2511
2512 // Conversion between Objective-C pointers.
2513 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2514 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2515 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2516 if (getLangOpts().CPlusPlus && LHS && RHS &&
2517 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2518 FromObjCPtr->getPointeeType()))
2519 return false;
2520 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2521 ToObjCPtr->getPointeeType(),
2522 ToType, Context);
2523 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2524 return true;
2525 }
2526
2527 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2528 // Okay: this is some kind of implicit downcast of Objective-C
2529 // interfaces, which is permitted. However, we're going to
2530 // complain about it.
2531 IncompatibleObjC = true;
2532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2533 ToObjCPtr->getPointeeType(),
2534 ToType, Context);
2535 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2536 return true;
2537 }
2538 }
2539 // Beyond this point, both types need to be C pointers or block pointers.
2540 QualType ToPointeeType;
2541 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2542 ToPointeeType = ToCPtr->getPointeeType();
2543 else if (const BlockPointerType *ToBlockPtr =
2544 ToType->getAs<BlockPointerType>()) {
2545 // Objective C++: We're able to convert from a pointer to any object
2546 // to a block pointer type.
2547 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2548 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2549 return true;
2550 }
2551 ToPointeeType = ToBlockPtr->getPointeeType();
2552 }
2553 else if (FromType->getAs<BlockPointerType>() &&
2554 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2555 // Objective C++: We're able to convert from a block pointer type to a
2556 // pointer to any object.
2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558 return true;
2559 }
2560 else
2561 return false;
2562
2563 QualType FromPointeeType;
2564 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2565 FromPointeeType = FromCPtr->getPointeeType();
2566 else if (const BlockPointerType *FromBlockPtr =
2567 FromType->getAs<BlockPointerType>())
2568 FromPointeeType = FromBlockPtr->getPointeeType();
2569 else
2570 return false;
2571
2572 // If we have pointers to pointers, recursively check whether this
2573 // is an Objective-C conversion.
2574 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2575 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2576 IncompatibleObjC)) {
2577 // We always complain about this conversion.
2578 IncompatibleObjC = true;
2579 ConvertedType = Context.getPointerType(ConvertedType);
2580 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2581 return true;
2582 }
2583 // Allow conversion of pointee being objective-c pointer to another one;
2584 // as in I* to id.
2585 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2586 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2587 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2588 IncompatibleObjC)) {
2589
2590 ConvertedType = Context.getPointerType(ConvertedType);
2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2592 return true;
2593 }
2594
2595 // If we have pointers to functions or blocks, check whether the only
2596 // differences in the argument and result types are in Objective-C
2597 // pointer conversions. If so, we permit the conversion (but
2598 // complain about it).
2599 const FunctionProtoType *FromFunctionType
2600 = FromPointeeType->getAs<FunctionProtoType>();
2601 const FunctionProtoType *ToFunctionType
2602 = ToPointeeType->getAs<FunctionProtoType>();
2603 if (FromFunctionType && ToFunctionType) {
2604 // If the function types are exactly the same, this isn't an
2605 // Objective-C pointer conversion.
2606 if (Context.getCanonicalType(FromPointeeType)
2607 == Context.getCanonicalType(ToPointeeType))
2608 return false;
2609
2610 // Perform the quick checks that will tell us whether these
2611 // function types are obviously different.
2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2614 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2615 return false;
2616
2617 bool HasObjCConversion = false;
2618 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2619 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2620 // Okay, the types match exactly. Nothing to do.
2621 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2622 ToFunctionType->getReturnType(),
2623 ConvertedType, IncompatibleObjC)) {
2624 // Okay, we have an Objective-C pointer conversion.
2625 HasObjCConversion = true;
2626 } else {
2627 // Function types are too different. Abort.
2628 return false;
2629 }
2630
2631 // Check argument types.
2632 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2633 ArgIdx != NumArgs; ++ArgIdx) {
2634 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2635 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2636 if (Context.getCanonicalType(FromArgType)
2637 == Context.getCanonicalType(ToArgType)) {
2638 // Okay, the types match exactly. Nothing to do.
2639 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2640 ConvertedType, IncompatibleObjC)) {
2641 // Okay, we have an Objective-C pointer conversion.
2642 HasObjCConversion = true;
2643 } else {
2644 // Argument types are too different. Abort.
2645 return false;
2646 }
2647 }
2648
2649 if (HasObjCConversion) {
2650 // We had an Objective-C conversion. Allow this pointer
2651 // conversion, but complain about it.
2652 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2653 IncompatibleObjC = true;
2654 return true;
2655 }
2656 }
2657
2658 return false;
2659}
2660
2661/// Determine whether this is an Objective-C writeback conversion,
2662/// used for parameter passing when performing automatic reference counting.
2663///
2664/// \param FromType The type we're converting form.
2665///
2666/// \param ToType The type we're converting to.
2667///
2668/// \param ConvertedType The type that will be produced after applying
2669/// this conversion.
2670bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2671 QualType &ConvertedType) {
2672 if (!getLangOpts().ObjCAutoRefCount ||
2673 Context.hasSameUnqualifiedType(FromType, ToType))
2674 return false;
2675
2676 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2677 QualType ToPointee;
2678 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2679 ToPointee = ToPointer->getPointeeType();
2680 else
2681 return false;
2682
2683 Qualifiers ToQuals = ToPointee.getQualifiers();
2684 if (!ToPointee->isObjCLifetimeType() ||
2685 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2686 !ToQuals.withoutObjCLifetime().empty())
2687 return false;
2688
2689 // Argument must be a pointer to __strong to __weak.
2690 QualType FromPointee;
2691 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2692 FromPointee = FromPointer->getPointeeType();
2693 else
2694 return false;
2695
2696 Qualifiers FromQuals = FromPointee.getQualifiers();
2697 if (!FromPointee->isObjCLifetimeType() ||
2698 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2699 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2700 return false;
2701
2702 // Make sure that we have compatible qualifiers.
2703 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2704 if (!ToQuals.compatiblyIncludes(FromQuals))
2705 return false;
2706
2707 // Remove qualifiers from the pointee type we're converting from; they
2708 // aren't used in the compatibility check belong, and we'll be adding back
2709 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2710 FromPointee = FromPointee.getUnqualifiedType();
2711
2712 // The unqualified form of the pointee types must be compatible.
2713 ToPointee = ToPointee.getUnqualifiedType();
2714 bool IncompatibleObjC;
2715 if (Context.typesAreCompatible(FromPointee, ToPointee))
2716 FromPointee = ToPointee;
2717 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2718 IncompatibleObjC))
2719 return false;
2720
2721 /// Construct the type we're converting to, which is a pointer to
2722 /// __autoreleasing pointee.
2723 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2724 ConvertedType = Context.getPointerType(FromPointee);
2725 return true;
2726}
2727
2728bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2729 QualType& ConvertedType) {
2730 QualType ToPointeeType;
2731 if (const BlockPointerType *ToBlockPtr =
2732 ToType->getAs<BlockPointerType>())
2733 ToPointeeType = ToBlockPtr->getPointeeType();
2734 else
2735 return false;
2736
2737 QualType FromPointeeType;
2738 if (const BlockPointerType *FromBlockPtr =
2739 FromType->getAs<BlockPointerType>())
2740 FromPointeeType = FromBlockPtr->getPointeeType();
2741 else
2742 return false;
2743 // We have pointer to blocks, check whether the only
2744 // differences in the argument and result types are in Objective-C
2745 // pointer conversions. If so, we permit the conversion.
2746
2747 const FunctionProtoType *FromFunctionType
2748 = FromPointeeType->getAs<FunctionProtoType>();
2749 const FunctionProtoType *ToFunctionType
2750 = ToPointeeType->getAs<FunctionProtoType>();
2751
2752 if (!FromFunctionType || !ToFunctionType)
2753 return false;
2754
2755 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2756 return true;
2757
2758 // Perform the quick checks that will tell us whether these
2759 // function types are obviously different.
2760 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2761 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2762 return false;
2763
2764 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2765 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2766 if (FromEInfo != ToEInfo)
2767 return false;
2768
2769 bool IncompatibleObjC = false;
2770 if (Context.hasSameType(FromFunctionType->getReturnType(),
2771 ToFunctionType->getReturnType())) {
2772 // Okay, the types match exactly. Nothing to do.
2773 } else {
2774 QualType RHS = FromFunctionType->getReturnType();
2775 QualType LHS = ToFunctionType->getReturnType();
2776 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2777 !RHS.hasQualifiers() && LHS.hasQualifiers())
2778 LHS = LHS.getUnqualifiedType();
2779
2780 if (Context.hasSameType(RHS,LHS)) {
2781 // OK exact match.
2782 } else if (isObjCPointerConversion(RHS, LHS,
2783 ConvertedType, IncompatibleObjC)) {
2784 if (IncompatibleObjC)
2785 return false;
2786 // Okay, we have an Objective-C pointer conversion.
2787 }
2788 else
2789 return false;
2790 }
2791
2792 // Check argument types.
2793 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2794 ArgIdx != NumArgs; ++ArgIdx) {
2795 IncompatibleObjC = false;
2796 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2797 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2798 if (Context.hasSameType(FromArgType, ToArgType)) {
2799 // Okay, the types match exactly. Nothing to do.
2800 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2801 ConvertedType, IncompatibleObjC)) {
2802 if (IncompatibleObjC)
2803 return false;
2804 // Okay, we have an Objective-C pointer conversion.
2805 } else
2806 // Argument types are too different. Abort.
2807 return false;
2808 }
2809
2810 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2811 bool CanUseToFPT, CanUseFromFPT;
2812 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2813 CanUseToFPT, CanUseFromFPT,
2814 NewParamInfos))
2815 return false;
2816
2817 ConvertedType = ToType;
2818 return true;
2819}
2820
2821enum {
2822 ft_default,
2823 ft_different_class,
2824 ft_parameter_arity,
2825 ft_parameter_mismatch,
2826 ft_return_type,
2827 ft_qualifer_mismatch,
2828 ft_noexcept
2829};
2830
2831/// Attempts to get the FunctionProtoType from a Type. Handles
2832/// MemberFunctionPointers properly.
2833static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2834 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2835 return FPT;
2836
2837 if (auto *MPT = FromType->getAs<MemberPointerType>())
2838 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2839
2840 return nullptr;
2841}
2842
2843/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2844/// function types. Catches different number of parameter, mismatch in
2845/// parameter types, and different return types.
2846void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2847 QualType FromType, QualType ToType) {
2848 // If either type is not valid, include no extra info.
2849 if (FromType.isNull() || ToType.isNull()) {
2850 PDiag << ft_default;
2851 return;
2852 }
2853
2854 // Get the function type from the pointers.
2855 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2856 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2857 *ToMember = ToType->getAs<MemberPointerType>();
2858 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2859 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2860 << QualType(FromMember->getClass(), 0);
2861 return;
2862 }
2863 FromType = FromMember->getPointeeType();
2864 ToType = ToMember->getPointeeType();
2865 }
2866
2867 if (FromType->isPointerType())
2868 FromType = FromType->getPointeeType();
2869 if (ToType->isPointerType())
2870 ToType = ToType->getPointeeType();
2871
2872 // Remove references.
2873 FromType = FromType.getNonReferenceType();
2874 ToType = ToType.getNonReferenceType();
2875
2876 // Don't print extra info for non-specialized template functions.
2877 if (FromType->isInstantiationDependentType() &&
2878 !FromType->getAs<TemplateSpecializationType>()) {
2879 PDiag << ft_default;
2880 return;
2881 }
2882
2883 // No extra info for same types.
2884 if (Context.hasSameType(FromType, ToType)) {
2885 PDiag << ft_default;
2886 return;
2887 }
2888
2889 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2890 *ToFunction = tryGetFunctionProtoType(ToType);
2891
2892 // Both types need to be function types.
2893 if (!FromFunction || !ToFunction) {
2894 PDiag << ft_default;
2895 return;
2896 }
2897
2898 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2899 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2900 << FromFunction->getNumParams();
2901 return;
2902 }
2903
2904 // Handle different parameter types.
2905 unsigned ArgPos;
2906 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2907 PDiag << ft_parameter_mismatch << ArgPos + 1
2908 << ToFunction->getParamType(ArgPos)
2909 << FromFunction->getParamType(ArgPos);
2910 return;
2911 }
2912
2913 // Handle different return type.
2914 if (!Context.hasSameType(FromFunction->getReturnType(),
2915 ToFunction->getReturnType())) {
2916 PDiag << ft_return_type << ToFunction->getReturnType()
2917 << FromFunction->getReturnType();
2918 return;
2919 }
2920
2921 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2922 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2923 << FromFunction->getMethodQuals();
2924 return;
2925 }
2926
2927 // Handle exception specification differences on canonical type (in C++17
2928 // onwards).
2929 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2930 ->isNothrow() !=
2931 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2932 ->isNothrow()) {
2933 PDiag << ft_noexcept;
2934 return;
2935 }
2936
2937 // Unable to find a difference, so add no extra info.
2938 PDiag << ft_default;
2939}
2940
2941/// FunctionParamTypesAreEqual - This routine checks two function proto types
2942/// for equality of their argument types. Caller has already checked that
2943/// they have same number of arguments. If the parameters are different,
2944/// ArgPos will have the parameter index of the first different parameter.
2945bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2946 const FunctionProtoType *NewType,
2947 unsigned *ArgPos) {
2948 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2949 N = NewType->param_type_begin(),
2950 E = OldType->param_type_end();
2951 O && (O != E); ++O, ++N) {
2952 // Ignore address spaces in pointee type. This is to disallow overloading
2953 // on __ptr32/__ptr64 address spaces.
2954 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2955 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2956
2957 if (!Context.hasSameType(Old, New)) {
2958 if (ArgPos)
2959 *ArgPos = O - OldType->param_type_begin();
2960 return false;
2961 }
2962 }
2963 return true;
2964}
2965
2966/// CheckPointerConversion - Check the pointer conversion from the
2967/// expression From to the type ToType. This routine checks for
2968/// ambiguous or inaccessible derived-to-base pointer
2969/// conversions for which IsPointerConversion has already returned
2970/// true. It returns true and produces a diagnostic if there was an
2971/// error, or returns false otherwise.
2972bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2973 CastKind &Kind,
2974 CXXCastPath& BasePath,
2975 bool IgnoreBaseAccess,
2976 bool Diagnose) {
2977 QualType FromType = From->getType();
2978 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2979
2980 Kind = CK_BitCast;
2981
2982 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2983 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2984 Expr::NPCK_ZeroExpression) {
2985 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2986 DiagRuntimeBehavior(From->getExprLoc(), From,
2987 PDiag(diag::warn_impcast_bool_to_null_pointer)
2988 << ToType << From->getSourceRange());
2989 else if (!isUnevaluatedContext())
2990 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2991 << ToType << From->getSourceRange();
2992 }
2993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2994 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2995 QualType FromPointeeType = FromPtrType->getPointeeType(),
2996 ToPointeeType = ToPtrType->getPointeeType();
2997
2998 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2999 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3000 // We must have a derived-to-base conversion. Check an
3001 // ambiguous or inaccessible conversion.
3002 unsigned InaccessibleID = 0;
3003 unsigned AmbigiousID = 0;
3004 if (Diagnose) {
3005 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3006 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3007 }
3008 if (CheckDerivedToBaseConversion(
3009 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3010 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3011 &BasePath, IgnoreBaseAccess))
3012 return true;
3013
3014 // The conversion was successful.
3015 Kind = CK_DerivedToBase;
3016 }
3017
3018 if (Diagnose && !IsCStyleOrFunctionalCast &&
3019 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3020 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
3021 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
;
3022 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3023 << From->getSourceRange();
3024 }
3025 }
3026 } else if (const ObjCObjectPointerType *ToPtrType =
3027 ToType->getAs<ObjCObjectPointerType>()) {
3028 if (const ObjCObjectPointerType *FromPtrType =
3029 FromType->getAs<ObjCObjectPointerType>()) {
3030 // Objective-C++ conversions are always okay.
3031 // FIXME: We should have a different class of conversions for the
3032 // Objective-C++ implicit conversions.
3033 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3034 return false;
3035 } else if (FromType->isBlockPointerType()) {
3036 Kind = CK_BlockPointerToObjCPointerCast;
3037 } else {
3038 Kind = CK_CPointerToObjCPointerCast;
3039 }
3040 } else if (ToType->isBlockPointerType()) {
3041 if (!FromType->isBlockPointerType())
3042 Kind = CK_AnyPointerToBlockPointerCast;
3043 }
3044
3045 // We shouldn't fall into this case unless it's valid for other
3046 // reasons.
3047 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3048 Kind = CK_NullToPointer;
3049
3050 return false;
3051}
3052
3053/// IsMemberPointerConversion - Determines whether the conversion of the
3054/// expression From, which has the (possibly adjusted) type FromType, can be
3055/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3056/// If so, returns true and places the converted type (that might differ from
3057/// ToType in its cv-qualifiers at some level) into ConvertedType.
3058bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3059 QualType ToType,
3060 bool InOverloadResolution,
3061 QualType &ConvertedType) {
3062 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3063 if (!ToTypePtr)
3064 return false;
3065
3066 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3067 if (From->isNullPointerConstant(Context,
3068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3069 : Expr::NPC_ValueDependentIsNull)) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073
3074 // Otherwise, both types have to be member pointers.
3075 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3076 if (!FromTypePtr)
3077 return false;
3078
3079 // A pointer to member of B can be converted to a pointer to member of D,
3080 // where D is derived from B (C++ 4.11p2).
3081 QualType FromClass(FromTypePtr->getClass(), 0);
3082 QualType ToClass(ToTypePtr->getClass(), 0);
3083
3084 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3085 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3086 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3087 ToClass.getTypePtr());
3088 return true;
3089 }
3090
3091 return false;
3092}
3093
3094/// CheckMemberPointerConversion - Check the member pointer conversion from the
3095/// expression From to the type ToType. This routine checks for ambiguous or
3096/// virtual or inaccessible base-to-derived member pointer conversions
3097/// for which IsMemberPointerConversion has already returned true. It returns
3098/// true and produces a diagnostic if there was an error, or returns false
3099/// otherwise.
3100bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3101 CastKind &Kind,
3102 CXXCastPath &BasePath,
3103 bool IgnoreBaseAccess) {
3104 QualType FromType = From->getType();
3105 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3106 if (!FromPtrType) {
3107 // This must be a null pointer to member pointer conversion
3108 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3109 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3110 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
;
3111 Kind = CK_NullToMemberPointer;
3112 return false;
3113 }
3114
3115 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3116 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
3117 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118
3119 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3120 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3121
3122 // FIXME: What about dependent types?
3123 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
;
3124 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125
3126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3127 /*DetectVirtual=*/true);
3128 bool DerivationOkay =
3129 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3130 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132 (void)DerivationOkay;
3133
3134 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3135 getUnqualifiedType())) {
3136 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3137 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3138 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3139 return true;
3140 }
3141
3142 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3143 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3144 << FromClass << ToClass << QualType(VBase, 0)
3145 << From->getSourceRange();
3146 return true;
3147 }
3148
3149 if (!IgnoreBaseAccess)
3150 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3151 Paths.front(),
3152 diag::err_downcast_from_inaccessible_base);
3153
3154 // Must be a base to derived member conversion.
3155 BuildBasePathArray(Paths, BasePath);
3156 Kind = CK_BaseToDerivedMemberPointer;
3157 return false;
3158}
3159
3160/// Determine whether the lifetime conversion between the two given
3161/// qualifiers sets is nontrivial.
3162static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3163 Qualifiers ToQuals) {
3164 // Converting anything to const __unsafe_unretained is trivial.
3165 if (ToQuals.hasConst() &&
3166 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3167 return false;
3168
3169 return true;
3170}
3171
3172/// Perform a single iteration of the loop for checking if a qualification
3173/// conversion is valid.
3174///
3175/// Specifically, check whether any change between the qualifiers of \p
3176/// FromType and \p ToType is permissible, given knowledge about whether every
3177/// outer layer is const-qualified.
3178static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3179 bool CStyle,
3180 bool &PreviousToQualsIncludeConst,
3181 bool &ObjCLifetimeConversion) {
3182 Qualifiers FromQuals = FromType.getQualifiers();
3183 Qualifiers ToQuals = ToType.getQualifiers();
3184
3185 // Ignore __unaligned qualifier if this type is void.
3186 if (ToType.getUnqualifiedType()->isVoidType())
3187 FromQuals.removeUnaligned();
3188
3189 // Objective-C ARC:
3190 // Check Objective-C lifetime conversions.
3191 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3192 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194 ObjCLifetimeConversion = true;
3195 FromQuals.removeObjCLifetime();
3196 ToQuals.removeObjCLifetime();
3197 } else {
3198 // Qualification conversions cannot cast between different
3199 // Objective-C lifetime qualifiers.
3200 return false;
3201 }
3202 }
3203
3204 // Allow addition/removal of GC attributes but not changing GC attributes.
3205 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207 FromQuals.removeObjCGCAttr();
3208 ToQuals.removeObjCGCAttr();
3209 }
3210
3211 // -- for every j > 0, if const is in cv 1,j then const is in cv
3212 // 2,j, and similarly for volatile.
3213 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3214 return false;
3215
3216 // For a C-style cast, just require the address spaces to overlap.
3217 // FIXME: Does "superset" also imply the representation of a pointer is the
3218 // same? We're assuming that it does here and in compatiblyIncludes.
3219 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3220 !FromQuals.isAddressSpaceSupersetOf(ToQuals))
3221 return false;
3222
3223 // -- if the cv 1,j and cv 2,j are different, then const is in
3224 // every cv for 0 < k < j.
3225 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3226 !PreviousToQualsIncludeConst)
3227 return false;
3228
3229 // Keep track of whether all prior cv-qualifiers in the "to" type
3230 // include const.
3231 PreviousToQualsIncludeConst =
3232 PreviousToQualsIncludeConst && ToQuals.hasConst();
3233 return true;
3234}
3235
3236/// IsQualificationConversion - Determines whether the conversion from
3237/// an rvalue of type FromType to ToType is a qualification conversion
3238/// (C++ 4.4).
3239///
3240/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3241/// when the qualification conversion involves a change in the Objective-C
3242/// object lifetime.
3243bool
3244Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3245 bool CStyle, bool &ObjCLifetimeConversion) {
3246 FromType = Context.getCanonicalType(FromType);
3247 ToType = Context.getCanonicalType(ToType);
3248 ObjCLifetimeConversion = false;
3249
3250 // If FromType and ToType are the same type, this is not a
3251 // qualification conversion.
3252 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3253 return false;
3254
3255 // (C++ 4.4p4):
3256 // A conversion can add cv-qualifiers at levels other than the first
3257 // in multi-level pointers, subject to the following rules: [...]
3258 bool PreviousToQualsIncludeConst = true;
3259 bool UnwrappedAnyPointer = false;
3260 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3261 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3262 PreviousToQualsIncludeConst,
3263 ObjCLifetimeConversion))
3264 return false;
3265 UnwrappedAnyPointer = true;
3266 }
3267
3268 // We are left with FromType and ToType being the pointee types
3269 // after unwrapping the original FromType and ToType the same number
3270 // of times. If we unwrapped any pointers, and if FromType and
3271 // ToType have the same unqualified type (since we checked
3272 // qualifiers above), then this is a qualification conversion.
3273 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3274}
3275
3276/// - Determine whether this is a conversion from a scalar type to an
3277/// atomic type.
3278///
3279/// If successful, updates \c SCS's second and third steps in the conversion
3280/// sequence to finish the conversion.
3281static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3282 bool InOverloadResolution,
3283 StandardConversionSequence &SCS,
3284 bool CStyle) {
3285 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3286 if (!ToAtomic)
3287 return false;
3288
3289 StandardConversionSequence InnerSCS;
3290 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3291 InOverloadResolution, InnerSCS,
3292 CStyle, /*AllowObjCWritebackConversion=*/false))
3293 return false;
3294
3295 SCS.Second = InnerSCS.Second;
3296 SCS.setToType(1, InnerSCS.getToType(1));
3297 SCS.Third = InnerSCS.Third;
3298 SCS.QualificationIncludesObjCLifetime
3299 = InnerSCS.QualificationIncludesObjCLifetime;
3300 SCS.setToType(2, InnerSCS.getToType(2));
3301 return true;
3302}
3303
3304static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3305 CXXConstructorDecl *Constructor,
3306 QualType Type) {
3307 const FunctionProtoType *CtorType =
24
'CtorType' initialized to a null pointer value
3308 Constructor->getType()->getAs<FunctionProtoType>();
23
Assuming the object is not a 'FunctionProtoType'
3309 if (CtorType->getNumParams() > 0) {
25
Called C++ object pointer is null
3310 QualType FirstArg = CtorType->getParamType(0);
3311 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3312 return true;
3313 }
3314 return false;
3315}
3316
3317static OverloadingResult
3318IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3319 CXXRecordDecl *To,
3320 UserDefinedConversionSequence &User,
3321 OverloadCandidateSet &CandidateSet,
3322 bool AllowExplicit) {
3323 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3324 for (auto *D : S.LookupConstructors(To)) {
3325 auto Info = getConstructorInfo(D);
3326 if (!Info)
18
Taking false branch
3327 continue;
3328
3329 bool Usable = !Info.Constructor->isInvalidDecl() &&
19
Assuming the condition is true
3330 S.isInitListConstructor(Info.Constructor);
3331 if (Usable) {
20
Assuming 'Usable' is true
21
Taking true branch
3332 // If the first argument is (a reference to) the target type,
3333 // suppress conversions.
3334 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
22
Calling 'isFirstArgumentCompatibleWithType'
3335 S.Context, Info.Constructor, ToType);
3336 if (Info.ConstructorTmpl)
3337 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3338 /*ExplicitArgs*/ nullptr, From,
3339 CandidateSet, SuppressUserConversions,
3340 /*PartialOverloading*/ false,
3341 AllowExplicit);
3342 else
3343 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3344 CandidateSet, SuppressUserConversions,
3345 /*PartialOverloading*/ false, AllowExplicit);
3346 }
3347 }
3348
3349 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3350
3351 OverloadCandidateSet::iterator Best;
3352 switch (auto Result =
3353 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3354 case OR_Deleted:
3355 case OR_Success: {
3356 // Record the standard conversion we used and the conversion function.
3357 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3358 QualType ThisType = Constructor->getThisType();
3359 // Initializer lists don't have conversions as such.
3360 User.Before.setAsIdentityConversion();
3361 User.HadMultipleCandidates = HadMultipleCandidates;
3362 User.ConversionFunction = Constructor;
3363 User.FoundConversionFunction = Best->FoundDecl;
3364 User.After.setAsIdentityConversion();
3365 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3366 User.After.setAllToTypes(ToType);
3367 return Result;
3368 }
3369
3370 case OR_No_Viable_Function:
3371 return OR_No_Viable_Function;
3372 case OR_Ambiguous:
3373 return OR_Ambiguous;
3374 }
3375
3376 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3376)
;
3377}
3378
3379/// Determines whether there is a user-defined conversion sequence
3380/// (C++ [over.ics.user]) that converts expression From to the type
3381/// ToType. If such a conversion exists, User will contain the
3382/// user-defined conversion sequence that performs such a conversion
3383/// and this routine will return true. Otherwise, this routine returns
3384/// false and User is unspecified.
3385///
3386/// \param AllowExplicit true if the conversion should consider C++0x
3387/// "explicit" conversion functions as well as non-explicit conversion
3388/// functions (C++0x [class.conv.fct]p2).
3389///
3390/// \param AllowObjCConversionOnExplicit true if the conversion should
3391/// allow an extra Objective-C pointer conversion on uses of explicit
3392/// constructors. Requires \c AllowExplicit to also be set.
3393static OverloadingResult
3394IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3395 UserDefinedConversionSequence &User,
3396 OverloadCandidateSet &CandidateSet,
3397 bool AllowExplicit,
3398 bool AllowObjCConversionOnExplicit) {
3399 assert
4.1
'AllowExplicit' is false
4.2
'AllowObjCConversionOnExplicit' is false
(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3399, __PRETTY_FUNCTION__))
;
5
'?' condition is true
3400 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3401 3402 // Whether we will only visit constructors. 3403 bool ConstructorsOnly = false; 3404 3405 // If the type we are conversion to is a class type, enumerate its 3406 // constructors. 3407 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
6
Assuming the object is a 'RecordType'
7
Assuming 'ToRecordType' is non-null
8
Taking true branch
3408 // C++ [over.match.ctor]p1: 3409 // When objects of class type are direct-initialized (8.5), or 3410 // copy-initialized from an expression of the same or a 3411 // derived class type (8.5), overload resolution selects the 3412 // constructor. [...] For copy-initialization, the candidate 3413 // functions are all the converting constructors (12.3.1) of 3414 // that class. The argument list is the expression-list within 3415 // the parentheses of the initializer. 3416 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
9
Assuming the condition is false
11
Taking false branch
3417 (From->getType()->getAs<RecordType>() &&
10
Assuming the object is not a 'RecordType'
3418 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3419 ConstructorsOnly = true; 3420 3421 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
12
Taking false branch
3422 // We're not going to find any constructors. 3423 } else if (CXXRecordDecl *ToRecordDecl
13.1
'ToRecordDecl' is non-null
14
Taking true branch
3424 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
13
Assuming the object is a 'CXXRecordDecl'
3425 3426 Expr **Args = &From; 3427 unsigned NumArgs = 1; 3428 bool ListInitializing = false; 3429 if (InitListExpr *InitList
15.1
'InitList' is non-null
= dyn_cast<InitListExpr>(From)) {
15
Assuming 'From' is a 'InitListExpr'
16
Taking true branch
3430 // But first, see if there is an init-list-constructor that will work. 3431 OverloadingResult Result = IsInitializerListConstructorConversion(
17
Calling 'IsInitializerListConstructorConversion'
3432 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3433 if (Result != OR_No_Viable_Function) 3434 return Result; 3435 // Never mind. 3436 CandidateSet.clear( 3437 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3438 3439 // If we're list-initializing, we pass the individual elements as 3440 // arguments, not the entire list. 3441 Args = InitList->getInits(); 3442 NumArgs = InitList->getNumInits(); 3443 ListInitializing = true; 3444 } 3445 3446 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3447 auto Info = getConstructorInfo(D); 3448 if (!Info) 3449 continue; 3450 3451 bool Usable = !Info.Constructor->isInvalidDecl(); 3452 if (!ListInitializing) 3453 Usable = Usable && Info.Constructor->isConvertingConstructor( 3454 /*AllowExplicit*/ true); 3455 if (Usable) { 3456 bool SuppressUserConversions = !ConstructorsOnly; 3457 if (SuppressUserConversions && ListInitializing) { 3458 SuppressUserConversions = false; 3459 if (NumArgs == 1) { 3460 // If the first argument is (a reference to) the target type, 3461 // suppress conversions. 3462 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3463 S.Context, Info.Constructor, ToType); 3464 } 3465 } 3466 if (Info.ConstructorTmpl) 3467 S.AddTemplateOverloadCandidate( 3468 Info.ConstructorTmpl, Info.FoundDecl, 3469 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3470 CandidateSet, SuppressUserConversions, 3471 /*PartialOverloading*/ false, AllowExplicit); 3472 else 3473 // Allow one user-defined conversion when user specifies a 3474 // From->ToType conversion via an static cast (c-style, etc). 3475 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3476 llvm::makeArrayRef(Args, NumArgs), 3477 CandidateSet, SuppressUserConversions, 3478 /*PartialOverloading*/ false, AllowExplicit); 3479 } 3480 } 3481 } 3482 } 3483 3484 // Enumerate conversion functions, if we're allowed to. 3485 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3486 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3487 // No conversion functions from incomplete types. 3488 } else if (const RecordType *FromRecordType = 3489 From->getType()->getAs<RecordType>()) { 3490 if (CXXRecordDecl *FromRecordDecl 3491 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3492 // Add all of the conversion functions as candidates. 3493 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3494 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3495 DeclAccessPair FoundDecl = I.getPair(); 3496 NamedDecl *D = FoundDecl.getDecl(); 3497 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3498 if (isa<UsingShadowDecl>(D)) 3499 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3500 3501 CXXConversionDecl *Conv; 3502 FunctionTemplateDecl *ConvTemplate; 3503 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3504 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3505 else 3506 Conv = cast<CXXConversionDecl>(D); 3507 3508 if (ConvTemplate) 3509 S.AddTemplateConversionCandidate( 3510 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3511 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3512 else 3513 S.AddConversionCandidate( 3514 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3515 AllowObjCConversionOnExplicit, AllowExplicit); 3516 } 3517 } 3518 } 3519 3520 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3521 3522 OverloadCandidateSet::iterator Best; 3523 switch (auto Result = 3524 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3525 case OR_Success: 3526 case OR_Deleted: 3527 // Record the standard conversion we used and the conversion function. 3528 if (CXXConstructorDecl *Constructor 3529 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3530 // C++ [over.ics.user]p1: 3531 // If the user-defined conversion is specified by a 3532 // constructor (12.3.1), the initial standard conversion 3533 // sequence converts the source type to the type required by 3534 // the argument of the constructor. 3535 // 3536 QualType ThisType = Constructor->getThisType(); 3537 if (isa<InitListExpr>(From)) { 3538 // Initializer lists don't have conversions as such. 3539 User.Before.setAsIdentityConversion(); 3540 } else { 3541 if (Best->Conversions[0].isEllipsis()) 3542 User.EllipsisConversion = true; 3543 else { 3544 User.Before = Best->Conversions[0].Standard; 3545 User.EllipsisConversion = false; 3546 } 3547 } 3548 User.HadMultipleCandidates = HadMultipleCandidates; 3549 User.ConversionFunction = Constructor; 3550 User.FoundConversionFunction = Best->FoundDecl; 3551 User.After.setAsIdentityConversion(); 3552 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3553 User.After.setAllToTypes(ToType); 3554 return Result; 3555 } 3556 if (CXXConversionDecl *Conversion 3557 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3558 // C++ [over.ics.user]p1: 3559 // 3560 // [...] If the user-defined conversion is specified by a 3561 // conversion function (12.3.2), the initial standard 3562 // conversion sequence converts the source type to the 3563 // implicit object parameter of the conversion function. 3564 User.Before = Best->Conversions[0].Standard; 3565 User.HadMultipleCandidates = HadMultipleCandidates; 3566 User.ConversionFunction = Conversion; 3567 User.FoundConversionFunction = Best->FoundDecl; 3568 User.EllipsisConversion = false; 3569 3570 // C++ [over.ics.user]p2: 3571 // The second standard conversion sequence converts the 3572 // result of the user-defined conversion to the target type 3573 // for the sequence. Since an implicit conversion sequence 3574 // is an initialization, the special rules for 3575 // initialization by user-defined conversion apply when 3576 // selecting the best user-defined conversion for a 3577 // user-defined conversion sequence (see 13.3.3 and 3578 // 13.3.3.1). 3579 User.After = Best->FinalConversion; 3580 return Result; 3581 } 3582 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3582)
; 3583 3584 case OR_No_Viable_Function: 3585 return OR_No_Viable_Function; 3586 3587 case OR_Ambiguous: 3588 return OR_Ambiguous; 3589 } 3590 3591 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3591)
; 3592} 3593 3594bool 3595Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3596 ImplicitConversionSequence ICS; 3597 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3598 OverloadCandidateSet::CSK_Normal); 3599 OverloadingResult OvResult = 3600 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4
Calling 'IsUserDefinedConversion'
3601 CandidateSet, false, false); 3602 3603 if (!(OvResult == OR_Ambiguous || 3604 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3605 return false; 3606 3607 auto Cands = CandidateSet.CompleteCandidates( 3608 *this, 3609 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3610 From); 3611 if (OvResult == OR_Ambiguous) 3612 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3613 << From->getType() << ToType << From->getSourceRange(); 3614 else { // OR_No_Viable_Function && !CandidateSet.empty() 3615 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3616 diag::err_typecheck_nonviable_condition_incomplete, 3617 From->getType(), From->getSourceRange())) 3618 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3619 << false << From->getType() << From->getSourceRange() << ToType; 3620 } 3621 3622 CandidateSet.NoteCandidates( 3623 *this, From, Cands); 3624 return true; 3625} 3626 3627/// Compare the user-defined conversion functions or constructors 3628/// of two user-defined conversion sequences to determine whether any ordering 3629/// is possible. 3630static ImplicitConversionSequence::CompareKind 3631compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3632 FunctionDecl *Function2) { 3633 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3634 return ImplicitConversionSequence::Indistinguishable; 3635 3636 // Objective-C++: 3637 // If both conversion functions are implicitly-declared conversions from 3638 // a lambda closure type to a function pointer and a block pointer, 3639 // respectively, always prefer the conversion to a function pointer, 3640 // because the function pointer is more lightweight and is more likely 3641 // to keep code working. 3642 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3643 if (!Conv1) 3644 return ImplicitConversionSequence::Indistinguishable; 3645 3646 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3647 if (!Conv2) 3648 return ImplicitConversionSequence::Indistinguishable; 3649 3650 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3651 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3652 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3653 if (Block1 != Block2) 3654 return Block1 ? ImplicitConversionSequence::Worse 3655 : ImplicitConversionSequence::Better; 3656 } 3657 3658 return ImplicitConversionSequence::Indistinguishable; 3659} 3660 3661static bool hasDeprecatedStringLiteralToCharPtrConversion( 3662 const ImplicitConversionSequence &ICS) { 3663 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3664 (ICS.isUserDefined() && 3665 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3666} 3667 3668/// CompareImplicitConversionSequences - Compare two implicit 3669/// conversion sequences to determine whether one is better than the 3670/// other or if they are indistinguishable (C++ 13.3.3.2). 3671static ImplicitConversionSequence::CompareKind 3672CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3673 const ImplicitConversionSequence& ICS1, 3674 const ImplicitConversionSequence& ICS2) 3675{ 3676 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3677 // conversion sequences (as defined in 13.3.3.1) 3678 // -- a standard conversion sequence (13.3.3.1.1) is a better 3679 // conversion sequence than a user-defined conversion sequence or 3680 // an ellipsis conversion sequence, and 3681 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3682 // conversion sequence than an ellipsis conversion sequence 3683 // (13.3.3.1.3). 3684 // 3685 // C++0x [over.best.ics]p10: 3686 // For the purpose of ranking implicit conversion sequences as 3687 // described in 13.3.3.2, the ambiguous conversion sequence is 3688 // treated as a user-defined sequence that is indistinguishable 3689 // from any other user-defined conversion sequence. 3690 3691 // String literal to 'char *' conversion has been deprecated in C++03. It has 3692 // been removed from C++11. We still accept this conversion, if it happens at 3693 // the best viable function. Otherwise, this conversion is considered worse 3694 // than ellipsis conversion. Consider this as an extension; this is not in the 3695 // standard. For example: 3696 // 3697 // int &f(...); // #1 3698 // void f(char*); // #2 3699 // void g() { int &r = f("foo"); } 3700 // 3701 // In C++03, we pick #2 as the best viable function. 3702 // In C++11, we pick #1 as the best viable function, because ellipsis 3703 // conversion is better than string-literal to char* conversion (since there 3704 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3705 // convert arguments, #2 would be the best viable function in C++11. 3706 // If the best viable function has this conversion, a warning will be issued 3707 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3708 3709 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3710 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3711 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3712 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3713 ? ImplicitConversionSequence::Worse 3714 : ImplicitConversionSequence::Better; 3715 3716 if (ICS1.getKindRank() < ICS2.getKindRank()) 3717 return ImplicitConversionSequence::Better; 3718 if (ICS2.getKindRank() < ICS1.getKindRank()) 3719 return ImplicitConversionSequence::Worse; 3720 3721 // The following checks require both conversion sequences to be of 3722 // the same kind. 3723 if (ICS1.getKind() != ICS2.getKind()) 3724 return ImplicitConversionSequence::Indistinguishable; 3725 3726 ImplicitConversionSequence::CompareKind Result = 3727 ImplicitConversionSequence::Indistinguishable; 3728 3729 // Two implicit conversion sequences of the same form are 3730 // indistinguishable conversion sequences unless one of the 3731 // following rules apply: (C++ 13.3.3.2p3): 3732 3733 // List-initialization sequence L1 is a better conversion sequence than 3734 // list-initialization sequence L2 if: 3735 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3736 // if not that, 3737 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3738 // and N1 is smaller than N2., 3739 // even if one of the other rules in this paragraph would otherwise apply. 3740 if (!ICS1.isBad()) { 3741 if (ICS1.isStdInitializerListElement() && 3742 !ICS2.isStdInitializerListElement()) 3743 return ImplicitConversionSequence::Better; 3744 if (!ICS1.isStdInitializerListElement() && 3745 ICS2.isStdInitializerListElement()) 3746 return ImplicitConversionSequence::Worse; 3747 } 3748 3749 if (ICS1.isStandard()) 3750 // Standard conversion sequence S1 is a better conversion sequence than 3751 // standard conversion sequence S2 if [...] 3752 Result = CompareStandardConversionSequences(S, Loc, 3753 ICS1.Standard, ICS2.Standard); 3754 else if (ICS1.isUserDefined()) { 3755 // User-defined conversion sequence U1 is a better conversion 3756 // sequence than another user-defined conversion sequence U2 if 3757 // they contain the same user-defined conversion function or 3758 // constructor and if the second standard conversion sequence of 3759 // U1 is better than the second standard conversion sequence of 3760 // U2 (C++ 13.3.3.2p3). 3761 if (ICS1.UserDefined.ConversionFunction == 3762 ICS2.UserDefined.ConversionFunction) 3763 Result = CompareStandardConversionSequences(S, Loc, 3764 ICS1.UserDefined.After, 3765 ICS2.UserDefined.After); 3766 else 3767 Result = compareConversionFunctions(S, 3768 ICS1.UserDefined.ConversionFunction, 3769 ICS2.UserDefined.ConversionFunction); 3770 } 3771 3772 return Result; 3773} 3774 3775// Per 13.3.3.2p3, compare the given standard conversion sequences to 3776// determine if one is a proper subset of the other. 3777static ImplicitConversionSequence::CompareKind 3778compareStandardConversionSubsets(ASTContext &Context, 3779 const StandardConversionSequence& SCS1, 3780 const StandardConversionSequence& SCS2) { 3781 ImplicitConversionSequence::CompareKind Result 3782 = ImplicitConversionSequence::Indistinguishable; 3783 3784 // the identity conversion sequence is considered to be a subsequence of 3785 // any non-identity conversion sequence 3786 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3787 return ImplicitConversionSequence::Better; 3788 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3789 return ImplicitConversionSequence::Worse; 3790 3791 if (SCS1.Second != SCS2.Second) { 3792 if (SCS1.Second == ICK_Identity) 3793 Result = ImplicitConversionSequence::Better; 3794 else if (SCS2.Second == ICK_Identity) 3795 Result = ImplicitConversionSequence::Worse; 3796 else 3797 return ImplicitConversionSequence::Indistinguishable; 3798 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3799 return ImplicitConversionSequence::Indistinguishable; 3800 3801 if (SCS1.Third == SCS2.Third) { 3802 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3803 : ImplicitConversionSequence::Indistinguishable; 3804 } 3805 3806 if (SCS1.Third == ICK_Identity) 3807 return Result == ImplicitConversionSequence::Worse 3808 ? ImplicitConversionSequence::Indistinguishable 3809 : ImplicitConversionSequence::Better; 3810 3811 if (SCS2.Third == ICK_Identity) 3812 return Result == ImplicitConversionSequence::Better 3813 ? ImplicitConversionSequence::Indistinguishable 3814 : ImplicitConversionSequence::Worse; 3815 3816 return ImplicitConversionSequence::Indistinguishable; 3817} 3818 3819/// Determine whether one of the given reference bindings is better 3820/// than the other based on what kind of bindings they are. 3821static bool 3822isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3823 const StandardConversionSequence &SCS2) { 3824 // C++0x [over.ics.rank]p3b4: 3825 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3826 // implicit object parameter of a non-static member function declared 3827 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3828 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3829 // lvalue reference to a function lvalue and S2 binds an rvalue 3830 // reference*. 3831 // 3832 // FIXME: Rvalue references. We're going rogue with the above edits, 3833 // because the semantics in the current C++0x working paper (N3225 at the 3834 // time of this writing) break the standard definition of std::forward 3835 // and std::reference_wrapper when dealing with references to functions. 3836 // Proposed wording changes submitted to CWG for consideration. 3837 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3838 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3839 return false; 3840 3841 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3842 SCS2.IsLvalueReference) || 3843 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3844 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3845} 3846 3847enum class FixedEnumPromotion { 3848 None, 3849 ToUnderlyingType, 3850 ToPromotedUnderlyingType 3851}; 3852 3853/// Returns kind of fixed enum promotion the \a SCS uses. 3854static FixedEnumPromotion 3855getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3856 3857 if (SCS.Second != ICK_Integral_Promotion) 3858 return FixedEnumPromotion::None; 3859 3860 QualType FromType = SCS.getFromType(); 3861 if (!FromType->isEnumeralType()) 3862 return FixedEnumPromotion::None; 3863 3864 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3865 if (!Enum->isFixed()) 3866 return FixedEnumPromotion::None; 3867 3868 QualType UnderlyingType = Enum->getIntegerType(); 3869 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3870 return FixedEnumPromotion::ToUnderlyingType; 3871 3872 return FixedEnumPromotion::ToPromotedUnderlyingType; 3873} 3874 3875/// CompareStandardConversionSequences - Compare two standard 3876/// conversion sequences to determine whether one is better than the 3877/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3878static ImplicitConversionSequence::CompareKind 3879CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3880 const StandardConversionSequence& SCS1, 3881 const StandardConversionSequence& SCS2) 3882{ 3883 // Standard conversion sequence S1 is a better conversion sequence 3884 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3885 3886 // -- S1 is a proper subsequence of S2 (comparing the conversion 3887 // sequences in the canonical form defined by 13.3.3.1.1, 3888 // excluding any Lvalue Transformation; the identity conversion 3889 // sequence is considered to be a subsequence of any 3890 // non-identity conversion sequence) or, if not that, 3891 if (ImplicitConversionSequence::CompareKind CK 3892 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3893 return CK; 3894 3895 // -- the rank of S1 is better than the rank of S2 (by the rules 3896 // defined below), or, if not that, 3897 ImplicitConversionRank Rank1 = SCS1.getRank(); 3898 ImplicitConversionRank Rank2 = SCS2.getRank(); 3899 if (Rank1 < Rank2) 3900 return ImplicitConversionSequence::Better; 3901 else if (Rank2 < Rank1) 3902 return ImplicitConversionSequence::Worse; 3903 3904 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3905 // are indistinguishable unless one of the following rules 3906 // applies: 3907 3908 // A conversion that is not a conversion of a pointer, or 3909 // pointer to member, to bool is better than another conversion 3910 // that is such a conversion. 3911 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3912 return SCS2.isPointerConversionToBool() 3913 ? ImplicitConversionSequence::Better 3914 : ImplicitConversionSequence::Worse; 3915 3916 // C++14 [over.ics.rank]p4b2: 3917 // This is retroactively applied to C++11 by CWG 1601. 3918 // 3919 // A conversion that promotes an enumeration whose underlying type is fixed 3920 // to its underlying type is better than one that promotes to the promoted 3921 // underlying type, if the two are different. 3922 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3923 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3924 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3925 FEP1 != FEP2) 3926 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3927 ? ImplicitConversionSequence::Better 3928 : ImplicitConversionSequence::Worse; 3929 3930 // C++ [over.ics.rank]p4b2: 3931 // 3932 // If class B is derived directly or indirectly from class A, 3933 // conversion of B* to A* is better than conversion of B* to 3934 // void*, and conversion of A* to void* is better than conversion 3935 // of B* to void*. 3936 bool SCS1ConvertsToVoid 3937 = SCS1.isPointerConversionToVoidPointer(S.Context); 3938 bool SCS2ConvertsToVoid 3939 = SCS2.isPointerConversionToVoidPointer(S.Context); 3940 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3941 // Exactly one of the conversion sequences is a conversion to 3942 // a void pointer; it's the worse conversion. 3943 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3944 : ImplicitConversionSequence::Worse; 3945 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3946 // Neither conversion sequence converts to a void pointer; compare 3947 // their derived-to-base conversions. 3948 if (ImplicitConversionSequence::CompareKind DerivedCK 3949 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3950 return DerivedCK; 3951 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3952 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3953 // Both conversion sequences are conversions to void 3954 // pointers. Compare the source types to determine if there's an 3955 // inheritance relationship in their sources. 3956 QualType FromType1 = SCS1.getFromType(); 3957 QualType FromType2 = SCS2.getFromType(); 3958 3959 // Adjust the types we're converting from via the array-to-pointer 3960 // conversion, if we need to. 3961 if (SCS1.First == ICK_Array_To_Pointer) 3962 FromType1 = S.Context.getArrayDecayedType(FromType1); 3963 if (SCS2.First == ICK_Array_To_Pointer) 3964 FromType2 = S.Context.getArrayDecayedType(FromType2); 3965 3966 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3967 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3968 3969 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3970 return ImplicitConversionSequence::Better; 3971 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3972 return ImplicitConversionSequence::Worse; 3973 3974 // Objective-C++: If one interface is more specific than the 3975 // other, it is the better one. 3976 const ObjCObjectPointerType* FromObjCPtr1 3977 = FromType1->getAs<ObjCObjectPointerType>(); 3978 const ObjCObjectPointerType* FromObjCPtr2 3979 = FromType2->getAs<ObjCObjectPointerType>(); 3980 if (FromObjCPtr1 && FromObjCPtr2) { 3981 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3982 FromObjCPtr2); 3983 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3984 FromObjCPtr1); 3985 if (AssignLeft != AssignRight) { 3986 return AssignLeft? ImplicitConversionSequence::Better 3987 : ImplicitConversionSequence::Worse; 3988 } 3989 } 3990 } 3991 3992 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3993 // Check for a better reference binding based on the kind of bindings. 3994 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3995 return ImplicitConversionSequence::Better; 3996 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3997 return ImplicitConversionSequence::Worse; 3998 } 3999 4000 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4001 // bullet 3). 4002 if (ImplicitConversionSequence::CompareKind QualCK 4003 = CompareQualificationConversions(S, SCS1, SCS2)) 4004 return QualCK; 4005 4006 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4007 // C++ [over.ics.rank]p3b4: 4008 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4009 // which the references refer are the same type except for 4010 // top-level cv-qualifiers, and the type to which the reference 4011 // initialized by S2 refers is more cv-qualified than the type 4012 // to which the reference initialized by S1 refers. 4013 QualType T1 = SCS1.getToType(2); 4014 QualType T2 = SCS2.getToType(2); 4015 T1 = S.Context.getCanonicalType(T1); 4016 T2 = S.Context.getCanonicalType(T2); 4017 Qualifiers T1Quals, T2Quals; 4018 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4019 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4020 if (UnqualT1 == UnqualT2) { 4021 // Objective-C++ ARC: If the references refer to objects with different 4022 // lifetimes, prefer bindings that don't change lifetime. 4023 if (SCS1.ObjCLifetimeConversionBinding != 4024 SCS2.ObjCLifetimeConversionBinding) { 4025 return SCS1.ObjCLifetimeConversionBinding 4026 ? ImplicitConversionSequence::Worse 4027 : ImplicitConversionSequence::Better; 4028 } 4029 4030 // If the type is an array type, promote the element qualifiers to the 4031 // type for comparison. 4032 if (isa<ArrayType>(T1) && T1Quals) 4033 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4034 if (isa<ArrayType>(T2) && T2Quals) 4035 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4036 if (T2.isMoreQualifiedThan(T1)) 4037 return ImplicitConversionSequence::Better; 4038 if (T1.isMoreQualifiedThan(T2)) 4039 return ImplicitConversionSequence::Worse; 4040 } 4041 } 4042 4043 // In Microsoft mode, prefer an integral conversion to a 4044 // floating-to-integral conversion if the integral conversion 4045 // is between types of the same size. 4046 // For example: 4047 // void f(float); 4048 // void f(int); 4049 // int main { 4050 // long a; 4051 // f(a); 4052 // } 4053 // Here, MSVC will call f(int) instead of generating a compile error 4054 // as clang will do in standard mode. 4055 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4056 SCS2.Second == ICK_Floating_Integral && 4057 S.Context.getTypeSize(SCS1.getFromType()) == 4058 S.Context.getTypeSize(SCS1.getToType(2))) 4059 return ImplicitConversionSequence::Better; 4060 4061 // Prefer a compatible vector conversion over a lax vector conversion 4062 // For example: 4063 // 4064 // typedef float __v4sf __attribute__((__vector_size__(16))); 4065 // void f(vector float); 4066 // void f(vector signed int); 4067 // int main() { 4068 // __v4sf a; 4069 // f(a); 4070 // } 4071 // Here, we'd like to choose f(vector float) and not 4072 // report an ambiguous call error 4073 if (SCS1.Second == ICK_Vector_Conversion && 4074 SCS2.Second == ICK_Vector_Conversion) { 4075 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4076 SCS1.getFromType(), SCS1.getToType(2)); 4077 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4078 SCS2.getFromType(), SCS2.getToType(2)); 4079 4080 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4081 return SCS1IsCompatibleVectorConversion 4082 ? ImplicitConversionSequence::Better 4083 : ImplicitConversionSequence::Worse; 4084 } 4085 4086 return ImplicitConversionSequence::Indistinguishable; 4087} 4088 4089/// CompareQualificationConversions - Compares two standard conversion 4090/// sequences to determine whether they can be ranked based on their 4091/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4092static ImplicitConversionSequence::CompareKind 4093CompareQualificationConversions(Sema &S, 4094 const StandardConversionSequence& SCS1, 4095 const StandardConversionSequence& SCS2) { 4096 // C++ 13.3.3.2p3: 4097 // -- S1 and S2 differ only in their qualification conversion and 4098 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4099 // cv-qualification signature of type T1 is a proper subset of 4100 // the cv-qualification signature of type T2, and S1 is not the 4101 // deprecated string literal array-to-pointer conversion (4.2). 4102 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4103 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4104 return ImplicitConversionSequence::Indistinguishable; 4105 4106 // FIXME: the example in the standard doesn't use a qualification 4107 // conversion (!) 4108 QualType T1 = SCS1.getToType(2); 4109 QualType T2 = SCS2.getToType(2); 4110 T1 = S.Context.getCanonicalType(T1); 4111 T2 = S.Context.getCanonicalType(T2); 4112 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4112, __PRETTY_FUNCTION__))
; 4113 Qualifiers T1Quals, T2Quals; 4114 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4115 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4116 4117 // If the types are the same, we won't learn anything by unwrapping 4118 // them. 4119 if (UnqualT1 == UnqualT2) 4120 return ImplicitConversionSequence::Indistinguishable; 4121 4122 ImplicitConversionSequence::CompareKind Result 4123 = ImplicitConversionSequence::Indistinguishable; 4124 4125 // Objective-C++ ARC: 4126 // Prefer qualification conversions not involving a change in lifetime 4127 // to qualification conversions that do not change lifetime. 4128 if (SCS1.QualificationIncludesObjCLifetime != 4129 SCS2.QualificationIncludesObjCLifetime) { 4130 Result = SCS1.QualificationIncludesObjCLifetime 4131 ? ImplicitConversionSequence::Worse 4132 : ImplicitConversionSequence::Better; 4133 } 4134 4135 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4136 // Within each iteration of the loop, we check the qualifiers to 4137 // determine if this still looks like a qualification 4138 // conversion. Then, if all is well, we unwrap one more level of 4139 // pointers or pointers-to-members and do it all again 4140 // until there are no more pointers or pointers-to-members left 4141 // to unwrap. This essentially mimics what 4142 // IsQualificationConversion does, but here we're checking for a 4143 // strict subset of qualifiers. 4144 if (T1.getQualifiers().withoutObjCLifetime() == 4145 T2.getQualifiers().withoutObjCLifetime()) 4146 // The qualifiers are the same, so this doesn't tell us anything 4147 // about how the sequences rank. 4148 // ObjC ownership quals are omitted above as they interfere with 4149 // the ARC overload rule. 4150 ; 4151 else if (T2.isMoreQualifiedThan(T1)) { 4152 // T1 has fewer qualifiers, so it could be the better sequence. 4153 if (Result == ImplicitConversionSequence::Worse) 4154 // Neither has qualifiers that are a subset of the other's 4155 // qualifiers. 4156 return ImplicitConversionSequence::Indistinguishable; 4157 4158 Result = ImplicitConversionSequence::Better; 4159 } else if (T1.isMoreQualifiedThan(T2)) { 4160 // T2 has fewer qualifiers, so it could be the better sequence. 4161 if (Result == ImplicitConversionSequence::Better) 4162 // Neither has qualifiers that are a subset of the other's 4163 // qualifiers. 4164 return ImplicitConversionSequence::Indistinguishable; 4165 4166 Result = ImplicitConversionSequence::Worse; 4167 } else { 4168 // Qualifiers are disjoint. 4169 return ImplicitConversionSequence::Indistinguishable; 4170 } 4171 4172 // If the types after this point are equivalent, we're done. 4173 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4174 break; 4175 } 4176 4177 // Check that the winning standard conversion sequence isn't using 4178 // the deprecated string literal array to pointer conversion. 4179 switch (Result) { 4180 case ImplicitConversionSequence::Better: 4181 if (SCS1.DeprecatedStringLiteralToCharPtr) 4182 Result = ImplicitConversionSequence::Indistinguishable; 4183 break; 4184 4185 case ImplicitConversionSequence::Indistinguishable: 4186 break; 4187 4188 case ImplicitConversionSequence::Worse: 4189 if (SCS2.DeprecatedStringLiteralToCharPtr) 4190 Result = ImplicitConversionSequence::Indistinguishable; 4191 break; 4192 } 4193 4194 return Result; 4195} 4196 4197/// CompareDerivedToBaseConversions - Compares two standard conversion 4198/// sequences to determine whether they can be ranked based on their 4199/// various kinds of derived-to-base conversions (C++ 4200/// [over.ics.rank]p4b3). As part of these checks, we also look at 4201/// conversions between Objective-C interface types. 4202static ImplicitConversionSequence::CompareKind 4203CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4204 const StandardConversionSequence& SCS1, 4205 const StandardConversionSequence& SCS2) { 4206 QualType FromType1 = SCS1.getFromType(); 4207 QualType ToType1 = SCS1.getToType(1); 4208 QualType FromType2 = SCS2.getFromType(); 4209 QualType ToType2 = SCS2.getToType(1); 4210 4211 // Adjust the types we're converting from via the array-to-pointer 4212 // conversion, if we need to. 4213 if (SCS1.First == ICK_Array_To_Pointer) 4214 FromType1 = S.Context.getArrayDecayedType(FromType1); 4215 if (SCS2.First == ICK_Array_To_Pointer) 4216 FromType2 = S.Context.getArrayDecayedType(FromType2); 4217 4218 // Canonicalize all of the types. 4219 FromType1 = S.Context.getCanonicalType(FromType1); 4220 ToType1 = S.Context.getCanonicalType(ToType1); 4221 FromType2 = S.Context.getCanonicalType(FromType2); 4222 ToType2 = S.Context.getCanonicalType(ToType2); 4223 4224 // C++ [over.ics.rank]p4b3: 4225 // 4226 // If class B is derived directly or indirectly from class A and 4227 // class C is derived directly or indirectly from B, 4228 // 4229 // Compare based on pointer conversions. 4230 if (SCS1.Second == ICK_Pointer_Conversion && 4231 SCS2.Second == ICK_Pointer_Conversion && 4232 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4233 FromType1->isPointerType() && FromType2->isPointerType() && 4234 ToType1->isPointerType() && ToType2->isPointerType()) { 4235 QualType FromPointee1 = 4236 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4237 QualType ToPointee1 = 4238 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4239 QualType FromPointee2 = 4240 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4241 QualType ToPointee2 = 4242 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4243 4244 // -- conversion of C* to B* is better than conversion of C* to A*, 4245 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4246 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4247 return ImplicitConversionSequence::Better; 4248 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4249 return ImplicitConversionSequence::Worse; 4250 } 4251 4252 // -- conversion of B* to A* is better than conversion of C* to A*, 4253 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4254 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4255 return ImplicitConversionSequence::Better; 4256 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4257 return ImplicitConversionSequence::Worse; 4258 } 4259 } else if (SCS1.Second == ICK_Pointer_Conversion && 4260 SCS2.Second == ICK_Pointer_Conversion) { 4261 const ObjCObjectPointerType *FromPtr1 4262 = FromType1->getAs<ObjCObjectPointerType>(); 4263 const ObjCObjectPointerType *FromPtr2 4264 = FromType2->getAs<ObjCObjectPointerType>(); 4265 const ObjCObjectPointerType *ToPtr1 4266 = ToType1->getAs<ObjCObjectPointerType>(); 4267 const ObjCObjectPointerType *ToPtr2 4268 = ToType2->getAs<ObjCObjectPointerType>(); 4269 4270 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4271 // Apply the same conversion ranking rules for Objective-C pointer types 4272 // that we do for C++ pointers to class types. However, we employ the 4273 // Objective-C pseudo-subtyping relationship used for assignment of 4274 // Objective-C pointer types. 4275 bool FromAssignLeft 4276 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4277 bool FromAssignRight 4278 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4279 bool ToAssignLeft 4280 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4281 bool ToAssignRight 4282 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4283 4284 // A conversion to an a non-id object pointer type or qualified 'id' 4285 // type is better than a conversion to 'id'. 4286 if (ToPtr1->isObjCIdType() && 4287 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4288 return ImplicitConversionSequence::Worse; 4289 if (ToPtr2->isObjCIdType() && 4290 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4291 return ImplicitConversionSequence::Better; 4292 4293 // A conversion to a non-id object pointer type is better than a 4294 // conversion to a qualified 'id' type 4295 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4296 return ImplicitConversionSequence::Worse; 4297 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4298 return ImplicitConversionSequence::Better; 4299 4300 // A conversion to an a non-Class object pointer type or qualified 'Class' 4301 // type is better than a conversion to 'Class'. 4302 if (ToPtr1->isObjCClassType() && 4303 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4304 return ImplicitConversionSequence::Worse; 4305 if (ToPtr2->isObjCClassType() && 4306 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4307 return ImplicitConversionSequence::Better; 4308 4309 // A conversion to a non-Class object pointer type is better than a 4310 // conversion to a qualified 'Class' type. 4311 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4312 return ImplicitConversionSequence::Worse; 4313 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4314 return ImplicitConversionSequence::Better; 4315 4316 // -- "conversion of C* to B* is better than conversion of C* to A*," 4317 if (S.Context.hasSameType(FromType1, FromType2) && 4318 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4319 (ToAssignLeft != ToAssignRight)) { 4320 if (FromPtr1->isSpecialized()) { 4321 // "conversion of B<A> * to B * is better than conversion of B * to 4322 // C *. 4323 bool IsFirstSame = 4324 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4325 bool IsSecondSame = 4326 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4327 if (IsFirstSame) { 4328 if (!IsSecondSame) 4329 return ImplicitConversionSequence::Better; 4330 } else if (IsSecondSame) 4331 return ImplicitConversionSequence::Worse; 4332 } 4333 return ToAssignLeft? ImplicitConversionSequence::Worse 4334 : ImplicitConversionSequence::Better; 4335 } 4336 4337 // -- "conversion of B* to A* is better than conversion of C* to A*," 4338 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4339 (FromAssignLeft != FromAssignRight)) 4340 return FromAssignLeft? ImplicitConversionSequence::Better 4341 : ImplicitConversionSequence::Worse; 4342 } 4343 } 4344 4345 // Ranking of member-pointer types. 4346 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4347 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4348 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4349 const MemberPointerType * FromMemPointer1 = 4350 FromType1->getAs<MemberPointerType>(); 4351 const MemberPointerType * ToMemPointer1 = 4352 ToType1->getAs<MemberPointerType>(); 4353 const MemberPointerType * FromMemPointer2 = 4354 FromType2->getAs<MemberPointerType>(); 4355 const MemberPointerType * ToMemPointer2 = 4356 ToType2->getAs<MemberPointerType>(); 4357 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4358 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4359 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4360 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4361 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4362 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4363 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4364 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4365 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4366 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4367 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4368 return ImplicitConversionSequence::Worse; 4369 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4370 return ImplicitConversionSequence::Better; 4371 } 4372 // conversion of B::* to C::* is better than conversion of A::* to C::* 4373 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4374 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4375 return ImplicitConversionSequence::Better; 4376 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4377 return ImplicitConversionSequence::Worse; 4378 } 4379 } 4380 4381 if (SCS1.Second == ICK_Derived_To_Base) { 4382 // -- conversion of C to B is better than conversion of C to A, 4383 // -- binding of an expression of type C to a reference of type 4384 // B& is better than binding an expression of type C to a 4385 // reference of type A&, 4386 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4387 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4388 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4389 return ImplicitConversionSequence::Better; 4390 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4391 return ImplicitConversionSequence::Worse; 4392 } 4393 4394 // -- conversion of B to A is better than conversion of C to A. 4395 // -- binding of an expression of type B to a reference of type 4396 // A& is better than binding an expression of type C to a 4397 // reference of type A&, 4398 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4399 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4400 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4401 return ImplicitConversionSequence::Better; 4402 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4403 return ImplicitConversionSequence::Worse; 4404 } 4405 } 4406 4407 return ImplicitConversionSequence::Indistinguishable; 4408} 4409 4410/// Determine whether the given type is valid, e.g., it is not an invalid 4411/// C++ class. 4412static bool isTypeValid(QualType T) { 4413 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4414 return !Record->isInvalidDecl(); 4415 4416 return true; 4417} 4418 4419static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4420 if (!T.getQualifiers().hasUnaligned()) 4421 return T; 4422 4423 Qualifiers Q; 4424 T = Ctx.getUnqualifiedArrayType(T, Q); 4425 Q.removeUnaligned(); 4426 return Ctx.getQualifiedType(T, Q); 4427} 4428 4429/// CompareReferenceRelationship - Compare the two types T1 and T2 to 4430/// determine whether they are reference-compatible, 4431/// reference-related, or incompatible, for use in C++ initialization by 4432/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4433/// type, and the first type (T1) is the pointee type of the reference 4434/// type being initialized. 4435Sema::ReferenceCompareResult 4436Sema::CompareReferenceRelationship(SourceLocation Loc, 4437 QualType OrigT1, QualType OrigT2, 4438 ReferenceConversions *ConvOut) { 4439 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
4440 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
; 4441 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4441, __PRETTY_FUNCTION__))
; 4442 4443 QualType T1 = Context.getCanonicalType(OrigT1); 4444 QualType T2 = Context.getCanonicalType(OrigT2); 4445 Qualifiers T1Quals, T2Quals; 4446 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4447 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4448 4449 ReferenceConversions ConvTmp; 4450 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4451 Conv = ReferenceConversions(); 4452 4453 // C++2a [dcl.init.ref]p4: 4454 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4455 // reference-related to "cv2 T2" if T1 is similar to T2, or 4456 // T1 is a base class of T2. 4457 // "cv1 T1" is reference-compatible with "cv2 T2" if 4458 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4459 // "pointer to cv1 T1" via a standard conversion sequence. 4460 4461 // Check for standard conversions we can apply to pointers: derived-to-base 4462 // conversions, ObjC pointer conversions, and function pointer conversions. 4463 // (Qualification conversions are checked last.) 4464 QualType ConvertedT2; 4465 if (UnqualT1 == UnqualT2) { 4466 // Nothing to do. 4467 } else if (isCompleteType(Loc, OrigT2) && 4468 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4469 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4470 Conv |= ReferenceConversions::DerivedToBase; 4471 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4472 UnqualT2->isObjCObjectOrInterfaceType() && 4473 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4474 Conv |= ReferenceConversions::ObjC; 4475 else if (UnqualT2->isFunctionType() && 4476 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4477 Conv |= ReferenceConversions::Function; 4478 // No need to check qualifiers; function types don't have them. 4479 return Ref_Compatible; 4480 } 4481 bool ConvertedReferent = Conv != 0; 4482 4483 // We can have a qualification conversion. Compute whether the types are 4484 // similar at the same time. 4485 bool PreviousToQualsIncludeConst = true; 4486 bool TopLevel = true; 4487 do { 4488 if (T1 == T2) 4489 break; 4490 4491 // We will need a qualification conversion. 4492 Conv |= ReferenceConversions::Qualification; 4493 4494 // Track whether we performed a qualification conversion anywhere other 4495 // than the top level. This matters for ranking reference bindings in 4496 // overload resolution. 4497 if (!TopLevel) 4498 Conv |= ReferenceConversions::NestedQualification; 4499 4500 // MS compiler ignores __unaligned qualifier for references; do the same. 4501 T1 = withoutUnaligned(Context, T1); 4502 T2 = withoutUnaligned(Context, T2); 4503 4504 // If we find a qualifier mismatch, the types are not reference-compatible, 4505 // but are still be reference-related if they're similar. 4506 bool ObjCLifetimeConversion = false; 4507 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, 4508 PreviousToQualsIncludeConst, 4509 ObjCLifetimeConversion)) 4510 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4511 ? Ref_Related 4512 : Ref_Incompatible; 4513 4514 // FIXME: Should we track this for any level other than the first? 4515 if (ObjCLifetimeConversion) 4516 Conv |= ReferenceConversions::ObjCLifetime; 4517 4518 TopLevel = false; 4519 } while (Context.UnwrapSimilarTypes(T1, T2)); 4520 4521 // At this point, if the types are reference-related, we must either have the 4522 // same inner type (ignoring qualifiers), or must have already worked out how 4523 // to convert the referent. 4524 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4525 ? Ref_Compatible 4526 : Ref_Incompatible; 4527} 4528 4529/// Look for a user-defined conversion to a value reference-compatible 4530/// with DeclType. Return true if something definite is found. 4531static bool 4532FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4533 QualType DeclType, SourceLocation DeclLoc, 4534 Expr *Init, QualType T2, bool AllowRvalues, 4535 bool AllowExplicit) { 4536 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4536, __PRETTY_FUNCTION__))
; 4537 CXXRecordDecl *T2RecordDecl 4538 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4539 4540 OverloadCandidateSet CandidateSet( 4541 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4542 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4543 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4544 NamedDecl *D = *I; 4545 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4546 if (isa<UsingShadowDecl>(D)) 4547 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4548 4549 FunctionTemplateDecl *ConvTemplate 4550 = dyn_cast<FunctionTemplateDecl>(D); 4551 CXXConversionDecl *Conv; 4552 if (ConvTemplate) 4553 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4554 else 4555 Conv = cast<CXXConversionDecl>(D); 4556 4557 if (AllowRvalues) { 4558 // If we are initializing an rvalue reference, don't permit conversion 4559 // functions that return lvalues. 4560 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4561 const ReferenceType *RefType 4562 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4563 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4564 continue; 4565 } 4566 4567 if (!ConvTemplate && 4568 S.CompareReferenceRelationship( 4569 DeclLoc, 4570 Conv->getConversionType() 4571 .getNonReferenceType() 4572 .getUnqualifiedType(), 4573 DeclType.getNonReferenceType().getUnqualifiedType()) == 4574 Sema::Ref_Incompatible) 4575 continue; 4576 } else { 4577 // If the conversion function doesn't return a reference type, 4578 // it can't be considered for this conversion. An rvalue reference 4579 // is only acceptable if its referencee is a function type. 4580 4581 const ReferenceType *RefType = 4582 Conv->getConversionType()->getAs<ReferenceType>(); 4583 if (!RefType || 4584 (!RefType->isLValueReferenceType() && 4585 !RefType->getPointeeType()->isFunctionType())) 4586 continue; 4587 } 4588 4589 if (ConvTemplate) 4590 S.AddTemplateConversionCandidate( 4591 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4592 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4593 else 4594 S.AddConversionCandidate( 4595 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4596 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4597 } 4598 4599 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4600 4601 OverloadCandidateSet::iterator Best; 4602 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4603 case OR_Success: 4604 // C++ [over.ics.ref]p1: 4605 // 4606 // [...] If the parameter binds directly to the result of 4607 // applying a conversion function to the argument 4608 // expression, the implicit conversion sequence is a 4609 // user-defined conversion sequence (13.3.3.1.2), with the 4610 // second standard conversion sequence either an identity 4611 // conversion or, if the conversion function returns an 4612 // entity of a type that is a derived class of the parameter 4613 // type, a derived-to-base Conversion. 4614 if (!Best->FinalConversion.DirectBinding) 4615 return false; 4616 4617 ICS.setUserDefined(); 4618 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4619 ICS.UserDefined.After = Best->FinalConversion; 4620 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4621 ICS.UserDefined.ConversionFunction = Best->Function; 4622 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4623 ICS.UserDefined.EllipsisConversion = false; 4624 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4625 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4626 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
; 4627 return true; 4628 4629 case OR_Ambiguous: 4630 ICS.setAmbiguous(); 4631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4632 Cand != CandidateSet.end(); ++Cand) 4633 if (Cand->Best) 4634 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4635 return true; 4636 4637 case OR_No_Viable_Function: 4638 case OR_Deleted: 4639 // There was no suitable conversion, or we found a deleted 4640 // conversion; continue with other checks. 4641 return false; 4642 } 4643 4644 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4644)
; 4645} 4646 4647/// Compute an implicit conversion sequence for reference 4648/// initialization. 4649static ImplicitConversionSequence 4650TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4651 SourceLocation DeclLoc, 4652 bool SuppressUserConversions, 4653 bool AllowExplicit) { 4654 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4654, __PRETTY_FUNCTION__))
; 4655 4656 // Most paths end in a failed conversion. 4657 ImplicitConversionSequence ICS; 4658 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4659 4660 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4661 QualType T2 = Init->getType(); 4662 4663 // If the initializer is the address of an overloaded function, try 4664 // to resolve the overloaded function. If all goes well, T2 is the 4665 // type of the resulting function. 4666 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4667 DeclAccessPair Found; 4668 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4669 false, Found)) 4670 T2 = Fn->getType(); 4671 } 4672 4673 // Compute some basic properties of the types and the initializer. 4674 bool isRValRef = DeclType->isRValueReferenceType(); 4675 Expr::Classification InitCategory = Init->Classify(S.Context); 4676 4677 Sema::ReferenceConversions RefConv; 4678 Sema::ReferenceCompareResult RefRelationship = 4679 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4680 4681 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4682 ICS.setStandard(); 4683 ICS.Standard.First = ICK_Identity; 4684 // FIXME: A reference binding can be a function conversion too. We should 4685 // consider that when ordering reference-to-function bindings. 4686 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4687 ? ICK_Derived_To_Base 4688 : (RefConv & Sema::ReferenceConversions::ObjC) 4689 ? ICK_Compatible_Conversion 4690 : ICK_Identity; 4691 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4692 // a reference binding that performs a non-top-level qualification 4693 // conversion as a qualification conversion, not as an identity conversion. 4694 ICS.Standard.Third = (RefConv & 4695 Sema::ReferenceConversions::NestedQualification) 4696 ? ICK_Qualification 4697 : ICK_Identity; 4698 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4699 ICS.Standard.setToType(0, T2); 4700 ICS.Standard.setToType(1, T1); 4701 ICS.Standard.setToType(2, T1); 4702 ICS.Standard.ReferenceBinding = true; 4703 ICS.Standard.DirectBinding = BindsDirectly; 4704 ICS.Standard.IsLvalueReference = !isRValRef; 4705 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4706 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4708 ICS.Standard.ObjCLifetimeConversionBinding = 4709 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4710 ICS.Standard.CopyConstructor = nullptr; 4711 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4712 }; 4713 4714 // C++0x [dcl.init.ref]p5: 4715 // A reference to type "cv1 T1" is initialized by an expression 4716 // of type "cv2 T2" as follows: 4717 4718 // -- If reference is an lvalue reference and the initializer expression 4719 if (!isRValRef) { 4720 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4721 // reference-compatible with "cv2 T2," or 4722 // 4723 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4724 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4725 // C++ [over.ics.ref]p1: 4726 // When a parameter of reference type binds directly (8.5.3) 4727 // to an argument expression, the implicit conversion sequence 4728 // is the identity conversion, unless the argument expression 4729 // has a type that is a derived class of the parameter type, 4730 // in which case the implicit conversion sequence is a 4731 // derived-to-base Conversion (13.3.3.1). 4732 SetAsReferenceBinding(/*BindsDirectly=*/true); 4733 4734 // Nothing more to do: the inaccessibility/ambiguity check for 4735 // derived-to-base conversions is suppressed when we're 4736 // computing the implicit conversion sequence (C++ 4737 // [over.best.ics]p2). 4738 return ICS; 4739 } 4740 4741 // -- has a class type (i.e., T2 is a class type), where T1 is 4742 // not reference-related to T2, and can be implicitly 4743 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4744 // is reference-compatible with "cv3 T3" 92) (this 4745 // conversion is selected by enumerating the applicable 4746 // conversion functions (13.3.1.6) and choosing the best 4747 // one through overload resolution (13.3)), 4748 if (!SuppressUserConversions && T2->isRecordType() && 4749 S.isCompleteType(DeclLoc, T2) && 4750 RefRelationship == Sema::Ref_Incompatible) { 4751 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4752 Init, T2, /*AllowRvalues=*/false, 4753 AllowExplicit)) 4754 return ICS; 4755 } 4756 } 4757 4758 // -- Otherwise, the reference shall be an lvalue reference to a 4759 // non-volatile const type (i.e., cv1 shall be const), or the reference 4760 // shall be an rvalue reference. 4761 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4762 return ICS; 4763 4764 // -- If the initializer expression 4765 // 4766 // -- is an xvalue, class prvalue, array prvalue or function 4767 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4768 if (RefRelationship == Sema::Ref_Compatible && 4769 (InitCategory.isXValue() || 4770 (InitCategory.isPRValue() && 4771 (T2->isRecordType() || T2->isArrayType())) || 4772 (InitCategory.isLValue() && T2->isFunctionType()))) { 4773 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4774 // binding unless we're binding to a class prvalue. 4775 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4776 // allow the use of rvalue references in C++98/03 for the benefit of 4777 // standard library implementors; therefore, we need the xvalue check here. 4778 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4779 !(InitCategory.isPRValue() || T2->isRecordType())); 4780 return ICS; 4781 } 4782 4783 // -- has a class type (i.e., T2 is a class type), where T1 is not 4784 // reference-related to T2, and can be implicitly converted to 4785 // an xvalue, class prvalue, or function lvalue of type 4786 // "cv3 T3", where "cv1 T1" is reference-compatible with 4787 // "cv3 T3", 4788 // 4789 // then the reference is bound to the value of the initializer 4790 // expression in the first case and to the result of the conversion 4791 // in the second case (or, in either case, to an appropriate base 4792 // class subobject). 4793 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4794 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4795 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4796 Init, T2, /*AllowRvalues=*/true, 4797 AllowExplicit)) { 4798 // In the second case, if the reference is an rvalue reference 4799 // and the second standard conversion sequence of the 4800 // user-defined conversion sequence includes an lvalue-to-rvalue 4801 // conversion, the program is ill-formed. 4802 if (ICS.isUserDefined() && isRValRef && 4803 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4804 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4805 4806 return ICS; 4807 } 4808 4809 // A temporary of function type cannot be created; don't even try. 4810 if (T1->isFunctionType()) 4811 return ICS; 4812 4813 // -- Otherwise, a temporary of type "cv1 T1" is created and 4814 // initialized from the initializer expression using the 4815 // rules for a non-reference copy initialization (8.5). The 4816 // reference is then bound to the temporary. If T1 is 4817 // reference-related to T2, cv1 must be the same 4818 // cv-qualification as, or greater cv-qualification than, 4819 // cv2; otherwise, the program is ill-formed. 4820 if (RefRelationship == Sema::Ref_Related) { 4821 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4822 // we would be reference-compatible or reference-compatible with 4823 // added qualification. But that wasn't the case, so the reference 4824 // initialization fails. 4825 // 4826 // Note that we only want to check address spaces and cvr-qualifiers here. 4827 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4828 Qualifiers T1Quals = T1.getQualifiers(); 4829 Qualifiers T2Quals = T2.getQualifiers(); 4830 T1Quals.removeObjCGCAttr(); 4831 T1Quals.removeObjCLifetime(); 4832 T2Quals.removeObjCGCAttr(); 4833 T2Quals.removeObjCLifetime(); 4834 // MS compiler ignores __unaligned qualifier for references; do the same. 4835 T1Quals.removeUnaligned(); 4836 T2Quals.removeUnaligned(); 4837 if (!T1Quals.compatiblyIncludes(T2Quals)) 4838 return ICS; 4839 } 4840 4841 // If at least one of the types is a class type, the types are not 4842 // related, and we aren't allowed any user conversions, the 4843 // reference binding fails. This case is important for breaking 4844 // recursion, since TryImplicitConversion below will attempt to 4845 // create a temporary through the use of a copy constructor. 4846 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4847 (T1->isRecordType() || T2->isRecordType())) 4848 return ICS; 4849 4850 // If T1 is reference-related to T2 and the reference is an rvalue 4851 // reference, the initializer expression shall not be an lvalue. 4852 if (RefRelationship >= Sema::Ref_Related && 4853 isRValRef && Init->Classify(S.Context).isLValue()) 4854 return ICS; 4855 4856 // C++ [over.ics.ref]p2: 4857 // When a parameter of reference type is not bound directly to 4858 // an argument expression, the conversion sequence is the one 4859 // required to convert the argument expression to the 4860 // underlying type of the reference according to 4861 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4862 // to copy-initializing a temporary of the underlying type with 4863 // the argument expression. Any difference in top-level 4864 // cv-qualification is subsumed by the initialization itself 4865 // and does not constitute a conversion. 4866 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4867 /*AllowExplicit=*/false, 4868 /*InOverloadResolution=*/false, 4869 /*CStyle=*/false, 4870 /*AllowObjCWritebackConversion=*/false, 4871 /*AllowObjCConversionOnExplicit=*/false); 4872 4873 // Of course, that's still a reference binding. 4874 if (ICS.isStandard()) { 4875 ICS.Standard.ReferenceBinding = true; 4876 ICS.Standard.IsLvalueReference = !isRValRef; 4877 ICS.Standard.BindsToFunctionLvalue = false; 4878 ICS.Standard.BindsToRvalue = true; 4879 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4880 ICS.Standard.ObjCLifetimeConversionBinding = false; 4881 } else if (ICS.isUserDefined()) { 4882 const ReferenceType *LValRefType = 4883 ICS.UserDefined.ConversionFunction->getReturnType() 4884 ->getAs<LValueReferenceType>(); 4885 4886 // C++ [over.ics.ref]p3: 4887 // Except for an implicit object parameter, for which see 13.3.1, a 4888 // standard conversion sequence cannot be formed if it requires [...] 4889 // binding an rvalue reference to an lvalue other than a function 4890 // lvalue. 4891 // Note that the function case is not possible here. 4892 if (DeclType->isRValueReferenceType() && LValRefType) { 4893 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4894 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4895 // reference to an rvalue! 4896 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4897 return ICS; 4898 } 4899 4900 ICS.UserDefined.After.ReferenceBinding = true; 4901 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4902 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4903 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4904 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4905 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4906 } 4907 4908 return ICS; 4909} 4910 4911static ImplicitConversionSequence 4912TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4913 bool SuppressUserConversions, 4914 bool InOverloadResolution, 4915 bool AllowObjCWritebackConversion, 4916 bool AllowExplicit = false); 4917 4918/// TryListConversion - Try to copy-initialize a value of type ToType from the 4919/// initializer list From. 4920static ImplicitConversionSequence 4921TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4922 bool SuppressUserConversions, 4923 bool InOverloadResolution, 4924 bool AllowObjCWritebackConversion) { 4925 // C++11 [over.ics.list]p1: 4926 // When an argument is an initializer list, it is not an expression and 4927 // special rules apply for converting it to a parameter type. 4928 4929 ImplicitConversionSequence Result; 4930 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4931 4932 // We need a complete type for what follows. Incomplete types can never be 4933 // initialized from init lists. 4934 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4935 return Result; 4936 4937 // Per DR1467: 4938 // If the parameter type is a class X and the initializer list has a single 4939 // element of type cv U, where U is X or a class derived from X, the 4940 // implicit conversion sequence is the one required to convert the element 4941 // to the parameter type. 4942 // 4943 // Otherwise, if the parameter type is a character array [... ] 4944 // and the initializer list has a single element that is an 4945 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4946 // implicit conversion sequence is the identity conversion. 4947 if (From->getNumInits() == 1) { 4948 if (ToType->isRecordType()) { 4949 QualType InitType = From->getInit(0)->getType(); 4950 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4951 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4952 return TryCopyInitialization(S, From->getInit(0), ToType, 4953 SuppressUserConversions, 4954 InOverloadResolution, 4955 AllowObjCWritebackConversion); 4956 } 4957 // FIXME: Check the other conditions here: array of character type, 4958 // initializer is a string literal. 4959 if (ToType->isArrayType()) { 4960 InitializedEntity Entity = 4961 InitializedEntity::InitializeParameter(S.Context, ToType, 4962 /*Consumed=*/false); 4963 if (S.CanPerformCopyInitialization(Entity, From)) { 4964 Result.setStandard(); 4965 Result.Standard.setAsIdentityConversion(); 4966 Result.Standard.setFromType(ToType); 4967 Result.Standard.setAllToTypes(ToType); 4968 return Result; 4969 } 4970 } 4971 } 4972 4973 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4974 // C++11 [over.ics.list]p2: 4975 // If the parameter type is std::initializer_list<X> or "array of X" and 4976 // all the elements can be implicitly converted to X, the implicit 4977 // conversion sequence is the worst conversion necessary to convert an 4978 // element of the list to X. 4979 // 4980 // C++14 [over.ics.list]p3: 4981 // Otherwise, if the parameter type is "array of N X", if the initializer 4982 // list has exactly N elements or if it has fewer than N elements and X is 4983 // default-constructible, and if all the elements of the initializer list 4984 // can be implicitly converted to X, the implicit conversion sequence is 4985 // the worst conversion necessary to convert an element of the list to X. 4986 // 4987 // FIXME: We're missing a lot of these checks. 4988 bool toStdInitializerList = false; 4989 QualType X; 4990 if (ToType->isArrayType()) 4991 X = S.Context.getAsArrayType(ToType)->getElementType(); 4992 else 4993 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4994 if (!X.isNull()) { 4995 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4996 Expr *Init = From->getInit(i); 4997 ImplicitConversionSequence ICS = 4998 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4999 InOverloadResolution, 5000 AllowObjCWritebackConversion); 5001 // If a single element isn't convertible, fail. 5002 if (ICS.isBad()) { 5003 Result = ICS; 5004 break; 5005 } 5006 // Otherwise, look for the worst conversion. 5007 if (Result.isBad() || CompareImplicitConversionSequences( 5008 S, From->getBeginLoc(), ICS, Result) == 5009 ImplicitConversionSequence::Worse) 5010 Result = ICS; 5011 } 5012 5013 // For an empty list, we won't have computed any conversion sequence. 5014 // Introduce the identity conversion sequence. 5015 if (From->getNumInits() == 0) { 5016 Result.setStandard(); 5017 Result.Standard.setAsIdentityConversion(); 5018 Result.Standard.setFromType(ToType); 5019 Result.Standard.setAllToTypes(ToType); 5020 } 5021 5022 Result.setStdInitializerListElement(toStdInitializerList); 5023 return Result; 5024 } 5025 5026 // C++14 [over.ics.list]p4: 5027 // C++11 [over.ics.list]p3: 5028 // Otherwise, if the parameter is a non-aggregate class X and overload 5029 // resolution chooses a single best constructor [...] the implicit 5030 // conversion sequence is a user-defined conversion sequence. If multiple 5031 // constructors are viable but none is better than the others, the 5032 // implicit conversion sequence is a user-defined conversion sequence. 5033 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5034 // This function can deal with initializer lists. 5035 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5036 /*AllowExplicit=*/false, 5037 InOverloadResolution, /*CStyle=*/false, 5038 AllowObjCWritebackConversion, 5039 /*AllowObjCConversionOnExplicit=*/false); 5040 } 5041 5042 // C++14 [over.ics.list]p5: 5043 // C++11 [over.ics.list]p4: 5044 // Otherwise, if the parameter has an aggregate type which can be 5045 // initialized from the initializer list [...] the implicit conversion 5046 // sequence is a user-defined conversion sequence. 5047 if (ToType->isAggregateType()) { 5048 // Type is an aggregate, argument is an init list. At this point it comes 5049 // down to checking whether the initialization works. 5050 // FIXME: Find out whether this parameter is consumed or not. 5051 InitializedEntity Entity = 5052 InitializedEntity::InitializeParameter(S.Context, ToType, 5053 /*Consumed=*/false); 5054 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5055 From)) { 5056 Result.setUserDefined(); 5057 Result.UserDefined.Before.setAsIdentityConversion(); 5058 // Initializer lists don't have a type. 5059 Result.UserDefined.Before.setFromType(QualType()); 5060 Result.UserDefined.Before.setAllToTypes(QualType()); 5061 5062 Result.UserDefined.After.setAsIdentityConversion(); 5063 Result.UserDefined.After.setFromType(ToType); 5064 Result.UserDefined.After.setAllToTypes(ToType); 5065 Result.UserDefined.ConversionFunction = nullptr; 5066 } 5067 return Result; 5068 } 5069 5070 // C++14 [over.ics.list]p6: 5071 // C++11 [over.ics.list]p5: 5072 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5073 if (ToType->isReferenceType()) { 5074 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5075 // mention initializer lists in any way. So we go by what list- 5076 // initialization would do and try to extrapolate from that. 5077 5078 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5079 5080 // If the initializer list has a single element that is reference-related 5081 // to the parameter type, we initialize the reference from that. 5082 if (From->getNumInits() == 1) { 5083 Expr *Init = From->getInit(0); 5084 5085 QualType T2 = Init->getType(); 5086 5087 // If the initializer is the address of an overloaded function, try 5088 // to resolve the overloaded function. If all goes well, T2 is the 5089 // type of the resulting function. 5090 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5091 DeclAccessPair Found; 5092 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5093 Init, ToType, false, Found)) 5094 T2 = Fn->getType(); 5095 } 5096 5097 // Compute some basic properties of the types and the initializer. 5098 Sema::ReferenceCompareResult RefRelationship = 5099 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5100 5101 if (RefRelationship >= Sema::Ref_Related) { 5102 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5103 SuppressUserConversions, 5104 /*AllowExplicit=*/false); 5105 } 5106 } 5107 5108 // Otherwise, we bind the reference to a temporary created from the 5109 // initializer list. 5110 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5111 InOverloadResolution, 5112 AllowObjCWritebackConversion); 5113 if (Result.isFailure()) 5114 return Result; 5115 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
5116 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
; 5117 5118 // Can we even bind to a temporary? 5119 if (ToType->isRValueReferenceType() || 5120 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5121 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5122 Result.UserDefined.After; 5123 SCS.ReferenceBinding = true; 5124 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5125 SCS.BindsToRvalue = true; 5126 SCS.BindsToFunctionLvalue = false; 5127 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5128 SCS.ObjCLifetimeConversionBinding = false; 5129 } else 5130 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5131 From, ToType); 5132 return Result; 5133 } 5134 5135 // C++14 [over.ics.list]p7: 5136 // C++11 [over.ics.list]p6: 5137 // Otherwise, if the parameter type is not a class: 5138 if (!ToType->isRecordType()) { 5139 // - if the initializer list has one element that is not itself an 5140 // initializer list, the implicit conversion sequence is the one 5141 // required to convert the element to the parameter type. 5142 unsigned NumInits = From->getNumInits(); 5143 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5144 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5145 SuppressUserConversions, 5146 InOverloadResolution, 5147 AllowObjCWritebackConversion); 5148 // - if the initializer list has no elements, the implicit conversion 5149 // sequence is the identity conversion. 5150 else if (NumInits == 0) { 5151 Result.setStandard(); 5152 Result.Standard.setAsIdentityConversion(); 5153 Result.Standard.setFromType(ToType); 5154 Result.Standard.setAllToTypes(ToType); 5155 } 5156 return Result; 5157 } 5158 5159 // C++14 [over.ics.list]p8: 5160 // C++11 [over.ics.list]p7: 5161 // In all cases other than those enumerated above, no conversion is possible 5162 return Result; 5163} 5164 5165/// TryCopyInitialization - Try to copy-initialize a value of type 5166/// ToType from the expression From. Return the implicit conversion 5167/// sequence required to pass this argument, which may be a bad 5168/// conversion sequence (meaning that the argument cannot be passed to 5169/// a parameter of this type). If @p SuppressUserConversions, then we 5170/// do not permit any user-defined conversion sequences. 5171static ImplicitConversionSequence 5172TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5173 bool SuppressUserConversions, 5174 bool InOverloadResolution, 5175 bool AllowObjCWritebackConversion, 5176 bool AllowExplicit) { 5177 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5178 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5179 InOverloadResolution,AllowObjCWritebackConversion); 5180 5181 if (ToType->isReferenceType()) 5182 return TryReferenceInit(S, From, ToType, 5183 /*FIXME:*/ From->getBeginLoc(), 5184 SuppressUserConversions, AllowExplicit); 5185 5186 return TryImplicitConversion(S, From, ToType, 5187 SuppressUserConversions, 5188 /*AllowExplicit=*/false, 5189 InOverloadResolution, 5190 /*CStyle=*/false, 5191 AllowObjCWritebackConversion, 5192 /*AllowObjCConversionOnExplicit=*/false); 5193} 5194 5195static bool TryCopyInitialization(const CanQualType FromQTy, 5196 const CanQualType ToQTy, 5197 Sema &S, 5198 SourceLocation Loc, 5199 ExprValueKind FromVK) { 5200 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5201 ImplicitConversionSequence ICS = 5202 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5203 5204 return !ICS.isBad(); 5205} 5206 5207/// TryObjectArgumentInitialization - Try to initialize the object 5208/// parameter of the given member function (@c Method) from the 5209/// expression @p From. 5210static ImplicitConversionSequence 5211TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5212 Expr::Classification FromClassification, 5213 CXXMethodDecl *Method, 5214 CXXRecordDecl *ActingContext) { 5215 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5216 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5217 // const volatile object. 5218 Qualifiers Quals = Method->getMethodQualifiers(); 5219 if (isa<CXXDestructorDecl>(Method)) { 5220 Quals.addConst(); 5221 Quals.addVolatile(); 5222 } 5223 5224 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5225 5226 // Set up the conversion sequence as a "bad" conversion, to allow us 5227 // to exit early. 5228 ImplicitConversionSequence ICS; 5229 5230 // We need to have an object of class type. 5231 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5232 FromType = PT->getPointeeType(); 5233 5234 // When we had a pointer, it's implicitly dereferenced, so we 5235 // better have an lvalue. 5236 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5236, __PRETTY_FUNCTION__))
; 5237 } 5238 5239 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5239, __PRETTY_FUNCTION__))
; 5240 5241 // C++0x [over.match.funcs]p4: 5242 // For non-static member functions, the type of the implicit object 5243 // parameter is 5244 // 5245 // - "lvalue reference to cv X" for functions declared without a 5246 // ref-qualifier or with the & ref-qualifier 5247 // - "rvalue reference to cv X" for functions declared with the && 5248 // ref-qualifier 5249 // 5250 // where X is the class of which the function is a member and cv is the 5251 // cv-qualification on the member function declaration. 5252 // 5253 // However, when finding an implicit conversion sequence for the argument, we 5254 // are not allowed to perform user-defined conversions 5255 // (C++ [over.match.funcs]p5). We perform a simplified version of 5256 // reference binding here, that allows class rvalues to bind to 5257 // non-constant references. 5258 5259 // First check the qualifiers. 5260 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5261 if (ImplicitParamType.getCVRQualifiers() 5262 != FromTypeCanon.getLocalCVRQualifiers() && 5263 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5264 ICS.setBad(BadConversionSequence::bad_qualifiers, 5265 FromType, ImplicitParamType); 5266 return ICS; 5267 } 5268 5269 if (FromTypeCanon.hasAddressSpace()) { 5270 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5271 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5272 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5273 ICS.setBad(BadConversionSequence::bad_qualifiers, 5274 FromType, ImplicitParamType); 5275 return ICS; 5276 } 5277 } 5278 5279 // Check that we have either the same type or a derived type. It 5280 // affects the conversion rank. 5281 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5282 ImplicitConversionKind SecondKind; 5283 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5284 SecondKind = ICK_Identity; 5285 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5286 SecondKind = ICK_Derived_To_Base; 5287 else { 5288 ICS.setBad(BadConversionSequence::unrelated_class, 5289 FromType, ImplicitParamType); 5290 return ICS; 5291 } 5292 5293 // Check the ref-qualifier. 5294 switch (Method->getRefQualifier()) { 5295 case RQ_None: 5296 // Do nothing; we don't care about lvalueness or rvalueness. 5297 break; 5298 5299 case RQ_LValue: 5300 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5301 // non-const lvalue reference cannot bind to an rvalue 5302 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5303 ImplicitParamType); 5304 return ICS; 5305 } 5306 break; 5307 5308 case RQ_RValue: 5309 if (!FromClassification.isRValue()) { 5310 // rvalue reference cannot bind to an lvalue 5311 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5312 ImplicitParamType); 5313 return ICS; 5314 } 5315 break; 5316 } 5317 5318 // Success. Mark this as a reference binding. 5319 ICS.setStandard(); 5320 ICS.Standard.setAsIdentityConversion(); 5321 ICS.Standard.Second = SecondKind; 5322 ICS.Standard.setFromType(FromType); 5323 ICS.Standard.setAllToTypes(ImplicitParamType); 5324 ICS.Standard.ReferenceBinding = true; 5325 ICS.Standard.DirectBinding = true; 5326 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5327 ICS.Standard.BindsToFunctionLvalue = false; 5328 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5329 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5330 = (Method->getRefQualifier() == RQ_None); 5331 return ICS; 5332} 5333 5334/// PerformObjectArgumentInitialization - Perform initialization of 5335/// the implicit object parameter for the given Method with the given 5336/// expression. 5337ExprResult 5338Sema::PerformObjectArgumentInitialization(Expr *From, 5339 NestedNameSpecifier *Qualifier, 5340 NamedDecl *FoundDecl, 5341 CXXMethodDecl *Method) { 5342 QualType FromRecordType, DestType; 5343 QualType ImplicitParamRecordType = 5344 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5345 5346 Expr::Classification FromClassification; 5347 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5348 FromRecordType = PT->getPointeeType(); 5349 DestType = Method->getThisType(); 5350 FromClassification = Expr::Classification::makeSimpleLValue(); 5351 } else { 5352 FromRecordType = From->getType(); 5353 DestType = ImplicitParamRecordType; 5354 FromClassification = From->Classify(Context); 5355 5356 // When performing member access on an rvalue, materialize a temporary. 5357 if (From->isRValue()) { 5358 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5359 Method->getRefQualifier() != 5360 RefQualifierKind::RQ_RValue); 5361 } 5362 } 5363 5364 // Note that we always use the true parent context when performing 5365 // the actual argument initialization. 5366 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5367 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5368 Method->getParent()); 5369 if (ICS.isBad()) { 5370 switch (ICS.Bad.Kind) { 5371 case BadConversionSequence::bad_qualifiers: { 5372 Qualifiers FromQs = FromRecordType.getQualifiers(); 5373 Qualifiers ToQs = DestType.getQualifiers(); 5374 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5375 if (CVR) { 5376 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5377 << Method->getDeclName() << FromRecordType << (CVR - 1) 5378 << From->getSourceRange(); 5379 Diag(Method->getLocation(), diag::note_previous_decl) 5380 << Method->getDeclName(); 5381 return ExprError(); 5382 } 5383 break; 5384 } 5385 5386 case BadConversionSequence::lvalue_ref_to_rvalue: 5387 case BadConversionSequence::rvalue_ref_to_lvalue: { 5388 bool IsRValueQualified = 5389 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5390 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5391 << Method->getDeclName() << FromClassification.isRValue() 5392 << IsRValueQualified; 5393 Diag(Method->getLocation(), diag::note_previous_decl) 5394 << Method->getDeclName(); 5395 return ExprError(); 5396 } 5397 5398 case BadConversionSequence::no_conversion: 5399 case BadConversionSequence::unrelated_class: 5400 break; 5401 } 5402 5403 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5404 << ImplicitParamRecordType << FromRecordType 5405 << From->getSourceRange(); 5406 } 5407 5408 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5409 ExprResult FromRes = 5410 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5411 if (FromRes.isInvalid()) 5412 return ExprError(); 5413 From = FromRes.get(); 5414 } 5415 5416 if (!Context.hasSameType(From->getType(), DestType)) { 5417 CastKind CK; 5418 QualType PteeTy = DestType->getPointeeType(); 5419 LangAS DestAS = 5420 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5421 if (FromRecordType.getAddressSpace() != DestAS) 5422 CK = CK_AddressSpaceConversion; 5423 else 5424 CK = CK_NoOp; 5425 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5426 } 5427 return From; 5428} 5429 5430/// TryContextuallyConvertToBool - Attempt to contextually convert the 5431/// expression From to bool (C++0x [conv]p3). 5432static ImplicitConversionSequence 5433TryContextuallyConvertToBool(Sema &S, Expr *From) { 5434 return TryImplicitConversion(S, From, S.Context.BoolTy, 5435 /*SuppressUserConversions=*/false, 5436 /*AllowExplicit=*/true, 5437 /*InOverloadResolution=*/false, 5438 /*CStyle=*/false, 5439 /*AllowObjCWritebackConversion=*/false, 5440 /*AllowObjCConversionOnExplicit=*/false); 5441} 5442 5443/// PerformContextuallyConvertToBool - Perform a contextual conversion 5444/// of the expression From to bool (C++0x [conv]p3). 5445ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5446 if (checkPlaceholderForOverload(*this, From))
1
Taking false branch
5447 return ExprError(); 5448 5449 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5450 if (!ICS.isBad())
2
Taking false branch
5451 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5452 5453 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3
Calling 'Sema::DiagnoseMultipleUserDefinedConversion'
5454 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5455 << From->getType() << From->getSourceRange(); 5456 return ExprError(); 5457} 5458 5459/// Check that the specified conversion is permitted in a converted constant 5460/// expression, according to C++11 [expr.const]p3. Return true if the conversion 5461/// is acceptable. 5462static bool CheckConvertedConstantConversions(Sema &S, 5463 StandardConversionSequence &SCS) { 5464 // Since we know that the target type is an integral or unscoped enumeration 5465 // type, most conversion kinds are impossible. All possible First and Third 5466 // conversions are fine. 5467 switch (SCS.Second) { 5468 case ICK_Identity: 5469 case ICK_Function_Conversion: 5470 case ICK_Integral_Promotion: 5471 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5472 case ICK_Zero_Queue_Conversion: 5473 return true; 5474 5475 case ICK_Boolean_Conversion: 5476 // Conversion from an integral or unscoped enumeration type to bool is 5477 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5478 // conversion, so we allow it in a converted constant expression. 5479 // 5480 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5481 // a lot of popular code. We should at least add a warning for this 5482 // (non-conforming) extension. 5483 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5484 SCS.getToType(2)->isBooleanType(); 5485 5486 case ICK_Pointer_Conversion: 5487 case ICK_Pointer_Member: 5488 // C++1z: null pointer conversions and null member pointer conversions are 5489 // only permitted if the source type is std::nullptr_t. 5490 return SCS.getFromType()->isNullPtrType(); 5491 5492 case ICK_Floating_Promotion: 5493 case ICK_Complex_Promotion: 5494 case ICK_Floating_Conversion: 5495 case ICK_Complex_Conversion: 5496 case ICK_Floating_Integral: 5497 case ICK_Compatible_Conversion: 5498 case ICK_Derived_To_Base: 5499 case ICK_Vector_Conversion: 5500 case ICK_Vector_Splat: 5501 case ICK_Complex_Real: 5502 case ICK_Block_Pointer_Conversion: 5503 case ICK_TransparentUnionConversion: 5504 case ICK_Writeback_Conversion: 5505 case ICK_Zero_Event_Conversion: 5506 case ICK_C_Only_Conversion: 5507 case ICK_Incompatible_Pointer_Conversion: 5508 return false; 5509 5510 case ICK_Lvalue_To_Rvalue: 5511 case ICK_Array_To_Pointer: 5512 case ICK_Function_To_Pointer: 5513 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5513)
; 5514 5515 case ICK_Qualification: 5516 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5516)
; 5517 5518 case ICK_Num_Conversion_Kinds: 5519 break; 5520 } 5521 5522 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5522)
; 5523} 5524 5525/// CheckConvertedConstantExpression - Check that the expression From is a 5526/// converted constant expression of type T, perform the conversion and produce 5527/// the converted expression, per C++11 [expr.const]p3. 5528static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5529 QualType T, APValue &Value, 5530 Sema::CCEKind CCE, 5531 bool RequireInt) { 5532 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
5533 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
; 5534 5535 if (checkPlaceholderForOverload(S, From)) 5536 return ExprError(); 5537 5538 // C++1z [expr.const]p3: 5539 // A converted constant expression of type T is an expression, 5540 // implicitly converted to type T, where the converted 5541 // expression is a constant expression and the implicit conversion 5542 // sequence contains only [... list of conversions ...]. 5543 // C++1z [stmt.if]p2: 5544 // If the if statement is of the form if constexpr, the value of the 5545 // condition shall be a contextually converted constant expression of type 5546 // bool. 5547 ImplicitConversionSequence ICS = 5548 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5549 ? TryContextuallyConvertToBool(S, From) 5550 : TryCopyInitialization(S, From, T, 5551 /*SuppressUserConversions=*/false, 5552 /*InOverloadResolution=*/false, 5553 /*AllowObjCWritebackConversion=*/false, 5554 /*AllowExplicit=*/false); 5555 StandardConversionSequence *SCS = nullptr; 5556 switch (ICS.getKind()) { 5557 case ImplicitConversionSequence::StandardConversion: 5558 SCS = &ICS.Standard; 5559 break; 5560 case ImplicitConversionSequence::UserDefinedConversion: 5561 // We are converting to a non-class type, so the Before sequence 5562 // must be trivial. 5563 SCS = &ICS.UserDefined.After; 5564 break; 5565 case ImplicitConversionSequence::AmbiguousConversion: 5566 case ImplicitConversionSequence::BadConversion: 5567 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5568 return S.Diag(From->getBeginLoc(), 5569 diag::err_typecheck_converted_constant_expression) 5570 << From->getType() << From->getSourceRange() << T; 5571 return ExprError(); 5572 5573 case ImplicitConversionSequence::EllipsisConversion: 5574 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5574)
; 5575 } 5576 5577 // Check that we would only use permitted conversions. 5578 if (!CheckConvertedConstantConversions(S, *SCS)) { 5579 return S.Diag(From->getBeginLoc(), 5580 diag::err_typecheck_converted_constant_expression_disallowed) 5581 << From->getType() << From->getSourceRange() << T; 5582 } 5583 // [...] and where the reference binding (if any) binds directly. 5584 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5585 return S.Diag(From->getBeginLoc(), 5586 diag::err_typecheck_converted_constant_expression_indirect) 5587 << From->getType() << From->getSourceRange() << T; 5588 } 5589 5590 ExprResult Result = 5591 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5592 if (Result.isInvalid()) 5593 return Result; 5594 5595 // C++2a [intro.execution]p5: 5596 // A full-expression is [...] a constant-expression [...] 5597 Result = 5598 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5599 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5600 if (Result.isInvalid()) 5601 return Result; 5602 5603 // Check for a narrowing implicit conversion. 5604 APValue PreNarrowingValue; 5605 QualType PreNarrowingType; 5606 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5607 PreNarrowingType)) { 5608 case NK_Dependent_Narrowing: 5609 // Implicit conversion to a narrower type, but the expression is 5610 // value-dependent so we can't tell whether it's actually narrowing. 5611 case NK_Variable_Narrowing: 5612 // Implicit conversion to a narrower type, and the value is not a constant 5613 // expression. We'll diagnose this in a moment. 5614 case NK_Not_Narrowing: 5615 break; 5616 5617 case NK_Constant_Narrowing: 5618 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5619 << CCE << /*Constant*/ 1 5620 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5621 break; 5622 5623 case NK_Type_Narrowing: 5624 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5625 << CCE << /*Constant*/ 0 << From->getType() << T; 5626 break; 5627 } 5628 5629 if (Result.get()->isValueDependent()) { 5630 Value = APValue(); 5631 return Result; 5632 } 5633 5634 // Check the expression is a constant expression. 5635 SmallVector<PartialDiagnosticAt, 8> Notes; 5636 Expr::EvalResult Eval; 5637 Eval.Diag = &Notes; 5638 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5639 ? Expr::EvaluateForMangling 5640 : Expr::EvaluateForCodeGen; 5641 5642 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5643 (RequireInt && !Eval.Val.isInt())) { 5644 // The expression can't be folded, so we can't keep it at this position in 5645 // the AST. 5646 Result = ExprError(); 5647 } else { 5648 Value = Eval.Val; 5649 5650 if (Notes.empty()) { 5651 // It's a constant expression. 5652 return ConstantExpr::Create(S.Context, Result.get(), Value); 5653 } 5654 } 5655 5656 // It's not a constant expression. Produce an appropriate diagnostic. 5657 if (Notes.size() == 1 && 5658 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5659 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5660 else { 5661 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5662 << CCE << From->getSourceRange(); 5663 for (unsigned I = 0; I < Notes.size(); ++I) 5664 S.Diag(Notes[I].first, Notes[I].second); 5665 } 5666 return ExprError(); 5667} 5668 5669ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5670 APValue &Value, CCEKind CCE) { 5671 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5672} 5673 5674ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5675 llvm::APSInt &Value, 5676 CCEKind CCE) { 5677 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5677, __PRETTY_FUNCTION__))
; 5678 5679 APValue V; 5680 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5681 if (!R.isInvalid() && !R.get()->isValueDependent()) 5682 Value = V.getInt(); 5683 return R; 5684} 5685 5686 5687/// dropPointerConversions - If the given standard conversion sequence 5688/// involves any pointer conversions, remove them. This may change 5689/// the result type of the conversion sequence. 5690static void dropPointerConversion(StandardConversionSequence &SCS) { 5691 if (SCS.Second == ICK_Pointer_Conversion) { 5692 SCS.Second = ICK_Identity; 5693 SCS.Third = ICK_Identity; 5694 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5695 } 5696} 5697 5698/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5699/// convert the expression From to an Objective-C pointer type. 5700static ImplicitConversionSequence 5701TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5702 // Do an implicit conversion to 'id'. 5703 QualType Ty = S.Context.getObjCIdType(); 5704 ImplicitConversionSequence ICS 5705 = TryImplicitConversion(S, From, Ty, 5706 // FIXME: Are these flags correct? 5707 /*SuppressUserConversions=*/false, 5708 /*AllowExplicit=*/true, 5709 /*InOverloadResolution=*/false, 5710 /*CStyle=*/false, 5711 /*AllowObjCWritebackConversion=*/false, 5712 /*AllowObjCConversionOnExplicit=*/true); 5713 5714 // Strip off any final conversions to 'id'. 5715 switch (ICS.getKind()) { 5716 case ImplicitConversionSequence::BadConversion: 5717 case ImplicitConversionSequence::AmbiguousConversion: 5718 case ImplicitConversionSequence::EllipsisConversion: 5719 break; 5720 5721 case ImplicitConversionSequence::UserDefinedConversion: 5722 dropPointerConversion(ICS.UserDefined.After); 5723 break; 5724 5725 case ImplicitConversionSequence::StandardConversion: 5726 dropPointerConversion(ICS.Standard); 5727 break; 5728 } 5729 5730 return ICS; 5731} 5732 5733/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5734/// conversion of the expression From to an Objective-C pointer type. 5735/// Returns a valid but null ExprResult if no conversion sequence exists. 5736ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5737 if (checkPlaceholderForOverload(*this, From)) 5738 return ExprError(); 5739 5740 QualType Ty = Context.getObjCIdType(); 5741 ImplicitConversionSequence ICS = 5742 TryContextuallyConvertToObjCPointer(*this, From); 5743 if (!ICS.isBad()) 5744 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5745 return ExprResult(); 5746} 5747 5748/// Determine whether the provided type is an integral type, or an enumeration 5749/// type of a permitted flavor. 5750bool Sema::ICEConvertDiagnoser::match(QualType T) { 5751 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5752 : T->isIntegralOrUnscopedEnumerationType(); 5753} 5754 5755static ExprResult 5756diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5757 Sema::ContextualImplicitConverter &Converter, 5758 QualType T, UnresolvedSetImpl &ViableConversions) { 5759 5760 if (Converter.Suppress) 5761 return ExprError(); 5762 5763 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5764 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5765 CXXConversionDecl *Conv = 5766 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5767 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5768 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5769 } 5770 return From; 5771} 5772 5773static bool 5774diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5775 Sema::ContextualImplicitConverter &Converter, 5776 QualType T, bool HadMultipleCandidates, 5777 UnresolvedSetImpl &ExplicitConversions) { 5778 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5779 DeclAccessPair Found = ExplicitConversions[0]; 5780 CXXConversionDecl *Conversion = 5781 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5782 5783 // The user probably meant to invoke the given explicit 5784 // conversion; use it. 5785 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5786 std::string TypeStr; 5787 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5788 5789 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5790 << FixItHint::CreateInsertion(From->getBeginLoc(), 5791 "static_cast<" + TypeStr + ">(") 5792 << FixItHint::CreateInsertion( 5793 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5794 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5795 5796 // If we aren't in a SFINAE context, build a call to the 5797 // explicit conversion function. 5798 if (SemaRef.isSFINAEContext()) 5799 return true; 5800 5801 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5802 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5803 HadMultipleCandidates); 5804 if (Result.isInvalid()) 5805 return true; 5806 // Record usage of conversion in an implicit cast. 5807 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5808 CK_UserDefinedConversion, Result.get(), 5809 nullptr, Result.get()->getValueKind()); 5810 } 5811 return false; 5812} 5813 5814static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5815 Sema::ContextualImplicitConverter &Converter, 5816 QualType T, bool HadMultipleCandidates, 5817 DeclAccessPair &Found) { 5818 CXXConversionDecl *Conversion = 5819 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5820 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5821 5822 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5823 if (!Converter.SuppressConversion) { 5824 if (SemaRef.isSFINAEContext()) 5825 return true; 5826 5827 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5828 << From->getSourceRange(); 5829 } 5830 5831 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5832 HadMultipleCandidates); 5833 if (Result.isInvalid()) 5834 return true; 5835 // Record usage of conversion in an implicit cast. 5836 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5837 CK_UserDefinedConversion, Result.get(), 5838 nullptr, Result.get()->getValueKind()); 5839 return false; 5840} 5841 5842static ExprResult finishContextualImplicitConversion( 5843 Sema &SemaRef, SourceLocation Loc, Expr *From, 5844 Sema::ContextualImplicitConverter &Converter) { 5845 if (!Converter.match(From->getType()) && !Converter.Suppress) 5846 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5847 << From->getSourceRange(); 5848 5849 return SemaRef.DefaultLvalueConversion(From); 5850} 5851 5852static void 5853collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5854 UnresolvedSetImpl &ViableConversions, 5855 OverloadCandidateSet &CandidateSet) { 5856 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5857 DeclAccessPair FoundDecl = ViableConversions[I]; 5858 NamedDecl *D = FoundDecl.getDecl(); 5859 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5860 if (isa<UsingShadowDecl>(D)) 5861 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5862 5863 CXXConversionDecl *Conv; 5864 FunctionTemplateDecl *ConvTemplate; 5865 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5866 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5867 else 5868 Conv = cast<CXXConversionDecl>(D); 5869 5870 if (ConvTemplate) 5871 SemaRef.AddTemplateConversionCandidate( 5872 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5873 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5874 else 5875 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5876 ToType, CandidateSet, 5877 /*AllowObjCConversionOnExplicit=*/false, 5878 /*AllowExplicit*/ true); 5879 } 5880} 5881 5882/// Attempt to convert the given expression to a type which is accepted 5883/// by the given converter. 5884/// 5885/// This routine will attempt to convert an expression of class type to a 5886/// type accepted by the specified converter. In C++11 and before, the class 5887/// must have a single non-explicit conversion function converting to a matching 5888/// type. In C++1y, there can be multiple such conversion functions, but only 5889/// one target type. 5890/// 5891/// \param Loc The source location of the construct that requires the 5892/// conversion. 5893/// 5894/// \param From The expression we're converting from. 5895/// 5896/// \param Converter Used to control and diagnose the conversion process. 5897/// 5898/// \returns The expression, converted to an integral or enumeration type if 5899/// successful. 5900ExprResult Sema::PerformContextualImplicitConversion( 5901 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5902 // We can't perform any more checking for type-dependent expressions. 5903 if (From->isTypeDependent()) 5904 return From; 5905 5906 // Process placeholders immediately. 5907 if (From->hasPlaceholderType()) { 5908 ExprResult result = CheckPlaceholderExpr(From); 5909 if (result.isInvalid()) 5910 return result; 5911 From = result.get(); 5912 } 5913 5914 // If the expression already has a matching type, we're golden. 5915 QualType T = From->getType(); 5916 if (Converter.match(T)) 5917 return DefaultLvalueConversion(From); 5918 5919 // FIXME: Check for missing '()' if T is a function type? 5920 5921 // We can only perform contextual implicit conversions on objects of class 5922 // type. 5923 const RecordType *RecordTy = T->getAs<RecordType>(); 5924 if (!RecordTy || !getLangOpts().CPlusPlus) { 5925 if (!Converter.Suppress) 5926 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5927 return From; 5928 } 5929 5930 // We must have a complete class type. 5931 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5932 ContextualImplicitConverter &Converter; 5933 Expr *From; 5934 5935 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5936 : Converter(Converter), From(From) {} 5937 5938 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5939 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5940 } 5941 } IncompleteDiagnoser(Converter, From); 5942 5943 if (Converter.Suppress ? !isCompleteType(Loc, T) 5944 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5945 return From; 5946 5947 // Look for a conversion to an integral or enumeration type. 5948 UnresolvedSet<4> 5949 ViableConversions; // These are *potentially* viable in C++1y. 5950 UnresolvedSet<4> ExplicitConversions; 5951 const auto &Conversions = 5952 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5953 5954 bool HadMultipleCandidates = 5955 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5956 5957 // To check that there is only one target type, in C++1y: 5958 QualType ToType; 5959 bool HasUniqueTargetType = true; 5960 5961 // Collect explicit or viable (potentially in C++1y) conversions. 5962 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5963 NamedDecl *D = (*I)->getUnderlyingDecl(); 5964 CXXConversionDecl *Conversion; 5965 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5966 if (ConvTemplate) { 5967 if (getLangOpts().CPlusPlus14) 5968 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5969 else 5970 continue; // C++11 does not consider conversion operator templates(?). 5971 } else 5972 Conversion = cast<CXXConversionDecl>(D); 5973 5974 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5975 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5976 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
; 5977 5978 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5979 if (Converter.match(CurToType) || ConvTemplate) { 5980 5981 if (Conversion->isExplicit()) { 5982 // FIXME: For C++1y, do we need this restriction? 5983 // cf. diagnoseNoViableConversion() 5984 if (!ConvTemplate) 5985 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5986 } else { 5987 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5988 if (ToType.isNull()) 5989 ToType = CurToType.getUnqualifiedType(); 5990 else if (HasUniqueTargetType && 5991 (CurToType.getUnqualifiedType() != ToType)) 5992 HasUniqueTargetType = false; 5993 } 5994 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5995 } 5996 } 5997 } 5998 5999 if (getLangOpts().CPlusPlus14) { 6000 // C++1y [conv]p6: 6001 // ... An expression e of class type E appearing in such a context 6002 // is said to be contextually implicitly converted to a specified 6003 // type T and is well-formed if and only if e can be implicitly 6004 // converted to a type T that is determined as follows: E is searched 6005 // for conversion functions whose return type is cv T or reference to 6006 // cv T such that T is allowed by the context. There shall be 6007 // exactly one such T. 6008 6009 // If no unique T is found: 6010 if (ToType.isNull()) { 6011 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6012 HadMultipleCandidates, 6013 ExplicitConversions)) 6014 return ExprError(); 6015 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6016 } 6017 6018 // If more than one unique Ts are found: 6019 if (!HasUniqueTargetType) 6020 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6021 ViableConversions); 6022 6023 // If one unique T is found: 6024 // First, build a candidate set from the previously recorded 6025 // potentially viable conversions. 6026 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6027 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6028 CandidateSet); 6029 6030 // Then, perform overload resolution over the candidate set. 6031 OverloadCandidateSet::iterator Best; 6032 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6033 case OR_Success: { 6034 // Apply this conversion. 6035 DeclAccessPair Found = 6036 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6037 if (recordConversion(*this, Loc, From, Converter, T, 6038 HadMultipleCandidates, Found)) 6039 return ExprError(); 6040 break; 6041 } 6042 case OR_Ambiguous: 6043 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6044 ViableConversions); 6045 case OR_No_Viable_Function: 6046 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6047 HadMultipleCandidates, 6048 ExplicitConversions)) 6049 return ExprError(); 6050 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 6051 case OR_Deleted: 6052 // We'll complain below about a non-integral condition type. 6053 break; 6054 } 6055 } else { 6056 switch (ViableConversions.size()) { 6057 case 0: { 6058 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6059 HadMultipleCandidates, 6060 ExplicitConversions)) 6061 return ExprError(); 6062 6063 // We'll complain below about a non-integral condition type. 6064 break; 6065 } 6066 case 1: { 6067 // Apply this conversion. 6068 DeclAccessPair Found = ViableConversions[0]; 6069 if (recordConversion(*this, Loc, From, Converter, T, 6070 HadMultipleCandidates, Found)) 6071 return ExprError(); 6072 break; 6073 } 6074 default: 6075 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6076 ViableConversions); 6077 } 6078 } 6079 6080 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6081} 6082 6083/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6084/// an acceptable non-member overloaded operator for a call whose 6085/// arguments have types T1 (and, if non-empty, T2). This routine 6086/// implements the check in C++ [over.match.oper]p3b2 concerning 6087/// enumeration types. 6088static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6089 FunctionDecl *Fn, 6090 ArrayRef<Expr *> Args) { 6091 QualType T1 = Args[0]->getType(); 6092 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6093 6094 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6095 return true; 6096 6097 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6098 return true; 6099 6100 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 6101 if (Proto->getNumParams() < 1) 6102 return false; 6103 6104 if (T1->isEnumeralType()) { 6105 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6106 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6107 return true; 6108 } 6109 6110 if (Proto->getNumParams() < 2) 6111 return false; 6112 6113 if (!T2.isNull() && T2->isEnumeralType()) { 6114 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6115 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6116 return true; 6117 } 6118 6119 return false; 6120} 6121 6122/// AddOverloadCandidate - Adds the given function to the set of 6123/// candidate functions, using the given function call arguments. If 6124/// @p SuppressUserConversions, then don't allow user-defined 6125/// conversions via constructors or conversion operators. 6126/// 6127/// \param PartialOverloading true if we are performing "partial" overloading 6128/// based on an incomplete set of function arguments. This feature is used by 6129/// code completion. 6130void Sema::AddOverloadCandidate( 6131 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6132 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6133 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6134 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6135 OverloadCandidateParamOrder PO) { 6136 const FunctionProtoType *Proto 6137 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6138 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6138, __PRETTY_FUNCTION__))
; 6139 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
6140 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
; 6141 6142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6143 if (!isa<CXXConstructorDecl>(Method)) { 6144 // If we get here, it's because we're calling a member function 6145 // that is named without a member access expression (e.g., 6146 // "this->f") that was either written explicitly or created 6147 // implicitly. This can happen with a qualified call to a member 6148 // function, e.g., X::f(). We use an empty type for the implied 6149 // object argument (C++ [over.call.func]p3), and the acting context 6150 // is irrelevant. 6151 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6152 Expr::Classification::makeSimpleLValue(), Args, 6153 CandidateSet, SuppressUserConversions, 6154 PartialOverloading, EarlyConversions, PO); 6155 return; 6156 } 6157 // We treat a constructor like a non-member function, since its object 6158 // argument doesn't participate in overload resolution. 6159 } 6160 6161 if (!CandidateSet.isNewCandidate(Function, PO)) 6162 return; 6163 6164 // C++11 [class.copy]p11: [DR1402] 6165 // A defaulted move constructor that is defined as deleted is ignored by 6166 // overload resolution. 6167 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6168 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6169 Constructor->isMoveConstructor()) 6170 return; 6171 6172 // Overload resolution is always an unevaluated context. 6173 EnterExpressionEvaluationContext Unevaluated( 6174 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6175 6176 // C++ [over.match.oper]p3: 6177 // if no operand has a class type, only those non-member functions in the 6178 // lookup set that have a first parameter of type T1 or "reference to 6179 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6180 // is a right operand) a second parameter of type T2 or "reference to 6181 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6182 // candidate functions. 6183 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6184 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6185 return; 6186 6187 // Add this candidate 6188 OverloadCandidate &Candidate = 6189 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6190 Candidate.FoundDecl = FoundDecl; 6191 Candidate.Function = Function; 6192 Candidate.Viable = true; 6193 Candidate.RewriteKind = 6194 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6195 Candidate.IsSurrogate = false; 6196 Candidate.IsADLCandidate = IsADLCandidate; 6197 Candidate.IgnoreObjectArgument = false; 6198 Candidate.ExplicitCallArguments = Args.size(); 6199 6200 // Explicit functions are not actually candidates at all if we're not 6201 // allowing them in this context, but keep them around so we can point 6202 // to them in diagnostics. 6203 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6204 Candidate.Viable = false; 6205 Candidate.FailureKind = ovl_fail_explicit; 6206 return; 6207 } 6208 6209 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6210 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_non_default_multiversion_function; 6213 return; 6214 } 6215 6216 if (Constructor) { 6217 // C++ [class.copy]p3: 6218 // A member function template is never instantiated to perform the copy 6219 // of a class object to an object of its class type. 6220 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6221 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6222 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6223 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6224 ClassType))) { 6225 Candidate.Viable = false; 6226 Candidate.FailureKind = ovl_fail_illegal_constructor; 6227 return; 6228 } 6229 6230 // C++ [over.match.funcs]p8: (proposed DR resolution) 6231 // A constructor inherited from class type C that has a first parameter 6232 // of type "reference to P" (including such a constructor instantiated 6233 // from a template) is excluded from the set of candidate functions when 6234 // constructing an object of type cv D if the argument list has exactly 6235 // one argument and D is reference-related to P and P is reference-related 6236 // to C. 6237 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6238 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6239 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6240 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6241 QualType C = Context.getRecordType(Constructor->getParent()); 6242 QualType D = Context.getRecordType(Shadow->getParent()); 6243 SourceLocation Loc = Args.front()->getExprLoc(); 6244 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6245 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6246 Candidate.Viable = false; 6247 Candidate.FailureKind = ovl_fail_inhctor_slice; 6248 return; 6249 } 6250 } 6251 6252 // Check that the constructor is capable of constructing an object in the 6253 // destination address space. 6254 if (!Qualifiers::isAddressSpaceSupersetOf( 6255 Constructor->getMethodQualifiers().getAddressSpace(), 6256 CandidateSet.getDestAS())) { 6257 Candidate.Viable = false; 6258 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6259 } 6260 } 6261 6262 unsigned NumParams = Proto->getNumParams(); 6263 6264 // (C++ 13.3.2p2): A candidate function having fewer than m 6265 // parameters is viable only if it has an ellipsis in its parameter 6266 // list (8.3.5). 6267 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6268 !Proto->isVariadic()) { 6269 Candidate.Viable = false; 6270 Candidate.FailureKind = ovl_fail_too_many_arguments; 6271 return; 6272 } 6273 6274 // (C++ 13.3.2p2): A candidate function having more than m parameters 6275 // is viable only if the (m+1)st parameter has a default argument 6276 // (8.3.6). For the purposes of overload resolution, the 6277 // parameter list is truncated on the right, so that there are 6278 // exactly m parameters. 6279 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6280 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6281 // Not enough arguments. 6282 Candidate.Viable = false; 6283 Candidate.FailureKind = ovl_fail_too_few_arguments; 6284 return; 6285 } 6286 6287 // (CUDA B.1): Check for invalid calls between targets. 6288 if (getLangOpts().CUDA) 6289 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6290 // Skip the check for callers that are implicit members, because in this 6291 // case we may not yet know what the member's target is; the target is 6292 // inferred for the member automatically, based on the bases and fields of 6293 // the class. 6294 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6295 Candidate.Viable = false; 6296 Candidate.FailureKind = ovl_fail_bad_target; 6297 return; 6298 } 6299 6300 if (Expr *RequiresClause = Function->getTrailingRequiresClause()) { 6301 ConstraintSatisfaction Satisfaction; 6302 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 6303 !Satisfaction.IsSatisfied) { 6304 Candidate.Viable = false; 6305 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6306 return; 6307 } 6308 } 6309 6310 // Determine the implicit conversion sequences for each of the 6311 // arguments. 6312 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6313 unsigned ConvIdx = 6314 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6315 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6316 // We already formed a conversion sequence for this parameter during 6317 // template argument deduction. 6318 } else if (ArgIdx < NumParams) { 6319 // (C++ 13.3.2p3): for F to be a viable function, there shall 6320 // exist for each argument an implicit conversion sequence 6321 // (13.3.3.1) that converts that argument to the corresponding 6322 // parameter of F. 6323 QualType ParamType = Proto->getParamType(ArgIdx); 6324 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6325 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6326 /*InOverloadResolution=*/true, 6327 /*AllowObjCWritebackConversion=*/ 6328 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6329 if (Candidate.Conversions[ConvIdx].isBad()) { 6330 Candidate.Viable = false; 6331 Candidate.FailureKind = ovl_fail_bad_conversion; 6332 return; 6333 } 6334 } else { 6335 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6336 // argument for which there is no corresponding parameter is 6337 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6338 Candidate.Conversions[ConvIdx].setEllipsis(); 6339 } 6340 } 6341 6342 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6343 Candidate.Viable = false; 6344 Candidate.FailureKind = ovl_fail_enable_if; 6345 Candidate.DeductionFailure.Data = FailedAttr; 6346 return; 6347 } 6348 6349 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6350 Candidate.Viable = false; 6351 Candidate.FailureKind = ovl_fail_ext_disabled; 6352 return; 6353 } 6354} 6355 6356ObjCMethodDecl * 6357Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6358 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6359 if (Methods.size() <= 1) 6360 return nullptr; 6361 6362 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6363 bool Match = true; 6364 ObjCMethodDecl *Method = Methods[b]; 6365 unsigned NumNamedArgs = Sel.getNumArgs(); 6366 // Method might have more arguments than selector indicates. This is due 6367 // to addition of c-style arguments in method. 6368 if (Method->param_size() > NumNamedArgs) 6369 NumNamedArgs = Method->param_size(); 6370 if (Args.size() < NumNamedArgs) 6371 continue; 6372 6373 for (unsigned i = 0; i < NumNamedArgs; i++) { 6374 // We can't do any type-checking on a type-dependent argument. 6375 if (Args[i]->isTypeDependent()) { 6376 Match = false; 6377 break; 6378 } 6379 6380 ParmVarDecl *param = Method->parameters()[i]; 6381 Expr *argExpr = Args[i]; 6382 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6382, __PRETTY_FUNCTION__))
; 6383 6384 // Strip the unbridged-cast placeholder expression off unless it's 6385 // a consumed argument. 6386 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6387 !param->hasAttr<CFConsumedAttr>()) 6388 argExpr = stripARCUnbridgedCast(argExpr); 6389 6390 // If the parameter is __unknown_anytype, move on to the next method. 6391 if (param->getType() == Context.UnknownAnyTy) { 6392 Match = false; 6393 break; 6394 } 6395 6396 ImplicitConversionSequence ConversionState 6397 = TryCopyInitialization(*this, argExpr, param->getType(), 6398 /*SuppressUserConversions*/false, 6399 /*InOverloadResolution=*/true, 6400 /*AllowObjCWritebackConversion=*/ 6401 getLangOpts().ObjCAutoRefCount, 6402 /*AllowExplicit*/false); 6403 // This function looks for a reasonably-exact match, so we consider 6404 // incompatible pointer conversions to be a failure here. 6405 if (ConversionState.isBad() || 6406 (ConversionState.isStandard() && 6407 ConversionState.Standard.Second == 6408 ICK_Incompatible_Pointer_Conversion)) { 6409 Match = false; 6410 break; 6411 } 6412 } 6413 // Promote additional arguments to variadic methods. 6414 if (Match && Method->isVariadic()) { 6415 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6416 if (Args[i]->isTypeDependent()) { 6417 Match = false; 6418 break; 6419 } 6420 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6421 nullptr); 6422 if (Arg.isInvalid()) { 6423 Match = false; 6424 break; 6425 } 6426 } 6427 } else { 6428 // Check for extra arguments to non-variadic methods. 6429 if (Args.size() != NumNamedArgs) 6430 Match = false; 6431 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6432 // Special case when selectors have no argument. In this case, select 6433 // one with the most general result type of 'id'. 6434 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6435 QualType ReturnT = Methods[b]->getReturnType(); 6436 if (ReturnT->isObjCIdType()) 6437 return Methods[b]; 6438 } 6439 } 6440 } 6441 6442 if (Match) 6443 return Method; 6444 } 6445 return nullptr; 6446} 6447 6448static bool 6449convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6450 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6451 bool MissingImplicitThis, Expr *&ConvertedThis, 6452 SmallVectorImpl<Expr *> &ConvertedArgs) { 6453 if (ThisArg) { 6454 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6455 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
6456 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
; 6457 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6457, __PRETTY_FUNCTION__))
; 6458 ExprResult R = S.PerformObjectArgumentInitialization( 6459 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6460 if (R.isInvalid()) 6461 return false; 6462 ConvertedThis = R.get(); 6463 } else { 6464 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6465 (void)MD; 6466 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6467 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6468 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
; 6469 } 6470 ConvertedThis = nullptr; 6471 } 6472 6473 // Ignore any variadic arguments. Converting them is pointless, since the 6474 // user can't refer to them in the function condition. 6475 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6476 6477 // Convert the arguments. 6478 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6479 ExprResult R; 6480 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6481 S.Context, Function->getParamDecl(I)), 6482 SourceLocation(), Args[I]); 6483 6484 if (R.isInvalid()) 6485 return false; 6486 6487 ConvertedArgs.push_back(R.get()); 6488 } 6489 6490 if (Trap.hasErrorOccurred()) 6491 return false; 6492 6493 // Push default arguments if needed. 6494 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6495 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6496 ParmVarDecl *P = Function->getParamDecl(i); 6497 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6498 ? P->getUninstantiatedDefaultArg() 6499 : P->getDefaultArg(); 6500 // This can only happen in code completion, i.e. when PartialOverloading 6501 // is true. 6502 if (!DefArg) 6503 return false; 6504 ExprResult R = 6505 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6506 S.Context, Function->getParamDecl(i)), 6507 SourceLocation(), DefArg); 6508 if (R.isInvalid()) 6509 return false; 6510 ConvertedArgs.push_back(R.get()); 6511 } 6512 6513 if (Trap.hasErrorOccurred()) 6514 return false; 6515 } 6516 return true; 6517} 6518 6519EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6520 bool MissingImplicitThis) { 6521 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6522 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6523 return nullptr; 6524 6525 SFINAETrap Trap(*this); 6526 SmallVector<Expr *, 16> ConvertedArgs; 6527 // FIXME: We should look into making enable_if late-parsed. 6528 Expr *DiscardedThis; 6529 if (!convertArgsForAvailabilityChecks( 6530 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6531 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6532 return *EnableIfAttrs.begin(); 6533 6534 for (auto *EIA : EnableIfAttrs) { 6535 APValue Result; 6536 // FIXME: This doesn't consider value-dependent cases, because doing so is 6537 // very difficult. Ideally, we should handle them more gracefully. 6538 if (EIA->getCond()->isValueDependent() || 6539 !EIA->getCond()->EvaluateWithSubstitution( 6540 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6541 return EIA; 6542 6543 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6544 return EIA; 6545 } 6546 return nullptr; 6547} 6548 6549template <typename CheckFn> 6550static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6551 bool ArgDependent, SourceLocation Loc, 6552 CheckFn &&IsSuccessful) { 6553 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6554 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6555 if (ArgDependent == DIA->getArgDependent()) 6556 Attrs.push_back(DIA); 6557 } 6558 6559 // Common case: No diagnose_if attributes, so we can quit early. 6560 if (Attrs.empty()) 6561 return false; 6562 6563 auto WarningBegin = std::stable_partition( 6564 Attrs.begin(), Attrs.end(), 6565 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6566 6567 // Note that diagnose_if attributes are late-parsed, so they appear in the 6568 // correct order (unlike enable_if attributes). 6569 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6570 IsSuccessful); 6571 if (ErrAttr != WarningBegin) { 6572 const DiagnoseIfAttr *DIA = *ErrAttr; 6573 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6574 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6575 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6576 return true; 6577 } 6578 6579 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6580 if (IsSuccessful(DIA)) { 6581 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6582 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6583 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6584 } 6585 6586 return false; 6587} 6588 6589bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6590 const Expr *ThisArg, 6591 ArrayRef<const Expr *> Args, 6592 SourceLocation Loc) { 6593 return diagnoseDiagnoseIfAttrsWith( 6594 *this, Function, /*ArgDependent=*/true, Loc, 6595 [&](const DiagnoseIfAttr *DIA) { 6596 APValue Result; 6597 // It's sane to use the same Args for any redecl of this function, since 6598 // EvaluateWithSubstitution only cares about the position of each 6599 // argument in the arg list, not the ParmVarDecl* it maps to. 6600 if (!DIA->getCond()->EvaluateWithSubstitution( 6601 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6602 return false; 6603 return Result.isInt() && Result.getInt().getBoolValue(); 6604 }); 6605} 6606 6607bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6608 SourceLocation Loc) { 6609 return diagnoseDiagnoseIfAttrsWith( 6610 *this, ND, /*ArgDependent=*/false, Loc, 6611 [&](const DiagnoseIfAttr *DIA) { 6612 bool Result; 6613 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6614 Result; 6615 }); 6616} 6617 6618/// Add all of the function declarations in the given function set to 6619/// the overload candidate set. 6620void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6621 ArrayRef<Expr *> Args, 6622 OverloadCandidateSet &CandidateSet, 6623 TemplateArgumentListInfo *ExplicitTemplateArgs, 6624 bool SuppressUserConversions, 6625 bool PartialOverloading, 6626 bool FirstArgumentIsBase) { 6627 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6628 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6629 ArrayRef<Expr *> FunctionArgs = Args; 6630 6631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6632 FunctionDecl *FD = 6633 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6634 6635 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6636 QualType ObjectType; 6637 Expr::Classification ObjectClassification; 6638 if (Args.size() > 0) { 6639 if (Expr *E = Args[0]) { 6640 // Use the explicit base to restrict the lookup: 6641 ObjectType = E->getType(); 6642 // Pointers in the object arguments are implicitly dereferenced, so we 6643 // always classify them as l-values. 6644 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6645 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6646 else 6647 ObjectClassification = E->Classify(Context); 6648 } // .. else there is an implicit base. 6649 FunctionArgs = Args.slice(1); 6650 } 6651 if (FunTmpl) { 6652 AddMethodTemplateCandidate( 6653 FunTmpl, F.getPair(), 6654 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6655 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6656 FunctionArgs, CandidateSet, SuppressUserConversions, 6657 PartialOverloading); 6658 } else { 6659 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6660 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6661 ObjectClassification, FunctionArgs, CandidateSet, 6662 SuppressUserConversions, PartialOverloading); 6663 } 6664 } else { 6665 // This branch handles both standalone functions and static methods. 6666 6667 // Slice the first argument (which is the base) when we access 6668 // static method as non-static. 6669 if (Args.size() > 0 && 6670 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6671 !isa<CXXConstructorDecl>(FD)))) { 6672 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6672, __PRETTY_FUNCTION__))
; 6673 FunctionArgs = Args.slice(1); 6674 } 6675 if (FunTmpl) { 6676 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6677 ExplicitTemplateArgs, FunctionArgs, 6678 CandidateSet, SuppressUserConversions, 6679 PartialOverloading); 6680 } else { 6681 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6682 SuppressUserConversions, PartialOverloading); 6683 } 6684 } 6685 } 6686} 6687 6688/// AddMethodCandidate - Adds a named decl (which is some kind of 6689/// method) as a method candidate to the given overload set. 6690void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6691 Expr::Classification ObjectClassification, 6692 ArrayRef<Expr *> Args, 6693 OverloadCandidateSet &CandidateSet, 6694 bool SuppressUserConversions, 6695 OverloadCandidateParamOrder PO) { 6696 NamedDecl *Decl = FoundDecl.getDecl(); 6697 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6698 6699 if (isa<UsingShadowDecl>(Decl)) 6700 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6701 6702 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6703 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
6704 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
; 6705 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6706 /*ExplicitArgs*/ nullptr, ObjectType, 6707 ObjectClassification, Args, CandidateSet, 6708 SuppressUserConversions, false, PO); 6709 } else { 6710 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6711 ObjectType, ObjectClassification, Args, CandidateSet, 6712 SuppressUserConversions, false, None, PO); 6713 } 6714} 6715 6716/// AddMethodCandidate - Adds the given C++ member function to the set 6717/// of candidate functions, using the given function call arguments 6718/// and the object argument (@c Object). For example, in a call 6719/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6720/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6721/// allow user-defined conversions via constructors or conversion 6722/// operators. 6723void 6724Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6725 CXXRecordDecl *ActingContext, QualType ObjectType, 6726 Expr::Classification ObjectClassification, 6727 ArrayRef<Expr *> Args, 6728 OverloadCandidateSet &CandidateSet, 6729 bool SuppressUserConversions, 6730 bool PartialOverloading, 6731 ConversionSequenceList EarlyConversions, 6732 OverloadCandidateParamOrder PO) { 6733 const FunctionProtoType *Proto 6734 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6735 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6735, __PRETTY_FUNCTION__))
; 6736 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
6737 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
; 6738 6739 if (!CandidateSet.isNewCandidate(Method, PO)) 6740 return; 6741 6742 // C++11 [class.copy]p23: [DR1402] 6743 // A defaulted move assignment operator that is defined as deleted is 6744 // ignored by overload resolution. 6745 if (Method->isDefaulted() && Method->isDeleted() && 6746 Method->isMoveAssignmentOperator()) 6747 return; 6748 6749 // Overload resolution is always an unevaluated context. 6750 EnterExpressionEvaluationContext Unevaluated( 6751 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6752 6753 // Add this candidate 6754 OverloadCandidate &Candidate = 6755 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6756 Candidate.FoundDecl = FoundDecl; 6757 Candidate.Function = Method; 6758 Candidate.RewriteKind = 6759 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6760 Candidate.IsSurrogate = false; 6761 Candidate.IgnoreObjectArgument = false; 6762 Candidate.ExplicitCallArguments = Args.size(); 6763 6764 unsigned NumParams = Proto->getNumParams(); 6765 6766 // (C++ 13.3.2p2): A candidate function having fewer than m 6767 // parameters is viable only if it has an ellipsis in its parameter 6768 // list (8.3.5). 6769 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6770 !Proto->isVariadic()) { 6771 Candidate.Viable = false; 6772 Candidate.FailureKind = ovl_fail_too_many_arguments; 6773 return; 6774 } 6775 6776 // (C++ 13.3.2p2): A candidate function having more than m parameters 6777 // is viable only if the (m+1)st parameter has a default argument 6778 // (8.3.6). For the purposes of overload resolution, the 6779 // parameter list is truncated on the right, so that there are 6780 // exactly m parameters. 6781 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6782 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6783 // Not enough arguments. 6784 Candidate.Viable = false; 6785 Candidate.FailureKind = ovl_fail_too_few_arguments; 6786 return; 6787 } 6788 6789 Candidate.Viable = true; 6790 6791 if (Method->isStatic() || ObjectType.isNull()) 6792 // The implicit object argument is ignored. 6793 Candidate.IgnoreObjectArgument = true; 6794 else { 6795 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6796 // Determine the implicit conversion sequence for the object 6797 // parameter. 6798 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6799 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6800 Method, ActingContext); 6801 if (Candidate.Conversions[ConvIdx].isBad()) { 6802 Candidate.Viable = false; 6803 Candidate.FailureKind = ovl_fail_bad_conversion; 6804 return; 6805 } 6806 } 6807 6808 // (CUDA B.1): Check for invalid calls between targets. 6809 if (getLangOpts().CUDA) 6810 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6811 if (!IsAllowedCUDACall(Caller, Method)) { 6812 Candidate.Viable = false; 6813 Candidate.FailureKind = ovl_fail_bad_target; 6814 return; 6815 } 6816 6817 if (Expr *RequiresClause = Method->getTrailingRequiresClause()) { 6818 ConstraintSatisfaction Satisfaction; 6819 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 6820 !Satisfaction.IsSatisfied) { 6821 Candidate.Viable = false; 6822 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6823 return; 6824 } 6825 } 6826 6827 // Determine the implicit conversion sequences for each of the 6828 // arguments. 6829 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6830 unsigned ConvIdx = 6831 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6832 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6833 // We already formed a conversion sequence for this parameter during 6834 // template argument deduction. 6835 } else if (ArgIdx < NumParams) { 6836 // (C++ 13.3.2p3): for F to be a viable function, there shall 6837 // exist for each argument an implicit conversion sequence 6838 // (13.3.3.1) that converts that argument to the corresponding 6839 // parameter of F. 6840 QualType ParamType = Proto->getParamType(ArgIdx); 6841 Candidate.Conversions[ConvIdx] 6842 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6843 SuppressUserConversions, 6844 /*InOverloadResolution=*/true, 6845 /*AllowObjCWritebackConversion=*/ 6846 getLangOpts().ObjCAutoRefCount); 6847 if (Candidate.Conversions[ConvIdx].isBad()) { 6848 Candidate.Viable = false; 6849 Candidate.FailureKind = ovl_fail_bad_conversion; 6850 return; 6851 } 6852 } else { 6853 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6854 // argument for which there is no corresponding parameter is 6855 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6856 Candidate.Conversions[ConvIdx].setEllipsis(); 6857 } 6858 } 6859 6860 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6861 Candidate.Viable = false; 6862 Candidate.FailureKind = ovl_fail_enable_if; 6863 Candidate.DeductionFailure.Data = FailedAttr; 6864 return; 6865 } 6866 6867 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6868 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6869 Candidate.Viable = false; 6870 Candidate.FailureKind = ovl_non_default_multiversion_function; 6871 } 6872} 6873 6874/// Add a C++ member function template as a candidate to the candidate 6875/// set, using template argument deduction to produce an appropriate member 6876/// function template specialization. 6877void Sema::AddMethodTemplateCandidate( 6878 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6879 CXXRecordDecl *ActingContext, 6880 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6881 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6882 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6883 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6884 if (!CandidateSet.isNewCandidate(MethodTmpl, 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 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6901 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6902 return CheckNonDependentConversions( 6903 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6904 SuppressUserConversions, ActingContext, ObjectType, 6905 ObjectClassification, PO); 6906 })) { 6907 OverloadCandidate &Candidate = 6908 CandidateSet.addCandidate(Conversions.size(), Conversions); 6909 Candidate.FoundDecl = FoundDecl; 6910 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6911 Candidate.Viable = false; 6912 Candidate.RewriteKind = 6913 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6914 Candidate.IsSurrogate = false; 6915 Candidate.IgnoreObjectArgument = 6916 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6917 ObjectType.isNull(); 6918 Candidate.ExplicitCallArguments = Args.size(); 6919 if (Result == TDK_NonDependentConversionFailure) 6920 Candidate.FailureKind = ovl_fail_bad_conversion; 6921 else { 6922 Candidate.FailureKind = ovl_fail_bad_deduction; 6923 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6924 Info); 6925 } 6926 return; 6927 } 6928 6929 // Add the function template specialization produced by template argument 6930 // deduction as a candidate. 6931 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6931, __PRETTY_FUNCTION__))
; 6932 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
6933 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
; 6934 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6935 ActingContext, ObjectType, ObjectClassification, Args, 6936 CandidateSet, SuppressUserConversions, PartialOverloading, 6937 Conversions, PO); 6938} 6939 6940/// Determine whether a given function template has a simple explicit specifier 6941/// or a non-value-dependent explicit-specification that evaluates to true. 6942static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6943 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6944} 6945 6946/// Add a C++ function template specialization as a candidate 6947/// in the candidate set, using template argument deduction to produce 6948/// an appropriate function template specialization. 6949void Sema::AddTemplateOverloadCandidate( 6950 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6951 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6952 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6953 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6954 OverloadCandidateParamOrder PO) { 6955 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6956 return; 6957 6958 // If the function template has a non-dependent explicit specification, 6959 // exclude it now if appropriate; we are not permitted to perform deduction 6960 // and substitution in this case. 6961 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6962 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6963 Candidate.FoundDecl = FoundDecl; 6964 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6965 Candidate.Viable = false; 6966 Candidate.FailureKind = ovl_fail_explicit; 6967 return; 6968 } 6969 6970 // C++ [over.match.funcs]p7: 6971 // In each case where a candidate is a function template, candidate 6972 // function template specializations are generated using template argument 6973 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6974 // candidate functions in the usual way.113) A given name can refer to one 6975 // or more function templates and also to a set of overloaded non-template 6976 // functions. In such a case, the candidate functions generated from each 6977 // function template are combined with the set of non-template candidate 6978 // functions. 6979 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6980 FunctionDecl *Specialization = nullptr; 6981 ConversionSequenceList Conversions; 6982 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6983 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6984 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6985 return CheckNonDependentConversions( 6986 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6987 SuppressUserConversions, nullptr, QualType(), {}, PO); 6988 })) { 6989 OverloadCandidate &Candidate = 6990 CandidateSet.addCandidate(Conversions.size(), Conversions); 6991 Candidate.FoundDecl = FoundDecl; 6992 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6993 Candidate.Viable = false; 6994 Candidate.RewriteKind = 6995 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6996 Candidate.IsSurrogate = false; 6997 Candidate.IsADLCandidate = IsADLCandidate; 6998 // Ignore the object argument if there is one, since we don't have an object 6999 // type. 7000 Candidate.IgnoreObjectArgument = 7001 isa<CXXMethodDecl>(Candidate.Function) && 7002 !isa<CXXConstructorDecl>(Candidate.Function); 7003 Candidate.ExplicitCallArguments = Args.size(); 7004 if (Result == TDK_NonDependentConversionFailure) 7005 Candidate.FailureKind = ovl_fail_bad_conversion; 7006 else { 7007 Candidate.FailureKind = ovl_fail_bad_deduction; 7008 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7009 Info); 7010 } 7011 return; 7012 } 7013 7014 // Add the function template specialization produced by template argument 7015 // deduction as a candidate. 7016 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7016, __PRETTY_FUNCTION__))
; 7017 AddOverloadCandidate( 7018 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7019 PartialOverloading, AllowExplicit, 7020 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7021} 7022 7023/// Check that implicit conversion sequences can be formed for each argument 7024/// whose corresponding parameter has a non-dependent type, per DR1391's 7025/// [temp.deduct.call]p10. 7026bool Sema::CheckNonDependentConversions( 7027 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7028 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7029 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7030 CXXRecordDecl *ActingContext, QualType ObjectType, 7031 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7032 // FIXME: The cases in which we allow explicit conversions for constructor 7033 // arguments never consider calling a constructor template. It's not clear 7034 // that is correct. 7035 const bool AllowExplicit = false; 7036 7037 auto *FD = FunctionTemplate->getTemplatedDecl(); 7038 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7039 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7040 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7041 7042 Conversions = 7043 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7044 7045 // Overload resolution is always an unevaluated context. 7046 EnterExpressionEvaluationContext Unevaluated( 7047 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7048 7049 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7050 // require that, but this check should never result in a hard error, and 7051 // overload resolution is permitted to sidestep instantiations. 7052 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7053 !ObjectType.isNull()) { 7054 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7055 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7056 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7057 Method, ActingContext); 7058 if (Conversions[ConvIdx].isBad()) 7059 return true; 7060 } 7061 7062 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7063 ++I) { 7064 QualType ParamType = ParamTypes[I]; 7065 if (!ParamType->isDependentType()) { 7066 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7067 ? 0 7068 : (ThisConversions + I); 7069 Conversions[ConvIdx] 7070 = TryCopyInitialization(*this, Args[I], ParamType, 7071 SuppressUserConversions, 7072 /*InOverloadResolution=*/true, 7073 /*AllowObjCWritebackConversion=*/ 7074 getLangOpts().ObjCAutoRefCount, 7075 AllowExplicit); 7076 if (Conversions[ConvIdx].isBad()) 7077 return true; 7078 } 7079 } 7080 7081 return false; 7082} 7083 7084/// Determine whether this is an allowable conversion from the result 7085/// of an explicit conversion operator to the expected type, per C++ 7086/// [over.match.conv]p1 and [over.match.ref]p1. 7087/// 7088/// \param ConvType The return type of the conversion function. 7089/// 7090/// \param ToType The type we are converting to. 7091/// 7092/// \param AllowObjCPointerConversion Allow a conversion from one 7093/// Objective-C pointer to another. 7094/// 7095/// \returns true if the conversion is allowable, false otherwise. 7096static bool isAllowableExplicitConversion(Sema &S, 7097 QualType ConvType, QualType ToType, 7098 bool AllowObjCPointerConversion) { 7099 QualType ToNonRefType = ToType.getNonReferenceType(); 7100 7101 // Easy case: the types are the same. 7102 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7103 return true; 7104 7105 // Allow qualification conversions. 7106 bool ObjCLifetimeConversion; 7107 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7108 ObjCLifetimeConversion)) 7109 return true; 7110 7111 // If we're not allowed to consider Objective-C pointer conversions, 7112 // we're done. 7113 if (!AllowObjCPointerConversion) 7114 return false; 7115 7116 // Is this an Objective-C pointer conversion? 7117 bool IncompatibleObjC = false; 7118 QualType ConvertedType; 7119 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7120 IncompatibleObjC); 7121} 7122 7123/// AddConversionCandidate - Add a C++ conversion function as a 7124/// candidate in the candidate set (C++ [over.match.conv], 7125/// C++ [over.match.copy]). From is the expression we're converting from, 7126/// and ToType is the type that we're eventually trying to convert to 7127/// (which may or may not be the same type as the type that the 7128/// conversion function produces). 7129void Sema::AddConversionCandidate( 7130 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7131 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7132 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7133 bool AllowExplicit, bool AllowResultConversion) { 7134 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
7135 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
; 7136 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7137 if (!CandidateSet.isNewCandidate(Conversion)) 7138 return; 7139 7140 // If the conversion function has an undeduced return type, trigger its 7141 // deduction now. 7142 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7143 if (DeduceReturnType(Conversion, From->getExprLoc())) 7144 return; 7145 ConvType = Conversion->getConversionType().getNonReferenceType(); 7146 } 7147 7148 // If we don't allow any conversion of the result type, ignore conversion 7149 // functions that don't convert to exactly (possibly cv-qualified) T. 7150 if (!AllowResultConversion && 7151 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7152 return; 7153 7154 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7155 // operator is only a candidate if its return type is the target type or 7156 // can be converted to the target type with a qualification conversion. 7157 // 7158 // FIXME: Include such functions in the candidate list and explain why we 7159 // can't select them. 7160 if (Conversion->isExplicit() && 7161 !isAllowableExplicitConversion(*this, ConvType, ToType, 7162 AllowObjCConversionOnExplicit)) 7163 return; 7164 7165 // Overload resolution is always an unevaluated context. 7166 EnterExpressionEvaluationContext Unevaluated( 7167 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7168 7169 // Add this candidate 7170 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7171 Candidate.FoundDecl = FoundDecl; 7172 Candidate.Function = Conversion; 7173 Candidate.IsSurrogate = false; 7174 Candidate.IgnoreObjectArgument = false; 7175 Candidate.FinalConversion.setAsIdentityConversion(); 7176 Candidate.FinalConversion.setFromType(ConvType); 7177 Candidate.FinalConversion.setAllToTypes(ToType); 7178 Candidate.Viable = true; 7179 Candidate.ExplicitCallArguments = 1; 7180 7181 // Explicit functions are not actually candidates at all if we're not 7182 // allowing them in this context, but keep them around so we can point 7183 // to them in diagnostics. 7184 if (!AllowExplicit && Conversion->isExplicit()) { 7185 Candidate.Viable = false; 7186 Candidate.FailureKind = ovl_fail_explicit; 7187 return; 7188 } 7189 7190 // C++ [over.match.funcs]p4: 7191 // For conversion functions, the function is considered to be a member of 7192 // the class of the implicit implied object argument for the purpose of 7193 // defining the type of the implicit object parameter. 7194 // 7195 // Determine the implicit conversion sequence for the implicit 7196 // object parameter. 7197 QualType ImplicitParamType = From->getType(); 7198 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7199 ImplicitParamType = FromPtrType->getPointeeType(); 7200 CXXRecordDecl *ConversionContext 7201 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7202 7203 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7204 *this, CandidateSet.getLocation(), From->getType(), 7205 From->Classify(Context), Conversion, ConversionContext); 7206 7207 if (Candidate.Conversions[0].isBad()) { 7208 Candidate.Viable = false; 7209 Candidate.FailureKind = ovl_fail_bad_conversion; 7210 return; 7211 } 7212 7213 Expr *RequiresClause = Conversion->getTrailingRequiresClause(); 7214 if (RequiresClause) { 7215 ConstraintSatisfaction Satisfaction; 7216 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 7217 !Satisfaction.IsSatisfied) { 7218 Candidate.Viable = false; 7219 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7220 return; 7221 } 7222 } 7223 7224 // We won't go through a user-defined type conversion function to convert a 7225 // derived to base as such conversions are given Conversion Rank. They only 7226 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7227 QualType FromCanon 7228 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7229 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7230 if (FromCanon == ToCanon || 7231 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7232 Candidate.Viable = false; 7233 Candidate.FailureKind = ovl_fail_trivial_conversion; 7234 return; 7235 } 7236 7237 // To determine what the conversion from the result of calling the 7238 // conversion function to the type we're eventually trying to 7239 // convert to (ToType), we need to synthesize a call to the 7240 // conversion function and attempt copy initialization from it. This 7241 // makes sure that we get the right semantics with respect to 7242 // lvalues/rvalues and the type. Fortunately, we can allocate this 7243 // call on the stack and we don't need its arguments to be 7244 // well-formed. 7245 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7246 VK_LValue, From->getBeginLoc()); 7247 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7248 Context.getPointerType(Conversion->getType()), 7249 CK_FunctionToPointerDecay, 7250 &ConversionRef, VK_RValue); 7251 7252 QualType ConversionType = Conversion->getConversionType(); 7253 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7254 Candidate.Viable = false; 7255 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7256 return; 7257 } 7258 7259 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7260 7261 // Note that it is safe to allocate CallExpr on the stack here because 7262 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7263 // allocator). 7264 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7265 7266 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7267 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7268 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7269 7270 ImplicitConversionSequence ICS = 7271 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7272 /*SuppressUserConversions=*/true, 7273 /*InOverloadResolution=*/false, 7274 /*AllowObjCWritebackConversion=*/false); 7275 7276 switch (ICS.getKind()) { 7277 case ImplicitConversionSequence::StandardConversion: 7278 Candidate.FinalConversion = ICS.Standard; 7279 7280 // C++ [over.ics.user]p3: 7281 // If the user-defined conversion is specified by a specialization of a 7282 // conversion function template, the second standard conversion sequence 7283 // shall have exact match rank. 7284 if (Conversion->getPrimaryTemplate() && 7285 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7286 Candidate.Viable = false; 7287 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7288 return; 7289 } 7290 7291 // C++0x [dcl.init.ref]p5: 7292 // In the second case, if the reference is an rvalue reference and 7293 // the second standard conversion sequence of the user-defined 7294 // conversion sequence includes an lvalue-to-rvalue conversion, the 7295 // program is ill-formed. 7296 if (ToType->isRValueReferenceType() && 7297 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7298 Candidate.Viable = false; 7299 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7300 return; 7301 } 7302 break; 7303 7304 case ImplicitConversionSequence::BadConversion: 7305 Candidate.Viable = false; 7306 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7307 return; 7308 7309 default: 7310 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
7311 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
; 7312 } 7313 7314 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7315 Candidate.Viable = false; 7316 Candidate.FailureKind = ovl_fail_enable_if; 7317 Candidate.DeductionFailure.Data = FailedAttr; 7318 return; 7319 } 7320 7321 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7322 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7323 Candidate.Viable = false; 7324 Candidate.FailureKind = ovl_non_default_multiversion_function; 7325 } 7326} 7327 7328/// Adds a conversion function template specialization 7329/// candidate to the overload set, using template argument deduction 7330/// to deduce the template arguments of the conversion function 7331/// template from the type that we are converting to (C++ 7332/// [temp.deduct.conv]). 7333void Sema::AddTemplateConversionCandidate( 7334 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7335 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7336 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7337 bool AllowExplicit, bool AllowResultConversion) { 7338 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
7339 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
; 7340 7341 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7342 return; 7343 7344 // If the function template has a non-dependent explicit specification, 7345 // exclude it now if appropriate; we are not permitted to perform deduction 7346 // and substitution in this case. 7347 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7348 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7349 Candidate.FoundDecl = FoundDecl; 7350 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7351 Candidate.Viable = false; 7352 Candidate.FailureKind = ovl_fail_explicit; 7353 return; 7354 } 7355 7356 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7357 CXXConversionDecl *Specialization = nullptr; 7358 if (TemplateDeductionResult Result 7359 = DeduceTemplateArguments(FunctionTemplate, ToType, 7360 Specialization, Info)) { 7361 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7362 Candidate.FoundDecl = FoundDecl; 7363 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7364 Candidate.Viable = false; 7365 Candidate.FailureKind = ovl_fail_bad_deduction; 7366 Candidate.IsSurrogate = false; 7367 Candidate.IgnoreObjectArgument = false; 7368 Candidate.ExplicitCallArguments = 1; 7369 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7370 Info); 7371 return; 7372 } 7373 7374 // Add the conversion function template specialization produced by 7375 // template argument deduction as a candidate. 7376 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
; 7377 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7378 CandidateSet, AllowObjCConversionOnExplicit, 7379 AllowExplicit, AllowResultConversion); 7380} 7381 7382/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7383/// converts the given @c Object to a function pointer via the 7384/// conversion function @c Conversion, and then attempts to call it 7385/// with the given arguments (C++ [over.call.object]p2-4). Proto is 7386/// the type of function that we'll eventually be calling. 7387void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7388 DeclAccessPair FoundDecl, 7389 CXXRecordDecl *ActingContext, 7390 const FunctionProtoType *Proto, 7391 Expr *Object, 7392 ArrayRef<Expr *> Args, 7393 OverloadCandidateSet& CandidateSet) { 7394 if (!CandidateSet.isNewCandidate(Conversion)) 7395 return; 7396 7397 // Overload resolution is always an unevaluated context. 7398 EnterExpressionEvaluationContext Unevaluated( 7399 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7400 7401 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7402 Candidate.FoundDecl = FoundDecl; 7403 Candidate.Function = nullptr; 7404 Candidate.Surrogate = Conversion; 7405 Candidate.Viable = true; 7406 Candidate.IsSurrogate = true; 7407 Candidate.IgnoreObjectArgument = false; 7408 Candidate.ExplicitCallArguments = Args.size(); 7409 7410 // Determine the implicit conversion sequence for the implicit 7411 // object parameter. 7412 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7413 *this, CandidateSet.getLocation(), Object->getType(), 7414 Object->Classify(Context), Conversion, ActingContext); 7415 if (ObjectInit.isBad()) { 7416 Candidate.Viable = false; 7417 Candidate.FailureKind = ovl_fail_bad_conversion; 7418 Candidate.Conversions[0] = ObjectInit; 7419 return; 7420 } 7421 7422 // The first conversion is actually a user-defined conversion whose 7423 // first conversion is ObjectInit's standard conversion (which is 7424 // effectively a reference binding). Record it as such. 7425 Candidate.Conversions[0].setUserDefined(); 7426 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7427 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7428 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7429 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7430 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7431 Candidate.Conversions[0].UserDefined.After 7432 = Candidate.Conversions[0].UserDefined.Before; 7433 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7434 7435 // Find the 7436 unsigned NumParams = Proto->getNumParams(); 7437 7438 // (C++ 13.3.2p2): A candidate function having fewer than m 7439 // parameters is viable only if it has an ellipsis in its parameter 7440 // list (8.3.5). 7441 if (Args.size() > NumParams && !Proto->isVariadic()) { 7442 Candidate.Viable = false; 7443 Candidate.FailureKind = ovl_fail_too_many_arguments; 7444 return; 7445 } 7446 7447 // Function types don't have any default arguments, so just check if 7448 // we have enough arguments. 7449 if (Args.size() < NumParams) { 7450 // Not enough arguments. 7451 Candidate.Viable = false; 7452 Candidate.FailureKind = ovl_fail_too_few_arguments; 7453 return; 7454 } 7455 7456 // Determine the implicit conversion sequences for each of the 7457 // arguments. 7458 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7459 if (ArgIdx < NumParams) { 7460 // (C++ 13.3.2p3): for F to be a viable function, there shall 7461 // exist for each argument an implicit conversion sequence 7462 // (13.3.3.1) that converts that argument to the corresponding 7463 // parameter of F. 7464 QualType ParamType = Proto->getParamType(ArgIdx); 7465 Candidate.Conversions[ArgIdx + 1] 7466 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7467 /*SuppressUserConversions=*/false, 7468 /*InOverloadResolution=*/false, 7469 /*AllowObjCWritebackConversion=*/ 7470 getLangOpts().ObjCAutoRefCount); 7471 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7472 Candidate.Viable = false; 7473 Candidate.FailureKind = ovl_fail_bad_conversion; 7474 return; 7475 } 7476 } else { 7477 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7478 // argument for which there is no corresponding parameter is 7479 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7480 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7481 } 7482 } 7483 7484 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7485 Candidate.Viable = false; 7486 Candidate.FailureKind = ovl_fail_enable_if; 7487 Candidate.DeductionFailure.Data = FailedAttr; 7488 return; 7489 } 7490} 7491 7492/// Add all of the non-member operator function declarations in the given 7493/// function set to the overload candidate set. 7494void Sema::AddNonMemberOperatorCandidates( 7495 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7496 OverloadCandidateSet &CandidateSet, 7497 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7498 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7499 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7500 ArrayRef<Expr *> FunctionArgs = Args; 7501 7502 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7503 FunctionDecl *FD = 7504 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7505 7506 // Don't consider rewritten functions if we're not rewriting. 7507 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7508 continue; 7509 7510 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
7511 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
; 7512 7513 if (FunTmpl) { 7514 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7515 FunctionArgs, CandidateSet); 7516 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7517 AddTemplateOverloadCandidate( 7518 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7519 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7520 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7521 } else { 7522 if (ExplicitTemplateArgs) 7523 continue; 7524 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7525 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7526 AddOverloadCandidate(FD, F.getPair(), 7527 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7528 false, false, true, false, ADLCallKind::NotADL, 7529 None, OverloadCandidateParamOrder::Reversed); 7530 } 7531 } 7532} 7533 7534/// Add overload candidates for overloaded operators that are 7535/// member functions. 7536/// 7537/// Add the overloaded operator candidates that are member functions 7538/// for the operator Op that was used in an operator expression such 7539/// as "x Op y". , Args/NumArgs provides the operator arguments, and 7540/// CandidateSet will store the added overload candidates. (C++ 7541/// [over.match.oper]). 7542void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7543 SourceLocation OpLoc, 7544 ArrayRef<Expr *> Args, 7545 OverloadCandidateSet &CandidateSet, 7546 OverloadCandidateParamOrder PO) { 7547 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7548 7549 // C++ [over.match.oper]p3: 7550 // For a unary operator @ with an operand of a type whose 7551 // cv-unqualified version is T1, and for a binary operator @ with 7552 // a left operand of a type whose cv-unqualified version is T1 and 7553 // a right operand of a type whose cv-unqualified version is T2, 7554 // three sets of candidate functions, designated member 7555 // candidates, non-member candidates and built-in candidates, are 7556 // constructed as follows: 7557 QualType T1 = Args[0]->getType(); 7558 7559 // -- If T1 is a complete class type or a class currently being 7560 // defined, the set of member candidates is the result of the 7561 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7562 // the set of member candidates is empty. 7563 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7564 // Complete the type if it can be completed. 7565 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7566 return; 7567 // If the type is neither complete nor being defined, bail out now. 7568 if (!T1Rec->getDecl()->getDefinition()) 7569 return; 7570 7571 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7572 LookupQualifiedName(Operators, T1Rec->getDecl()); 7573 Operators.suppressDiagnostics(); 7574 7575 for (LookupResult::iterator Oper = Operators.begin(), 7576 OperEnd = Operators.end(); 7577 Oper != OperEnd; 7578 ++Oper) 7579 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7580 Args[0]->Classify(Context), Args.slice(1), 7581 CandidateSet, /*SuppressUserConversion=*/false, PO); 7582 } 7583} 7584 7585/// AddBuiltinCandidate - Add a candidate for a built-in 7586/// operator. ResultTy and ParamTys are the result and parameter types 7587/// of the built-in candidate, respectively. Args and NumArgs are the 7588/// arguments being passed to the candidate. IsAssignmentOperator 7589/// should be true when this built-in candidate is an assignment 7590/// operator. NumContextualBoolArguments is the number of arguments 7591/// (at the beginning of the argument list) that will be contextually 7592/// converted to bool. 7593void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7594 OverloadCandidateSet& CandidateSet, 7595 bool IsAssignmentOperator, 7596 unsigned NumContextualBoolArguments) { 7597 // Overload resolution is always an unevaluated context. 7598 EnterExpressionEvaluationContext Unevaluated( 7599 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7600 7601 // Add this candidate 7602 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7603 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7604 Candidate.Function = nullptr; 7605 Candidate.IsSurrogate = false; 7606 Candidate.IgnoreObjectArgument = false; 7607 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7608 7609 // Determine the implicit conversion sequences for each of the 7610 // arguments. 7611 Candidate.Viable = true; 7612 Candidate.ExplicitCallArguments = Args.size(); 7613 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7614 // C++ [over.match.oper]p4: 7615 // For the built-in assignment operators, conversions of the 7616 // left operand are restricted as follows: 7617 // -- no temporaries are introduced to hold the left operand, and 7618 // -- no user-defined conversions are applied to the left 7619 // operand to achieve a type match with the left-most 7620 // parameter of a built-in candidate. 7621 // 7622 // We block these conversions by turning off user-defined 7623 // conversions, since that is the only way that initialization of 7624 // a reference to a non-class type can occur from something that 7625 // is not of the same type. 7626 if (ArgIdx < NumContextualBoolArguments) { 7627 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
7628 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
; 7629 Candidate.Conversions[ArgIdx] 7630 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7631 } else { 7632 Candidate.Conversions[ArgIdx] 7633 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7634 ArgIdx == 0 && IsAssignmentOperator, 7635 /*InOverloadResolution=*/false, 7636 /*AllowObjCWritebackConversion=*/ 7637 getLangOpts().ObjCAutoRefCount); 7638 } 7639 if (Candidate.Conversions[ArgIdx].isBad()) { 7640 Candidate.Viable = false; 7641 Candidate.FailureKind = ovl_fail_bad_conversion; 7642 break; 7643 } 7644 } 7645} 7646 7647namespace { 7648 7649/// BuiltinCandidateTypeSet - A set of types that will be used for the 7650/// candidate operator functions for built-in operators (C++ 7651/// [over.built]). The types are separated into pointer types and 7652/// enumeration types. 7653class BuiltinCandidateTypeSet { 7654 /// TypeSet - A set of types. 7655 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7656 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7657 7658 /// PointerTypes - The set of pointer types that will be used in the 7659 /// built-in candidates. 7660 TypeSet PointerTypes; 7661 7662 /// MemberPointerTypes - The set of member pointer types that will be 7663 /// used in the built-in candidates. 7664 TypeSet MemberPointerTypes; 7665 7666 /// EnumerationTypes - The set of enumeration types that will be 7667 /// used in the built-in candidates. 7668 TypeSet EnumerationTypes; 7669 7670 /// The set of vector types that will be used in the built-in 7671 /// candidates. 7672 TypeSet VectorTypes; 7673 7674 /// A flag indicating non-record types are viable candidates 7675 bool HasNonRecordTypes; 7676 7677 /// A flag indicating whether either arithmetic or enumeration types 7678 /// were present in the candidate set. 7679 bool HasArithmeticOrEnumeralTypes; 7680 7681 /// A flag indicating whether the nullptr type was present in the 7682 /// candidate set. 7683 bool HasNullPtrType; 7684 7685 /// Sema - The semantic analysis instance where we are building the 7686 /// candidate type set. 7687 Sema &SemaRef; 7688 7689 /// Context - The AST context in which we will build the type sets. 7690 ASTContext &Context; 7691 7692 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7693 const Qualifiers &VisibleQuals); 7694 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7695 7696public: 7697 /// iterator - Iterates through the types that are part of the set. 7698 typedef TypeSet::iterator iterator; 7699 7700 BuiltinCandidateTypeSet(Sema &SemaRef) 7701 : HasNonRecordTypes(false), 7702 HasArithmeticOrEnumeralTypes(false), 7703 HasNullPtrType(false), 7704 SemaRef(SemaRef), 7705 Context(SemaRef.Context) { } 7706 7707 void AddTypesConvertedFrom(QualType Ty, 7708 SourceLocation Loc, 7709 bool AllowUserConversions, 7710 bool AllowExplicitConversions, 7711 const Qualifiers &VisibleTypeConversionsQuals); 7712 7713 /// pointer_begin - First pointer type found; 7714 iterator pointer_begin() { return PointerTypes.begin(); } 7715 7716 /// pointer_end - Past the last pointer type found; 7717 iterator pointer_end() { return PointerTypes.end(); } 7718 7719 /// member_pointer_begin - First member pointer type found; 7720 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7721 7722 /// member_pointer_end - Past the last member pointer type found; 7723 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7724 7725 /// enumeration_begin - First enumeration type found; 7726 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7727 7728 /// enumeration_end - Past the last enumeration type found; 7729 iterator enumeration_end() { return EnumerationTypes.end(); } 7730 7731 iterator vector_begin() { return VectorTypes.begin(); } 7732 iterator vector_end() { return VectorTypes.end(); } 7733 7734 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7735 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7736 bool hasNullPtrType() const { return HasNullPtrType; } 7737}; 7738 7739} // end anonymous namespace 7740 7741/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7742/// the set of pointer types along with any more-qualified variants of 7743/// that type. For example, if @p Ty is "int const *", this routine 7744/// will add "int const *", "int const volatile *", "int const 7745/// restrict *", and "int const volatile restrict *" to the set of 7746/// pointer types. Returns true if the add of @p Ty itself succeeded, 7747/// false otherwise. 7748/// 7749/// FIXME: what to do about extended qualifiers? 7750bool 7751BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7752 const Qualifiers &VisibleQuals) { 7753 7754 // Insert this type. 7755 if (!PointerTypes.insert(Ty)) 7756 return false; 7757 7758 QualType PointeeTy; 7759 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7760 bool buildObjCPtr = false; 7761 if (!PointerTy) { 7762 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7763 PointeeTy = PTy->getPointeeType(); 7764 buildObjCPtr = true; 7765 } else { 7766 PointeeTy = PointerTy->getPointeeType(); 7767 } 7768 7769 // Don't add qualified variants of arrays. For one, they're not allowed 7770 // (the qualifier would sink to the element type), and for another, the 7771 // only overload situation where it matters is subscript or pointer +- int, 7772 // and those shouldn't have qualifier variants anyway. 7773 if (PointeeTy->isArrayType()) 7774 return true; 7775 7776 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7777 bool hasVolatile = VisibleQuals.hasVolatile(); 7778 bool hasRestrict = VisibleQuals.hasRestrict(); 7779 7780 // Iterate through all strict supersets of BaseCVR. 7781 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7782 if ((CVR | BaseCVR) != CVR) continue; 7783 // Skip over volatile if no volatile found anywhere in the types. 7784 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7785 7786 // Skip over restrict if no restrict found anywhere in the types, or if 7787 // the type cannot be restrict-qualified. 7788 if ((CVR & Qualifiers::Restrict) && 7789 (!hasRestrict || 7790 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7791 continue; 7792 7793 // Build qualified pointee type. 7794 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7795 7796 // Build qualified pointer type. 7797 QualType QPointerTy; 7798 if (!buildObjCPtr) 7799 QPointerTy = Context.getPointerType(QPointeeTy); 7800 else 7801 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7802 7803 // Insert qualified pointer type. 7804 PointerTypes.insert(QPointerTy); 7805 } 7806 7807 return true; 7808} 7809 7810/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7811/// to the set of pointer types along with any more-qualified variants of 7812/// that type. For example, if @p Ty is "int const *", this routine 7813/// will add "int const *", "int const volatile *", "int const 7814/// restrict *", and "int const volatile restrict *" to the set of 7815/// pointer types. Returns true if the add of @p Ty itself succeeded, 7816/// false otherwise. 7817/// 7818/// FIXME: what to do about extended qualifiers? 7819bool 7820BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7821 QualType Ty) { 7822 // Insert this type. 7823 if (!MemberPointerTypes.insert(Ty)) 7824 return false; 7825 7826 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7827 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7827, __PRETTY_FUNCTION__))
; 7828 7829 QualType PointeeTy = PointerTy->getPointeeType(); 7830 // Don't add qualified variants of arrays. For one, they're not allowed 7831 // (the qualifier would sink to the element type), and for another, the 7832 // only overload situation where it matters is subscript or pointer +- int, 7833 // and those shouldn't have qualifier variants anyway. 7834 if (PointeeTy->isArrayType()) 7835 return true; 7836 const Type *ClassTy = PointerTy->getClass(); 7837 7838 // Iterate through all strict supersets of the pointee type's CVR 7839 // qualifiers. 7840 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7841 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7842 if ((CVR | BaseCVR) != CVR) continue; 7843 7844 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7845 MemberPointerTypes.insert( 7846 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7847 } 7848 7849 return true; 7850} 7851 7852/// AddTypesConvertedFrom - Add each of the types to which the type @p 7853/// Ty can be implicit converted to the given set of @p Types. We're 7854/// primarily interested in pointer types and enumeration types. We also 7855/// take member pointer types, for the conditional operator. 7856/// AllowUserConversions is true if we should look at the conversion 7857/// functions of a class type, and AllowExplicitConversions if we 7858/// should also include the explicit conversion functions of a class 7859/// type. 7860void 7861BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7862 SourceLocation Loc, 7863 bool AllowUserConversions, 7864 bool AllowExplicitConversions, 7865 const Qualifiers &VisibleQuals) { 7866 // Only deal with canonical types. 7867 Ty = Context.getCanonicalType(Ty); 7868 7869 // Look through reference types; they aren't part of the type of an 7870 // expression for the purposes of conversions. 7871 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7872 Ty = RefTy->getPointeeType(); 7873 7874 // If we're dealing with an array type, decay to the pointer. 7875 if (Ty->isArrayType()) 7876 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7877 7878 // Otherwise, we don't care about qualifiers on the type. 7879 Ty = Ty.getLocalUnqualifiedType(); 7880 7881 // Flag if we ever add a non-record type. 7882 const RecordType *TyRec = Ty->getAs<RecordType>(); 7883 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7884 7885 // Flag if we encounter an arithmetic type. 7886 HasArithmeticOrEnumeralTypes = 7887 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7888 7889 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7890 PointerTypes.insert(Ty); 7891 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7892 // Insert our type, and its more-qualified variants, into the set 7893 // of types. 7894 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7895 return; 7896 } else if (Ty->isMemberPointerType()) { 7897 // Member pointers are far easier, since the pointee can't be converted. 7898 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7899 return; 7900 } else if (Ty->isEnumeralType()) { 7901 HasArithmeticOrEnumeralTypes = true; 7902 EnumerationTypes.insert(Ty); 7903 } else if (Ty->isVectorType()) { 7904 // We treat vector types as arithmetic types in many contexts as an 7905 // extension. 7906 HasArithmeticOrEnumeralTypes = true; 7907 VectorTypes.insert(Ty); 7908 } else if (Ty->isNullPtrType()) { 7909 HasNullPtrType = true; 7910 } else if (AllowUserConversions && TyRec) { 7911 // No conversion functions in incomplete types. 7912 if (!SemaRef.isCompleteType(Loc, Ty)) 7913 return; 7914 7915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7916 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7917 if (isa<UsingShadowDecl>(D)) 7918 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7919 7920 // Skip conversion function templates; they don't tell us anything 7921 // about which builtin types we can convert to. 7922 if (isa<FunctionTemplateDecl>(D)) 7923 continue; 7924 7925 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7926 if (AllowExplicitConversions || !Conv->isExplicit()) { 7927 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7928 VisibleQuals); 7929 } 7930 } 7931 } 7932} 7933/// Helper function for adjusting address spaces for the pointer or reference 7934/// operands of builtin operators depending on the argument. 7935static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7936 Expr *Arg) { 7937 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7938} 7939 7940/// Helper function for AddBuiltinOperatorCandidates() that adds 7941/// the volatile- and non-volatile-qualified assignment operators for the 7942/// given type to the candidate set. 7943static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7944 QualType T, 7945 ArrayRef<Expr *> Args, 7946 OverloadCandidateSet &CandidateSet) { 7947 QualType ParamTypes[2]; 7948 7949 // T& operator=(T&, T) 7950 ParamTypes[0] = S.Context.getLValueReferenceType( 7951 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7952 ParamTypes[1] = T; 7953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7954 /*IsAssignmentOperator=*/true); 7955 7956 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7957 // volatile T& operator=(volatile T&, T) 7958 ParamTypes[0] = S.Context.getLValueReferenceType( 7959 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7960 Args[0])); 7961 ParamTypes[1] = T; 7962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7963 /*IsAssignmentOperator=*/true); 7964 } 7965} 7966 7967/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7968/// if any, found in visible type conversion functions found in ArgExpr's type. 7969static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7970 Qualifiers VRQuals; 7971 const RecordType *TyRec; 7972 if (const MemberPointerType *RHSMPType = 7973 ArgExpr->getType()->getAs<MemberPointerType>()) 7974 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7975 else 7976 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7977 if (!TyRec) { 7978 // Just to be safe, assume the worst case. 7979 VRQuals.addVolatile(); 7980 VRQuals.addRestrict(); 7981 return VRQuals; 7982 } 7983 7984 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7985 if (!ClassDecl->hasDefinition()) 7986 return VRQuals; 7987 7988 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7989 if (isa<UsingShadowDecl>(D)) 7990 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7991 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7992 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7993 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7994 CanTy = ResTypeRef->getPointeeType(); 7995 // Need to go down the pointer/mempointer chain and add qualifiers 7996 // as see them. 7997 bool done = false; 7998 while (!done) { 7999 if (CanTy.isRestrictQualified()) 8000 VRQuals.addRestrict(); 8001 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8002 CanTy = ResTypePtr->getPointeeType(); 8003 else if (const MemberPointerType *ResTypeMPtr = 8004 CanTy->getAs<MemberPointerType>()) 8005 CanTy = ResTypeMPtr->getPointeeType(); 8006 else 8007 done = true; 8008 if (CanTy.isVolatileQualified()) 8009 VRQuals.addVolatile(); 8010 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8011 return VRQuals; 8012 } 8013 } 8014 } 8015 return VRQuals; 8016} 8017 8018namespace { 8019 8020/// Helper class to manage the addition of builtin operator overload 8021/// candidates. It provides shared state and utility methods used throughout 8022/// the process, as well as a helper method to add each group of builtin 8023/// operator overloads from the standard to a candidate set. 8024class BuiltinOperatorOverloadBuilder { 8025 // Common instance state available to all overload candidate addition methods. 8026 Sema &S; 8027 ArrayRef<Expr *> Args; 8028 Qualifiers VisibleTypeConversionsQuals; 8029 bool HasArithmeticOrEnumeralCandidateType; 8030 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8031 OverloadCandidateSet &CandidateSet; 8032 8033 static constexpr int ArithmeticTypesCap = 24; 8034 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8035 8036 // Define some indices used to iterate over the arithmetic types in 8037 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8038 // types are that preserved by promotion (C++ [over.built]p2). 8039 unsigned FirstIntegralType, 8040 LastIntegralType; 8041 unsigned FirstPromotedIntegralType, 8042 LastPromotedIntegralType; 8043 unsigned FirstPromotedArithmeticType, 8044 LastPromotedArithmeticType; 8045 unsigned NumArithmeticTypes; 8046 8047 void InitArithmeticTypes() { 8048 // Start of promoted types. 8049 FirstPromotedArithmeticType = 0; 8050 ArithmeticTypes.push_back(S.Context.FloatTy); 8051 ArithmeticTypes.push_back(S.Context.DoubleTy); 8052 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8053 if (S.Context.getTargetInfo().hasFloat128Type()) 8054 ArithmeticTypes.push_back(S.Context.Float128Ty); 8055 8056 // Start of integral types. 8057 FirstIntegralType = ArithmeticTypes.size(); 8058 FirstPromotedIntegralType = ArithmeticTypes.size(); 8059 ArithmeticTypes.push_back(S.Context.IntTy); 8060 ArithmeticTypes.push_back(S.Context.LongTy); 8061 ArithmeticTypes.push_back(S.Context.LongLongTy); 8062 if (S.Context.getTargetInfo().hasInt128Type()) 8063 ArithmeticTypes.push_back(S.Context.Int128Ty); 8064 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8065 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8066 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8067 if (S.Context.getTargetInfo().hasInt128Type()) 8068 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8069 LastPromotedIntegralType = ArithmeticTypes.size(); 8070 LastPromotedArithmeticType = ArithmeticTypes.size(); 8071 // End of promoted types. 8072 8073 ArithmeticTypes.push_back(S.Context.BoolTy); 8074 ArithmeticTypes.push_back(S.Context.CharTy); 8075 ArithmeticTypes.push_back(S.Context.WCharTy); 8076 if (S.Context.getLangOpts().Char8) 8077 ArithmeticTypes.push_back(S.Context.Char8Ty); 8078 ArithmeticTypes.push_back(S.Context.Char16Ty); 8079 ArithmeticTypes.push_back(S.Context.Char32Ty); 8080 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8081 ArithmeticTypes.push_back(S.Context.ShortTy); 8082 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8083 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8084 LastIntegralType = ArithmeticTypes.size(); 8085 NumArithmeticTypes = ArithmeticTypes.size(); 8086 // End of integral types. 8087 // FIXME: What about complex? What about half? 8088 8089 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
8090 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
; 8091 } 8092 8093 /// Helper method to factor out the common pattern of adding overloads 8094 /// for '++' and '--' builtin operators. 8095 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8096 bool HasVolatile, 8097 bool HasRestrict) { 8098 QualType ParamTypes[2] = { 8099 S.Context.getLValueReferenceType(CandidateTy), 8100 S.Context.IntTy 8101 }; 8102 8103 // Non-volatile version. 8104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8105 8106 // Use a heuristic to reduce number of builtin candidates in the set: 8107 // add volatile version only if there are conversions to a volatile type. 8108 if (HasVolatile) { 8109 ParamTypes[0] = 8110 S.Context.getLValueReferenceType( 8111 S.Context.getVolatileType(CandidateTy)); 8112 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8113 } 8114 8115 // Add restrict version only if there are conversions to a restrict type 8116 // and our candidate type is a non-restrict-qualified pointer. 8117 if (HasRestrict && CandidateTy->isAnyPointerType() && 8118 !CandidateTy.isRestrictQualified()) { 8119 ParamTypes[0] 8120 = S.Context.getLValueReferenceType( 8121 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8123 8124 if (HasVolatile) { 8125 ParamTypes[0] 8126 = S.Context.getLValueReferenceType( 8127 S.Context.getCVRQualifiedType(CandidateTy, 8128 (Qualifiers::Volatile | 8129 Qualifiers::Restrict))); 8130 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8131 } 8132 } 8133 8134 } 8135 8136public: 8137 BuiltinOperatorOverloadBuilder( 8138 Sema &S, ArrayRef<Expr *> Args, 8139 Qualifiers VisibleTypeConversionsQuals, 8140 bool HasArithmeticOrEnumeralCandidateType, 8141 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8142 OverloadCandidateSet &CandidateSet) 8143 : S(S), Args(Args), 8144 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8145 HasArithmeticOrEnumeralCandidateType( 8146 HasArithmeticOrEnumeralCandidateType), 8147 CandidateTypes(CandidateTypes), 8148 CandidateSet(CandidateSet) { 8149 8150 InitArithmeticTypes(); 8151 } 8152 8153 // Increment is deprecated for bool since C++17. 8154 // 8155 // C++ [over.built]p3: 8156 // 8157 // For every pair (T, VQ), where T is an arithmetic type other 8158 // than bool, and VQ is either volatile or empty, there exist 8159 // candidate operator functions of the form 8160 // 8161 // VQ T& operator++(VQ T&); 8162 // T operator++(VQ T&, int); 8163 // 8164 // C++ [over.built]p4: 8165 // 8166 // For every pair (T, VQ), where T is an arithmetic type other 8167 // than bool, and VQ is either volatile or empty, there exist 8168 // candidate operator functions of the form 8169 // 8170 // VQ T& operator--(VQ T&); 8171 // T operator--(VQ T&, int); 8172 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8173 if (!HasArithmeticOrEnumeralCandidateType) 8174 return; 8175 8176 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8177 const auto TypeOfT = ArithmeticTypes[Arith]; 8178 if (TypeOfT == S.Context.BoolTy) { 8179 if (Op == OO_MinusMinus) 8180 continue; 8181 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8182 continue; 8183 } 8184 addPlusPlusMinusMinusStyleOverloads( 8185 TypeOfT, 8186 VisibleTypeConversionsQuals.hasVolatile(), 8187 VisibleTypeConversionsQuals.hasRestrict()); 8188 } 8189 } 8190 8191 // C++ [over.built]p5: 8192 // 8193 // For every pair (T, VQ), where T is a cv-qualified or 8194 // cv-unqualified object type, and VQ is either volatile or 8195 // empty, there exist candidate operator functions of the form 8196 // 8197 // T*VQ& operator++(T*VQ&); 8198 // T*VQ& operator--(T*VQ&); 8199 // T* operator++(T*VQ&, int); 8200 // T* operator--(T*VQ&, int); 8201 void addPlusPlusMinusMinusPointerOverloads() { 8202 for (BuiltinCandidateTypeSet::iterator 8203 Ptr = CandidateTypes[0].pointer_begin(), 8204 PtrEnd = CandidateTypes[0].pointer_end(); 8205 Ptr != PtrEnd; ++Ptr) { 8206 // Skip pointer types that aren't pointers to object types. 8207 if (!(*Ptr)->getPointeeType()->isObjectType()) 8208 continue; 8209 8210 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8211 (!(*Ptr).isVolatileQualified() && 8212 VisibleTypeConversionsQuals.hasVolatile()), 8213 (!(*Ptr).isRestrictQualified() && 8214 VisibleTypeConversionsQuals.hasRestrict())); 8215 } 8216 } 8217 8218 // C++ [over.built]p6: 8219 // For every cv-qualified or cv-unqualified object type T, there 8220 // exist candidate operator functions of the form 8221 // 8222 // T& operator*(T*); 8223 // 8224 // C++ [over.built]p7: 8225 // For every function type T that does not have cv-qualifiers or a 8226 // ref-qualifier, there exist candidate operator functions of the form 8227 // T& operator*(T*); 8228 void addUnaryStarPointerOverloads() { 8229 for (BuiltinCandidateTypeSet::iterator 8230 Ptr = CandidateTypes[0].pointer_begin(), 8231 PtrEnd = CandidateTypes[0].pointer_end(); 8232 Ptr != PtrEnd; ++Ptr) { 8233 QualType ParamTy = *Ptr; 8234 QualType PointeeTy = ParamTy->getPointeeType(); 8235 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8236 continue; 8237 8238 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8239 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8240 continue; 8241 8242 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8243 } 8244 } 8245 8246 // C++ [over.built]p9: 8247 // For every promoted arithmetic type T, there exist candidate 8248 // operator functions of the form 8249 // 8250 // T operator+(T); 8251 // T operator-(T); 8252 void addUnaryPlusOrMinusArithmeticOverloads() { 8253 if (!HasArithmeticOrEnumeralCandidateType) 8254 return; 8255 8256 for (unsigned Arith = FirstPromotedArithmeticType; 8257 Arith < LastPromotedArithmeticType; ++Arith) { 8258 QualType ArithTy = ArithmeticTypes[Arith]; 8259 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8260 } 8261 8262 // Extension: We also add these operators for vector types. 8263 for (BuiltinCandidateTypeSet::iterator 8264 Vec = CandidateTypes[0].vector_begin(), 8265 VecEnd = CandidateTypes[0].vector_end(); 8266 Vec != VecEnd; ++Vec) { 8267 QualType VecTy = *Vec; 8268 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8269 } 8270 } 8271 8272 // C++ [over.built]p8: 8273 // For every type T, there exist candidate operator functions of 8274 // the form 8275 // 8276 // T* operator+(T*); 8277 void addUnaryPlusPointerOverloads() { 8278 for (BuiltinCandidateTypeSet::iterator 8279 Ptr = CandidateTypes[0].pointer_begin(), 8280 PtrEnd = CandidateTypes[0].pointer_end(); 8281 Ptr != PtrEnd; ++Ptr) { 8282 QualType ParamTy = *Ptr; 8283 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8284 } 8285 } 8286 8287 // C++ [over.built]p10: 8288 // For every promoted integral type T, there exist candidate 8289 // operator functions of the form 8290 // 8291 // T operator~(T); 8292 void addUnaryTildePromotedIntegralOverloads() { 8293 if (!HasArithmeticOrEnumeralCandidateType) 8294 return; 8295 8296 for (unsigned Int = FirstPromotedIntegralType; 8297 Int < LastPromotedIntegralType; ++Int) { 8298 QualType IntTy = ArithmeticTypes[Int]; 8299 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8300 } 8301 8302 // Extension: We also add this operator for vector types. 8303 for (BuiltinCandidateTypeSet::iterator 8304 Vec = CandidateTypes[0].vector_begin(), 8305 VecEnd = CandidateTypes[0].vector_end(); 8306 Vec != VecEnd; ++Vec) { 8307 QualType VecTy = *Vec; 8308 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8309 } 8310 } 8311 8312 // C++ [over.match.oper]p16: 8313 // For every pointer to member type T or type std::nullptr_t, there 8314 // exist candidate operator functions of the form 8315 // 8316 // bool operator==(T,T); 8317 // bool operator!=(T,T); 8318 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8319 /// Set of (canonical) types that we've already handled. 8320 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8321 8322 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8323 for (BuiltinCandidateTypeSet::iterator 8324 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8325 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8326 MemPtr != MemPtrEnd; 8327 ++MemPtr) { 8328 // Don't add the same builtin candidate twice. 8329 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8330 continue; 8331 8332 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8334 } 8335 8336 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8337 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8338 if (AddedTypes.insert(NullPtrTy).second) { 8339 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8340 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8341 } 8342 } 8343 } 8344 } 8345 8346 // C++ [over.built]p15: 8347 // 8348 // For every T, where T is an enumeration type or a pointer type, 8349 // there exist candidate operator functions of the form 8350 // 8351 // bool operator<(T, T); 8352 // bool operator>(T, T); 8353 // bool operator<=(T, T); 8354 // bool operator>=(T, T); 8355 // bool operator==(T, T); 8356 // bool operator!=(T, T); 8357 // R operator<=>(T, T) 8358 void addGenericBinaryPointerOrEnumeralOverloads() { 8359 // C++ [over.match.oper]p3: 8360 // [...]the built-in candidates include all of the candidate operator 8361 // functions defined in 13.6 that, compared to the given operator, [...] 8362 // do not have the same parameter-type-list as any non-template non-member 8363 // candidate. 8364 // 8365 // Note that in practice, this only affects enumeration types because there 8366 // aren't any built-in candidates of record type, and a user-defined operator 8367 // must have an operand of record or enumeration type. Also, the only other 8368 // overloaded operator with enumeration arguments, operator=, 8369 // cannot be overloaded for enumeration types, so this is the only place 8370 // where we must suppress candidates like this. 8371 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8372 UserDefinedBinaryOperators; 8373 8374 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8375 if (CandidateTypes[ArgIdx].enumeration_begin() != 8376 CandidateTypes[ArgIdx].enumeration_end()) { 8377 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8378 CEnd = CandidateSet.end(); 8379 C != CEnd; ++C) { 8380 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8381 continue; 8382 8383 if (C->Function->isFunctionTemplateSpecialization()) 8384 continue; 8385 8386 // We interpret "same parameter-type-list" as applying to the 8387 // "synthesized candidate, with the order of the two parameters 8388 // reversed", not to the original function. 8389 bool Reversed = C->RewriteKind & CRK_Reversed; 8390 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8391 ->getType() 8392 .getUnqualifiedType(); 8393 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8394 ->getType() 8395 .getUnqualifiedType(); 8396 8397 // Skip if either parameter isn't of enumeral type. 8398 if (!FirstParamType->isEnumeralType() || 8399 !SecondParamType->isEnumeralType()) 8400 continue; 8401 8402 // Add this operator to the set of known user-defined operators. 8403 UserDefinedBinaryOperators.insert( 8404 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8405 S.Context.getCanonicalType(SecondParamType))); 8406 } 8407 } 8408 } 8409 8410 /// Set of (canonical) types that we've already handled. 8411 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8412 8413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8414 for (BuiltinCandidateTypeSet::iterator 8415 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8416 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8417 Ptr != PtrEnd; ++Ptr) { 8418 // Don't add the same builtin candidate twice. 8419 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8420 continue; 8421 8422 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8424 } 8425 for (BuiltinCandidateTypeSet::iterator 8426 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8427 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8428 Enum != EnumEnd; ++Enum) { 8429 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8430 8431 // Don't add the same builtin candidate twice, or if a user defined 8432 // candidate exists. 8433 if (!AddedTypes.insert(CanonType).second || 8434 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8435 CanonType))) 8436 continue; 8437 QualType ParamTypes[2] = { *Enum, *Enum }; 8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8439 } 8440 } 8441 } 8442 8443 // C++ [over.built]p13: 8444 // 8445 // For every cv-qualified or cv-unqualified object type T 8446 // there exist candidate operator functions of the form 8447 // 8448 // T* operator+(T*, ptrdiff_t); 8449 // T& operator[](T*, ptrdiff_t); [BELOW] 8450 // T* operator-(T*, ptrdiff_t); 8451 // T* operator+(ptrdiff_t, T*); 8452 // T& operator[](ptrdiff_t, T*); [BELOW] 8453 // 8454 // C++ [over.built]p14: 8455 // 8456 // For every T, where T is a pointer to object type, there 8457 // exist candidate operator functions of the form 8458 // 8459 // ptrdiff_t operator-(T, T); 8460 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8461 /// Set of (canonical) types that we've already handled. 8462 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8463 8464 for (int Arg = 0; Arg < 2; ++Arg) { 8465 QualType AsymmetricParamTypes[2] = { 8466 S.Context.getPointerDiffType(), 8467 S.Context.getPointerDiffType(), 8468 }; 8469 for (BuiltinCandidateTypeSet::iterator 8470 Ptr = CandidateTypes[Arg].pointer_begin(), 8471 PtrEnd = CandidateTypes[Arg].pointer_end(); 8472 Ptr != PtrEnd; ++Ptr) { 8473 QualType PointeeTy = (*Ptr)->getPointeeType(); 8474 if (!PointeeTy->isObjectType()) 8475 continue; 8476 8477 AsymmetricParamTypes[Arg] = *Ptr; 8478 if (Arg == 0 || Op == OO_Plus) { 8479 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8480 // T* operator+(ptrdiff_t, T*); 8481 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8482 } 8483 if (Op == OO_Minus) { 8484 // ptrdiff_t operator-(T, T); 8485 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8486 continue; 8487 8488 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8490 } 8491 } 8492 } 8493 } 8494 8495 // C++ [over.built]p12: 8496 // 8497 // For every pair of promoted arithmetic types L and R, there 8498 // exist candidate operator functions of the form 8499 // 8500 // LR operator*(L, R); 8501 // LR operator/(L, R); 8502 // LR operator+(L, R); 8503 // LR operator-(L, R); 8504 // bool operator<(L, R); 8505 // bool operator>(L, R); 8506 // bool operator<=(L, R); 8507 // bool operator>=(L, R); 8508 // bool operator==(L, R); 8509 // bool operator!=(L, R); 8510 // 8511 // where LR is the result of the usual arithmetic conversions 8512 // between types L and R. 8513 // 8514 // C++ [over.built]p24: 8515 // 8516 // For every pair of promoted arithmetic types L and R, there exist 8517 // candidate operator functions of the form 8518 // 8519 // LR operator?(bool, L, R); 8520 // 8521 // where LR is the result of the usual arithmetic conversions 8522 // between types L and R. 8523 // Our candidates ignore the first parameter. 8524 void addGenericBinaryArithmeticOverloads() { 8525 if (!HasArithmeticOrEnumeralCandidateType) 8526 return; 8527 8528 for (unsigned Left = FirstPromotedArithmeticType; 8529 Left < LastPromotedArithmeticType; ++Left) { 8530 for (unsigned Right = FirstPromotedArithmeticType; 8531 Right < LastPromotedArithmeticType; ++Right) { 8532 QualType LandR[2] = { ArithmeticTypes[Left], 8533 ArithmeticTypes[Right] }; 8534 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8535 } 8536 } 8537 8538 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8539 // conditional operator for vector types. 8540 for (BuiltinCandidateTypeSet::iterator 8541 Vec1 = CandidateTypes[0].vector_begin(), 8542 Vec1End = CandidateTypes[0].vector_end(); 8543 Vec1 != Vec1End; ++Vec1) { 8544 for (BuiltinCandidateTypeSet::iterator 8545 Vec2 = CandidateTypes[1].vector_begin(), 8546 Vec2End = CandidateTypes[1].vector_end(); 8547 Vec2 != Vec2End; ++Vec2) { 8548 QualType LandR[2] = { *Vec1, *Vec2 }; 8549 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8550 } 8551 } 8552 } 8553 8554 // C++2a [over.built]p14: 8555 // 8556 // For every integral type T there exists a candidate operator function 8557 // of the form 8558 // 8559 // std::strong_ordering operator<=>(T, T) 8560 // 8561 // C++2a [over.built]p15: 8562 // 8563 // For every pair of floating-point types L and R, there exists a candidate 8564 // operator function of the form 8565 // 8566 // std::partial_ordering operator<=>(L, R); 8567 // 8568 // FIXME: The current specification for integral types doesn't play nice with 8569 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8570 // comparisons. Under the current spec this can lead to ambiguity during 8571 // overload resolution. For example: 8572 // 8573 // enum A : int {a}; 8574 // auto x = (a <=> (long)42); 8575 // 8576 // error: call is ambiguous for arguments 'A' and 'long'. 8577 // note: candidate operator<=>(int, int) 8578 // note: candidate operator<=>(long, long) 8579 // 8580 // To avoid this error, this function deviates from the specification and adds 8581 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8582 // arithmetic types (the same as the generic relational overloads). 8583 // 8584 // For now this function acts as a placeholder. 8585 void addThreeWayArithmeticOverloads() { 8586 addGenericBinaryArithmeticOverloads(); 8587 } 8588 8589 // C++ [over.built]p17: 8590 // 8591 // For every pair of promoted integral types L and R, there 8592 // exist candidate operator functions of the form 8593 // 8594 // LR operator%(L, R); 8595 // LR operator&(L, R); 8596 // LR operator^(L, R); 8597 // LR operator|(L, R); 8598 // L operator<<(L, R); 8599 // L operator>>(L, R); 8600 // 8601 // where LR is the result of the usual arithmetic conversions 8602 // between types L and R. 8603 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8604 if (!HasArithmeticOrEnumeralCandidateType) 8605 return; 8606 8607 for (unsigned Left = FirstPromotedIntegralType; 8608 Left < LastPromotedIntegralType; ++Left) { 8609 for (unsigned Right = FirstPromotedIntegralType; 8610 Right < LastPromotedIntegralType; ++Right) { 8611 QualType LandR[2] = { ArithmeticTypes[Left], 8612 ArithmeticTypes[Right] }; 8613 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8614 } 8615 } 8616 } 8617 8618 // C++ [over.built]p20: 8619 // 8620 // For every pair (T, VQ), where T is an enumeration or 8621 // pointer to member type and VQ is either volatile or 8622 // empty, there exist candidate operator functions of the form 8623 // 8624 // VQ T& operator=(VQ T&, T); 8625 void addAssignmentMemberPointerOrEnumeralOverloads() { 8626 /// Set of (canonical) types that we've already handled. 8627 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8628 8629 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8630 for (BuiltinCandidateTypeSet::iterator 8631 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8632 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8633 Enum != EnumEnd; ++Enum) { 8634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8635 continue; 8636 8637 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8638 } 8639 8640 for (BuiltinCandidateTypeSet::iterator 8641 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8642 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8643 MemPtr != MemPtrEnd; ++MemPtr) { 8644 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8645 continue; 8646 8647 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8648 } 8649 } 8650 } 8651 8652 // C++ [over.built]p19: 8653 // 8654 // For every pair (T, VQ), where T is any type and VQ is either 8655 // volatile or empty, there exist candidate operator functions 8656 // of the form 8657 // 8658 // T*VQ& operator=(T*VQ&, T*); 8659 // 8660 // C++ [over.built]p21: 8661 // 8662 // For every pair (T, VQ), where T is a cv-qualified or 8663 // cv-unqualified object type and VQ is either volatile or 8664 // empty, there exist candidate operator functions of the form 8665 // 8666 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8667 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8668 void addAssignmentPointerOverloads(bool isEqualOp) { 8669 /// Set of (canonical) types that we've already handled. 8670 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8671 8672 for (BuiltinCandidateTypeSet::iterator 8673 Ptr = CandidateTypes[0].pointer_begin(), 8674 PtrEnd = CandidateTypes[0].pointer_end(); 8675 Ptr != PtrEnd; ++Ptr) { 8676 // If this is operator=, keep track of the builtin candidates we added. 8677 if (isEqualOp) 8678 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8679 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8680 continue; 8681 8682 // non-volatile version 8683 QualType ParamTypes[2] = { 8684 S.Context.getLValueReferenceType(*Ptr), 8685 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8686 }; 8687 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8688 /*IsAssignmentOperator=*/ isEqualOp); 8689 8690 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8691 VisibleTypeConversionsQuals.hasVolatile(); 8692 if (NeedVolatile) { 8693 // volatile version 8694 ParamTypes[0] = 8695 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8696 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8697 /*IsAssignmentOperator=*/isEqualOp); 8698 } 8699 8700 if (!(*Ptr).isRestrictQualified() && 8701 VisibleTypeConversionsQuals.hasRestrict()) { 8702 // restrict version 8703 ParamTypes[0] 8704 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8705 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8706 /*IsAssignmentOperator=*/isEqualOp); 8707 8708 if (NeedVolatile) { 8709 // volatile restrict version 8710 ParamTypes[0] 8711 = S.Context.getLValueReferenceType( 8712 S.Context.getCVRQualifiedType(*Ptr, 8713 (Qualifiers::Volatile | 8714 Qualifiers::Restrict))); 8715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8716 /*IsAssignmentOperator=*/isEqualOp); 8717 } 8718 } 8719 } 8720 8721 if (isEqualOp) { 8722 for (BuiltinCandidateTypeSet::iterator 8723 Ptr = CandidateTypes[1].pointer_begin(), 8724 PtrEnd = CandidateTypes[1].pointer_end(); 8725 Ptr != PtrEnd; ++Ptr) { 8726 // Make sure we don't add the same candidate twice. 8727 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8728 continue; 8729 8730 QualType ParamTypes[2] = { 8731 S.Context.getLValueReferenceType(*Ptr), 8732 *Ptr, 8733 }; 8734 8735 // non-volatile version 8736 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8737 /*IsAssignmentOperator=*/true); 8738 8739 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8740 VisibleTypeConversionsQuals.hasVolatile(); 8741 if (NeedVolatile) { 8742 // volatile version 8743 ParamTypes[0] = 8744 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8745 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8746 /*IsAssignmentOperator=*/true); 8747 } 8748 8749 if (!(*Ptr).isRestrictQualified() && 8750 VisibleTypeConversionsQuals.hasRestrict()) { 8751 // restrict version 8752 ParamTypes[0] 8753 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8755 /*IsAssignmentOperator=*/true); 8756 8757 if (NeedVolatile) { 8758 // volatile restrict version 8759 ParamTypes[0] 8760 = S.Context.getLValueReferenceType( 8761 S.Context.getCVRQualifiedType(*Ptr, 8762 (Qualifiers::Volatile | 8763 Qualifiers::Restrict))); 8764 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8765 /*IsAssignmentOperator=*/true); 8766 } 8767 } 8768 } 8769 } 8770 } 8771 8772 // C++ [over.built]p18: 8773 // 8774 // For every triple (L, VQ, R), where L is an arithmetic type, 8775 // VQ is either volatile or empty, and R is a promoted 8776 // arithmetic type, there exist candidate operator functions of 8777 // the form 8778 // 8779 // VQ L& operator=(VQ L&, R); 8780 // VQ L& operator*=(VQ L&, R); 8781 // VQ L& operator/=(VQ L&, R); 8782 // VQ L& operator+=(VQ L&, R); 8783 // VQ L& operator-=(VQ L&, R); 8784 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8785 if (!HasArithmeticOrEnumeralCandidateType) 8786 return; 8787 8788 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8789 for (unsigned Right = FirstPromotedArithmeticType; 8790 Right < LastPromotedArithmeticType; ++Right) { 8791 QualType ParamTypes[2]; 8792 ParamTypes[1] = ArithmeticTypes[Right]; 8793 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8794 S, ArithmeticTypes[Left], Args[0]); 8795 // Add this built-in operator as a candidate (VQ is empty). 8796 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8798 /*IsAssignmentOperator=*/isEqualOp); 8799 8800 // Add this built-in operator as a candidate (VQ is 'volatile'). 8801 if (VisibleTypeConversionsQuals.hasVolatile()) { 8802 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8803 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8804 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8805 /*IsAssignmentOperator=*/isEqualOp); 8806 } 8807 } 8808 } 8809 8810 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8811 for (BuiltinCandidateTypeSet::iterator 8812 Vec1 = CandidateTypes[0].vector_begin(), 8813 Vec1End = CandidateTypes[0].vector_end(); 8814 Vec1 != Vec1End; ++Vec1) { 8815 for (BuiltinCandidateTypeSet::iterator 8816 Vec2 = CandidateTypes[1].vector_begin(), 8817 Vec2End = CandidateTypes[1].vector_end(); 8818 Vec2 != Vec2End; ++Vec2) { 8819 QualType ParamTypes[2]; 8820 ParamTypes[1] = *Vec2; 8821 // Add this built-in operator as a candidate (VQ is empty). 8822 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8823 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8824 /*IsAssignmentOperator=*/isEqualOp); 8825 8826 // Add this built-in operator as a candidate (VQ is 'volatile'). 8827 if (VisibleTypeConversionsQuals.hasVolatile()) { 8828 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8829 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8830 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8831 /*IsAssignmentOperator=*/isEqualOp); 8832 } 8833 } 8834 } 8835 } 8836 8837 // C++ [over.built]p22: 8838 // 8839 // For every triple (L, VQ, R), where L is an integral type, VQ 8840 // is either volatile or empty, and R is a promoted integral 8841 // type, there exist candidate operator functions of the form 8842 // 8843 // VQ L& operator%=(VQ L&, R); 8844 // VQ L& operator<<=(VQ L&, R); 8845 // VQ L& operator>>=(VQ L&, R); 8846 // VQ L& operator&=(VQ L&, R); 8847 // VQ L& operator^=(VQ L&, R); 8848 // VQ L& operator|=(VQ L&, R); 8849 void addAssignmentIntegralOverloads() { 8850 if (!HasArithmeticOrEnumeralCandidateType) 8851 return; 8852 8853 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8854 for (unsigned Right = FirstPromotedIntegralType; 8855 Right < LastPromotedIntegralType; ++Right) { 8856 QualType ParamTypes[2]; 8857 ParamTypes[1] = ArithmeticTypes[Right]; 8858 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8859 S, ArithmeticTypes[Left], Args[0]); 8860 // Add this built-in operator as a candidate (VQ is empty). 8861 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8863 if (VisibleTypeConversionsQuals.hasVolatile()) { 8864 // Add this built-in operator as a candidate (VQ is 'volatile'). 8865 ParamTypes[0] = LeftBaseTy; 8866 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8867 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8868 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8869 } 8870 } 8871 } 8872 } 8873 8874 // C++ [over.operator]p23: 8875 // 8876 // There also exist candidate operator functions of the form 8877 // 8878 // bool operator!(bool); 8879 // bool operator&&(bool, bool); 8880 // bool operator||(bool, bool); 8881 void addExclaimOverload() { 8882 QualType ParamTy = S.Context.BoolTy; 8883 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8884 /*IsAssignmentOperator=*/false, 8885 /*NumContextualBoolArguments=*/1); 8886 } 8887 void addAmpAmpOrPipePipeOverload() { 8888 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8890 /*IsAssignmentOperator=*/false, 8891 /*NumContextualBoolArguments=*/2); 8892 } 8893 8894 // C++ [over.built]p13: 8895 // 8896 // For every cv-qualified or cv-unqualified object type T there 8897 // exist candidate operator functions of the form 8898 // 8899 // T* operator+(T*, ptrdiff_t); [ABOVE] 8900 // T& operator[](T*, ptrdiff_t); 8901 // T* operator-(T*, ptrdiff_t); [ABOVE] 8902 // T* operator+(ptrdiff_t, T*); [ABOVE] 8903 // T& operator[](ptrdiff_t, T*); 8904 void addSubscriptOverloads() { 8905 for (BuiltinCandidateTypeSet::iterator 8906 Ptr = CandidateTypes[0].pointer_begin(), 8907 PtrEnd = CandidateTypes[0].pointer_end(); 8908 Ptr != PtrEnd; ++Ptr) { 8909 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8910 QualType PointeeType = (*Ptr)->getPointeeType(); 8911 if (!PointeeType->isObjectType()) 8912 continue; 8913 8914 // T& operator[](T*, ptrdiff_t) 8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8916 } 8917 8918 for (BuiltinCandidateTypeSet::iterator 8919 Ptr = CandidateTypes[1].pointer_begin(), 8920 PtrEnd = CandidateTypes[1].pointer_end(); 8921 Ptr != PtrEnd; ++Ptr) { 8922 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8923 QualType PointeeType = (*Ptr)->getPointeeType(); 8924 if (!PointeeType->isObjectType()) 8925 continue; 8926 8927 // T& operator[](ptrdiff_t, T*) 8928 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8929 } 8930 } 8931 8932 // C++ [over.built]p11: 8933 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8934 // C1 is the same type as C2 or is a derived class of C2, T is an object 8935 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8936 // there exist candidate operator functions of the form 8937 // 8938 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8939 // 8940 // where CV12 is the union of CV1 and CV2. 8941 void addArrowStarOverloads() { 8942 for (BuiltinCandidateTypeSet::iterator 8943 Ptr = CandidateTypes[0].pointer_begin(), 8944 PtrEnd = CandidateTypes[0].pointer_end(); 8945 Ptr != PtrEnd; ++Ptr) { 8946 QualType C1Ty = (*Ptr); 8947 QualType C1; 8948 QualifierCollector Q1; 8949 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8950 if (!isa<RecordType>(C1)) 8951 continue; 8952 // heuristic to reduce number of builtin candidates in the set. 8953 // Add volatile/restrict version only if there are conversions to a 8954 // volatile/restrict type. 8955 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8956 continue; 8957 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8958 continue; 8959 for (BuiltinCandidateTypeSet::iterator 8960 MemPtr = CandidateTypes[1].member_pointer_begin(), 8961 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8962 MemPtr != MemPtrEnd; ++MemPtr) { 8963 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8964 QualType C2 = QualType(mptr->getClass(), 0); 8965 C2 = C2.getUnqualifiedType(); 8966 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8967 break; 8968 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8969 // build CV12 T& 8970 QualType T = mptr->getPointeeType(); 8971 if (!VisibleTypeConversionsQuals.hasVolatile() && 8972 T.isVolatileQualified()) 8973 continue; 8974 if (!VisibleTypeConversionsQuals.hasRestrict() && 8975 T.isRestrictQualified()) 8976 continue; 8977 T = Q1.apply(S.Context, T); 8978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8979 } 8980 } 8981 } 8982 8983 // Note that we don't consider the first argument, since it has been 8984 // contextually converted to bool long ago. The candidates below are 8985 // therefore added as binary. 8986 // 8987 // C++ [over.built]p25: 8988 // For every type T, where T is a pointer, pointer-to-member, or scoped 8989 // enumeration type, there exist candidate operator functions of the form 8990 // 8991 // T operator?(bool, T, T); 8992 // 8993 void addConditionalOperatorOverloads() { 8994 /// Set of (canonical) types that we've already handled. 8995 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8996 8997 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8998 for (BuiltinCandidateTypeSet::iterator 8999 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9000 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9001 Ptr != PtrEnd; ++Ptr) { 9002 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9003 continue; 9004 9005 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9007 } 9008 9009 for (BuiltinCandidateTypeSet::iterator 9010 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9011 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9012 MemPtr != MemPtrEnd; ++MemPtr) { 9013 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9014 continue; 9015 9016 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9018 } 9019 9020 if (S.getLangOpts().CPlusPlus11) { 9021 for (BuiltinCandidateTypeSet::iterator 9022 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9023 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9024 Enum != EnumEnd; ++Enum) { 9025 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9026 continue; 9027 9028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9029 continue; 9030 9031 QualType ParamTypes[2] = { *Enum, *Enum }; 9032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9033 } 9034 } 9035 } 9036 } 9037}; 9038 9039} // end anonymous namespace 9040 9041/// AddBuiltinOperatorCandidates - Add the appropriate built-in 9042/// operator overloads to the candidate set (C++ [over.built]), based 9043/// on the operator @p Op and the arguments given. For example, if the 9044/// operator is a binary '+', this routine might add "int 9045/// operator+(int, int)" to cover integer addition. 9046void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9047 SourceLocation OpLoc, 9048 ArrayRef<Expr *> Args, 9049 OverloadCandidateSet &CandidateSet) { 9050 // Find all of the types that the arguments can convert to, but only 9051 // if the operator we're looking at has built-in operator candidates 9052 // that make use of these types. Also record whether we encounter non-record 9053 // candidate types or either arithmetic or enumeral candidate types. 9054 Qualifiers VisibleTypeConversionsQuals; 9055 VisibleTypeConversionsQuals.addConst(); 9056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9057 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9058 9059 bool HasNonRecordCandidateType = false; 9060 bool HasArithmeticOrEnumeralCandidateType = false; 9061 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9063 CandidateTypes.emplace_back(*this); 9064 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9065 OpLoc, 9066 true, 9067 (Op == OO_Exclaim || 9068 Op == OO_AmpAmp || 9069 Op == OO_PipePipe), 9070 VisibleTypeConversionsQuals); 9071 HasNonRecordCandidateType = HasNonRecordCandidateType || 9072 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9073 HasArithmeticOrEnumeralCandidateType = 9074 HasArithmeticOrEnumeralCandidateType || 9075 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9076 } 9077 9078 // Exit early when no non-record types have been added to the candidate set 9079 // for any of the arguments to the operator. 9080 // 9081 // We can't exit early for !, ||, or &&, since there we have always have 9082 // 'bool' overloads. 9083 if (!HasNonRecordCandidateType && 9084 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9085 return; 9086 9087 // Setup an object to manage the common state for building overloads. 9088 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9089 VisibleTypeConversionsQuals, 9090 HasArithmeticOrEnumeralCandidateType, 9091 CandidateTypes, CandidateSet); 9092 9093 // Dispatch over the operation to add in only those overloads which apply. 9094 switch (Op) { 9095 case OO_None: 9096 case NUM_OVERLOADED_OPERATORS: 9097 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9097)
; 9098 9099 case OO_New: 9100 case OO_Delete: 9101 case OO_Array_New: 9102 case OO_Array_Delete: 9103 case OO_Call: 9104 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
9105 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
; 9106 9107 case OO_Comma: 9108 case OO_Arrow: 9109 case OO_Coawait: 9110 // C++ [over.match.oper]p3: 9111 // -- For the operator ',', the unary operator '&', the 9112 // operator '->', or the operator 'co_await', the 9113 // built-in candidates set is empty. 9114 break; 9115 9116 case OO_Plus: // '+' is either unary or binary 9117 if (Args.size() == 1) 9118 OpBuilder.addUnaryPlusPointerOverloads(); 9119 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9120 9121 case OO_Minus: // '-' is either unary or binary 9122 if (Args.size() == 1) { 9123 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9124 } else { 9125 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9126 OpBuilder.addGenericBinaryArithmeticOverloads(); 9127 } 9128 break; 9129 9130 case OO_Star: // '*' is either unary or binary 9131 if (Args.size() == 1) 9132 OpBuilder.addUnaryStarPointerOverloads(); 9133 else 9134 OpBuilder.addGenericBinaryArithmeticOverloads(); 9135 break; 9136 9137 case OO_Slash: 9138 OpBuilder.addGenericBinaryArithmeticOverloads(); 9139 break; 9140 9141 case OO_PlusPlus: 9142 case OO_MinusMinus: 9143 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9144 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9145 break; 9146 9147 case OO_EqualEqual: 9148 case OO_ExclaimEqual: 9149 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9150 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9151 9152 case OO_Less: 9153 case OO_Greater: 9154 case OO_LessEqual: 9155 case OO_GreaterEqual: 9156 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9157 OpBuilder.addGenericBinaryArithmeticOverloads(); 9158 break; 9159 9160 case OO_Spaceship: 9161 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9162 OpBuilder.addThreeWayArithmeticOverloads(); 9163 break; 9164 9165 case OO_Percent: 9166 case OO_Caret: 9167 case OO_Pipe: 9168 case OO_LessLess: 9169 case OO_GreaterGreater: 9170 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9171 break; 9172 9173 case OO_Amp: // '&' is either unary or binary 9174 if (Args.size() == 1) 9175 // C++ [over.match.oper]p3: 9176 // -- For the operator ',', the unary operator '&', or the 9177 // operator '->', the built-in candidates set is empty. 9178 break; 9179 9180 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9181 break; 9182 9183 case OO_Tilde: 9184 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9185 break; 9186 9187 case OO_Equal: 9188 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9189 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9190 9191 case OO_PlusEqual: 9192 case OO_MinusEqual: 9193 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9194 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9195 9196 case OO_StarEqual: 9197 case OO_SlashEqual: 9198 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9199 break; 9200 9201 case OO_PercentEqual: 9202 case OO_LessLessEqual: 9203 case OO_GreaterGreaterEqual: 9204 case OO_AmpEqual: 9205 case OO_CaretEqual: 9206 case OO_PipeEqual: 9207 OpBuilder.addAssignmentIntegralOverloads(); 9208 break; 9209 9210 case OO_Exclaim: 9211 OpBuilder.addExclaimOverload(); 9212 break; 9213 9214 case OO_AmpAmp: 9215 case OO_PipePipe: 9216 OpBuilder.addAmpAmpOrPipePipeOverload(); 9217 break; 9218 9219 case OO_Subscript: 9220 OpBuilder.addSubscriptOverloads(); 9221 break; 9222 9223 case OO_ArrowStar: 9224 OpBuilder.addArrowStarOverloads(); 9225 break; 9226 9227 case OO_Conditional: 9228 OpBuilder.addConditionalOperatorOverloads(); 9229 OpBuilder.addGenericBinaryArithmeticOverloads(); 9230 break; 9231 } 9232} 9233 9234/// Add function candidates found via argument-dependent lookup 9235/// to the set of overloading candidates. 9236/// 9237/// This routine performs argument-dependent name lookup based on the 9238/// given function name (which may also be an operator name) and adds 9239/// all of the overload candidates found by ADL to the overload 9240/// candidate set (C++ [basic.lookup.argdep]). 9241void 9242Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9243 SourceLocation Loc, 9244 ArrayRef<Expr *> Args, 9245 TemplateArgumentListInfo *ExplicitTemplateArgs, 9246 OverloadCandidateSet& CandidateSet, 9247 bool PartialOverloading) { 9248 ADLResult Fns; 9249 9250 // FIXME: This approach for uniquing ADL results (and removing 9251 // redundant candidates from the set) relies on pointer-equality, 9252 // which means we need to key off the canonical decl. However, 9253 // always going back to the canonical decl might not get us the 9254 // right set of default arguments. What default arguments are 9255 // we supposed to consider on ADL candidates, anyway? 9256 9257 // FIXME: Pass in the explicit template arguments? 9258 ArgumentDependentLookup(Name, Loc, Args, Fns); 9259 9260 // Erase all of the candidates we already knew about. 9261 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9262 CandEnd = CandidateSet.end(); 9263 Cand != CandEnd; ++Cand) 9264 if (Cand->Function) { 9265 Fns.erase(Cand->Function); 9266 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9267 Fns.erase(FunTmpl); 9268 } 9269 9270 // For each of the ADL candidates we found, add it to the overload 9271 // set. 9272 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9273 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9274 9275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9276 if (ExplicitTemplateArgs) 9277 continue; 9278 9279 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9280 /*SuppressUserConversions=*/false, PartialOverloading, 9281 /*AllowExplicit*/ true, 9282 /*AllowExplicitConversions*/ false, 9283 ADLCallKind::UsesADL); 9284 } else { 9285 AddTemplateOverloadCandidate( 9286 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9287 CandidateSet, 9288 /*SuppressUserConversions=*/false, PartialOverloading, 9289 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9290 } 9291 } 9292} 9293 9294namespace { 9295enum class Comparison { Equal, Better, Worse }; 9296} 9297 9298/// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9299/// overload resolution. 9300/// 9301/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9302/// Cand1's first N enable_if attributes have precisely the same conditions as 9303/// Cand2's first N enable_if attributes (where N = the number of enable_if 9304/// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9305/// 9306/// Note that you can have a pair of candidates such that Cand1's enable_if 9307/// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9308/// worse than Cand1's. 9309static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9310 const FunctionDecl *Cand2) { 9311 // Common case: One (or both) decls don't have enable_if attrs. 9312 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9313 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9314 if (!Cand1Attr || !Cand2Attr) { 9315 if (Cand1Attr == Cand2Attr) 9316 return Comparison::Equal; 9317 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9318 } 9319 9320 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9321 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9322 9323 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9324 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9325 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9326 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9327 9328 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9329 // has fewer enable_if attributes than Cand2, and vice versa. 9330 if (!Cand1A) 9331 return Comparison::Worse; 9332 if (!Cand2A) 9333 return Comparison::Better; 9334 9335 Cand1ID.clear(); 9336 Cand2ID.clear(); 9337 9338 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9339 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9340 if (Cand1ID != Cand2ID) 9341 return Comparison::Worse; 9342 } 9343 9344 return Comparison::Equal; 9345} 9346 9347static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9348 const OverloadCandidate &Cand2) { 9349 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9350 !Cand2.Function->isMultiVersion()) 9351 return false; 9352 9353 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9354 // is obviously better. 9355 if (Cand1.Function->isInvalidDecl()) return false; 9356 if (Cand2.Function->isInvalidDecl()) return true; 9357 9358 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9359 // cpu_dispatch, else arbitrarily based on the identifiers. 9360 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9361 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9362 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9363 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9364 9365 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9366 return false; 9367 9368 if (Cand1CPUDisp && !Cand2CPUDisp) 9369 return true; 9370 if (Cand2CPUDisp && !Cand1CPUDisp) 9371 return false; 9372 9373 if (Cand1CPUSpec && Cand2CPUSpec) { 9374 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9375 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9376 9377 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9378 FirstDiff = std::mismatch( 9379 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9380 Cand2CPUSpec->cpus_begin(), 9381 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9382 return LHS->getName() == RHS->getName(); 9383 }); 9384 9385 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9386 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9387 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
; 9388 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9389 } 9390 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9390)
; 9391} 9392 9393/// isBetterOverloadCandidate - Determines whether the first overload 9394/// candidate is a better candidate than the second (C++ 13.3.3p1). 9395bool clang::isBetterOverloadCandidate( 9396 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9397 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9398 // Define viable functions to be better candidates than non-viable 9399 // functions. 9400 if (!Cand2.Viable) 9401 return Cand1.Viable; 9402 else if (!Cand1.Viable) 9403 return false; 9404 9405 // C++ [over.match.best]p1: 9406 // 9407 // -- if F is a static member function, ICS1(F) is defined such 9408 // that ICS1(F) is neither better nor worse than ICS1(G) for 9409 // any function G, and, symmetrically, ICS1(G) is neither 9410 // better nor worse than ICS1(F). 9411 unsigned StartArg = 0; 9412 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9413 StartArg = 1; 9414 9415 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9416 // We don't allow incompatible pointer conversions in C++. 9417 if (!S.getLangOpts().CPlusPlus) 9418 return ICS.isStandard() && 9419 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9420 9421 // The only ill-formed conversion we allow in C++ is the string literal to 9422 // char* conversion, which is only considered ill-formed after C++11. 9423 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9424 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9425 }; 9426 9427 // Define functions that don't require ill-formed conversions for a given 9428 // argument to be better candidates than functions that do. 9429 unsigned NumArgs = Cand1.Conversions.size(); 9430 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9430, __PRETTY_FUNCTION__))
; 9431 bool HasBetterConversion = false; 9432 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9433 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9434 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9435 if (Cand1Bad != Cand2Bad) { 9436 if (Cand1Bad) 9437 return false; 9438 HasBetterConversion = true; 9439 } 9440 } 9441 9442 if (HasBetterConversion) 9443 return true; 9444 9445 // C++ [over.match.best]p1: 9446 // A viable function F1 is defined to be a better function than another 9447 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9448 // conversion sequence than ICSi(F2), and then... 9449 bool HasWorseConversion = false; 9450 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9451 switch (CompareImplicitConversionSequences(S, Loc, 9452 Cand1.Conversions[ArgIdx], 9453 Cand2.Conversions[ArgIdx])) { 9454 case ImplicitConversionSequence::Better: 9455 // Cand1 has a better conversion sequence. 9456 HasBetterConversion = true; 9457 break; 9458 9459 case ImplicitConversionSequence::Worse: 9460 if (Cand1.Function && Cand1.Function == Cand2.Function && 9461 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9462 // Work around large-scale breakage caused by considering reversed 9463 // forms of operator== in C++20: 9464 // 9465 // When comparing a function against its reversed form, if we have a 9466 // better conversion for one argument and a worse conversion for the 9467 // other, we prefer the non-reversed form. 9468 // 9469 // This prevents a conversion function from being considered ambiguous 9470 // with its own reversed form in various where it's only incidentally 9471 // heterogeneous. 9472 // 9473 // We diagnose this as an extension from CreateOverloadedBinOp. 9474 HasWorseConversion = true; 9475 break; 9476 } 9477 9478 // Cand1 can't be better than Cand2. 9479 return false; 9480 9481 case ImplicitConversionSequence::Indistinguishable: 9482 // Do nothing. 9483 break; 9484 } 9485 } 9486 9487 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9488 // ICSj(F2), or, if not that, 9489 if (HasBetterConversion) 9490 return true; 9491 if (HasWorseConversion) 9492 return false; 9493 9494 // -- the context is an initialization by user-defined conversion 9495 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9496 // from the return type of F1 to the destination type (i.e., 9497 // the type of the entity being initialized) is a better 9498 // conversion sequence than the standard conversion sequence 9499 // from the return type of F2 to the destination type. 9500 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9501 Cand1.Function && Cand2.Function && 9502 isa<CXXConversionDecl>(Cand1.Function) && 9503 isa<CXXConversionDecl>(Cand2.Function)) { 9504 // First check whether we prefer one of the conversion functions over the 9505 // other. This only distinguishes the results in non-standard, extension 9506 // cases such as the conversion from a lambda closure type to a function 9507 // pointer or block. 9508 ImplicitConversionSequence::CompareKind Result = 9509 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9510 if (Result == ImplicitConversionSequence::Indistinguishable) 9511 Result = CompareStandardConversionSequences(S, Loc, 9512 Cand1.FinalConversion, 9513 Cand2.FinalConversion); 9514 9515 if (Result != ImplicitConversionSequence::Indistinguishable) 9516 return Result == ImplicitConversionSequence::Better; 9517 9518 // FIXME: Compare kind of reference binding if conversion functions 9519 // convert to a reference type used in direct reference binding, per 9520 // C++14 [over.match.best]p1 section 2 bullet 3. 9521 } 9522 9523 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9524 // as combined with the resolution to CWG issue 243. 9525 // 9526 // When the context is initialization by constructor ([over.match.ctor] or 9527 // either phase of [over.match.list]), a constructor is preferred over 9528 // a conversion function. 9529 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9530 Cand1.Function && Cand2.Function && 9531 isa<CXXConstructorDecl>(Cand1.Function) != 9532 isa<CXXConstructorDecl>(Cand2.Function)) 9533 return isa<CXXConstructorDecl>(Cand1.Function); 9534 9535 // -- F1 is a non-template function and F2 is a function template 9536 // specialization, or, if not that, 9537 bool Cand1IsSpecialization = Cand1.Function && 9538 Cand1.Function->getPrimaryTemplate(); 9539 bool Cand2IsSpecialization = Cand2.Function && 9540 Cand2.Function->getPrimaryTemplate(); 9541 if (Cand1IsSpecialization != Cand2IsSpecialization) 9542 return Cand2IsSpecialization; 9543 9544 // -- F1 and F2 are function template specializations, and the function 9545 // template for F1 is more specialized than the template for F2 9546 // according to the partial ordering rules described in 14.5.5.2, or, 9547 // if not that, 9548 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9549 if (FunctionTemplateDecl *BetterTemplate 9550 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9551 Cand2.Function->getPrimaryTemplate(), 9552 Loc, 9553 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9554 : TPOC_Call, 9555 Cand1.ExplicitCallArguments, 9556 Cand2.ExplicitCallArguments)) 9557 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9558 } 9559 9560 // -— F1 and F2 are non-template functions with the same 9561 // parameter-type-lists, and F1 is more constrained than F2 [...], 9562 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9563 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9564 Cand2.Function->hasPrototype()) { 9565 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9566 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9567 if (PT1->getNumParams() == PT2->getNumParams() && 9568 PT1->isVariadic() == PT2->isVariadic() && 9569 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9570 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9571 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9572 if (RC1 && RC2) { 9573 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9574 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9575 {RC2}, AtLeastAsConstrained1)) 9576 return false; 9577 if (!AtLeastAsConstrained1) 9578 return false; 9579 if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9580 {RC1}, AtLeastAsConstrained2)) 9581 return false; 9582 if (!AtLeastAsConstrained2) 9583 return true; 9584 } else if (RC1 || RC2) 9585 return RC1 != nullptr; 9586 } 9587 } 9588 9589 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9590 // class B of D, and for all arguments the corresponding parameters of 9591 // F1 and F2 have the same type. 9592 // FIXME: Implement the "all parameters have the same type" check. 9593 bool Cand1IsInherited = 9594 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9595 bool Cand2IsInherited = 9596 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9597 if (Cand1IsInherited != Cand2IsInherited) 9598 return Cand2IsInherited; 9599 else if (Cand1IsInherited) { 9600 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9600, __PRETTY_FUNCTION__))
; 9601 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9602 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9603 if (Cand1Class->isDerivedFrom(Cand2Class)) 9604 return true; 9605 if (Cand2Class->isDerivedFrom(Cand1Class)) 9606 return false; 9607 // Inherited from sibling base classes: still ambiguous. 9608 } 9609 9610 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9611 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9612 // with reversed order of parameters and F1 is not 9613 // 9614 // We rank reversed + different operator as worse than just reversed, but 9615 // that comparison can never happen, because we only consider reversing for 9616 // the maximally-rewritten operator (== or <=>). 9617 if (Cand1.RewriteKind != Cand2.RewriteKind) 9618 return Cand1.RewriteKind < Cand2.RewriteKind; 9619 9620 // Check C++17 tie-breakers for deduction guides. 9621 { 9622 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9623 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9624 if (Guide1 && Guide2) { 9625 // -- F1 is generated from a deduction-guide and F2 is not 9626 if (Guide1->isImplicit() != Guide2->isImplicit()) 9627 return Guide2->isImplicit(); 9628 9629 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9630 if (Guide1->isCopyDeductionCandidate()) 9631 return true; 9632 } 9633 } 9634 9635 // Check for enable_if value-based overload resolution. 9636 if (Cand1.Function && Cand2.Function) { 9637 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9638 if (Cmp != Comparison::Equal) 9639 return Cmp == Comparison::Better; 9640 } 9641 9642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9643 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9644 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9645 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9646 } 9647 9648 bool HasPS1 = Cand1.Function != nullptr && 9649 functionHasPassObjectSizeParams(Cand1.Function); 9650 bool HasPS2 = Cand2.Function != nullptr && 9651 functionHasPassObjectSizeParams(Cand2.Function); 9652 if (HasPS1 != HasPS2 && HasPS1) 9653 return true; 9654 9655 return isBetterMultiversionCandidate(Cand1, Cand2); 9656} 9657 9658/// Determine whether two declarations are "equivalent" for the purposes of 9659/// name lookup and overload resolution. This applies when the same internal/no 9660/// linkage entity is defined by two modules (probably by textually including 9661/// the same header). In such a case, we don't consider the declarations to 9662/// declare the same entity, but we also don't want lookups with both 9663/// declarations visible to be ambiguous in some cases (this happens when using 9664/// a modularized libstdc++). 9665bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9666 const NamedDecl *B) { 9667 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9668 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9669 if (!VA || !VB) 9670 return false; 9671 9672 // The declarations must be declaring the same name as an internal linkage 9673 // entity in different modules. 9674 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9675 VB->getDeclContext()->getRedeclContext()) || 9676 getOwningModule(const_cast<ValueDecl *>(VA)) == 9677 getOwningModule(const_cast<ValueDecl *>(VB)) || 9678 VA->isExternallyVisible() || VB->isExternallyVisible()) 9679 return false; 9680 9681 // Check that the declarations appear to be equivalent. 9682 // 9683 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9684 // For constants and functions, we should check the initializer or body is 9685 // the same. For non-constant variables, we shouldn't allow it at all. 9686 if (Context.hasSameType(VA->getType(), VB->getType())) 9687 return true; 9688 9689 // Enum constants within unnamed enumerations will have different types, but 9690 // may still be similar enough to be interchangeable for our purposes. 9691 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9692 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9693 // Only handle anonymous enums. If the enumerations were named and 9694 // equivalent, they would have been merged to the same type. 9695 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9696 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9697 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9698 !Context.hasSameType(EnumA->getIntegerType(), 9699 EnumB->getIntegerType())) 9700 return false; 9701 // Allow this only if the value is the same for both enumerators. 9702 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9703 } 9704 } 9705 9706 // Nothing else is sufficiently similar. 9707 return false; 9708} 9709 9710void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9711 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9712 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9713 9714 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9715 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9716 << !M << (M ? M->getFullModuleName() : ""); 9717 9718 for (auto *E : Equiv) { 9719 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9720 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9721 << !M << (M ? M->getFullModuleName() : ""); 9722 } 9723} 9724 9725/// Computes the best viable function (C++ 13.3.3) 9726/// within an overload candidate set. 9727/// 9728/// \param Loc The location of the function name (or operator symbol) for 9729/// which overload resolution occurs. 9730/// 9731/// \param Best If overload resolution was successful or found a deleted 9732/// function, \p Best points to the candidate function found. 9733/// 9734/// \returns The result of overload resolution. 9735OverloadingResult 9736OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9737 iterator &Best) { 9738 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9739 std::transform(begin(), end(), std::back_inserter(Candidates), 9740 [](OverloadCandidate &Cand) { return &Cand; }); 9741 9742 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9743 // are accepted by both clang and NVCC. However, during a particular 9744 // compilation mode only one call variant is viable. We need to 9745 // exclude non-viable overload candidates from consideration based 9746 // only on their host/device attributes. Specifically, if one 9747 // candidate call is WrongSide and the other is SameSide, we ignore 9748 // the WrongSide candidate. 9749 if (S.getLangOpts().CUDA) { 9750 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9751 bool ContainsSameSideCandidate = 9752 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9753 // Check viable function only. 9754 return Cand->Viable && Cand->Function && 9755 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9756 Sema::CFP_SameSide; 9757 }); 9758 if (ContainsSameSideCandidate) { 9759 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9760 // Check viable function only to avoid unnecessary data copying/moving. 9761 return Cand->Viable && Cand->Function && 9762 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9763 Sema::CFP_WrongSide; 9764 }; 9765 llvm::erase_if(Candidates, IsWrongSideCandidate); 9766 } 9767 } 9768 9769 // Find the best viable function. 9770 Best = end(); 9771 for (auto *Cand : Candidates) { 9772 Cand->Best = false; 9773 if (Cand->Viable) 9774 if (Best == end() || 9775 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9776 Best = Cand; 9777 } 9778 9779 // If we didn't find any viable functions, abort. 9780 if (Best == end()) 9781 return OR_No_Viable_Function; 9782 9783 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9784 9785 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9786 PendingBest.push_back(&*Best); 9787 Best->Best = true; 9788 9789 // Make sure that this function is better than every other viable 9790 // function. If not, we have an ambiguity. 9791 while (!PendingBest.empty()) { 9792 auto *Curr = PendingBest.pop_back_val(); 9793 for (auto *Cand : Candidates) { 9794 if (Cand->Viable && !Cand->Best && 9795 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9796 PendingBest.push_back(Cand); 9797 Cand->Best = true; 9798 9799 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9800 Curr->Function)) 9801 EquivalentCands.push_back(Cand->Function); 9802 else 9803 Best = end(); 9804 } 9805 } 9806 } 9807 9808 // If we found more than one best candidate, this is ambiguous. 9809 if (Best == end()) 9810 return OR_Ambiguous; 9811 9812 // Best is the best viable function. 9813 if (Best->Function && Best->Function->isDeleted()) 9814 return OR_Deleted; 9815 9816 if (!EquivalentCands.empty()) 9817 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9818 EquivalentCands); 9819 9820 return OR_Success; 9821} 9822 9823namespace { 9824 9825enum OverloadCandidateKind { 9826 oc_function, 9827 oc_method, 9828 oc_reversed_binary_operator, 9829 oc_constructor, 9830 oc_implicit_default_constructor, 9831 oc_implicit_copy_constructor, 9832 oc_implicit_move_constructor, 9833 oc_implicit_copy_assignment, 9834 oc_implicit_move_assignment, 9835 oc_implicit_equality_comparison, 9836 oc_inherited_constructor 9837}; 9838 9839enum OverloadCandidateSelect { 9840 ocs_non_template, 9841 ocs_template, 9842 ocs_described_template, 9843}; 9844 9845static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9846ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9847 OverloadCandidateRewriteKind CRK, 9848 std::string &Description) { 9849 9850 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9851 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9852 isTemplate = true; 9853 Description = S.getTemplateArgumentBindingsText( 9854 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9855 } 9856 9857 OverloadCandidateSelect Select = [&]() { 9858 if (!Description.empty()) 9859 return ocs_described_template; 9860 return isTemplate ? ocs_template : ocs_non_template; 9861 }(); 9862 9863 OverloadCandidateKind Kind = [&]() { 9864 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9865 return oc_implicit_equality_comparison; 9866 9867 if (CRK & CRK_Reversed) 9868 return oc_reversed_binary_operator; 9869 9870 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9871 if (!Ctor->isImplicit()) { 9872 if (isa<ConstructorUsingShadowDecl>(Found)) 9873 return oc_inherited_constructor; 9874 else 9875 return oc_constructor; 9876 } 9877 9878 if (Ctor->isDefaultConstructor()) 9879 return oc_implicit_default_constructor; 9880 9881 if (Ctor->isMoveConstructor()) 9882 return oc_implicit_move_constructor; 9883 9884 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
9885 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
; 9886 return oc_implicit_copy_constructor; 9887 } 9888 9889 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9890 // This actually gets spelled 'candidate function' for now, but 9891 // it doesn't hurt to split it out. 9892 if (!Meth->isImplicit()) 9893 return oc_method; 9894 9895 if (Meth->isMoveAssignmentOperator()) 9896 return oc_implicit_move_assignment; 9897 9898 if (Meth->isCopyAssignmentOperator()) 9899 return oc_implicit_copy_assignment; 9900 9901 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9901, __PRETTY_FUNCTION__))
; 9902 return oc_method; 9903 } 9904 9905 return oc_function; 9906 }(); 9907 9908 return std::make_pair(Kind, Select); 9909} 9910 9911void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9912 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9913 // set. 9914 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9915 S.Diag(FoundDecl->getLocation(), 9916 diag::note_ovl_candidate_inherited_constructor) 9917 << Shadow->getNominatedBaseClass(); 9918} 9919 9920} // end anonymous namespace 9921 9922static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9923 const FunctionDecl *FD) { 9924 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9925 bool AlwaysTrue; 9926 if (EnableIf->getCond()->isValueDependent() || 9927 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9928 return false; 9929 if (!AlwaysTrue) 9930 return false; 9931 } 9932 return true; 9933} 9934 9935/// Returns true if we can take the address of the function. 9936/// 9937/// \param Complain - If true, we'll emit a diagnostic 9938/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9939/// we in overload resolution? 9940/// \param Loc - The location of the statement we're complaining about. Ignored 9941/// if we're not complaining, or if we're in overload resolution. 9942static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9943 bool Complain, 9944 bool InOverloadResolution, 9945 SourceLocation Loc) { 9946 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9947 if (Complain) { 9948 if (InOverloadResolution) 9949 S.Diag(FD->getBeginLoc(), 9950 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9951 else 9952 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9953 } 9954 return false; 9955 } 9956 9957 if (const Expr *RC = FD->getTrailingRequiresClause()) { 9958 ConstraintSatisfaction Satisfaction; 9959 if (S.CheckConstraintSatisfaction(RC, Satisfaction)) 9960 return false; 9961 if (!Satisfaction.IsSatisfied) { 9962 if (Complain) { 9963 if (InOverloadResolution) 9964 S.Diag(FD->getBeginLoc(), 9965 diag::note_ovl_candidate_unsatisfied_constraints); 9966 else 9967 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 9968 << FD; 9969 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 9970 } 9971 return false; 9972 } 9973 } 9974 9975 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9976 return P->hasAttr<PassObjectSizeAttr>(); 9977 }); 9978 if (I == FD->param_end()) 9979 return true; 9980 9981 if (Complain) { 9982 // Add one to ParamNo because it's user-facing 9983 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9984 if (InOverloadResolution) 9985 S.Diag(FD->getLocation(), 9986 diag::note_ovl_candidate_has_pass_object_size_params) 9987 << ParamNo; 9988 else 9989 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9990 << FD << ParamNo; 9991 } 9992 return false; 9993} 9994 9995static bool checkAddressOfCandidateIsAvailable(Sema &S, 9996 const FunctionDecl *FD) { 9997 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9998 /*InOverloadResolution=*/true, 9999 /*Loc=*/SourceLocation()); 10000} 10001 10002bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10003 bool Complain, 10004 SourceLocation Loc) { 10005 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10006 /*InOverloadResolution=*/false, 10007 Loc); 10008} 10009 10010// Notes the location of an overload candidate. 10011void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10012 OverloadCandidateRewriteKind RewriteKind, 10013 QualType DestType, bool TakingAddress) { 10014 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10015 return; 10016 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10017 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10018 return; 10019 10020 std::string FnDesc; 10021 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10022 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10023 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10024 << (unsigned)KSPair.first << (unsigned)KSPair.second 10025 << Fn << FnDesc; 10026 10027 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10028 Diag(Fn->getLocation(), PD); 10029 MaybeEmitInheritedConstructorNote(*this, Found); 10030} 10031 10032static void 10033MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10034 // Perhaps the ambiguity was caused by two atomic constraints that are 10035 // 'identical' but not equivalent: 10036 // 10037 // void foo() requires (sizeof(T) > 4) { } // #1 10038 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10039 // 10040 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10041 // #2 to subsume #1, but these constraint are not considered equivalent 10042 // according to the subsumption rules because they are not the same 10043 // source-level construct. This behavior is quite confusing and we should try 10044 // to help the user figure out what happened. 10045 10046 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10047 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10048 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10049 if (!I->Function) 10050 continue; 10051 SmallVector<const Expr *, 3> AC; 10052 if (auto *Template = I->Function->getPrimaryTemplate()) 10053 Template->getAssociatedConstraints(AC); 10054 else 10055 I->Function->getAssociatedConstraints(AC); 10056 if (AC.empty()) 10057 continue; 10058 if (FirstCand == nullptr) { 10059 FirstCand = I->Function; 10060 FirstAC = AC; 10061 } else if (SecondCand == nullptr) { 10062 SecondCand = I->Function; 10063 SecondAC = AC; 10064 } else { 10065 // We have more than one pair of constrained functions - this check is 10066 // expensive and we'd rather not try to diagnose it. 10067 return; 10068 } 10069 } 10070 if (!SecondCand) 10071 return; 10072 // The diagnostic can only happen if there are associated constraints on 10073 // both sides (there needs to be some identical atomic constraint). 10074 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10075 SecondCand, SecondAC)) 10076 // Just show the user one diagnostic, they'll probably figure it out 10077 // from here. 10078 return; 10079} 10080 10081// Notes the location of all overload candidates designated through 10082// OverloadedExpr 10083void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10084 bool TakingAddress) { 10085 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10085, __PRETTY_FUNCTION__))
; 10086 10087 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10088 OverloadExpr *OvlExpr = Ovl.Expression; 10089 10090 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10091 IEnd = OvlExpr->decls_end(); 10092 I != IEnd; ++I) { 10093 if (FunctionTemplateDecl *FunTmpl = 10094 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10095 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10096 TakingAddress); 10097 } else if (FunctionDecl *Fun 10098 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10099 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10100 } 10101 } 10102} 10103 10104/// Diagnoses an ambiguous conversion. The partial diagnostic is the 10105/// "lead" diagnostic; it will be given two arguments, the source and 10106/// target types of the conversion. 10107void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10108 Sema &S, 10109 SourceLocation CaretLoc, 10110 const PartialDiagnostic &PDiag) const { 10111 S.Diag(CaretLoc, PDiag) 10112 << Ambiguous.getFromType() << Ambiguous.getToType(); 10113 // FIXME: The note limiting machinery is borrowed from 10114 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10115 // refactoring here. 10116 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10117 unsigned CandsShown = 0; 10118 AmbiguousConversionSequence::const_iterator I, E; 10119 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10120 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10121 break; 10122 ++CandsShown; 10123 S.NoteOverloadCandidate(I->first, I->second); 10124 } 10125 if (I != E) 10126 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10127} 10128 10129static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10130 unsigned I, bool TakingCandidateAddress) { 10131 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10132 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10132, __PRETTY_FUNCTION__))
; 10133 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10133, __PRETTY_FUNCTION__))
; 10134 FunctionDecl *Fn = Cand->Function; 10135 10136 // There's a conversion slot for the object argument if this is a 10137 // non-constructor method. Note that 'I' corresponds the 10138 // conversion-slot index. 10139 bool isObjectArgument = false; 10140 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10141 if (I == 0) 10142 isObjectArgument = true; 10143 else 10144 I--; 10145 } 10146 10147 std::string FnDesc; 10148 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10149 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10150 FnDesc); 10151 10152 Expr *FromExpr = Conv.Bad.FromExpr; 10153 QualType FromTy = Conv.Bad.getFromType(); 10154 QualType ToTy = Conv.Bad.getToType(); 10155 10156 if (FromTy == S.Context.OverloadTy) { 10157 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10157, __PRETTY_FUNCTION__))
; 10158 Expr *E = FromExpr->IgnoreParens(); 10159 if (isa<UnaryOperator>(E)) 10160 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10161 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10162 10163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10164 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10166 << Name << I + 1; 10167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10168 return; 10169 } 10170 10171 // Do some hand-waving analysis to see if the non-viability is due 10172 // to a qualifier mismatch. 10173 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10174 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10175 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10176 CToTy = RT->getPointeeType(); 10177 else { 10178 // TODO: detect and diagnose the full richness of const mismatches. 10179 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10180 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10181 CFromTy = FromPT->getPointeeType(); 10182 CToTy = ToPT->getPointeeType(); 10183 } 10184 } 10185 10186 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10187 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10188 Qualifiers FromQs = CFromTy.getQualifiers(); 10189 Qualifiers ToQs = CToTy.getQualifiers(); 10190 10191 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10192 if (isObjectArgument) 10193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10194 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10195 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10196 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10197 else 10198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10200 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10201 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10202 << ToTy->isReferenceType() << I + 1; 10203 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10204 return; 10205 } 10206 10207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10209 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10211 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10212 << (unsigned)isObjectArgument << I + 1; 10213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10214 return; 10215 } 10216 10217 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10219 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10221 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10222 << (unsigned)isObjectArgument << I + 1; 10223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10224 return; 10225 } 10226 10227 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10231 << FromQs.hasUnaligned() << I + 1; 10232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10233 return; 10234 } 10235 10236 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10237 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10237, __PRETTY_FUNCTION__))
; 10238 10239 if (isObjectArgument) { 10240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10242 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10243 << (CVR - 1); 10244 } else { 10245 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10246 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10247 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10248 << (CVR - 1) << I + 1; 10249 } 10250 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10251 return; 10252 } 10253 10254 // Special diagnostic for failure to convert an initializer list, since 10255 // telling the user that it has type void is not useful. 10256 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10258 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10260 << ToTy << (unsigned)isObjectArgument << I + 1; 10261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10262 return; 10263 } 10264 10265 // Diagnose references or pointers to incomplete types differently, 10266 // since it's far from impossible that the incompleteness triggered 10267 // the failure. 10268 QualType TempFromTy = FromTy.getNonReferenceType(); 10269 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10270 TempFromTy = PTy->getPointeeType(); 10271 if (TempFromTy->isIncompleteType()) { 10272 // Emit the generic diagnostic and, optionally, add the hints to it. 10273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10274 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10276 << ToTy << (unsigned)isObjectArgument << I + 1 10277 << (unsigned)(Cand->Fix.Kind); 10278 10279 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10280 return; 10281 } 10282 10283 // Diagnose base -> derived pointer conversions. 10284 unsigned BaseToDerivedConversion = 0; 10285 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10286 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10287 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10288 FromPtrTy->getPointeeType()) && 10289 !FromPtrTy->getPointeeType()->isIncompleteType() && 10290 !ToPtrTy->getPointeeType()->isIncompleteType() && 10291 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10292 FromPtrTy->getPointeeType())) 10293 BaseToDerivedConversion = 1; 10294 } 10295 } else if (const ObjCObjectPointerType *FromPtrTy 10296 = FromTy->getAs<ObjCObjectPointerType>()) { 10297 if (const ObjCObjectPointerType *ToPtrTy 10298 = ToTy->getAs<ObjCObjectPointerType>()) 10299 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10300 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10301 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10302 FromPtrTy->getPointeeType()) && 10303 FromIface->isSuperClassOf(ToIface)) 10304 BaseToDerivedConversion = 2; 10305 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10306 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10307 !FromTy->isIncompleteType() && 10308 !ToRefTy->getPointeeType()->isIncompleteType() && 10309 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10310 BaseToDerivedConversion = 3; 10311 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10312 ToTy.getNonReferenceType().getCanonicalType() == 10313 FromTy.getNonReferenceType().getCanonicalType()) { 10314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10315 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10316 << (unsigned)isObjectArgument << I + 1 10317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10319 return; 10320 } 10321 } 10322 10323 if (BaseToDerivedConversion) { 10324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10325 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10326 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10327 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10328 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10329 return; 10330 } 10331 10332 if (isa<ObjCObjectPointerType>(CFromTy) && 10333 isa<PointerType>(CToTy)) { 10334 Qualifiers FromQs = CFromTy.getQualifiers(); 10335 Qualifiers ToQs = CToTy.getQualifiers(); 10336 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10338 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10339 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10340 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10342 return; 10343 } 10344 } 10345 10346 if (TakingCandidateAddress && 10347 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10348 return; 10349 10350 // Emit the generic diagnostic and, optionally, add the hints to it. 10351 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10352 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10353 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10354 << ToTy << (unsigned)isObjectArgument << I + 1 10355 << (unsigned)(Cand->Fix.Kind); 10356 10357 // If we can fix the conversion, suggest the FixIts. 10358 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10359 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10360 FDiag << *HI; 10361 S.Diag(Fn->getLocation(), FDiag); 10362 10363 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10364} 10365 10366/// Additional arity mismatch diagnosis specific to a function overload 10367/// candidates. This is not covered by the more general DiagnoseArityMismatch() 10368/// over a candidate in any candidate set. 10369static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10370 unsigned NumArgs) { 10371 FunctionDecl *Fn = Cand->Function; 10372 unsigned MinParams = Fn->getMinRequiredArguments(); 10373 10374 // With invalid overloaded operators, it's possible that we think we 10375 // have an arity mismatch when in fact it looks like we have the 10376 // right number of arguments, because only overloaded operators have 10377 // the weird behavior of overloading member and non-member functions. 10378 // Just don't report anything. 10379 if (Fn->isInvalidDecl() && 10380 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10381 return true; 10382 10383 if (NumArgs < MinParams) { 10384 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10385 (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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10386 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
; 10387 } else { 10388 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10389 (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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10390 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
; 10391 } 10392 10393 return false; 10394} 10395 10396/// General arity mismatch diagnosis over a candidate in a candidate set. 10397static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10398 unsigned NumFormalArgs) { 10399 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10400 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10401 " 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10402 " 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
; 10403 10404 FunctionDecl *Fn = cast<FunctionDecl>(D); 10405 10406 // TODO: treat calls to a missing default constructor as a special case 10407 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10408 unsigned MinParams = Fn->getMinRequiredArguments(); 10409 10410 // at least / at most / exactly 10411 unsigned mode, modeCount; 10412 if (NumFormalArgs < MinParams) { 10413 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10414 FnTy->isTemplateVariadic()) 10415 mode = 0; // "at least" 10416 else 10417 mode = 2; // "exactly" 10418 modeCount = MinParams; 10419 } else { 10420 if (MinParams != FnTy->getNumParams()) 10421 mode = 1; // "at most" 10422 else 10423 mode = 2; // "exactly" 10424 modeCount = FnTy->getNumParams(); 10425 } 10426 10427 std::string Description; 10428 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10429 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10430 10431 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10434 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10435 else 10436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10437 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10438 << Description << mode << modeCount << NumFormalArgs; 10439 10440 MaybeEmitInheritedConstructorNote(S, Found); 10441} 10442 10443/// Arity mismatch diagnosis specific to a function overload candidate. 10444static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10445 unsigned NumFormalArgs) { 10446 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10447 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10448} 10449 10450static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10451 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10452 return TD; 10453 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
10454 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
; 10455} 10456 10457/// Diagnose a failed template-argument deduction. 10458static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10459 DeductionFailureInfo &DeductionFailure, 10460 unsigned NumArgs, 10461 bool TakingCandidateAddress) { 10462 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10463 NamedDecl *ParamD; 10464 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10465 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10466 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10467 switch (DeductionFailure.Result) { 10468 case Sema::TDK_Success: 10469 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10469)
; 10470 10471 case Sema::TDK_Incomplete: { 10472 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10472, __PRETTY_FUNCTION__))
; 10473 S.Diag(Templated->getLocation(), 10474 diag::note_ovl_candidate_incomplete_deduction) 10475 << ParamD->getDeclName(); 10476 MaybeEmitInheritedConstructorNote(S, Found); 10477 return; 10478 } 10479 10480 case Sema::TDK_IncompletePack: { 10481 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10481, __PRETTY_FUNCTION__))
; 10482 S.Diag(Templated->getLocation(), 10483 diag::note_ovl_candidate_incomplete_deduction_pack) 10484 << ParamD->getDeclName() 10485 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10486 << *DeductionFailure.getFirstArg(); 10487 MaybeEmitInheritedConstructorNote(S, Found); 10488 return; 10489 } 10490 10491 case Sema::TDK_Underqualified: { 10492 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10492, __PRETTY_FUNCTION__))
; 10493 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10494 10495 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10496 10497 // Param will have been canonicalized, but it should just be a 10498 // qualified version of ParamD, so move the qualifiers to that. 10499 QualifierCollector Qs; 10500 Qs.strip(Param); 10501 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10502 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10502, __PRETTY_FUNCTION__))
; 10503 10504 // Arg has also been canonicalized, but there's nothing we can do 10505 // about that. It also doesn't matter as much, because it won't 10506 // have any template parameters in it (because deduction isn't 10507 // done on dependent types). 10508 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10509 10510 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10511 << ParamD->getDeclName() << Arg << NonCanonParam; 10512 MaybeEmitInheritedConstructorNote(S, Found); 10513 return; 10514 } 10515 10516 case Sema::TDK_Inconsistent: { 10517 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10517, __PRETTY_FUNCTION__))
; 10518 int which = 0; 10519 if (isa<TemplateTypeParmDecl>(ParamD)) 10520 which = 0; 10521 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10522 // Deduction might have failed because we deduced arguments of two 10523 // different types for a non-type template parameter. 10524 // FIXME: Use a different TDK value for this. 10525 QualType T1 = 10526 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10527 QualType T2 = 10528 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10529 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10530 S.Diag(Templated->getLocation(), 10531 diag::note_ovl_candidate_inconsistent_deduction_types) 10532 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10533 << *DeductionFailure.getSecondArg() << T2; 10534 MaybeEmitInheritedConstructorNote(S, Found); 10535 return; 10536 } 10537 10538 which = 1; 10539 } else { 10540 which = 2; 10541 } 10542 10543 // Tweak the diagnostic if the problem is that we deduced packs of 10544 // different arities. We'll print the actual packs anyway in case that 10545 // includes additional useful information. 10546 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10547 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10548 DeductionFailure.getFirstArg()->pack_size() != 10549 DeductionFailure.getSecondArg()->pack_size()) { 10550 which = 3; 10551 } 10552 10553 S.Diag(Templated->getLocation(), 10554 diag::note_ovl_candidate_inconsistent_deduction) 10555 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10556 << *DeductionFailure.getSecondArg(); 10557 MaybeEmitInheritedConstructorNote(S, Found); 10558 return; 10559 } 10560 10561 case Sema::TDK_InvalidExplicitArguments: 10562 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10562, __PRETTY_FUNCTION__))
; 10563 if (ParamD->getDeclName()) 10564 S.Diag(Templated->getLocation(), 10565 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10566 << ParamD->getDeclName(); 10567 else { 10568 int index = 0; 10569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10570 index = TTP->getIndex(); 10571 else if (NonTypeTemplateParmDecl *NTTP 10572 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10573 index = NTTP->getIndex(); 10574 else 10575 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10576 S.Diag(Templated->getLocation(), 10577 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10578 << (index + 1); 10579 } 10580 MaybeEmitInheritedConstructorNote(S, Found); 10581 return; 10582 10583 case Sema::TDK_ConstraintsNotSatisfied: { 10584 // Format the template argument list into the argument string. 10585 SmallString<128> TemplateArgString; 10586 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10587 TemplateArgString = " "; 10588 TemplateArgString += S.getTemplateArgumentBindingsText( 10589 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10590 if (TemplateArgString.size() == 1) 10591 TemplateArgString.clear(); 10592 S.Diag(Templated->getLocation(), 10593 diag::note_ovl_candidate_unsatisfied_constraints) 10594 << TemplateArgString; 10595 10596 S.DiagnoseUnsatisfiedConstraint( 10597 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10598 return; 10599 } 10600 case Sema::TDK_TooManyArguments: 10601 case Sema::TDK_TooFewArguments: 10602 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10603 return; 10604 10605 case Sema::TDK_InstantiationDepth: 10606 S.Diag(Templated->getLocation(), 10607 diag::note_ovl_candidate_instantiation_depth); 10608 MaybeEmitInheritedConstructorNote(S, Found); 10609 return; 10610 10611 case Sema::TDK_SubstitutionFailure: { 10612 // Format the template argument list into the argument string. 10613 SmallString<128> TemplateArgString; 10614 if (TemplateArgumentList *Args = 10615 DeductionFailure.getTemplateArgumentList()) { 10616 TemplateArgString = " "; 10617 TemplateArgString += S.getTemplateArgumentBindingsText( 10618 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10619 if (TemplateArgString.size() == 1) 10620 TemplateArgString.clear(); 10621 } 10622 10623 // If this candidate was disabled by enable_if, say so. 10624 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10625 if (PDiag && PDiag->second.getDiagID() == 10626 diag::err_typename_nested_not_found_enable_if) { 10627 // FIXME: Use the source range of the condition, and the fully-qualified 10628 // name of the enable_if template. These are both present in PDiag. 10629 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10630 << "'enable_if'" << TemplateArgString; 10631 return; 10632 } 10633 10634 // We found a specific requirement that disabled the enable_if. 10635 if (PDiag && PDiag->second.getDiagID() == 10636 diag::err_typename_nested_not_found_requirement) { 10637 S.Diag(Templated->getLocation(), 10638 diag::note_ovl_candidate_disabled_by_requirement) 10639 << PDiag->second.getStringArg(0) << TemplateArgString; 10640 return; 10641 } 10642 10643 // Format the SFINAE diagnostic into the argument string. 10644 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10645 // formatted message in another diagnostic. 10646 SmallString<128> SFINAEArgString; 10647 SourceRange R; 10648 if (PDiag) { 10649 SFINAEArgString = ": "; 10650 R = SourceRange(PDiag->first, PDiag->first); 10651 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10652 } 10653 10654 S.Diag(Templated->getLocation(), 10655 diag::note_ovl_candidate_substitution_failure) 10656 << TemplateArgString << SFINAEArgString << R; 10657 MaybeEmitInheritedConstructorNote(S, Found); 10658 return; 10659 } 10660 10661 case Sema::TDK_DeducedMismatch: 10662 case Sema::TDK_DeducedMismatchNested: { 10663 // Format the template argument list into the argument string. 10664 SmallString<128> TemplateArgString; 10665 if (TemplateArgumentList *Args = 10666 DeductionFailure.getTemplateArgumentList()) { 10667 TemplateArgString = " "; 10668 TemplateArgString += S.getTemplateArgumentBindingsText( 10669 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10670 if (TemplateArgString.size() == 1) 10671 TemplateArgString.clear(); 10672 } 10673 10674 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10675 << (*DeductionFailure.getCallArgIndex() + 1) 10676 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10677 << TemplateArgString 10678 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10679 break; 10680 } 10681 10682 case Sema::TDK_NonDeducedMismatch: { 10683 // FIXME: Provide a source location to indicate what we couldn't match. 10684 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10685 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10686 if (FirstTA.getKind() == TemplateArgument::Template && 10687 SecondTA.getKind() == TemplateArgument::Template) { 10688 TemplateName FirstTN = FirstTA.getAsTemplate(); 10689 TemplateName SecondTN = SecondTA.getAsTemplate(); 10690 if (FirstTN.getKind() == TemplateName::Template && 10691 SecondTN.getKind() == TemplateName::Template) { 10692 if (FirstTN.getAsTemplateDecl()->getName() == 10693 SecondTN.getAsTemplateDecl()->getName()) { 10694 // FIXME: This fixes a bad diagnostic where both templates are named 10695 // the same. This particular case is a bit difficult since: 10696 // 1) It is passed as a string to the diagnostic printer. 10697 // 2) The diagnostic printer only attempts to find a better 10698 // name for types, not decls. 10699 // Ideally, this should folded into the diagnostic printer. 10700 S.Diag(Templated->getLocation(), 10701 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10702 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10703 return; 10704 } 10705 } 10706 } 10707 10708 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10709 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10710 return; 10711 10712 // FIXME: For generic lambda parameters, check if the function is a lambda 10713 // call operator, and if so, emit a prettier and more informative 10714 // diagnostic that mentions 'auto' and lambda in addition to 10715 // (or instead of?) the canonical template type parameters. 10716 S.Diag(Templated->getLocation(), 10717 diag::note_ovl_candidate_non_deduced_mismatch) 10718 << FirstTA << SecondTA; 10719 return; 10720 } 10721 // TODO: diagnose these individually, then kill off 10722 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10723 case Sema::TDK_MiscellaneousDeductionFailure: 10724 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10725 MaybeEmitInheritedConstructorNote(S, Found); 10726 return; 10727 case Sema::TDK_CUDATargetMismatch: 10728 S.Diag(Templated->getLocation(), 10729 diag::note_cuda_ovl_candidate_target_mismatch); 10730 return; 10731 } 10732} 10733 10734/// Diagnose a failed template-argument deduction, for function calls. 10735static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10736 unsigned NumArgs, 10737 bool TakingCandidateAddress) { 10738 unsigned TDK = Cand->DeductionFailure.Result; 10739 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10740 if (CheckArityMismatch(S, Cand, NumArgs)) 10741 return; 10742 } 10743 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10744 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10745} 10746 10747/// CUDA: diagnose an invalid call across targets. 10748static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10749 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10750 FunctionDecl *Callee = Cand->Function; 10751 10752 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10753 CalleeTarget = S.IdentifyCUDATarget(Callee); 10754 10755 std::string FnDesc; 10756 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10757 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10758 Cand->getRewriteKind(), FnDesc); 10759 10760 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10761 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10762 << FnDesc /* Ignored */ 10763 << CalleeTarget << CallerTarget; 10764 10765 // This could be an implicit constructor for which we could not infer the 10766 // target due to a collsion. Diagnose that case. 10767 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10768 if (Meth != nullptr && Meth->isImplicit()) { 10769 CXXRecordDecl *ParentClass = Meth->getParent(); 10770 Sema::CXXSpecialMember CSM; 10771 10772 switch (FnKindPair.first) { 10773 default: 10774 return; 10775 case oc_implicit_default_constructor: 10776 CSM = Sema::CXXDefaultConstructor; 10777 break; 10778 case oc_implicit_copy_constructor: 10779 CSM = Sema::CXXCopyConstructor; 10780 break; 10781 case oc_implicit_move_constructor: 10782 CSM = Sema::CXXMoveConstructor; 10783 break; 10784 case oc_implicit_copy_assignment: 10785 CSM = Sema::CXXCopyAssignment; 10786 break; 10787 case oc_implicit_move_assignment: 10788 CSM = Sema::CXXMoveAssignment; 10789 break; 10790 }; 10791 10792 bool ConstRHS = false; 10793 if (Meth->getNumParams()) { 10794 if (const ReferenceType *RT = 10795 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10796 ConstRHS = RT->getPointeeType().isConstQualified(); 10797 } 10798 } 10799 10800 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10801 /* ConstRHS */ ConstRHS, 10802 /* Diagnose */ true); 10803 } 10804} 10805 10806static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10807 FunctionDecl *Callee = Cand->Function; 10808 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10809 10810 S.Diag(Callee->getLocation(), 10811 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10812 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10813} 10814 10815static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10816 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10817 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10817, __PRETTY_FUNCTION__))
; 10818 10819 unsigned Kind; 10820 switch (Cand->Function->getDeclKind()) { 10821 case Decl::Kind::CXXConstructor: 10822 Kind = 0; 10823 break; 10824 case Decl::Kind::CXXConversion: 10825 Kind = 1; 10826 break; 10827 case Decl::Kind::CXXDeductionGuide: 10828 Kind = Cand->Function->isImplicit() ? 0 : 2; 10829 break; 10830 default: 10831 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10831)
; 10832 } 10833 10834 // Note the location of the first (in-class) declaration; a redeclaration 10835 // (particularly an out-of-class definition) will typically lack the 10836 // 'explicit' specifier. 10837 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10838 FunctionDecl *First = Cand->Function->getFirstDecl(); 10839 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10840 First = Pattern->getFirstDecl(); 10841 10842 S.Diag(First->getLocation(), 10843 diag::note_ovl_candidate_explicit) 10844 << Kind << (ES.getExpr() ? 1 : 0) 10845 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10846} 10847 10848static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10849 FunctionDecl *Callee = Cand->Function; 10850 10851 S.Diag(Callee->getLocation(), 10852 diag::note_ovl_candidate_disabled_by_extension) 10853 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10854} 10855 10856/// Generates a 'note' diagnostic for an overload candidate. We've 10857/// already generated a primary error at the call site. 10858/// 10859/// It really does need to be a single diagnostic with its caret 10860/// pointed at the candidate declaration. Yes, this creates some 10861/// major challenges of technical writing. Yes, this makes pointing 10862/// out problems with specific arguments quite awkward. It's still 10863/// better than generating twenty screens of text for every failed 10864/// overload. 10865/// 10866/// It would be great to be able to express per-candidate problems 10867/// more richly for those diagnostic clients that cared, but we'd 10868/// still have to be just as careful with the default diagnostics. 10869/// \param CtorDestAS Addr space of object being constructed (for ctor 10870/// candidates only). 10871static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10872 unsigned NumArgs, 10873 bool TakingCandidateAddress, 10874 LangAS CtorDestAS = LangAS::Default) { 10875 FunctionDecl *Fn = Cand->Function; 10876 10877 // Note deleted candidates, but only if they're viable. 10878 if (Cand->Viable) { 10879 if (Fn->isDeleted()) { 10880 std::string FnDesc; 10881 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10882 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10883 Cand->getRewriteKind(), FnDesc); 10884 10885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10886 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10887 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10888 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10889 return; 10890 } 10891 10892 // We don't really have anything else to say about viable candidates. 10893 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10894 return; 10895 } 10896 10897 switch (Cand->FailureKind) { 10898 case ovl_fail_too_many_arguments: 10899 case ovl_fail_too_few_arguments: 10900 return DiagnoseArityMismatch(S, Cand, NumArgs); 10901 10902 case ovl_fail_bad_deduction: 10903 return DiagnoseBadDeduction(S, Cand, NumArgs, 10904 TakingCandidateAddress); 10905 10906 case ovl_fail_illegal_constructor: { 10907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10908 << (Fn->getPrimaryTemplate() ? 1 : 0); 10909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10910 return; 10911 } 10912 10913 case ovl_fail_object_addrspace_mismatch: { 10914 Qualifiers QualsForPrinting; 10915 QualsForPrinting.setAddressSpace(CtorDestAS); 10916 S.Diag(Fn->getLocation(), 10917 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10918 << QualsForPrinting; 10919 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10920 return; 10921 } 10922 10923 case ovl_fail_trivial_conversion: 10924 case ovl_fail_bad_final_conversion: 10925 case ovl_fail_final_conversion_not_exact: 10926 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10927 10928 case ovl_fail_bad_conversion: { 10929 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10930 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10931 if (Cand->Conversions[I].isBad()) 10932 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10933 10934 // FIXME: this currently happens when we're called from SemaInit 10935 // when user-conversion overload fails. Figure out how to handle 10936 // those conditions and diagnose them well. 10937 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10938 } 10939 10940 case ovl_fail_bad_target: 10941 return DiagnoseBadTarget(S, Cand); 10942 10943 case ovl_fail_enable_if: 10944 return DiagnoseFailedEnableIfAttr(S, Cand); 10945 10946 case ovl_fail_explicit: 10947 return DiagnoseFailedExplicitSpec(S, Cand); 10948 10949 case ovl_fail_ext_disabled: 10950 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10951 10952 case ovl_fail_inhctor_slice: 10953 // It's generally not interesting to note copy/move constructors here. 10954 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10955 return; 10956 S.Diag(Fn->getLocation(), 10957 diag::note_ovl_candidate_inherited_constructor_slice) 10958 << (Fn->getPrimaryTemplate() ? 1 : 0) 10959 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10960 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10961 return; 10962 10963 case ovl_fail_addr_not_available: { 10964 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10965 (void)Available; 10966 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10966, __PRETTY_FUNCTION__))
; 10967 break; 10968 } 10969 case ovl_non_default_multiversion_function: 10970 // Do nothing, these should simply be ignored. 10971 break; 10972 10973 case ovl_fail_constraints_not_satisfied: { 10974 std::string FnDesc; 10975 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10976 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10977 Cand->getRewriteKind(), FnDesc); 10978 10979 S.Diag(Fn->getLocation(), 10980 diag::note_ovl_candidate_constraints_not_satisfied) 10981 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10982 << FnDesc /* Ignored */; 10983 ConstraintSatisfaction Satisfaction; 10984 if (S.CheckConstraintSatisfaction(Fn->getTrailingRequiresClause(), 10985 Satisfaction)) 10986 break; 10987 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10988 } 10989 } 10990} 10991 10992static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10993 // Desugar the type of the surrogate down to a function type, 10994 // retaining as many typedefs as possible while still showing 10995 // the function type (and, therefore, its parameter types). 10996 QualType FnType = Cand->Surrogate->getConversionType(); 10997 bool isLValueReference = false; 10998 bool isRValueReference = false; 10999 bool isPointer = false; 11000 if (const LValueReferenceType *FnTypeRef = 11001 FnType->getAs<LValueReferenceType>()) { 11002 FnType = FnTypeRef->getPointeeType(); 11003 isLValueReference = true; 11004 } else if (const RValueReferenceType *FnTypeRef = 11005 FnType->getAs<RValueReferenceType>()) { 11006 FnType = FnTypeRef->getPointeeType(); 11007 isRValueReference = true; 11008 } 11009 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11010 FnType = FnTypePtr->getPointeeType(); 11011 isPointer = true; 11012 } 11013 // Desugar down to a function type. 11014 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11015 // Reconstruct the pointer/reference as appropriate. 11016 if (isPointer) FnType = S.Context.getPointerType(FnType); 11017 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11018 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11019 11020 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11021 << FnType; 11022} 11023 11024static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11025 SourceLocation OpLoc, 11026 OverloadCandidate *Cand) { 11027 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11027, __PRETTY_FUNCTION__))
; 11028 std::string TypeStr("operator"); 11029 TypeStr += Opc; 11030 TypeStr += "("; 11031 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11032 if (Cand->Conversions.size() == 1) { 11033 TypeStr += ")"; 11034 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11035 } else { 11036 TypeStr += ", "; 11037 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11038 TypeStr += ")"; 11039 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11040 } 11041} 11042 11043static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11044 OverloadCandidate *Cand) { 11045 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11046 if (ICS.isBad()) break; // all meaningless after first invalid 11047 if (!ICS.isAmbiguous()) continue; 11048 11049 ICS.DiagnoseAmbiguousConversion( 11050 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11051 } 11052} 11053 11054static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11055 if (Cand->Function) 11056 return Cand->Function->getLocation(); 11057 if (Cand->IsSurrogate) 11058 return Cand->Surrogate->getLocation(); 11059 return SourceLocation(); 11060} 11061 11062static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11063 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11064 case Sema::TDK_Success: 11065 case Sema::TDK_NonDependentConversionFailure: 11066 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11066)
; 11067 11068 case Sema::TDK_Invalid: 11069 case Sema::TDK_Incomplete: 11070 case Sema::TDK_IncompletePack: 11071 return 1; 11072 11073 case Sema::TDK_Underqualified: 11074 case Sema::TDK_Inconsistent: 11075 return 2; 11076 11077 case Sema::TDK_SubstitutionFailure: 11078 case Sema::TDK_DeducedMismatch: 11079 case Sema::TDK_ConstraintsNotSatisfied: 11080 case Sema::TDK_DeducedMismatchNested: 11081 case Sema::TDK_NonDeducedMismatch: 11082 case Sema::TDK_MiscellaneousDeductionFailure: 11083 case Sema::TDK_CUDATargetMismatch: 11084 return 3; 11085 11086 case Sema::TDK_InstantiationDepth: 11087 return 4; 11088 11089 case Sema::TDK_InvalidExplicitArguments: 11090 return 5; 11091 11092 case Sema::TDK_TooManyArguments: 11093 case Sema::TDK_TooFewArguments: 11094 return 6; 11095 } 11096 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11096)
; 11097} 11098 11099namespace { 11100struct CompareOverloadCandidatesForDisplay { 11101 Sema &S; 11102 SourceLocation Loc; 11103 size_t NumArgs; 11104 OverloadCandidateSet::CandidateSetKind CSK; 11105 11106 CompareOverloadCandidatesForDisplay( 11107 Sema &S, SourceLocation Loc, size_t NArgs, 11108 OverloadCandidateSet::CandidateSetKind CSK) 11109 : S(S), NumArgs(NArgs), CSK(CSK) {} 11110 11111 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11112 // If there are too many or too few arguments, that's the high-order bit we 11113 // want to sort by, even if the immediate failure kind was something else. 11114 if (C->FailureKind == ovl_fail_too_many_arguments || 11115 C->FailureKind == ovl_fail_too_few_arguments) 11116 return static_cast<OverloadFailureKind>(C->FailureKind); 11117 11118 if (C->Function) { 11119 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11120 return ovl_fail_too_many_arguments; 11121 if (NumArgs < C->Function->getMinRequiredArguments()) 11122 return ovl_fail_too_few_arguments; 11123 } 11124 11125 return static_cast<OverloadFailureKind>(C->FailureKind); 11126 } 11127 11128 bool operator()(const OverloadCandidate *L, 11129 const OverloadCandidate *R) { 11130 // Fast-path this check. 11131 if (L == R) return false; 11132 11133 // Order first by viability. 11134 if (L->Viable) { 11135 if (!R->Viable) return true; 11136 11137 // TODO: introduce a tri-valued comparison for overload 11138 // candidates. Would be more worthwhile if we had a sort 11139 // that could exploit it. 11140 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11141 return true; 11142 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11143 return false; 11144 } else if (R->Viable) 11145 return false; 11146 11147 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11147, __PRETTY_FUNCTION__))
; 11148 11149 // Criteria by which we can sort non-viable candidates: 11150 if (!L->Viable) { 11151 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11152 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11153 11154 // 1. Arity mismatches come after other candidates. 11155 if (LFailureKind == ovl_fail_too_many_arguments || 11156 LFailureKind == ovl_fail_too_few_arguments) { 11157 if (RFailureKind == ovl_fail_too_many_arguments || 11158 RFailureKind == ovl_fail_too_few_arguments) { 11159 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11160 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11161 if (LDist == RDist) { 11162 if (LFailureKind == RFailureKind) 11163 // Sort non-surrogates before surrogates. 11164 return !L->IsSurrogate && R->IsSurrogate; 11165 // Sort candidates requiring fewer parameters than there were 11166 // arguments given after candidates requiring more parameters 11167 // than there were arguments given. 11168 return LFailureKind == ovl_fail_too_many_arguments; 11169 } 11170 return LDist < RDist; 11171 } 11172 return false; 11173 } 11174 if (RFailureKind == ovl_fail_too_many_arguments || 11175 RFailureKind == ovl_fail_too_few_arguments) 11176 return true; 11177 11178 // 2. Bad conversions come first and are ordered by the number 11179 // of bad conversions and quality of good conversions. 11180 if (LFailureKind == ovl_fail_bad_conversion) { 11181 if (RFailureKind != ovl_fail_bad_conversion) 11182 return true; 11183 11184 // The conversion that can be fixed with a smaller number of changes, 11185 // comes first. 11186 unsigned numLFixes = L->Fix.NumConversionsFixed; 11187 unsigned numRFixes = R->Fix.NumConversionsFixed; 11188 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; 11189 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; 11190 if (numLFixes != numRFixes) { 11191 return numLFixes < numRFixes; 11192 } 11193 11194 // If there's any ordering between the defined conversions... 11195 // FIXME: this might not be transitive. 11196 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11196, __PRETTY_FUNCTION__))
; 11197 11198 int leftBetter = 0; 11199 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11200 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11201 switch (CompareImplicitConversionSequences(S, Loc, 11202 L->Conversions[I], 11203 R->Conversions[I])) { 11204 case ImplicitConversionSequence::Better: 11205 leftBetter++; 11206 break; 11207 11208 case ImplicitConversionSequence::Worse: 11209 leftBetter--; 11210 break; 11211 11212 case ImplicitConversionSequence::Indistinguishable: 11213 break; 11214 } 11215 } 11216 if (leftBetter > 0) return true; 11217 if (leftBetter < 0) return false; 11218 11219 } else if (RFailureKind == ovl_fail_bad_conversion) 11220 return false; 11221 11222 if (LFailureKind == ovl_fail_bad_deduction) { 11223 if (RFailureKind != ovl_fail_bad_deduction) 11224 return true; 11225 11226 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11227 return RankDeductionFailure(L->DeductionFailure) 11228 < RankDeductionFailure(R->DeductionFailure); 11229 } else if (RFailureKind == ovl_fail_bad_deduction) 11230 return false; 11231 11232 // TODO: others? 11233 } 11234 11235 // Sort everything else by location. 11236 SourceLocation LLoc = GetLocationForCandidate(L); 11237 SourceLocation RLoc = GetLocationForCandidate(R); 11238 11239 // Put candidates without locations (e.g. builtins) at the end. 11240 if (LLoc.isInvalid()) return false; 11241 if (RLoc.isInvalid()) return true; 11242 11243 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11244 } 11245}; 11246} 11247 11248/// CompleteNonViableCandidate - Normally, overload resolution only 11249/// computes up to the first bad conversion. Produces the FixIt set if 11250/// possible. 11251static void 11252CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11253 ArrayRef<Expr *> Args, 11254 OverloadCandidateSet::CandidateSetKind CSK) { 11255 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11255, __PRETTY_FUNCTION__))
; 11256 11257 // Don't do anything on failures other than bad conversion. 11258 if (Cand->FailureKind != ovl_fail_bad_conversion) 11259 return; 11260 11261 // We only want the FixIts if all the arguments can be corrected. 11262 bool Unfixable = false; 11263 // Use a implicit copy initialization to check conversion fixes. 11264 Cand->Fix.setConversionChecker(TryCopyInitialization); 11265 11266 // Attempt to fix the bad conversion. 11267 unsigned ConvCount = Cand->Conversions.size(); 11268 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11269 ++ConvIdx) { 11270 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11270, __PRETTY_FUNCTION__))
; 11271 if (Cand->Conversions[ConvIdx].isInitialized() && 11272 Cand->Conversions[ConvIdx].isBad()) { 11273 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11274 break; 11275 } 11276 } 11277 11278 // FIXME: this should probably be preserved from the overload 11279 // operation somehow. 11280 bool SuppressUserConversions = false; 11281 11282 unsigned ConvIdx = 0; 11283 unsigned ArgIdx = 0; 11284 ArrayRef<QualType> ParamTypes; 11285 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11286 11287 if (Cand->IsSurrogate) { 11288 QualType ConvType 11289 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11290 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11291 ConvType = ConvPtrType->getPointeeType(); 11292 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11293 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11294 ConvIdx = 1; 11295 } else if (Cand->Function) { 11296 ParamTypes = 11297 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11298 if (isa<CXXMethodDecl>(Cand->Function) && 11299 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11300 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11301 ConvIdx = 1; 11302 if (CSK == OverloadCandidateSet::CSK_Operator && 11303 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11304 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11305 ArgIdx = 1; 11306 } 11307 } else { 11308 // Builtin operator. 11309 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11309, __PRETTY_FUNCTION__))
; 11310 ParamTypes = Cand->BuiltinParamTypes; 11311 } 11312 11313 // Fill in the rest of the conversions. 11314 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11315 ConvIdx != ConvCount; 11316 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11317 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11317, __PRETTY_FUNCTION__))
; 11318 if (Cand->Conversions[ConvIdx].isInitialized()) { 11319 // We've already checked this conversion. 11320 } else if (ParamIdx < ParamTypes.size()) { 11321 if (ParamTypes[ParamIdx]->isDependentType()) 11322 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11323 Args[ArgIdx]->getType()); 11324 else { 11325 Cand->Conversions[ConvIdx] = 11326 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11327 SuppressUserConversions, 11328 /*InOverloadResolution=*/true, 11329 /*AllowObjCWritebackConversion=*/ 11330 S.getLangOpts().ObjCAutoRefCount); 11331 // Store the FixIt in the candidate if it exists. 11332 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11333 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11334 } 11335 } else 11336 Cand->Conversions[ConvIdx].setEllipsis(); 11337 } 11338} 11339 11340SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11341 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11342 SourceLocation OpLoc, 11343 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11344 // Sort the candidates by viability and position. Sorting directly would 11345 // be prohibitive, so we make a set of pointers and sort those. 11346 SmallVector<OverloadCandidate*, 32> Cands; 11347 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11348 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11349 if (!Filter(*Cand)) 11350 continue; 11351 switch (OCD) { 11352 case OCD_AllCandidates: 11353 if (!Cand->Viable) { 11354 if (!Cand->Function && !Cand->IsSurrogate) { 11355 // This a non-viable builtin candidate. We do not, in general, 11356 // want to list every possible builtin candidate. 11357 continue; 11358 } 11359 CompleteNonViableCandidate(S, Cand, Args, Kind); 11360 } 11361 break; 11362 11363 case OCD_ViableCandidates: 11364 if (!Cand->Viable) 11365 continue; 11366 break; 11367 11368 case OCD_AmbiguousCandidates: 11369 if (!Cand->Best) 11370 continue; 11371 break; 11372 } 11373 11374 Cands.push_back(Cand); 11375 } 11376 11377 llvm::stable_sort( 11378 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11379 11380 return Cands; 11381} 11382 11383/// When overload resolution fails, prints diagnostic messages containing the 11384/// candidates in the candidate set. 11385void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11386 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11387 StringRef Opc, SourceLocation OpLoc, 11388 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11389 11390 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11391 11392 S.Diag(PD.first, PD.second); 11393 11394 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11395 11396 if (OCD == OCD_AmbiguousCandidates) 11397 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11398} 11399 11400void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11401 ArrayRef<OverloadCandidate *> Cands, 11402 StringRef Opc, SourceLocation OpLoc) { 11403 bool ReportedAmbiguousConversions = false; 11404 11405 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11406 unsigned CandsShown = 0; 11407 auto I = Cands.begin(), E = Cands.end(); 11408 for (; I != E; ++I) { 11409 OverloadCandidate *Cand = *I; 11410 11411 // Set an arbitrary limit on the number of candidate functions we'll spam 11412 // the user with. FIXME: This limit should depend on details of the 11413 // candidate list. 11414 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11415 break; 11416 } 11417 ++CandsShown; 11418 11419 if (Cand->Function) 11420 NoteFunctionCandidate(S, Cand, Args.size(), 11421 /*TakingCandidateAddress=*/false, DestAS); 11422 else if (Cand->IsSurrogate) 11423 NoteSurrogateCandidate(S, Cand); 11424 else { 11425 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
11426 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
; 11427 // Generally we only see ambiguities including viable builtin 11428 // operators if overload resolution got screwed up by an 11429 // ambiguous user-defined conversion. 11430 // 11431 // FIXME: It's quite possible for different conversions to see 11432 // different ambiguities, though. 11433 if (!ReportedAmbiguousConversions) { 11434 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11435 ReportedAmbiguousConversions = true; 11436 } 11437 11438 // If this is a viable builtin, print it. 11439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11440 } 11441 } 11442 11443 if (I != E) 11444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11445} 11446 11447static SourceLocation 11448GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11449 return Cand->Specialization ? Cand->Specialization->getLocation() 11450 : SourceLocation(); 11451} 11452 11453namespace { 11454struct CompareTemplateSpecCandidatesForDisplay { 11455 Sema &S; 11456 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11457 11458 bool operator()(const TemplateSpecCandidate *L, 11459 const TemplateSpecCandidate *R) { 11460 // Fast-path this check. 11461 if (L == R) 11462 return false; 11463 11464 // Assuming that both candidates are not matches... 11465 11466 // Sort by the ranking of deduction failures. 11467 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11468 return RankDeductionFailure(L->DeductionFailure) < 11469 RankDeductionFailure(R->DeductionFailure); 11470 11471 // Sort everything else by location. 11472 SourceLocation LLoc = GetLocationForCandidate(L); 11473 SourceLocation RLoc = GetLocationForCandidate(R); 11474 11475 // Put candidates without locations (e.g. builtins) at the end. 11476 if (LLoc.isInvalid()) 11477 return false; 11478 if (RLoc.isInvalid()) 11479 return true; 11480 11481 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11482 } 11483}; 11484} 11485 11486/// Diagnose a template argument deduction failure. 11487/// We are treating these failures as overload failures due to bad 11488/// deductions. 11489void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11490 bool ForTakingAddress) { 11491 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11492 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11493} 11494 11495void TemplateSpecCandidateSet::destroyCandidates() { 11496 for (iterator i = begin(), e = end(); i != e; ++i) { 11497 i->DeductionFailure.Destroy(); 11498 } 11499} 11500 11501void TemplateSpecCandidateSet::clear() { 11502 destroyCandidates(); 11503 Candidates.clear(); 11504} 11505 11506/// NoteCandidates - When no template specialization match is found, prints 11507/// diagnostic messages containing the non-matching specializations that form 11508/// the candidate set. 11509/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11510/// OCD == OCD_AllCandidates and Cand->Viable == false. 11511void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11512 // Sort the candidates by position (assuming no candidate is a match). 11513 // Sorting directly would be prohibitive, so we make a set of pointers 11514 // and sort those. 11515 SmallVector<TemplateSpecCandidate *, 32> Cands; 11516 Cands.reserve(size()); 11517 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11518 if (Cand->Specialization) 11519 Cands.push_back(Cand); 11520 // Otherwise, this is a non-matching builtin candidate. We do not, 11521 // in general, want to list every possible builtin candidate. 11522 } 11523 11524 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11525 11526 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11527 // for generalization purposes (?). 11528 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11529 11530 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11531 unsigned CandsShown = 0; 11532 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11533 TemplateSpecCandidate *Cand = *I; 11534 11535 // Set an arbitrary limit on the number of candidates we'll spam 11536 // the user with. FIXME: This limit should depend on details of the 11537 // candidate list. 11538 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11539 break; 11540 ++CandsShown; 11541 11542 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
11543 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
; 11544 Cand->NoteDeductionFailure(S, ForTakingAddress); 11545 } 11546 11547 if (I != E) 11548 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11549} 11550 11551// [PossiblyAFunctionType] --> [Return] 11552// NonFunctionType --> NonFunctionType 11553// R (A) --> R(A) 11554// R (*)(A) --> R (A) 11555// R (&)(A) --> R (A) 11556// R (S::*)(A) --> R (A) 11557QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11558 QualType Ret = PossiblyAFunctionType; 11559 if (const PointerType *ToTypePtr = 11560 PossiblyAFunctionType->getAs<PointerType>()) 11561 Ret = ToTypePtr->getPointeeType(); 11562 else if (const ReferenceType *ToTypeRef = 11563 PossiblyAFunctionType->getAs<ReferenceType>()) 11564 Ret = ToTypeRef->getPointeeType(); 11565 else if (const MemberPointerType *MemTypePtr = 11566 PossiblyAFunctionType->getAs<MemberPointerType>()) 11567 Ret = MemTypePtr->getPointeeType(); 11568 Ret = 11569 Context.getCanonicalType(Ret).getUnqualifiedType(); 11570 return Ret; 11571} 11572 11573static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11574 bool Complain = true) { 11575 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11576 S.DeduceReturnType(FD, Loc, Complain)) 11577 return true; 11578 11579 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11580 if (S.getLangOpts().CPlusPlus17 && 11581 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11582 !S.ResolveExceptionSpec(Loc, FPT)) 11583 return true; 11584 11585 return false; 11586} 11587 11588namespace { 11589// A helper class to help with address of function resolution 11590// - allows us to avoid passing around all those ugly parameters 11591class AddressOfFunctionResolver { 11592 Sema& S; 11593 Expr* SourceExpr; 11594 const QualType& TargetType; 11595 QualType TargetFunctionType; // Extracted function type from target type 11596 11597 bool Complain; 11598 //DeclAccessPair& ResultFunctionAccessPair; 11599 ASTContext& Context; 11600 11601 bool TargetTypeIsNonStaticMemberFunction; 11602 bool FoundNonTemplateFunction; 11603 bool StaticMemberFunctionFromBoundPointer; 11604 bool HasComplained; 11605 11606 OverloadExpr::FindResult OvlExprInfo; 11607 OverloadExpr *OvlExpr; 11608 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11609 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11610 TemplateSpecCandidateSet FailedCandidates; 11611 11612public: 11613 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11614 const QualType &TargetType, bool Complain) 11615 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11616 Complain(Complain), Context(S.getASTContext()), 11617 TargetTypeIsNonStaticMemberFunction( 11618 !!TargetType->getAs<MemberPointerType>()), 11619 FoundNonTemplateFunction(false), 11620 StaticMemberFunctionFromBoundPointer(false), 11621 HasComplained(false), 11622 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11623 OvlExpr(OvlExprInfo.Expression), 11624 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11625 ExtractUnqualifiedFunctionTypeFromTargetType(); 11626 11627 if (TargetFunctionType->isFunctionType()) { 11628 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11629 if (!UME->isImplicitAccess() && 11630 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11631 StaticMemberFunctionFromBoundPointer = true; 11632 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11633 DeclAccessPair dap; 11634 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11635 OvlExpr, false, &dap)) { 11636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11637 if (!Method->isStatic()) { 11638 // If the target type is a non-function type and the function found 11639 // is a non-static member function, pretend as if that was the 11640 // target, it's the only possible type to end up with. 11641 TargetTypeIsNonStaticMemberFunction = true; 11642 11643 // And skip adding the function if its not in the proper form. 11644 // We'll diagnose this due to an empty set of functions. 11645 if (!OvlExprInfo.HasFormOfMemberPointer) 11646 return; 11647 } 11648 11649 Matches.push_back(std::make_pair(dap, Fn)); 11650 } 11651 return; 11652 } 11653 11654 if (OvlExpr->hasExplicitTemplateArgs()) 11655 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11656 11657 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11658 // C++ [over.over]p4: 11659 // If more than one function is selected, [...] 11660 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11661 if (FoundNonTemplateFunction) 11662 EliminateAllTemplateMatches(); 11663 else 11664 EliminateAllExceptMostSpecializedTemplate(); 11665 } 11666 } 11667 11668 if (S.getLangOpts().CUDA && Matches.size() > 1) 11669 EliminateSuboptimalCudaMatches(); 11670 } 11671 11672 bool hasComplained() const { return HasComplained; } 11673 11674private: 11675 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11676 QualType Discard; 11677 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11678 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11679 } 11680 11681 /// \return true if A is considered a better overload candidate for the 11682 /// desired type than B. 11683 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11684 // If A doesn't have exactly the correct type, we don't want to classify it 11685 // as "better" than anything else. This way, the user is required to 11686 // disambiguate for us if there are multiple candidates and no exact match. 11687 return candidateHasExactlyCorrectType(A) && 11688 (!candidateHasExactlyCorrectType(B) || 11689 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11690 } 11691 11692 /// \return true if we were able to eliminate all but one overload candidate, 11693 /// false otherwise. 11694 bool eliminiateSuboptimalOverloadCandidates() { 11695 // Same algorithm as overload resolution -- one pass to pick the "best", 11696 // another pass to be sure that nothing is better than the best. 11697 auto Best = Matches.begin(); 11698 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11699 if (isBetterCandidate(I->second, Best->second)) 11700 Best = I; 11701 11702 const FunctionDecl *BestFn = Best->second; 11703 auto IsBestOrInferiorToBest = [this, BestFn]( 11704 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11705 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11706 }; 11707 11708 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11709 // option, so we can potentially give the user a better error 11710 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11711 return false; 11712 Matches[0] = *Best; 11713 Matches.resize(1); 11714 return true; 11715 } 11716 11717 bool isTargetTypeAFunction() const { 11718 return TargetFunctionType->isFunctionType(); 11719 } 11720 11721 // [ToType] [Return] 11722 11723 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11724 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11725 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11726 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11727 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11728 } 11729 11730 // return true if any matching specializations were found 11731 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11732 const DeclAccessPair& CurAccessFunPair) { 11733 if (CXXMethodDecl *Method 11734 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11735 // Skip non-static function templates when converting to pointer, and 11736 // static when converting to member pointer. 11737 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11738 return false; 11739 } 11740 else if (TargetTypeIsNonStaticMemberFunction) 11741 return false; 11742 11743 // C++ [over.over]p2: 11744 // If the name is a function template, template argument deduction is 11745 // done (14.8.2.2), and if the argument deduction succeeds, the 11746 // resulting template argument list is used to generate a single 11747 // function template specialization, which is added to the set of 11748 // overloaded functions considered. 11749 FunctionDecl *Specialization = nullptr; 11750 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11751 if (Sema::TemplateDeductionResult Result 11752 = S.DeduceTemplateArguments(FunctionTemplate, 11753 &OvlExplicitTemplateArgs, 11754 TargetFunctionType, Specialization, 11755 Info, /*IsAddressOfFunction*/true)) { 11756 // Make a note of the failed deduction for diagnostics. 11757 FailedCandidates.addCandidate() 11758 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11759 MakeDeductionFailureInfo(Context, Result, Info)); 11760 return false; 11761 } 11762 11763 // Template argument deduction ensures that we have an exact match or 11764 // compatible pointer-to-function arguments that would be adjusted by ICS. 11765 // This function template specicalization works. 11766 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11767 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11768 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
; 11769 11770 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11771 return false; 11772 11773 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11774 return true; 11775 } 11776 11777 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11778 const DeclAccessPair& CurAccessFunPair) { 11779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11780 // Skip non-static functions when converting to pointer, and static 11781 // when converting to member pointer. 11782 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11783 return false; 11784 } 11785 else if (TargetTypeIsNonStaticMemberFunction) 11786 return false; 11787 11788 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11789 if (S.getLangOpts().CUDA) 11790 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11791 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11792 return false; 11793 if (FunDecl->isMultiVersion()) { 11794 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11795 if (TA && !TA->isDefaultVersion()) 11796 return false; 11797 } 11798 11799 // If any candidate has a placeholder return type, trigger its deduction 11800 // now. 11801 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11802 Complain)) { 11803 HasComplained |= Complain; 11804 return false; 11805 } 11806 11807 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11808 return false; 11809 11810 // If we're in C, we need to support types that aren't exactly identical. 11811 if (!S.getLangOpts().CPlusPlus || 11812 candidateHasExactlyCorrectType(FunDecl)) { 11813 Matches.push_back(std::make_pair( 11814 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11815 FoundNonTemplateFunction = true; 11816 return true; 11817 } 11818 } 11819 11820 return false; 11821 } 11822 11823 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11824 bool Ret = false; 11825 11826 // If the overload expression doesn't have the form of a pointer to 11827 // member, don't try to convert it to a pointer-to-member type. 11828 if (IsInvalidFormOfPointerToMemberFunction()) 11829 return false; 11830 11831 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11832 E = OvlExpr->decls_end(); 11833 I != E; ++I) { 11834 // Look through any using declarations to find the underlying function. 11835 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11836 11837 // C++ [over.over]p3: 11838 // Non-member functions and static member functions match 11839 // targets of type "pointer-to-function" or "reference-to-function." 11840 // Nonstatic member functions match targets of 11841 // type "pointer-to-member-function." 11842 // Note that according to DR 247, the containing class does not matter. 11843 if (FunctionTemplateDecl *FunctionTemplate 11844 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11845 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11846 Ret = true; 11847 } 11848 // If we have explicit template arguments supplied, skip non-templates. 11849 else if (!OvlExpr->hasExplicitTemplateArgs() && 11850 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11851 Ret = true; 11852 } 11853 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11853, __PRETTY_FUNCTION__))
; 11854 return Ret; 11855 } 11856 11857 void EliminateAllExceptMostSpecializedTemplate() { 11858 // [...] and any given function template specialization F1 is 11859 // eliminated if the set contains a second function template 11860 // specialization whose function template is more specialized 11861 // than the function template of F1 according to the partial 11862 // ordering rules of 14.5.5.2. 11863 11864 // The algorithm specified above is quadratic. We instead use a 11865 // two-pass algorithm (similar to the one used to identify the 11866 // best viable function in an overload set) that identifies the 11867 // best function template (if it exists). 11868 11869 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11870 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11871 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11872 11873 // TODO: It looks like FailedCandidates does not serve much purpose 11874 // here, since the no_viable diagnostic has index 0. 11875 UnresolvedSetIterator Result = S.getMostSpecialized( 11876 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11877 SourceExpr->getBeginLoc(), S.PDiag(), 11878 S.PDiag(diag::err_addr_ovl_ambiguous) 11879 << Matches[0].second->getDeclName(), 11880 S.PDiag(diag::note_ovl_candidate) 11881 << (unsigned)oc_function << (unsigned)ocs_described_template, 11882 Complain, TargetFunctionType); 11883 11884 if (Result != MatchesCopy.end()) { 11885 // Make it the first and only element 11886 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11887 Matches[0].second = cast<FunctionDecl>(*Result); 11888 Matches.resize(1); 11889 } else 11890 HasComplained |= Complain; 11891 } 11892 11893 void EliminateAllTemplateMatches() { 11894 // [...] any function template specializations in the set are 11895 // eliminated if the set also contains a non-template function, [...] 11896 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11897 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11898 ++I; 11899 else { 11900 Matches[I] = Matches[--N]; 11901 Matches.resize(N); 11902 } 11903 } 11904 } 11905 11906 void EliminateSuboptimalCudaMatches() { 11907 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11908 } 11909 11910public: 11911 void ComplainNoMatchesFound() const { 11912 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11912, __PRETTY_FUNCTION__))
; 11913 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11914 << OvlExpr->getName() << TargetFunctionType 11915 << OvlExpr->getSourceRange(); 11916 if (FailedCandidates.empty()) 11917 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11918 /*TakingAddress=*/true); 11919 else { 11920 // We have some deduction failure messages. Use them to diagnose 11921 // the function templates, and diagnose the non-template candidates 11922 // normally. 11923 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11924 IEnd = OvlExpr->decls_end(); 11925 I != IEnd; ++I) 11926 if (FunctionDecl *Fun = 11927 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11928 if (!functionHasPassObjectSizeParams(Fun)) 11929 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11930 /*TakingAddress=*/true); 11931 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11932 } 11933 } 11934 11935 bool IsInvalidFormOfPointerToMemberFunction() const { 11936 return TargetTypeIsNonStaticMemberFunction && 11937 !OvlExprInfo.HasFormOfMemberPointer; 11938 } 11939 11940 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11941 // TODO: Should we condition this on whether any functions might 11942 // have matched, or is it more appropriate to do that in callers? 11943 // TODO: a fixit wouldn't hurt. 11944 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11945 << TargetType << OvlExpr->getSourceRange(); 11946 } 11947 11948 bool IsStaticMemberFunctionFromBoundPointer() const { 11949 return StaticMemberFunctionFromBoundPointer; 11950 } 11951 11952 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11953 S.Diag(OvlExpr->getBeginLoc(), 11954 diag::err_invalid_form_pointer_member_function) 11955 << OvlExpr->getSourceRange(); 11956 } 11957 11958 void ComplainOfInvalidConversion() const { 11959 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11960 << OvlExpr->getName() << TargetType; 11961 } 11962 11963 void ComplainMultipleMatchesFound() const { 11964 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11964, __PRETTY_FUNCTION__))
; 11965 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11966 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11967 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11968 /*TakingAddress=*/true); 11969 } 11970 11971 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11972 11973 int getNumMatches() const { return Matches.size(); } 11974 11975 FunctionDecl* getMatchingFunctionDecl() const { 11976 if (Matches.size() != 1) return nullptr; 11977 return Matches[0].second; 11978 } 11979 11980 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11981 if (Matches.size() != 1) return nullptr; 11982 return &Matches[0].first; 11983 } 11984}; 11985} 11986 11987/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11988/// an overloaded function (C++ [over.over]), where @p From is an 11989/// expression with overloaded function type and @p ToType is the type 11990/// we're trying to resolve to. For example: 11991/// 11992/// @code 11993/// int f(double); 11994/// int f(int); 11995/// 11996/// int (*pfd)(double) = f; // selects f(double) 11997/// @endcode 11998/// 11999/// This routine returns the resulting FunctionDecl if it could be 12000/// resolved, and NULL otherwise. When @p Complain is true, this 12001/// routine will emit diagnostics if there is an error. 12002FunctionDecl * 12003Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12004 QualType TargetType, 12005 bool Complain, 12006 DeclAccessPair &FoundResult, 12007 bool *pHadMultipleCandidates) { 12008 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12008, __PRETTY_FUNCTION__))
; 12009 12010 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12011 Complain); 12012 int NumMatches = Resolver.getNumMatches(); 12013 FunctionDecl *Fn = nullptr; 12014 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12015 if (NumMatches == 0 && ShouldComplain) { 12016 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12017 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12018 else 12019 Resolver.ComplainNoMatchesFound(); 12020 } 12021 else if (NumMatches > 1 && ShouldComplain) 12022 Resolver.ComplainMultipleMatchesFound(); 12023 else if (NumMatches == 1) { 12024 Fn = Resolver.getMatchingFunctionDecl(); 12025 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12025, __PRETTY_FUNCTION__))
; 12026 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12027 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12028 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12029 if (Complain) { 12030 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12031 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12032 else 12033 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12034 } 12035 } 12036 12037 if (pHadMultipleCandidates) 12038 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12039 return Fn; 12040} 12041 12042/// Given an expression that refers to an overloaded function, try to 12043/// resolve that function to a single function that can have its address taken. 12044/// This will modify `Pair` iff it returns non-null. 12045/// 12046/// This routine can only succeed if from all of the candidates in the overload 12047/// set for SrcExpr that can have their addresses taken, there is one candidate 12048/// that is more constrained than the rest. 12049FunctionDecl * 12050Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12051 OverloadExpr::FindResult R = OverloadExpr::find(E); 12052 OverloadExpr *Ovl = R.Expression; 12053 bool IsResultAmbiguous = false; 12054 FunctionDecl *Result = nullptr; 12055 DeclAccessPair DAP; 12056 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12057 12058 auto CheckMoreConstrained = 12059 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12060 SmallVector<const Expr *, 1> AC1, AC2; 12061 FD1->getAssociatedConstraints(AC1); 12062 FD2->getAssociatedConstraints(AC2); 12063 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12064 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12065 return None; 12066 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12067 return None; 12068 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12069 return None; 12070 return AtLeastAsConstrained1; 12071 }; 12072 12073 // Don't use the AddressOfResolver because we're specifically looking for 12074 // cases where we have one overload candidate that lacks 12075 // enable_if/pass_object_size/... 12076 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12077 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12078 if (!FD) 12079 return nullptr; 12080 12081 if (!checkAddressOfFunctionIsAvailable(FD)) 12082 continue; 12083 12084 // We have more than one result - see if it is more constrained than the 12085 // previous one. 12086 if (Result) { 12087 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12088 Result); 12089 if (!MoreConstrainedThanPrevious) { 12090 IsResultAmbiguous = true; 12091 AmbiguousDecls.push_back(FD); 12092 continue; 12093 } 12094 if (!*MoreConstrainedThanPrevious) 12095 continue; 12096 // FD is more constrained - replace Result with it. 12097 } 12098 IsResultAmbiguous = false; 12099 DAP = I.getPair(); 12100 Result = FD; 12101 } 12102 12103 if (IsResultAmbiguous) 12104 return nullptr; 12105 12106 if (Result) { 12107 SmallVector<const Expr *, 1> ResultAC; 12108 // We skipped over some ambiguous declarations which might be ambiguous with 12109 // the selected result. 12110 for (FunctionDecl *Skipped : AmbiguousDecls) 12111 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12112 return nullptr; 12113 Pair = DAP; 12114 } 12115 return Result; 12116} 12117 12118/// Given an overloaded function, tries to turn it into a non-overloaded 12119/// function reference using resolveAddressOfSingleOverloadCandidate. This 12120/// will perform access checks, diagnose the use of the resultant decl, and, if 12121/// requested, potentially perform a function-to-pointer decay. 12122/// 12123/// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12124/// Otherwise, returns true. This may emit diagnostics and return true. 12125bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12126 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12127 Expr *E = SrcExpr.get(); 12128 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12128, __PRETTY_FUNCTION__))
; 12129 12130 DeclAccessPair DAP; 12131 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12132 if (!Found || Found->isCPUDispatchMultiVersion() || 12133 Found->isCPUSpecificMultiVersion()) 12134 return false; 12135 12136 // Emitting multiple diagnostics for a function that is both inaccessible and 12137 // unavailable is consistent with our behavior elsewhere. So, always check 12138 // for both. 12139 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12140 CheckAddressOfMemberAccess(E, DAP); 12141 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12142 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12143 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12144 else 12145 SrcExpr = Fixed; 12146 return true; 12147} 12148 12149/// Given an expression that refers to an overloaded function, try to 12150/// resolve that overloaded function expression down to a single function. 12151/// 12152/// This routine can only resolve template-ids that refer to a single function 12153/// template, where that template-id refers to a single template whose template 12154/// arguments are either provided by the template-id or have defaults, 12155/// as described in C++0x [temp.arg.explicit]p3. 12156/// 12157/// If no template-ids are found, no diagnostics are emitted and NULL is 12158/// returned. 12159FunctionDecl * 12160Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12161 bool Complain, 12162 DeclAccessPair *FoundResult) { 12163 // C++ [over.over]p1: 12164 // [...] [Note: any redundant set of parentheses surrounding the 12165 // overloaded function name is ignored (5.1). ] 12166 // C++ [over.over]p1: 12167 // [...] The overloaded function name can be preceded by the & 12168 // operator. 12169 12170 // If we didn't actually find any template-ids, we're done. 12171 if (!ovl->hasExplicitTemplateArgs()) 12172 return nullptr; 12173 12174 TemplateArgumentListInfo ExplicitTemplateArgs; 12175 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12176 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12177 12178 // Look through all of the overloaded functions, searching for one 12179 // whose type matches exactly. 12180 FunctionDecl *Matched = nullptr; 12181 for (UnresolvedSetIterator I = ovl->decls_begin(), 12182 E = ovl->decls_end(); I != E; ++I) { 12183 // C++0x [temp.arg.explicit]p3: 12184 // [...] In contexts where deduction is done and fails, or in contexts 12185 // where deduction is not done, if a template argument list is 12186 // specified and it, along with any default template arguments, 12187 // identifies a single function template specialization, then the 12188 // template-id is an lvalue for the function template specialization. 12189 FunctionTemplateDecl *FunctionTemplate 12190 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12191 12192 // C++ [over.over]p2: 12193 // If the name is a function template, template argument deduction is 12194 // done (14.8.2.2), and if the argument deduction succeeds, the 12195 // resulting template argument list is used to generate a single 12196 // function template specialization, which is added to the set of 12197 // overloaded functions considered. 12198 FunctionDecl *Specialization = nullptr; 12199 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12200 if (TemplateDeductionResult Result 12201 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12202 Specialization, Info, 12203 /*IsAddressOfFunction*/true)) { 12204 // Make a note of the failed deduction for diagnostics. 12205 // TODO: Actually use the failed-deduction info? 12206 FailedCandidates.addCandidate() 12207 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12208 MakeDeductionFailureInfo(Context, Result, Info)); 12209 continue; 12210 } 12211 12212 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12212, __PRETTY_FUNCTION__))
; 12213 12214 // Multiple matches; we can't resolve to a single declaration. 12215 if (Matched) { 12216 if (Complain) { 12217 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12218 << ovl->getName(); 12219 NoteAllOverloadCandidates(ovl); 12220 } 12221 return nullptr; 12222 } 12223 12224 Matched = Specialization; 12225 if (FoundResult) *FoundResult = I.getPair(); 12226 } 12227 12228 if (Matched && 12229 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12230 return nullptr; 12231 12232 return Matched; 12233} 12234 12235// Resolve and fix an overloaded expression that can be resolved 12236// because it identifies a single function template specialization. 12237// 12238// Last three arguments should only be supplied if Complain = true 12239// 12240// Return true if it was logically possible to so resolve the 12241// expression, regardless of whether or not it succeeded. Always 12242// returns true if 'complain' is set. 12243bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12244 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12245 bool complain, SourceRange OpRangeForComplaining, 12246 QualType DestTypeForComplaining, 12247 unsigned DiagIDForComplaining) { 12248 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12248, __PRETTY_FUNCTION__))
; 12249 12250 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12251 12252 DeclAccessPair found; 12253 ExprResult SingleFunctionExpression; 12254 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12255 ovl.Expression, /*complain*/ false, &found)) { 12256 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12257 SrcExpr = ExprError(); 12258 return true; 12259 } 12260 12261 // It is only correct to resolve to an instance method if we're 12262 // resolving a form that's permitted to be a pointer to member. 12263 // Otherwise we'll end up making a bound member expression, which 12264 // is illegal in all the contexts we resolve like this. 12265 if (!ovl.HasFormOfMemberPointer && 12266 isa<CXXMethodDecl>(fn) && 12267 cast<CXXMethodDecl>(fn)->isInstance()) { 12268 if (!complain) return false; 12269 12270 Diag(ovl.Expression->getExprLoc(), 12271 diag::err_bound_member_function) 12272 << 0 << ovl.Expression->getSourceRange(); 12273 12274 // TODO: I believe we only end up here if there's a mix of 12275 // static and non-static candidates (otherwise the expression 12276 // would have 'bound member' type, not 'overload' type). 12277 // Ideally we would note which candidate was chosen and why 12278 // the static candidates were rejected. 12279 SrcExpr = ExprError(); 12280 return true; 12281 } 12282 12283 // Fix the expression to refer to 'fn'. 12284 SingleFunctionExpression = 12285 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12286 12287 // If desired, do function-to-pointer decay. 12288 if (doFunctionPointerConverion) { 12289 SingleFunctionExpression = 12290 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12291 if (SingleFunctionExpression.isInvalid()) { 12292 SrcExpr = ExprError(); 12293 return true; 12294 } 12295 } 12296 } 12297 12298 if (!SingleFunctionExpression.isUsable()) { 12299 if (complain) { 12300 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12301 << ovl.Expression->getName() 12302 << DestTypeForComplaining 12303 << OpRangeForComplaining 12304 << ovl.Expression->getQualifierLoc().getSourceRange(); 12305 NoteAllOverloadCandidates(SrcExpr.get()); 12306 12307 SrcExpr = ExprError(); 12308 return true; 12309 } 12310 12311 return false; 12312 } 12313 12314 SrcExpr = SingleFunctionExpression; 12315 return true; 12316} 12317 12318/// Add a single candidate to the overload set. 12319static void AddOverloadedCallCandidate(Sema &S, 12320 DeclAccessPair FoundDecl, 12321 TemplateArgumentListInfo *ExplicitTemplateArgs, 12322 ArrayRef<Expr *> Args, 12323 OverloadCandidateSet &CandidateSet, 12324 bool PartialOverloading, 12325 bool KnownValid) { 12326 NamedDecl *Callee = FoundDecl.getDecl(); 12327 if (isa<UsingShadowDecl>(Callee)) 12328 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12329 12330 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12331 if (ExplicitTemplateArgs) { 12332 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12332, __PRETTY_FUNCTION__))
; 12333 return; 12334 } 12335 // Prevent ill-formed function decls to be added as overload candidates. 12336 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12337 return; 12338 12339 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12340 /*SuppressUserConversions=*/false, 12341 PartialOverloading); 12342 return; 12343 } 12344 12345 if (FunctionTemplateDecl *FuncTemplate 12346 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12347 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12348 ExplicitTemplateArgs, Args, CandidateSet, 12349 /*SuppressUserConversions=*/false, 12350 PartialOverloading); 12351 return; 12352 } 12353 12354 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12354, __PRETTY_FUNCTION__))
; 12355} 12356 12357/// Add the overload candidates named by callee and/or found by argument 12358/// dependent lookup to the given overload set. 12359void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12360 ArrayRef<Expr *> Args, 12361 OverloadCandidateSet &CandidateSet, 12362 bool PartialOverloading) { 12363 12364#ifndef NDEBUG 12365 // Verify that ArgumentDependentLookup is consistent with the rules 12366 // in C++0x [basic.lookup.argdep]p3: 12367 // 12368 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12369 // and let Y be the lookup set produced by argument dependent 12370 // lookup (defined as follows). If X contains 12371 // 12372 // -- a declaration of a class member, or 12373 // 12374 // -- a block-scope function declaration that is not a 12375 // using-declaration, or 12376 // 12377 // -- a declaration that is neither a function or a function 12378 // template 12379 // 12380 // then Y is empty. 12381 12382 if (ULE->requiresADL()) { 12383 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12384 E = ULE->decls_end(); I != E; ++I) { 12385 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12385, __PRETTY_FUNCTION__))
; 12386 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
12387 !(*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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
; 12388 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12388, __PRETTY_FUNCTION__))
; 12389 } 12390 } 12391#endif 12392 12393 // It would be nice to avoid this copy. 12394 TemplateArgumentListInfo TABuffer; 12395 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12396 if (ULE->hasExplicitTemplateArgs()) { 12397 ULE->copyTemplateArgumentsInto(TABuffer); 12398 ExplicitTemplateArgs = &TABuffer; 12399 } 12400 12401 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12402 E = ULE->decls_end(); I != E; ++I) 12403 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12404 CandidateSet, PartialOverloading, 12405 /*KnownValid*/ true); 12406 12407 if (ULE->requiresADL()) 12408 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12409 Args, ExplicitTemplateArgs, 12410 CandidateSet, PartialOverloading); 12411} 12412 12413/// Determine whether a declaration with the specified name could be moved into 12414/// a different namespace. 12415static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12416 switch (Name.getCXXOverloadedOperator()) { 12417 case OO_New: case OO_Array_New: 12418 case OO_Delete: case OO_Array_Delete: 12419 return false; 12420 12421 default: 12422 return true; 12423 } 12424} 12425 12426/// Attempt to recover from an ill-formed use of a non-dependent name in a 12427/// template, where the non-dependent name was declared after the template 12428/// was defined. This is common in code written for a compilers which do not 12429/// correctly implement two-stage name lookup. 12430/// 12431/// Returns true if a viable candidate was found and a diagnostic was issued. 12432static bool 12433DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12434 const CXXScopeSpec &SS, LookupResult &R, 12435 OverloadCandidateSet::CandidateSetKind CSK, 12436 TemplateArgumentListInfo *ExplicitTemplateArgs, 12437 ArrayRef<Expr *> Args, 12438 bool *DoDiagnoseEmptyLookup = nullptr) { 12439 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12440 return false; 12441 12442 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12443 if (DC->isTransparentContext()) 12444 continue; 12445 12446 SemaRef.LookupQualifiedName(R, DC); 12447 12448 if (!R.empty()) { 12449 R.suppressDiagnostics(); 12450 12451 if (isa<CXXRecordDecl>(DC)) { 12452 // Don't diagnose names we find in classes; we get much better 12453 // diagnostics for these from DiagnoseEmptyLookup. 12454 R.clear(); 12455 if (DoDiagnoseEmptyLookup) 12456 *DoDiagnoseEmptyLookup = true; 12457 return false; 12458 } 12459 12460 OverloadCandidateSet Candidates(FnLoc, CSK); 12461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12462 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12463 ExplicitTemplateArgs, Args, 12464 Candidates, false, /*KnownValid*/ false); 12465 12466 OverloadCandidateSet::iterator Best; 12467 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12468 // No viable functions. Don't bother the user with notes for functions 12469 // which don't work and shouldn't be found anyway. 12470 R.clear(); 12471 return false; 12472 } 12473 12474 // Find the namespaces where ADL would have looked, and suggest 12475 // declaring the function there instead. 12476 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12477 Sema::AssociatedClassSet AssociatedClasses; 12478 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12479 AssociatedNamespaces, 12480 AssociatedClasses); 12481 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12482 if (canBeDeclaredInNamespace(R.getLookupName())) { 12483 DeclContext *Std = SemaRef.getStdNamespace(); 12484 for (Sema::AssociatedNamespaceSet::iterator 12485 it = AssociatedNamespaces.begin(), 12486 end = AssociatedNamespaces.end(); it != end; ++it) { 12487 // Never suggest declaring a function within namespace 'std'. 12488 if (Std && Std->Encloses(*it)) 12489 continue; 12490 12491 // Never suggest declaring a function within a namespace with a 12492 // reserved name, like __gnu_cxx. 12493 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12494 if (NS && 12495 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12496 continue; 12497 12498 SuggestedNamespaces.insert(*it); 12499 } 12500 } 12501 12502 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12503 << R.getLookupName(); 12504 if (SuggestedNamespaces.empty()) { 12505 SemaRef.Diag(Best->Function->getLocation(), 12506 diag::note_not_found_by_two_phase_lookup) 12507 << R.getLookupName() << 0; 12508 } else if (SuggestedNamespaces.size() == 1) { 12509 SemaRef.Diag(Best->Function->getLocation(), 12510 diag::note_not_found_by_two_phase_lookup) 12511 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12512 } else { 12513 // FIXME: It would be useful to list the associated namespaces here, 12514 // but the diagnostics infrastructure doesn't provide a way to produce 12515 // a localized representation of a list of items. 12516 SemaRef.Diag(Best->Function->getLocation(), 12517 diag::note_not_found_by_two_phase_lookup) 12518 << R.getLookupName() << 2; 12519 } 12520 12521 // Try to recover by calling this function. 12522 return true; 12523 } 12524 12525 R.clear(); 12526 } 12527 12528 return false; 12529} 12530 12531/// Attempt to recover from ill-formed use of a non-dependent operator in a 12532/// template, where the non-dependent operator was declared after the template 12533/// was defined. 12534/// 12535/// Returns true if a viable candidate was found and a diagnostic was issued. 12536static bool 12537DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12538 SourceLocation OpLoc, 12539 ArrayRef<Expr *> Args) { 12540 DeclarationName OpName = 12541 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12542 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12543 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12544 OverloadCandidateSet::CSK_Operator, 12545 /*ExplicitTemplateArgs=*/nullptr, Args); 12546} 12547 12548namespace { 12549class BuildRecoveryCallExprRAII { 12550 Sema &SemaRef; 12551public: 12552 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12553 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12553, __PRETTY_FUNCTION__))
; 12554 SemaRef.IsBuildingRecoveryCallExpr = true; 12555 } 12556 12557 ~BuildRecoveryCallExprRAII() { 12558 SemaRef.IsBuildingRecoveryCallExpr = false; 12559 } 12560}; 12561 12562} 12563 12564/// Attempts to recover from a call where no functions were found. 12565/// 12566/// Returns true if new candidates were found. 12567static ExprResult 12568BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12569 UnresolvedLookupExpr *ULE, 12570 SourceLocation LParenLoc, 12571 MutableArrayRef<Expr *> Args, 12572 SourceLocation RParenLoc, 12573 bool EmptyLookup, bool AllowTypoCorrection) { 12574 // Do not try to recover if it is already building a recovery call. 12575 // This stops infinite loops for template instantiations like 12576 // 12577 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12578 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12579 // 12580 if (SemaRef.IsBuildingRecoveryCallExpr) 12581 return ExprError(); 12582 BuildRecoveryCallExprRAII RCE(SemaRef); 12583 12584 CXXScopeSpec SS; 12585 SS.Adopt(ULE->getQualifierLoc()); 12586 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12587 12588 TemplateArgumentListInfo TABuffer; 12589 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12590 if (ULE->hasExplicitTemplateArgs()) { 12591 ULE->copyTemplateArgumentsInto(TABuffer); 12592 ExplicitTemplateArgs = &TABuffer; 12593 } 12594 12595 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12596 Sema::LookupOrdinaryName); 12597 bool DoDiagnoseEmptyLookup = EmptyLookup; 12598 if (!DiagnoseTwoPhaseLookup( 12599 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12600 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12601 NoTypoCorrectionCCC NoTypoValidator{}; 12602 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12603 ExplicitTemplateArgs != nullptr, 12604 dyn_cast<MemberExpr>(Fn)); 12605 CorrectionCandidateCallback &Validator = 12606 AllowTypoCorrection 12607 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12608 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12609 if (!DoDiagnoseEmptyLookup || 12610 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12611 Args)) 12612 return ExprError(); 12613 } 12614 12615 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12615, __PRETTY_FUNCTION__))
; 12616 12617 // If recovery created an ambiguity, just bail out. 12618 if (R.isAmbiguous()) { 12619 R.suppressDiagnostics(); 12620 return ExprError(); 12621 } 12622 12623 // Build an implicit member call if appropriate. Just drop the 12624 // casts and such from the call, we don't really care. 12625 ExprResult NewFn = ExprError(); 12626 if ((*R.begin())->isCXXClassMember()) 12627 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12628 ExplicitTemplateArgs, S); 12629 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12630 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12631 ExplicitTemplateArgs); 12632 else 12633 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12634 12635 if (NewFn.isInvalid()) 12636 return ExprError(); 12637 12638 // This shouldn't cause an infinite loop because we're giving it 12639 // an expression with viable lookup results, which should never 12640 // end up here. 12641 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12642 MultiExprArg(Args.data(), Args.size()), 12643 RParenLoc); 12644} 12645 12646/// Constructs and populates an OverloadedCandidateSet from 12647/// the given function. 12648/// \returns true when an the ExprResult output parameter has been set. 12649bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12650 UnresolvedLookupExpr *ULE, 12651 MultiExprArg Args, 12652 SourceLocation RParenLoc, 12653 OverloadCandidateSet *CandidateSet, 12654 ExprResult *Result) { 12655#ifndef NDEBUG 12656 if (ULE->requiresADL()) { 12657 // To do ADL, we must have found an unqualified name. 12658 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12658, __PRETTY_FUNCTION__))
; 12659 12660 // We don't perform ADL for implicit declarations of builtins. 12661 // Verify that this was correctly set up. 12662 FunctionDecl *F; 12663 if (ULE->decls_begin() != ULE->decls_end() && 12664 ULE->decls_begin() + 1 == ULE->decls_end() && 12665 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12666 F->getBuiltinID() && F->isImplicit()) 12667 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12667)
; 12668 12669 // We don't perform ADL in C. 12670 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12670, __PRETTY_FUNCTION__))
; 12671 } 12672#endif 12673 12674 UnbridgedCastsSet UnbridgedCasts; 12675 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12676 *Result = ExprError(); 12677 return true; 12678 } 12679 12680 // Add the functions denoted by the callee to the set of candidate 12681 // functions, including those from argument-dependent lookup. 12682 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12683 12684 if (getLangOpts().MSVCCompat && 12685 CurContext->isDependentContext() && !isSFINAEContext() && 12686 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12687 12688 OverloadCandidateSet::iterator Best; 12689 if (CandidateSet->empty() || 12690 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12691 OR_No_Viable_Function) { 12692 // In Microsoft mode, if we are inside a template class member function 12693 // then create a type dependent CallExpr. The goal is to postpone name 12694 // lookup to instantiation time to be able to search into type dependent 12695 // base classes. 12696 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12697 VK_RValue, RParenLoc); 12698 CE->setTypeDependent(true); 12699 CE->setValueDependent(true); 12700 CE->setInstantiationDependent(true); 12701 *Result = CE; 12702 return true; 12703 } 12704 } 12705 12706 if (CandidateSet->empty()) 12707 return false; 12708 12709 UnbridgedCasts.restore(); 12710 return false; 12711} 12712 12713/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12714/// the completed call expression. If overload resolution fails, emits 12715/// diagnostics and returns ExprError() 12716static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12717 UnresolvedLookupExpr *ULE, 12718 SourceLocation LParenLoc, 12719 MultiExprArg Args, 12720 SourceLocation RParenLoc, 12721 Expr *ExecConfig, 12722 OverloadCandidateSet *CandidateSet, 12723 OverloadCandidateSet::iterator *Best, 12724 OverloadingResult OverloadResult, 12725 bool AllowTypoCorrection) { 12726 if (CandidateSet->empty()) 12727 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12728 RParenLoc, /*EmptyLookup=*/true, 12729 AllowTypoCorrection); 12730 12731 switch (OverloadResult) { 12732 case OR_Success: { 12733 FunctionDecl *FDecl = (*Best)->Function; 12734 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12735 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12736 return ExprError(); 12737 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12738 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12739 ExecConfig, /*IsExecConfig=*/false, 12740 (*Best)->IsADLCandidate); 12741 } 12742 12743 case OR_No_Viable_Function: { 12744 // Try to recover by looking for viable functions which the user might 12745 // have meant to call. 12746 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12747 Args, RParenLoc, 12748 /*EmptyLookup=*/false, 12749 AllowTypoCorrection); 12750 if (!Recovery.isInvalid()) 12751 return Recovery; 12752 12753 // If the user passes in a function that we can't take the address of, we 12754 // generally end up emitting really bad error messages. Here, we attempt to 12755 // emit better ones. 12756 for (const Expr *Arg : Args) { 12757 if (!Arg->getType()->isFunctionType()) 12758 continue; 12759 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12760 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12761 if (FD && 12762 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12763 Arg->getExprLoc())) 12764 return ExprError(); 12765 } 12766 } 12767 12768 CandidateSet->NoteCandidates( 12769 PartialDiagnosticAt( 12770 Fn->getBeginLoc(), 12771 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12772 << ULE->getName() << Fn->getSourceRange()), 12773 SemaRef, OCD_AllCandidates, Args); 12774 break; 12775 } 12776 12777 case OR_Ambiguous: 12778 CandidateSet->NoteCandidates( 12779 PartialDiagnosticAt(Fn->getBeginLoc(), 12780 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12781 << ULE->getName() << Fn->getSourceRange()), 12782 SemaRef, OCD_AmbiguousCandidates, Args); 12783 break; 12784 12785 case OR_Deleted: { 12786 CandidateSet->NoteCandidates( 12787 PartialDiagnosticAt(Fn->getBeginLoc(), 12788 SemaRef.PDiag(diag::err_ovl_deleted_call) 12789 << ULE->getName() << Fn->getSourceRange()), 12790 SemaRef, OCD_AllCandidates, Args); 12791 12792 // We emitted an error for the unavailable/deleted function call but keep 12793 // the call in the AST. 12794 FunctionDecl *FDecl = (*Best)->Function; 12795 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12796 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12797 ExecConfig, /*IsExecConfig=*/false, 12798 (*Best)->IsADLCandidate); 12799 } 12800 } 12801 12802 // Overload resolution failed. 12803 return ExprError(); 12804} 12805 12806static void markUnaddressableCandidatesUnviable(Sema &S, 12807 OverloadCandidateSet &CS) { 12808 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12809 if (I->Viable && 12810 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12811 I->Viable = false; 12812 I->FailureKind = ovl_fail_addr_not_available; 12813 } 12814 } 12815} 12816 12817/// BuildOverloadedCallExpr - Given the call expression that calls Fn 12818/// (which eventually refers to the declaration Func) and the call 12819/// arguments Args/NumArgs, attempt to resolve the function call down 12820/// to a specific function. If overload resolution succeeds, returns 12821/// the call expression produced by overload resolution. 12822/// Otherwise, emits diagnostics and returns ExprError. 12823ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12824 UnresolvedLookupExpr *ULE, 12825 SourceLocation LParenLoc, 12826 MultiExprArg Args, 12827 SourceLocation RParenLoc, 12828 Expr *ExecConfig, 12829 bool AllowTypoCorrection, 12830 bool CalleesAddressIsTaken) { 12831 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12832 OverloadCandidateSet::CSK_Normal); 12833 ExprResult result; 12834 12835 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12836 &result)) 12837 return result; 12838 12839 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12840 // functions that aren't addressible are considered unviable. 12841 if (CalleesAddressIsTaken) 12842 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12843 12844 OverloadCandidateSet::iterator Best; 12845 OverloadingResult OverloadResult = 12846 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12847 12848 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12849 ExecConfig, &CandidateSet, &Best, 12850 OverloadResult, AllowTypoCorrection); 12851} 12852 12853static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12854 return Functions.size() > 1 || 12855 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12856} 12857 12858/// Create a unary operation that may resolve to an overloaded 12859/// operator. 12860/// 12861/// \param OpLoc The location of the operator itself (e.g., '*'). 12862/// 12863/// \param Opc The UnaryOperatorKind that describes this operator. 12864/// 12865/// \param Fns The set of non-member functions that will be 12866/// considered by overload resolution. The caller needs to build this 12867/// set based on the context using, e.g., 12868/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12869/// set should not contain any member functions; those will be added 12870/// by CreateOverloadedUnaryOp(). 12871/// 12872/// \param Input The input argument. 12873ExprResult 12874Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12875 const UnresolvedSetImpl &Fns, 12876 Expr *Input, bool PerformADL) { 12877 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12878 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12878, __PRETTY_FUNCTION__))
; 12879 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12880 // TODO: provide better source location info. 12881 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12882 12883 if (checkPlaceholderForOverload(*this, Input)) 12884 return ExprError(); 12885 12886 Expr *Args[2] = { Input, nullptr }; 12887 unsigned NumArgs = 1; 12888 12889 // For post-increment and post-decrement, add the implicit '0' as 12890 // the second argument, so that we know this is a post-increment or 12891 // post-decrement. 12892 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12893 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12894 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12895 SourceLocation()); 12896 NumArgs = 2; 12897 } 12898 12899 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12900 12901 if (Input->isTypeDependent()) { 12902 if (Fns.empty()) 12903 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12904 VK_RValue, OK_Ordinary, OpLoc, false); 12905 12906 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12907 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12908 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12909 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12910 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12911 Context.DependentTy, VK_RValue, OpLoc, 12912 FPOptions()); 12913 } 12914 12915 // Build an empty overload set. 12916 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12917 12918 // Add the candidates from the given function set. 12919 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12920 12921 // Add operator candidates that are member functions. 12922 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12923 12924 // Add candidates from ADL. 12925 if (PerformADL) { 12926 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12927 /*ExplicitTemplateArgs*/nullptr, 12928 CandidateSet); 12929 } 12930 12931 // Add builtin operator candidates. 12932 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12933 12934 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12935 12936 // Perform overload resolution. 12937 OverloadCandidateSet::iterator Best; 12938 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12939 case OR_Success: { 12940 // We found a built-in operator or an overloaded operator. 12941 FunctionDecl *FnDecl = Best->Function; 12942 12943 if (FnDecl) { 12944 Expr *Base = nullptr; 12945 // We matched an overloaded operator. Build a call to that 12946 // operator. 12947 12948 // Convert the arguments. 12949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12950 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12951 12952 ExprResult InputRes = 12953 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12954 Best->FoundDecl, Method); 12955 if (InputRes.isInvalid()) 12956 return ExprError(); 12957 Base = Input = InputRes.get(); 12958 } else { 12959 // Convert the arguments. 12960 ExprResult InputInit 12961 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12962 Context, 12963 FnDecl->getParamDecl(0)), 12964 SourceLocation(), 12965 Input); 12966 if (InputInit.isInvalid()) 12967 return ExprError(); 12968 Input = InputInit.get(); 12969 } 12970 12971 // Build the actual expression node. 12972 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12973 Base, HadMultipleCandidates, 12974 OpLoc); 12975 if (FnExpr.isInvalid()) 12976 return ExprError(); 12977 12978 // Determine the result type. 12979 QualType ResultTy = FnDecl->getReturnType(); 12980 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12981 ResultTy = ResultTy.getNonLValueExprType(Context); 12982 12983 Args[0] = Input; 12984 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12985 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12986 FPOptions(), Best->IsADLCandidate); 12987 12988 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12989 return ExprError(); 12990 12991 if (CheckFunctionCall(FnDecl, TheCall, 12992 FnDecl->getType()->castAs<FunctionProtoType>())) 12993 return ExprError(); 12994 12995 return MaybeBindToTemporary(TheCall); 12996 } else { 12997 // We matched a built-in operator. Convert the arguments, then 12998 // break out so that we will build the appropriate built-in 12999 // operator node. 13000 ExprResult InputRes = PerformImplicitConversion( 13001 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13002 CCK_ForBuiltinOverloadedOp); 13003 if (InputRes.isInvalid()) 13004 return ExprError(); 13005 Input = InputRes.get(); 13006 break; 13007 } 13008 } 13009 13010 case OR_No_Viable_Function: 13011 // This is an erroneous use of an operator which can be overloaded by 13012 // a non-member function. Check for non-member operators which were 13013 // defined too late to be candidates. 13014 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13015 // FIXME: Recover by calling the found function. 13016 return ExprError(); 13017 13018 // No viable function; fall through to handling this as a 13019 // built-in operator, which will produce an error message for us. 13020 break; 13021 13022 case OR_Ambiguous: 13023 CandidateSet.NoteCandidates( 13024 PartialDiagnosticAt(OpLoc, 13025 PDiag(diag::err_ovl_ambiguous_oper_unary) 13026 << UnaryOperator::getOpcodeStr(Opc) 13027 << Input->getType() << Input->getSourceRange()), 13028 *this, OCD_AmbiguousCandidates, ArgsArray, 13029 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13030 return ExprError(); 13031 13032 case OR_Deleted: 13033 CandidateSet.NoteCandidates( 13034 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13035 << UnaryOperator::getOpcodeStr(Opc) 13036 << Input->getSourceRange()), 13037 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13038 OpLoc); 13039 return ExprError(); 13040 } 13041 13042 // Either we found no viable overloaded operator or we matched a 13043 // built-in operator. In either case, fall through to trying to 13044 // build a built-in operation. 13045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13046} 13047 13048/// Perform lookup for an overloaded binary operator. 13049void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13050 OverloadedOperatorKind Op, 13051 const UnresolvedSetImpl &Fns, 13052 ArrayRef<Expr *> Args, bool PerformADL) { 13053 SourceLocation OpLoc = CandidateSet.getLocation(); 13054 13055 OverloadedOperatorKind ExtraOp = 13056 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13057 ? getRewrittenOverloadedOperator(Op) 13058 : OO_None; 13059 13060 // Add the candidates from the given function set. This also adds the 13061 // rewritten candidates using these functions if necessary. 13062 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13063 13064 // Add operator candidates that are member functions. 13065 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13066 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13067 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13068 OverloadCandidateParamOrder::Reversed); 13069 13070 // In C++20, also add any rewritten member candidates. 13071 if (ExtraOp) { 13072 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13073 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13074 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13075 CandidateSet, 13076 OverloadCandidateParamOrder::Reversed); 13077 } 13078 13079 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13080 // performed for an assignment operator (nor for operator[] nor operator->, 13081 // which don't get here). 13082 if (Op != OO_Equal && PerformADL) { 13083 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13084 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13085 /*ExplicitTemplateArgs*/ nullptr, 13086 CandidateSet); 13087 if (ExtraOp) { 13088 DeclarationName ExtraOpName = 13089 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13090 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13091 /*ExplicitTemplateArgs*/ nullptr, 13092 CandidateSet); 13093 } 13094 } 13095 13096 // Add builtin operator candidates. 13097 // 13098 // FIXME: We don't add any rewritten candidates here. This is strictly 13099 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13100 // resulting in our selecting a rewritten builtin candidate. For example: 13101 // 13102 // enum class E { e }; 13103 // bool operator!=(E, E) requires false; 13104 // bool k = E::e != E::e; 13105 // 13106 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13107 // it seems unreasonable to consider rewritten builtin candidates. A core 13108 // issue has been filed proposing to removed this requirement. 13109 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13110} 13111 13112/// Create a binary operation that may resolve to an overloaded 13113/// operator. 13114/// 13115/// \param OpLoc The location of the operator itself (e.g., '+'). 13116/// 13117/// \param Opc The BinaryOperatorKind that describes this operator. 13118/// 13119/// \param Fns The set of non-member functions that will be 13120/// considered by overload resolution. The caller needs to build this 13121/// set based on the context using, e.g., 13122/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13123/// set should not contain any member functions; those will be added 13124/// by CreateOverloadedBinOp(). 13125/// 13126/// \param LHS Left-hand argument. 13127/// \param RHS Right-hand argument. 13128/// \param PerformADL Whether to consider operator candidates found by ADL. 13129/// \param AllowRewrittenCandidates Whether to consider candidates found by 13130/// C++20 operator rewrites. 13131/// \param DefaultedFn If we are synthesizing a defaulted operator function, 13132/// the function in question. Such a function is never a candidate in 13133/// our overload resolution. This also enables synthesizing a three-way 13134/// comparison from < and == as described in C++20 [class.spaceship]p1. 13135ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13136 BinaryOperatorKind Opc, 13137 const UnresolvedSetImpl &Fns, Expr *LHS, 13138 Expr *RHS, bool PerformADL, 13139 bool AllowRewrittenCandidates, 13140 FunctionDecl *DefaultedFn) { 13141 Expr *Args[2] = { LHS, RHS }; 13142 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13143 13144 if (!getLangOpts().CPlusPlus2a) 13145 AllowRewrittenCandidates = false; 13146 13147 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13148 13149 // If either side is type-dependent, create an appropriate dependent 13150 // expression. 13151 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13152 if (Fns.empty()) { 13153 // If there are no functions to store, just build a dependent 13154 // BinaryOperator or CompoundAssignment. 13155 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13156 return new (Context) BinaryOperator( 13157 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 13158 OpLoc, FPFeatures); 13159 13160 return new (Context) CompoundAssignOperator( 13161 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 13162 Context.DependentTy, Context.DependentTy, OpLoc, 13163 FPFeatures); 13164 } 13165 13166 // FIXME: save results of ADL from here? 13167 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13168 // TODO: provide better source location info in DNLoc component. 13169 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13170 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13171 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13172 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13173 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13174 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13175 Context.DependentTy, VK_RValue, OpLoc, 13176 FPFeatures); 13177 } 13178 13179 // Always do placeholder-like conversions on the RHS. 13180 if (checkPlaceholderForOverload(*this, Args[1])) 13181 return ExprError(); 13182 13183 // Do placeholder-like conversion on the LHS; note that we should 13184 // not get here with a PseudoObject LHS. 13185 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13185, __PRETTY_FUNCTION__))
; 13186 if (checkPlaceholderForOverload(*this, Args[0])) 13187 return ExprError(); 13188 13189 // If this is the assignment operator, we only perform overload resolution 13190 // if the left-hand side is a class or enumeration type. This is actually 13191 // a hack. The standard requires that we do overload resolution between the 13192 // various built-in candidates, but as DR507 points out, this can lead to 13193 // problems. So we do it this way, which pretty much follows what GCC does. 13194 // Note that we go the traditional code path for compound assignment forms. 13195 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13196 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13197 13198 // If this is the .* operator, which is not overloadable, just 13199 // create a built-in binary operator. 13200 if (Opc == BO_PtrMemD) 13201 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13202 13203 // Build the overload set. 13204 OverloadCandidateSet CandidateSet( 13205 OpLoc, OverloadCandidateSet::CSK_Operator, 13206 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13207 if (DefaultedFn) 13208 CandidateSet.exclude(DefaultedFn); 13209 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13210 13211 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13212 13213 // Perform overload resolution. 13214 OverloadCandidateSet::iterator Best; 13215 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13216 case OR_Success: { 13217 // We found a built-in operator or an overloaded operator. 13218 FunctionDecl *FnDecl = Best->Function; 13219 13220 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 13221 if (IsReversed) 13222 std::swap(Args[0], Args[1]); 13223 13224 if (FnDecl) { 13225 Expr *Base = nullptr; 13226 // We matched an overloaded operator. Build a call to that 13227 // operator. 13228 13229 OverloadedOperatorKind ChosenOp = 13230 FnDecl->getDeclName().getCXXOverloadedOperator(); 13231 13232 // C++2a [over.match.oper]p9: 13233 // If a rewritten operator== candidate is selected by overload 13234 // resolution for an operator@, its return type shall be cv bool 13235 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13236 !FnDecl->getReturnType()->isBooleanType()) { 13237 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 13238 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13239 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13240 Diag(FnDecl->getLocation(), diag::note_declared_at); 13241 return ExprError(); 13242 } 13243 13244 if (AllowRewrittenCandidates && !IsReversed && 13245 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 13246 // We could have reversed this operator, but didn't. Check if the 13247 // reversed form was a viable candidate, and if so, if it had a 13248 // better conversion for either parameter. If so, this call is 13249 // formally ambiguous, and allowing it is an extension. 13250 for (OverloadCandidate &Cand : CandidateSet) { 13251 if (Cand.Viable && Cand.Function == FnDecl && 13252 Cand.RewriteKind & CRK_Reversed) { 13253 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13254 if (CompareImplicitConversionSequences( 13255 *this, OpLoc, Cand.Conversions[ArgIdx], 13256 Best->Conversions[ArgIdx]) == 13257 ImplicitConversionSequence::Better) { 13258 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13259 << BinaryOperator::getOpcodeStr(Opc) 13260 << Args[0]->getType() << Args[1]->getType() 13261 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13262 Diag(FnDecl->getLocation(), 13263 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13264 } 13265 } 13266 break; 13267 } 13268 } 13269 } 13270 13271 // Convert the arguments. 13272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13273 // Best->Access is only meaningful for class members. 13274 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13275 13276 ExprResult Arg1 = 13277 PerformCopyInitialization( 13278 InitializedEntity::InitializeParameter(Context, 13279 FnDecl->getParamDecl(0)), 13280 SourceLocation(), Args[1]); 13281 if (Arg1.isInvalid()) 13282 return ExprError(); 13283 13284 ExprResult Arg0 = 13285 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13286 Best->FoundDecl, Method); 13287 if (Arg0.isInvalid()) 13288 return ExprError(); 13289 Base = Args[0] = Arg0.getAs<Expr>(); 13290 Args[1] = RHS = Arg1.getAs<Expr>(); 13291 } else { 13292 // Convert the arguments. 13293 ExprResult Arg0 = PerformCopyInitialization( 13294 InitializedEntity::InitializeParameter(Context, 13295 FnDecl->getParamDecl(0)), 13296 SourceLocation(), Args[0]); 13297 if (Arg0.isInvalid()) 13298 return ExprError(); 13299 13300 ExprResult Arg1 = 13301 PerformCopyInitialization( 13302 InitializedEntity::InitializeParameter(Context, 13303 FnDecl->getParamDecl(1)), 13304 SourceLocation(), Args[1]); 13305 if (Arg1.isInvalid()) 13306 return ExprError(); 13307 Args[0] = LHS = Arg0.getAs<Expr>(); 13308 Args[1] = RHS = Arg1.getAs<Expr>(); 13309 } 13310 13311 // Build the actual expression node. 13312 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13313 Best->FoundDecl, Base, 13314 HadMultipleCandidates, OpLoc); 13315 if (FnExpr.isInvalid()) 13316 return ExprError(); 13317 13318 // Determine the result type. 13319 QualType ResultTy = FnDecl->getReturnType(); 13320 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13321 ResultTy = ResultTy.getNonLValueExprType(Context); 13322 13323 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13324 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13325 FPFeatures, Best->IsADLCandidate); 13326 13327 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13328 FnDecl)) 13329 return ExprError(); 13330 13331 ArrayRef<const Expr *> ArgsArray(Args, 2); 13332 const Expr *ImplicitThis = nullptr; 13333 // Cut off the implicit 'this'. 13334 if (isa<CXXMethodDecl>(FnDecl)) { 13335 ImplicitThis = ArgsArray[0]; 13336 ArgsArray = ArgsArray.slice(1); 13337 } 13338 13339 // Check for a self move. 13340 if (Op == OO_Equal) 13341 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13342 13343 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13344 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13345 VariadicDoesNotApply); 13346 13347 ExprResult R = MaybeBindToTemporary(TheCall); 13348 if (R.isInvalid()) 13349 return ExprError(); 13350 13351 // For a rewritten candidate, we've already reversed the arguments 13352 // if needed. Perform the rest of the rewrite now. 13353 if ((Best->RewriteKind & CRK_DifferentOperator) || 13354 (Op == OO_Spaceship && IsReversed)) { 13355 if (Op == OO_ExclaimEqual) { 13356 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13356, __PRETTY_FUNCTION__))
; 13357 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13358 } else { 13359 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13359, __PRETTY_FUNCTION__))
; 13360 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13361 Expr *ZeroLiteral = 13362 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13363 13364 Sema::CodeSynthesisContext Ctx; 13365 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13366 Ctx.Entity = FnDecl; 13367 pushCodeSynthesisContext(Ctx); 13368 13369 R = CreateOverloadedBinOp( 13370 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13371 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13372 /*AllowRewrittenCandidates=*/false); 13373 13374 popCodeSynthesisContext(); 13375 } 13376 if (R.isInvalid()) 13377 return ExprError(); 13378 } else { 13379 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13379, __PRETTY_FUNCTION__))
; 13380 } 13381 13382 // Make a note in the AST if we did any rewriting. 13383 if (Best->RewriteKind != CRK_None) 13384 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13385 13386 return R; 13387 } else { 13388 // We matched a built-in operator. Convert the arguments, then 13389 // break out so that we will build the appropriate built-in 13390 // operator node. 13391 ExprResult ArgsRes0 = PerformImplicitConversion( 13392 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13393 AA_Passing, CCK_ForBuiltinOverloadedOp); 13394 if (ArgsRes0.isInvalid()) 13395 return ExprError(); 13396 Args[0] = ArgsRes0.get(); 13397 13398 ExprResult ArgsRes1 = PerformImplicitConversion( 13399 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13400 AA_Passing, CCK_ForBuiltinOverloadedOp); 13401 if (ArgsRes1.isInvalid()) 13402 return ExprError(); 13403 Args[1] = ArgsRes1.get(); 13404 break; 13405 } 13406 } 13407 13408 case OR_No_Viable_Function: { 13409 // C++ [over.match.oper]p9: 13410 // If the operator is the operator , [...] and there are no 13411 // viable functions, then the operator is assumed to be the 13412 // built-in operator and interpreted according to clause 5. 13413 if (Opc == BO_Comma) 13414 break; 13415 13416 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13417 // compare result using '==' and '<'. 13418 if (DefaultedFn && Opc == BO_Cmp) { 13419 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13420 Args[1], DefaultedFn); 13421 if (E.isInvalid() || E.isUsable()) 13422 return E; 13423 } 13424 13425 // For class as left operand for assignment or compound assignment 13426 // operator do not fall through to handling in built-in, but report that 13427 // no overloaded assignment operator found 13428 ExprResult Result = ExprError(); 13429 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13430 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13431 Args, OpLoc); 13432 if (Args[0]->getType()->isRecordType() && 13433 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13434 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13435 << BinaryOperator::getOpcodeStr(Opc) 13436 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13437 if (Args[0]->getType()->isIncompleteType()) { 13438 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13439 << Args[0]->getType() 13440 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13441 } 13442 } else { 13443 // This is an erroneous use of an operator which can be overloaded by 13444 // a non-member function. Check for non-member operators which were 13445 // defined too late to be candidates. 13446 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13447 // FIXME: Recover by calling the found function. 13448 return ExprError(); 13449 13450 // No viable function; try to create a built-in operation, which will 13451 // produce an error. Then, show the non-viable candidates. 13452 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13453 } 13454 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
13455 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
; 13456 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13457 return Result; 13458 } 13459 13460 case OR_Ambiguous: 13461 CandidateSet.NoteCandidates( 13462 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13463 << BinaryOperator::getOpcodeStr(Opc) 13464 << Args[0]->getType() 13465 << Args[1]->getType() 13466 << Args[0]->getSourceRange() 13467 << Args[1]->getSourceRange()), 13468 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13469 OpLoc); 13470 return ExprError(); 13471 13472 case OR_Deleted: 13473 if (isImplicitlyDeleted(Best->Function)) { 13474 FunctionDecl *DeletedFD = Best->Function; 13475 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13476 if (DFK.isSpecialMember()) { 13477 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13478 << Args[0]->getType() << DFK.asSpecialMember(); 13479 } else { 13480 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13480, __PRETTY_FUNCTION__))
; 13481 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13482 << Args[0]->getType() << DeletedFD; 13483 } 13484 13485 // The user probably meant to call this special member. Just 13486 // explain why it's deleted. 13487 NoteDeletedFunction(DeletedFD); 13488 return ExprError(); 13489 } 13490 CandidateSet.NoteCandidates( 13491 PartialDiagnosticAt( 13492 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13493 << getOperatorSpelling(Best->Function->getDeclName() 13494 .getCXXOverloadedOperator()) 13495 << Args[0]->getSourceRange() 13496 << Args[1]->getSourceRange()), 13497 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13498 OpLoc); 13499 return ExprError(); 13500 } 13501 13502 // We matched a built-in operator; build it. 13503 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13504} 13505 13506ExprResult Sema::BuildSynthesizedThreeWayComparison( 13507 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13508 FunctionDecl *DefaultedFn) { 13509 const ComparisonCategoryInfo *Info = 13510 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13511 // If we're not producing a known comparison category type, we can't 13512 // synthesize a three-way comparison. Let the caller diagnose this. 13513 if (!Info) 13514 return ExprResult((Expr*)nullptr); 13515 13516 // If we ever want to perform this synthesis more generally, we will need to 13517 // apply the temporary materialization conversion to the operands. 13518 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
13519 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
; 13520 Expr *OrigLHS = LHS; 13521 Expr *OrigRHS = RHS; 13522 13523 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13524 // each of them multiple times below. 13525 LHS = new (Context) 13526 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13527 LHS->getObjectKind(), LHS); 13528 RHS = new (Context) 13529 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13530 RHS->getObjectKind(), RHS); 13531 13532 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13533 DefaultedFn); 13534 if (Eq.isInvalid()) 13535 return ExprError(); 13536 13537 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13538 true, DefaultedFn); 13539 if (Less.isInvalid()) 13540 return ExprError(); 13541 13542 ExprResult Greater; 13543 if (Info->isPartial()) { 13544 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13545 DefaultedFn); 13546 if (Greater.isInvalid()) 13547 return ExprError(); 13548 } 13549 13550 // Form the list of comparisons we're going to perform. 13551 struct Comparison { 13552 ExprResult Cmp; 13553 ComparisonCategoryResult Result; 13554 } Comparisons[4] = 13555 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13556 : ComparisonCategoryResult::Equivalent}, 13557 {Less, ComparisonCategoryResult::Less}, 13558 {Greater, ComparisonCategoryResult::Greater}, 13559 {ExprResult(), ComparisonCategoryResult::Unordered}, 13560 }; 13561 13562 int I = Info->isPartial() ? 3 : 2; 13563 13564 // Combine the comparisons with suitable conditional expressions. 13565 ExprResult Result; 13566 for (; I >= 0; --I) { 13567 // Build a reference to the comparison category constant. 13568 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13569 // FIXME: Missing a constant for a comparison category. Diagnose this? 13570 if (!VI) 13571 return ExprResult((Expr*)nullptr); 13572 ExprResult ThisResult = 13573 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13574 if (ThisResult.isInvalid()) 13575 return ExprError(); 13576 13577 // Build a conditional unless this is the final case. 13578 if (Result.get()) { 13579 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13580 ThisResult.get(), Result.get()); 13581 if (Result.isInvalid()) 13582 return ExprError(); 13583 } else { 13584 Result = ThisResult; 13585 } 13586 } 13587 13588 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13589 // bind the OpaqueValueExprs before they're (repeatedly) used. 13590 Expr *SyntacticForm = new (Context) 13591 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13592 Result.get()->getValueKind(), 13593 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13594 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13595 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13596} 13597 13598ExprResult 13599Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13600 SourceLocation RLoc, 13601 Expr *Base, Expr *Idx) { 13602 Expr *Args[2] = { Base, Idx }; 13603 DeclarationName OpName = 13604 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13605 13606 // If either side is type-dependent, create an appropriate dependent 13607 // expression. 13608 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13609 13610 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13611 // CHECKME: no 'operator' keyword? 13612 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13613 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13614 UnresolvedLookupExpr *Fn 13615 = UnresolvedLookupExpr::Create(Context, NamingClass, 13616 NestedNameSpecifierLoc(), OpNameInfo, 13617 /*ADL*/ true, /*Overloaded*/ false, 13618 UnresolvedSetIterator(), 13619 UnresolvedSetIterator()); 13620 // Can't add any actual overloads yet 13621 13622 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13623 Context.DependentTy, VK_RValue, RLoc, 13624 FPOptions()); 13625 } 13626 13627 // Handle placeholders on both operands. 13628 if (checkPlaceholderForOverload(*this, Args[0])) 13629 return ExprError(); 13630 if (checkPlaceholderForOverload(*this, Args[1])) 13631 return ExprError(); 13632 13633 // Build an empty overload set. 13634 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13635 13636 // Subscript can only be overloaded as a member function. 13637 13638 // Add operator candidates that are member functions. 13639 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13640 13641 // Add builtin operator candidates. 13642 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13643 13644 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13645 13646 // Perform overload resolution. 13647 OverloadCandidateSet::iterator Best; 13648 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13649 case OR_Success: { 13650 // We found a built-in operator or an overloaded operator. 13651 FunctionDecl *FnDecl = Best->Function; 13652 13653 if (FnDecl) { 13654 // We matched an overloaded operator. Build a call to that 13655 // operator. 13656 13657 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13658 13659 // Convert the arguments. 13660 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13661 ExprResult Arg0 = 13662 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13663 Best->FoundDecl, Method); 13664 if (Arg0.isInvalid()) 13665 return ExprError(); 13666 Args[0] = Arg0.get(); 13667 13668 // Convert the arguments. 13669 ExprResult InputInit 13670 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13671 Context, 13672 FnDecl->getParamDecl(0)), 13673 SourceLocation(), 13674 Args[1]); 13675 if (InputInit.isInvalid()) 13676 return ExprError(); 13677 13678 Args[1] = InputInit.getAs<Expr>(); 13679 13680 // Build the actual expression node. 13681 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13682 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13683 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13684 Best->FoundDecl, 13685 Base, 13686 HadMultipleCandidates, 13687 OpLocInfo.getLoc(), 13688 OpLocInfo.getInfo()); 13689 if (FnExpr.isInvalid()) 13690 return ExprError(); 13691 13692 // Determine the result type 13693 QualType ResultTy = FnDecl->getReturnType(); 13694 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13695 ResultTy = ResultTy.getNonLValueExprType(Context); 13696 13697 CXXOperatorCallExpr *TheCall = 13698 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13699 Args, ResultTy, VK, RLoc, FPOptions()); 13700 13701 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13702 return ExprError(); 13703 13704 if (CheckFunctionCall(Method, TheCall, 13705 Method->getType()->castAs<FunctionProtoType>())) 13706 return ExprError(); 13707 13708 return MaybeBindToTemporary(TheCall); 13709 } else { 13710 // We matched a built-in operator. Convert the arguments, then 13711 // break out so that we will build the appropriate built-in 13712 // operator node. 13713 ExprResult ArgsRes0 = PerformImplicitConversion( 13714 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13715 AA_Passing, CCK_ForBuiltinOverloadedOp); 13716 if (ArgsRes0.isInvalid()) 13717 return ExprError(); 13718 Args[0] = ArgsRes0.get(); 13719 13720 ExprResult ArgsRes1 = PerformImplicitConversion( 13721 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13722 AA_Passing, CCK_ForBuiltinOverloadedOp); 13723 if (ArgsRes1.isInvalid()) 13724 return ExprError(); 13725 Args[1] = ArgsRes1.get(); 13726 13727 break; 13728 } 13729 } 13730 13731 case OR_No_Viable_Function: { 13732 PartialDiagnostic PD = CandidateSet.empty() 13733 ? (PDiag(diag::err_ovl_no_oper) 13734 << Args[0]->getType() << /*subscript*/ 0 13735 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13736 : (PDiag(diag::err_ovl_no_viable_subscript) 13737 << Args[0]->getType() << Args[0]->getSourceRange() 13738 << Args[1]->getSourceRange()); 13739 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13740 OCD_AllCandidates, Args, "[]", LLoc); 13741 return ExprError(); 13742 } 13743 13744 case OR_Ambiguous: 13745 CandidateSet.NoteCandidates( 13746 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13747 << "[]" << Args[0]->getType() 13748 << Args[1]->getType() 13749 << Args[0]->getSourceRange() 13750 << Args[1]->getSourceRange()), 13751 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13752 return ExprError(); 13753 13754 case OR_Deleted: 13755 CandidateSet.NoteCandidates( 13756 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13757 << "[]" << Args[0]->getSourceRange() 13758 << Args[1]->getSourceRange()), 13759 *this, OCD_AllCandidates, Args, "[]", LLoc); 13760 return ExprError(); 13761 } 13762 13763 // We matched a built-in operator; build it. 13764 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13765} 13766 13767/// BuildCallToMemberFunction - Build a call to a member 13768/// function. MemExpr is the expression that refers to the member 13769/// function (and includes the object parameter), Args/NumArgs are the 13770/// arguments to the function call (not including the object 13771/// parameter). The caller needs to validate that the member 13772/// expression refers to a non-static member function or an overloaded 13773/// member function. 13774ExprResult 13775Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13776 SourceLocation LParenLoc, 13777 MultiExprArg Args, 13778 SourceLocation RParenLoc) { 13779 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
13780 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
; 13781 13782 // Dig out the member expression. This holds both the object 13783 // argument and the member function we're referring to. 13784 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13785 13786 // Determine whether this is a call to a pointer-to-member function. 13787 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13788 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13788, __PRETTY_FUNCTION__))
; 13789 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13789, __PRETTY_FUNCTION__))
; 13790 13791 QualType fnType = 13792 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13793 13794 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13795 QualType resultType = proto->getCallResultType(Context); 13796 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13797 13798 // Check that the object type isn't more qualified than the 13799 // member function we're calling. 13800 Qualifiers funcQuals = proto->getMethodQuals(); 13801 13802 QualType objectType = op->getLHS()->getType(); 13803 if (op->getOpcode() == BO_PtrMemI) 13804 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13805 Qualifiers objectQuals = objectType.getQualifiers(); 13806 13807 Qualifiers difference = objectQuals - funcQuals; 13808 difference.removeObjCGCAttr(); 13809 difference.removeAddressSpace(); 13810 if (difference) { 13811 std::string qualsString = difference.getAsString(); 13812 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13813 << fnType.getUnqualifiedType() 13814 << qualsString 13815 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13816 } 13817 13818 CXXMemberCallExpr *call = 13819 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13820 valueKind, RParenLoc, proto->getNumParams()); 13821 13822 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13823 call, nullptr)) 13824 return ExprError(); 13825 13826 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13827 return ExprError(); 13828 13829 if (CheckOtherCall(call, proto)) 13830 return ExprError(); 13831 13832 return MaybeBindToTemporary(call); 13833 } 13834 13835 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13836 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13837 RParenLoc); 13838 13839 UnbridgedCastsSet UnbridgedCasts; 13840 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13841 return ExprError(); 13842 13843 MemberExpr *MemExpr; 13844 CXXMethodDecl *Method = nullptr; 13845 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13846 NestedNameSpecifier *Qualifier = nullptr; 13847 if (isa<MemberExpr>(NakedMemExpr)) { 13848 MemExpr = cast<MemberExpr>(NakedMemExpr); 13849 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13850 FoundDecl = MemExpr->getFoundDecl(); 13851 Qualifier = MemExpr->getQualifier(); 13852 UnbridgedCasts.restore(); 13853 } else { 13854 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13855 Qualifier = UnresExpr->getQualifier(); 13856 13857 QualType ObjectType = UnresExpr->getBaseType(); 13858 Expr::Classification ObjectClassification 13859 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13860 : UnresExpr->getBase()->Classify(Context); 13861 13862 // Add overload candidates 13863 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13864 OverloadCandidateSet::CSK_Normal); 13865 13866 // FIXME: avoid copy. 13867 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13868 if (UnresExpr->hasExplicitTemplateArgs()) { 13869 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13870 TemplateArgs = &TemplateArgsBuffer; 13871 } 13872 13873 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13874 E = UnresExpr->decls_end(); I != E; ++I) { 13875 13876 NamedDecl *Func = *I; 13877 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13878 if (isa<UsingShadowDecl>(Func)) 13879 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13880 13881 13882 // Microsoft supports direct constructor calls. 13883 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13884 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13885 CandidateSet, 13886 /*SuppressUserConversions*/ false); 13887 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13888 // If explicit template arguments were provided, we can't call a 13889 // non-template member function. 13890 if (TemplateArgs) 13891 continue; 13892 13893 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13894 ObjectClassification, Args, CandidateSet, 13895 /*SuppressUserConversions=*/false); 13896 } else { 13897 AddMethodTemplateCandidate( 13898 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13899 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13900 /*SuppressUserConversions=*/false); 13901 } 13902 } 13903 13904 DeclarationName DeclName = UnresExpr->getMemberName(); 13905 13906 UnbridgedCasts.restore(); 13907 13908 OverloadCandidateSet::iterator Best; 13909 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13910 Best)) { 13911 case OR_Success: 13912 Method = cast<CXXMethodDecl>(Best->Function); 13913 FoundDecl = Best->FoundDecl; 13914 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13915 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13916 return ExprError(); 13917 // If FoundDecl is different from Method (such as if one is a template 13918 // and the other a specialization), make sure DiagnoseUseOfDecl is 13919 // called on both. 13920 // FIXME: This would be more comprehensively addressed by modifying 13921 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13922 // being used. 13923 if (Method != FoundDecl.getDecl() && 13924 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13925 return ExprError(); 13926 break; 13927 13928 case OR_No_Viable_Function: 13929 CandidateSet.NoteCandidates( 13930 PartialDiagnosticAt( 13931 UnresExpr->getMemberLoc(), 13932 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13933 << DeclName << MemExprE->getSourceRange()), 13934 *this, OCD_AllCandidates, Args); 13935 // FIXME: Leaking incoming expressions! 13936 return ExprError(); 13937 13938 case OR_Ambiguous: 13939 CandidateSet.NoteCandidates( 13940 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13941 PDiag(diag::err_ovl_ambiguous_member_call) 13942 << DeclName << MemExprE->getSourceRange()), 13943 *this, OCD_AmbiguousCandidates, Args); 13944 // FIXME: Leaking incoming expressions! 13945 return ExprError(); 13946 13947 case OR_Deleted: 13948 CandidateSet.NoteCandidates( 13949 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13950 PDiag(diag::err_ovl_deleted_member_call) 13951 << DeclName << MemExprE->getSourceRange()), 13952 *this, OCD_AllCandidates, Args); 13953 // FIXME: Leaking incoming expressions! 13954 return ExprError(); 13955 } 13956 13957 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13958 13959 // If overload resolution picked a static member, build a 13960 // non-member call based on that function. 13961 if (Method->isStatic()) { 13962 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13963 RParenLoc); 13964 } 13965 13966 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13967 } 13968 13969 QualType ResultType = Method->getReturnType(); 13970 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13971 ResultType = ResultType.getNonLValueExprType(Context); 13972 13973 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13973, __PRETTY_FUNCTION__))
; 13974 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13975 CXXMemberCallExpr *TheCall = 13976 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13977 RParenLoc, Proto->getNumParams()); 13978 13979 // Check for a valid return type. 13980 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13981 TheCall, Method)) 13982 return ExprError(); 13983 13984 // Convert the object argument (for a non-static member function call). 13985 // We only need to do this if there was actually an overload; otherwise 13986 // it was done at lookup. 13987 if (!Method->isStatic()) { 13988 ExprResult ObjectArg = 13989 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13990 FoundDecl, Method); 13991 if (ObjectArg.isInvalid()) 13992 return ExprError(); 13993 MemExpr->setBase(ObjectArg.get()); 13994 } 13995 13996 // Convert the rest of the arguments 13997 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13998 RParenLoc)) 13999 return ExprError(); 14000 14001 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14002 14003 if (CheckFunctionCall(Method, TheCall, Proto)) 14004 return ExprError(); 14005 14006 // In the case the method to call was not selected by the overloading 14007 // resolution process, we still need to handle the enable_if attribute. Do 14008 // that here, so it will not hide previous -- and more relevant -- errors. 14009 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14010 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 14011 Diag(MemE->getMemberLoc(), 14012 diag::err_ovl_no_viable_member_function_in_call) 14013 << Method << Method->getSourceRange(); 14014 Diag(Method->getLocation(), 14015 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14016 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14017 return ExprError(); 14018 } 14019 } 14020 14021 if ((isa<CXXConstructorDecl>(CurContext) || 14022 isa<CXXDestructorDecl>(CurContext)) && 14023 TheCall->getMethodDecl()->isPure()) { 14024 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14025 14026 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14027 MemExpr->performsVirtualDispatch(getLangOpts())) { 14028 Diag(MemExpr->getBeginLoc(), 14029 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14030 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14031 << MD->getParent()->getDeclName(); 14032 14033 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14034 if (getLangOpts().AppleKext) 14035 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14036 << MD->getParent()->getDeclName() << MD->getDeclName(); 14037 } 14038 } 14039 14040 if (CXXDestructorDecl *DD = 14041 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14042 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14043 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14044 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14045 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14046 MemExpr->getMemberLoc()); 14047 } 14048 14049 return MaybeBindToTemporary(TheCall); 14050} 14051 14052/// BuildCallToObjectOfClassType - Build a call to an object of class 14053/// type (C++ [over.call.object]), which can end up invoking an 14054/// overloaded function call operator (@c operator()) or performing a 14055/// user-defined conversion on the object argument. 14056ExprResult 14057Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14058 SourceLocation LParenLoc, 14059 MultiExprArg Args, 14060 SourceLocation RParenLoc) { 14061 if (checkPlaceholderForOverload(*this, Obj)) 14062 return ExprError(); 14063 ExprResult Object = Obj; 14064 14065 UnbridgedCastsSet UnbridgedCasts; 14066 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14067 return ExprError(); 14068 14069 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
14070 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
; 14071 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 14072 14073 // C++ [over.call.object]p1: 14074 // If the primary-expression E in the function call syntax 14075 // evaluates to a class object of type "cv T", then the set of 14076 // candidate functions includes at least the function call 14077 // operators of T. The function call operators of T are obtained by 14078 // ordinary lookup of the name operator() in the context of 14079 // (E).operator(). 14080 OverloadCandidateSet CandidateSet(LParenLoc, 14081 OverloadCandidateSet::CSK_Operator); 14082 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14083 14084 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14085 diag::err_incomplete_object_call, Object.get())) 14086 return true; 14087 14088 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14089 LookupQualifiedName(R, Record->getDecl()); 14090 R.suppressDiagnostics(); 14091 14092 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14093 Oper != OperEnd; ++Oper) { 14094 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14095 Object.get()->Classify(Context), Args, CandidateSet, 14096 /*SuppressUserConversion=*/false); 14097 } 14098 14099 // C++ [over.call.object]p2: 14100 // In addition, for each (non-explicit in C++0x) conversion function 14101 // declared in T of the form 14102 // 14103 // operator conversion-type-id () cv-qualifier; 14104 // 14105 // where cv-qualifier is the same cv-qualification as, or a 14106 // greater cv-qualification than, cv, and where conversion-type-id 14107 // denotes the type "pointer to function of (P1,...,Pn) returning 14108 // R", or the type "reference to pointer to function of 14109 // (P1,...,Pn) returning R", or the type "reference to function 14110 // of (P1,...,Pn) returning R", a surrogate call function [...] 14111 // is also considered as a candidate function. Similarly, 14112 // surrogate call functions are added to the set of candidate 14113 // functions for each conversion function declared in an 14114 // accessible base class provided the function is not hidden 14115 // within T by another intervening declaration. 14116 const auto &Conversions = 14117 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14118 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14119 NamedDecl *D = *I; 14120 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14121 if (isa<UsingShadowDecl>(D)) 14122 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14123 14124 // Skip over templated conversion functions; they aren't 14125 // surrogates. 14126 if (isa<FunctionTemplateDecl>(D)) 14127 continue; 14128 14129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14130 if (!Conv->isExplicit()) { 14131 // Strip the reference type (if any) and then the pointer type (if 14132 // any) to get down to what might be a function type. 14133 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14134 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14135 ConvType = ConvPtrType->getPointeeType(); 14136 14137 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14138 { 14139 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14140 Object.get(), Args, CandidateSet); 14141 } 14142 } 14143 } 14144 14145 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14146 14147 // Perform overload resolution. 14148 OverloadCandidateSet::iterator Best; 14149 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14150 Best)) { 14151 case OR_Success: 14152 // Overload resolution succeeded; we'll build the appropriate call 14153 // below. 14154 break; 14155 14156 case OR_No_Viable_Function: { 14157 PartialDiagnostic PD = 14158 CandidateSet.empty() 14159 ? (PDiag(diag::err_ovl_no_oper) 14160 << Object.get()->getType() << /*call*/ 1 14161 << Object.get()->getSourceRange()) 14162 : (PDiag(diag::err_ovl_no_viable_object_call) 14163 << Object.get()->getType() << Object.get()->getSourceRange()); 14164 CandidateSet.NoteCandidates( 14165 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14166 OCD_AllCandidates, Args); 14167 break; 14168 } 14169 case OR_Ambiguous: 14170 CandidateSet.NoteCandidates( 14171 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14172 PDiag(diag::err_ovl_ambiguous_object_call) 14173 << Object.get()->getType() 14174 << Object.get()->getSourceRange()), 14175 *this, OCD_AmbiguousCandidates, Args); 14176 break; 14177 14178 case OR_Deleted: 14179 CandidateSet.NoteCandidates( 14180 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14181 PDiag(diag::err_ovl_deleted_object_call) 14182 << Object.get()->getType() 14183 << Object.get()->getSourceRange()), 14184 *this, OCD_AllCandidates, Args); 14185 break; 14186 } 14187 14188 if (Best == CandidateSet.end()) 14189 return true; 14190 14191 UnbridgedCasts.restore(); 14192 14193 if (Best->Function == nullptr) { 14194 // Since there is no function declaration, this is one of the 14195 // surrogate candidates. Dig out the conversion function. 14196 CXXConversionDecl *Conv 14197 = cast<CXXConversionDecl>( 14198 Best->Conversions[0].UserDefined.ConversionFunction); 14199 14200 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14201 Best->FoundDecl); 14202 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14203 return ExprError(); 14204 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
14205 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
; 14206 // We selected one of the surrogate functions that converts the 14207 // object parameter to a function pointer. Perform the conversion 14208 // on the object argument, then let BuildCallExpr finish the job. 14209 14210 // Create an implicit member expr to refer to the conversion operator. 14211 // and then call it. 14212 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14213 Conv, HadMultipleCandidates); 14214 if (Call.isInvalid()) 14215 return ExprError(); 14216 // Record usage of conversion in an implicit cast. 14217 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14218 CK_UserDefinedConversion, Call.get(), 14219 nullptr, VK_RValue); 14220 14221 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14222 } 14223 14224 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14225 14226 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14227 // that calls this method, using Object for the implicit object 14228 // parameter and passing along the remaining arguments. 14229 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14230 14231 // An error diagnostic has already been printed when parsing the declaration. 14232 if (Method->isInvalidDecl()) 14233 return ExprError(); 14234 14235 const FunctionProtoType *Proto = 14236 Method->getType()->getAs<FunctionProtoType>(); 14237 14238 unsigned NumParams = Proto->getNumParams(); 14239 14240 DeclarationNameInfo OpLocInfo( 14241 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14242 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14243 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14244 Obj, HadMultipleCandidates, 14245 OpLocInfo.getLoc(), 14246 OpLocInfo.getInfo()); 14247 if (NewFn.isInvalid()) 14248 return true; 14249 14250 // The number of argument slots to allocate in the call. If we have default 14251 // arguments we need to allocate space for them as well. We additionally 14252 // need one more slot for the object parameter. 14253 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14254 14255 // Build the full argument list for the method call (the implicit object 14256 // parameter is placed at the beginning of the list). 14257 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14258 14259 bool IsError = false; 14260 14261 // Initialize the implicit object parameter. 14262 ExprResult ObjRes = 14263 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14264 Best->FoundDecl, Method); 14265 if (ObjRes.isInvalid()) 14266 IsError = true; 14267 else 14268 Object = ObjRes; 14269 MethodArgs[0] = Object.get(); 14270 14271 // Check the argument types. 14272 for (unsigned i = 0; i != NumParams; i++) { 14273 Expr *Arg; 14274 if (i < Args.size()) { 14275 Arg = Args[i]; 14276 14277 // Pass the argument. 14278 14279 ExprResult InputInit 14280 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14281 Context, 14282 Method->getParamDecl(i)), 14283 SourceLocation(), Arg); 14284 14285 IsError |= InputInit.isInvalid(); 14286 Arg = InputInit.getAs<Expr>(); 14287 } else { 14288 ExprResult DefArg 14289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14290 if (DefArg.isInvalid()) { 14291 IsError = true; 14292 break; 14293 } 14294 14295 Arg = DefArg.getAs<Expr>(); 14296 } 14297 14298 MethodArgs[i + 1] = Arg; 14299 } 14300 14301 // If this is a variadic call, handle args passed through "...". 14302 if (Proto->isVariadic()) { 14303 // Promote the arguments (C99 6.5.2.2p7). 14304 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14305 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14306 nullptr); 14307 IsError |= Arg.isInvalid(); 14308 MethodArgs[i + 1] = Arg.get(); 14309 } 14310 } 14311 14312 if (IsError) 14313 return true; 14314 14315 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14316 14317 // Once we've built TheCall, all of the expressions are properly owned. 14318 QualType ResultTy = Method->getReturnType(); 14319 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14320 ResultTy = ResultTy.getNonLValueExprType(Context); 14321 14322 CXXOperatorCallExpr *TheCall = 14323 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14324 ResultTy, VK, RParenLoc, FPOptions()); 14325 14326 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14327 return true; 14328 14329 if (CheckFunctionCall(Method, TheCall, Proto)) 14330 return true; 14331 14332 return MaybeBindToTemporary(TheCall); 14333} 14334 14335/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14336/// (if one exists), where @c Base is an expression of class type and 14337/// @c Member is the name of the member we're trying to find. 14338ExprResult 14339Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14340 bool *NoArrowOperatorFound) { 14341 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
14342 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
; 14343 14344 if (checkPlaceholderForOverload(*this, Base)) 14345 return ExprError(); 14346 14347 SourceLocation Loc = Base->getExprLoc(); 14348 14349 // C++ [over.ref]p1: 14350 // 14351 // [...] An expression x->m is interpreted as (x.operator->())->m 14352 // for a class object x of type T if T::operator->() exists and if 14353 // the operator is selected as the best match function by the 14354 // overload resolution mechanism (13.3). 14355 DeclarationName OpName = 14356 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14357 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14358 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 14359 14360 if (RequireCompleteType(Loc, Base->getType(), 14361 diag::err_typecheck_incomplete_tag, Base)) 14362 return ExprError(); 14363 14364 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14365 LookupQualifiedName(R, BaseRecord->getDecl()); 14366 R.suppressDiagnostics(); 14367 14368 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14369 Oper != OperEnd; ++Oper) { 14370 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14371 None, CandidateSet, /*SuppressUserConversion=*/false); 14372 } 14373 14374 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14375 14376 // Perform overload resolution. 14377 OverloadCandidateSet::iterator Best; 14378 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14379 case OR_Success: 14380 // Overload resolution succeeded; we'll build the call below. 14381 break; 14382 14383 case OR_No_Viable_Function: { 14384 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14385 if (CandidateSet.empty()) { 14386 QualType BaseType = Base->getType(); 14387 if (NoArrowOperatorFound) { 14388 // Report this specific error to the caller instead of emitting a 14389 // diagnostic, as requested. 14390 *NoArrowOperatorFound = true; 14391 return ExprError(); 14392 } 14393 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14394 << BaseType << Base->getSourceRange(); 14395 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14396 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14397 << FixItHint::CreateReplacement(OpLoc, "."); 14398 } 14399 } else 14400 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14401 << "operator->" << Base->getSourceRange(); 14402 CandidateSet.NoteCandidates(*this, Base, Cands); 14403 return ExprError(); 14404 } 14405 case OR_Ambiguous: 14406 CandidateSet.NoteCandidates( 14407 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14408 << "->" << Base->getType() 14409 << Base->getSourceRange()), 14410 *this, OCD_AmbiguousCandidates, Base); 14411 return ExprError(); 14412 14413 case OR_Deleted: 14414 CandidateSet.NoteCandidates( 14415 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14416 << "->" << Base->getSourceRange()), 14417 *this, OCD_AllCandidates, Base); 14418 return ExprError(); 14419 } 14420 14421 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14422 14423 // Convert the object parameter. 14424 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14425 ExprResult BaseResult = 14426 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14427 Best->FoundDecl, Method); 14428 if (BaseResult.isInvalid()) 14429 return ExprError(); 14430 Base = BaseResult.get(); 14431 14432 // Build the operator call. 14433 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14434 Base, HadMultipleCandidates, OpLoc); 14435 if (FnExpr.isInvalid()) 14436 return ExprError(); 14437 14438 QualType ResultTy = Method->getReturnType(); 14439 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14440 ResultTy = ResultTy.getNonLValueExprType(Context); 14441 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14442 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14443 14444 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14445 return ExprError(); 14446 14447 if (CheckFunctionCall(Method, TheCall, 14448 Method->getType()->castAs<FunctionProtoType>())) 14449 return ExprError(); 14450 14451 return MaybeBindToTemporary(TheCall); 14452} 14453 14454/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14455/// a literal operator described by the provided lookup results. 14456ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14457 DeclarationNameInfo &SuffixInfo, 14458 ArrayRef<Expr*> Args, 14459 SourceLocation LitEndLoc, 14460 TemplateArgumentListInfo *TemplateArgs) { 14461 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14462 14463 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14464 OverloadCandidateSet::CSK_Normal); 14465 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14466 TemplateArgs); 14467 14468 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14469 14470 // Perform overload resolution. This will usually be trivial, but might need 14471 // to perform substitutions for a literal operator template. 14472 OverloadCandidateSet::iterator Best; 14473 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14474 case OR_Success: 14475 case OR_Deleted: 14476 break; 14477 14478 case OR_No_Viable_Function: 14479 CandidateSet.NoteCandidates( 14480 PartialDiagnosticAt(UDSuffixLoc, 14481 PDiag(diag::err_ovl_no_viable_function_in_call) 14482 << R.getLookupName()), 14483 *this, OCD_AllCandidates, Args); 14484 return ExprError(); 14485 14486 case OR_Ambiguous: 14487 CandidateSet.NoteCandidates( 14488 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14489 << R.getLookupName()), 14490 *this, OCD_AmbiguousCandidates, Args); 14491 return ExprError(); 14492 } 14493 14494 FunctionDecl *FD = Best->Function; 14495 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14496 nullptr, HadMultipleCandidates, 14497 SuffixInfo.getLoc(), 14498 SuffixInfo.getInfo()); 14499 if (Fn.isInvalid()) 14500 return true; 14501 14502 // Check the argument types. This should almost always be a no-op, except 14503 // that array-to-pointer decay is applied to string literals. 14504 Expr *ConvArgs[2]; 14505 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14506 ExprResult InputInit = PerformCopyInitialization( 14507 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14508 SourceLocation(), Args[ArgIdx]); 14509 if (InputInit.isInvalid()) 14510 return true; 14511 ConvArgs[ArgIdx] = InputInit.get(); 14512 } 14513 14514 QualType ResultTy = FD->getReturnType(); 14515 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14516 ResultTy = ResultTy.getNonLValueExprType(Context); 14517 14518 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14519 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14520 VK, LitEndLoc, UDSuffixLoc); 14521 14522 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14523 return ExprError(); 14524 14525 if (CheckFunctionCall(FD, UDL, nullptr)) 14526 return ExprError(); 14527 14528 return MaybeBindToTemporary(UDL); 14529} 14530 14531/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14532/// given LookupResult is non-empty, it is assumed to describe a member which 14533/// will be invoked. Otherwise, the function will be found via argument 14534/// dependent lookup. 14535/// CallExpr is set to a valid expression and FRS_Success returned on success, 14536/// otherwise CallExpr is set to ExprError() and some non-success value 14537/// is returned. 14538Sema::ForRangeStatus 14539Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14540 SourceLocation RangeLoc, 14541 const DeclarationNameInfo &NameInfo, 14542 LookupResult &MemberLookup, 14543 OverloadCandidateSet *CandidateSet, 14544 Expr *Range, ExprResult *CallExpr) { 14545 Scope *S = nullptr; 14546 14547 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14548 if (!MemberLookup.empty()) { 14549 ExprResult MemberRef = 14550 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14551 /*IsPtr=*/false, CXXScopeSpec(), 14552 /*TemplateKWLoc=*/SourceLocation(), 14553 /*FirstQualifierInScope=*/nullptr, 14554 MemberLookup, 14555 /*TemplateArgs=*/nullptr, S); 14556 if (MemberRef.isInvalid()) { 14557 *CallExpr = ExprError(); 14558 return FRS_DiagnosticIssued; 14559 } 14560 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14561 if (CallExpr->isInvalid()) { 14562 *CallExpr = ExprError(); 14563 return FRS_DiagnosticIssued; 14564 } 14565 } else { 14566 UnresolvedSet<0> FoundNames; 14567 UnresolvedLookupExpr *Fn = 14568 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14569 NestedNameSpecifierLoc(), NameInfo, 14570 /*NeedsADL=*/true, /*Overloaded=*/false, 14571 FoundNames.begin(), FoundNames.end()); 14572 14573 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14574 CandidateSet, CallExpr); 14575 if (CandidateSet->empty() || CandidateSetError) { 14576 *CallExpr = ExprError(); 14577 return FRS_NoViableFunction; 14578 } 14579 OverloadCandidateSet::iterator Best; 14580 OverloadingResult OverloadResult = 14581 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14582 14583 if (OverloadResult == OR_No_Viable_Function) { 14584 *CallExpr = ExprError(); 14585 return FRS_NoViableFunction; 14586 } 14587 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14588 Loc, nullptr, CandidateSet, &Best, 14589 OverloadResult, 14590 /*AllowTypoCorrection=*/false); 14591 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14592 *CallExpr = ExprError(); 14593 return FRS_DiagnosticIssued; 14594 } 14595 } 14596 return FRS_Success; 14597} 14598 14599 14600/// FixOverloadedFunctionReference - E is an expression that refers to 14601/// a C++ overloaded function (possibly with some parentheses and 14602/// perhaps a '&' around it). We have resolved the overloaded function 14603/// to the function declaration Fn, so patch up the expression E to 14604/// refer (possibly indirectly) to Fn. Returns the new expr. 14605Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14606 FunctionDecl *Fn) { 14607 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14608 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14609 Found, Fn); 14610 if (SubExpr == PE->getSubExpr()) 14611 return PE; 14612 14613 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14614 } 14615 14616 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14617 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14618 Found, Fn); 14619 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14620 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14621 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
; 14622 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14622, __PRETTY_FUNCTION__))
; 14623 if (SubExpr == ICE->getSubExpr()) 14624 return ICE; 14625 14626 return ImplicitCastExpr::Create(Context, ICE->getType(), 14627 ICE->getCastKind(), 14628 SubExpr, nullptr, 14629 ICE->getValueKind()); 14630 } 14631 14632 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14633 if (!GSE->isResultDependent()) { 14634 Expr *SubExpr = 14635 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14636 if (SubExpr == GSE->getResultExpr()) 14637 return GSE; 14638 14639 // Replace the resulting type information before rebuilding the generic 14640 // selection expression. 14641 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14642 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14643 unsigned ResultIdx = GSE->getResultIndex(); 14644 AssocExprs[ResultIdx] = SubExpr; 14645 14646 return GenericSelectionExpr::Create( 14647 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14648 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14649 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14650 ResultIdx); 14651 } 14652 // Rather than fall through to the unreachable, return the original generic 14653 // selection expression. 14654 return GSE; 14655 } 14656 14657 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14658 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
14659 "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
; 14660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14661 if (Method->isStatic()) { 14662 // Do nothing: static member functions aren't any different 14663 // from non-member functions. 14664 } else { 14665 // Fix the subexpression, which really has to be an 14666 // UnresolvedLookupExpr holding an overloaded member function 14667 // or template. 14668 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14669 Found, Fn); 14670 if (SubExpr == UnOp->getSubExpr()) 14671 return UnOp; 14672 14673 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
14674 && "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
; 14675 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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
14676 && "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~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
; 14677 14678 // We have taken the address of a pointer to member 14679 // function. Perform the computation here so that we get the 14680 // appropriate pointer to member type. 14681 QualType ClassType 14682 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14683 QualType MemPtrType 14684 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14685 // Under the MS ABI, lock down the inheritance model now. 14686 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14687 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14688 14689 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14690 VK_RValue, OK_Ordinary, 14691 UnOp->getOperatorLoc(), false); 14692 } 14693 } 14694 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14695 Found, Fn); 14696 if (SubExpr == UnOp->getSubExpr()) 14697 return UnOp; 14698 14699 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14700 Context.getPointerType(SubExpr->getType()), 14701 VK_RValue, OK_Ordinary, 14702 UnOp->getOperatorLoc(), false); 14703 } 14704 14705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14706 // FIXME: avoid copy. 14707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14708 if (ULE->hasExplicitTemplateArgs()) { 14709 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14710 TemplateArgs = &TemplateArgsBuffer; 14711 } 14712 14713 DeclRefExpr *DRE = 14714 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14715 ULE->getQualifierLoc(), Found.getDecl(), 14716 ULE->getTemplateKeywordLoc(), TemplateArgs); 14717 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14718 return DRE; 14719 } 14720 14721 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14722 // FIXME: avoid copy. 14723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14724 if (MemExpr->hasExplicitTemplateArgs()) { 14725 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14726 TemplateArgs = &TemplateArgsBuffer; 14727 } 14728 14729 Expr *Base; 14730 14731 // If we're filling in a static method where we used to have an 14732 // implicit member access, rewrite to a simple decl ref. 14733 if (MemExpr->isImplicitAccess()) { 14734 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14735 DeclRefExpr *DRE = BuildDeclRefExpr( 14736 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14737 MemExpr->getQualifierLoc(), Found.getDecl(), 14738 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14739 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14740 return DRE; 14741 } else { 14742 SourceLocation Loc = MemExpr->getMemberLoc(); 14743 if (MemExpr->getQualifier()) 14744 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14745 Base = 14746 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14747 } 14748 } else 14749 Base = MemExpr->getBase(); 14750 14751 ExprValueKind valueKind; 14752 QualType type; 14753 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14754 valueKind = VK_LValue; 14755 type = Fn->getType(); 14756 } else { 14757 valueKind = VK_RValue; 14758 type = Context.BoundMemberTy; 14759 } 14760 14761 return BuildMemberExpr( 14762 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14763 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14764 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14765 type, valueKind, OK_Ordinary, TemplateArgs); 14766 } 14767 14768 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14768)
; 14769} 14770 14771ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14772 DeclAccessPair Found, 14773 FunctionDecl *Fn) { 14774 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14775}