1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38
39 using namespace clang;
40 using namespace sema;
41
functionHasPassObjectSizeParams(const FunctionDecl * FD)42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
46 }
47
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,const Expr * Base,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 const Expr *Base, bool HadMultipleCandidates,
52 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55 return ExprError();
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63 return ExprError();
64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
66 DeclRefExpr *DRE = new (S.Context)
67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
70
71 S.MarkDeclRefReferenced(DRE, Base);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
74 }
75
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle,
80 bool AllowObjCWritebackConversion);
81
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
91 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
93
94
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Promotion,
122 ICR_Promotion,
123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_OCL_Scalar_Widening,
135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
144 };
145 return Rank[(int)Kind];
146 }
147
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
156 "Function pointer conversion",
157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
160 "Complex promotion",
161 "Integral conversion",
162 "Floating conversion",
163 "Complex conversion",
164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
167 "Boolean conversion",
168 "Compatible-types conversion",
169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
172 "Complex-real conversion",
173 "Block Pointer conversion",
174 "Transparent Union Conversion",
175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
177 "C specific type conversion",
178 "Incompatible pointer conversion"
179 };
180 return Name[Kind];
181 }
182
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
setAsIdentityConversion()185 void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
189 DeprecatedStringLiteralToCharPtr = false;
190 QualificationIncludesObjCLifetime = false;
191 ReferenceBinding = false;
192 DirectBinding = false;
193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
197 ObjCLifetimeConversionBinding = false;
198 CopyConstructor = nullptr;
199 }
200
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
getRank() const204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213 }
214
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const219 bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isMemberPointerType() ||
227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
229 getFromType()->isNullPtrType() ||
230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234 }
235
236 /// isPointerConversionToVoidPointer - Determines whether this
237 /// conversion is a conversion of a pointer to a void pointer. This is
238 /// used as part of the ranking of standard conversion sequences (C++
239 /// 13.3.3.2p4).
240 bool
241 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const242 isPointerConversionToVoidPointer(ASTContext& Context) const {
243 QualType FromType = getFromType();
244 QualType ToType = getToType(1);
245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257 }
258
259 /// Skip any implicit casts which could be either part of a narrowing conversion
260 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(const Expr * Converted)261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
268 case CK_BooleanToSignedIntegral:
269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281 }
282
283 /// Check if this standard conversion sequence represents a narrowing
284 /// conversion, according to C++11 [dcl.init.list]p7.
285 ///
286 /// \param Ctx The AST context.
287 /// \param Converted The result of applying this standard conversion sequence.
288 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289 /// value of the expression prior to the narrowing conversion.
290 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291 /// type of the expression prior to the narrowing conversion.
292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293 /// from floating point types to integral types should be ignored.
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType,bool IgnoreFloatToIntegralConversion) const294 NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
310 switch (Second) {
311 // 'bool' is an integral type; dispatch to the right place to handle it.
312 case ICK_Boolean_Conversion:
313 if (FromType->isRealFloatingType())
314 goto FloatingIntegralConversion;
315 if (FromType->isIntegralOrUnscopedEnumerationType())
316 goto IntegralConversion;
317 // Boolean conversions can be from pointers and pointers to members
318 // [conv.bool], and those aren't considered narrowing conversions.
319 return NK_Not_Narrowing;
320
321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
328 FloatingIntegralConversion:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332 ToType->isRealFloatingType()) {
333 if (IgnoreFloatToIntegralConversion)
334 return NK_Not_Narrowing;
335 llvm::APSInt IntConstantValue;
336 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337 assert(Initializer && "Unknown conversion expression");
338
339 // If it's value-dependent, we can't tell whether it's narrowing.
340 if (Initializer->isValueDependent())
341 return NK_Dependent_Narrowing;
342
343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344 // Convert the integer to the floating type.
345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347 llvm::APFloat::rmNearestTiesToEven);
348 // And back.
349 llvm::APSInt ConvertedValue = IntConstantValue;
350 bool ignored;
351 Result.convertToInteger(ConvertedValue,
352 llvm::APFloat::rmTowardZero, &ignored);
353 // If the resulting value is different, this was a narrowing conversion.
354 if (IntConstantValue != ConvertedValue) {
355 ConstantValue = APValue(IntConstantValue);
356 ConstantType = Initializer->getType();
357 return NK_Constant_Narrowing;
358 }
359 } else {
360 // Variables are always narrowings.
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from long double to double or float, or from double to float, except
367 // where the source is a constant expression and the actual value after
368 // conversion is within the range of values that can be represented (even
369 // if it cannot be represented exactly), or
370 case ICK_Floating_Conversion:
371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373 // FromType is larger than ToType.
374 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
378 return NK_Dependent_Narrowing;
379
380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381 // Constant!
382 assert(ConstantValue.isFloat());
383 llvm::APFloat FloatVal = ConstantValue.getFloat();
384 // Convert the source value into the target type.
385 bool ignored;
386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387 Ctx.getFloatTypeSemantics(ToType),
388 llvm::APFloat::rmNearestTiesToEven, &ignored);
389 // If there was no overflow, the source value is within the range of
390 // values that can be represented.
391 if (ConvertStatus & llvm::APFloat::opOverflow) {
392 ConstantType = Initializer->getType();
393 return NK_Constant_Narrowing;
394 }
395 } else {
396 return NK_Variable_Narrowing;
397 }
398 }
399 return NK_Not_Narrowing;
400
401 // -- from an integer type or unscoped enumeration type to an integer type
402 // that cannot represent all the values of the original type, except where
403 // the source is a constant expression and the actual value after
404 // conversion will fit into the target type and will produce the original
405 // value when converted back to the original type.
406 case ICK_Integral_Conversion:
407 IntegralConversion: {
408 assert(FromType->isIntegralOrUnscopedEnumerationType());
409 assert(ToType->isIntegralOrUnscopedEnumerationType());
410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411 const unsigned FromWidth = Ctx.getIntWidth(FromType);
412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413 const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415 if (FromWidth > ToWidth ||
416 (FromWidth == ToWidth && FromSigned != ToSigned) ||
417 (FromSigned && !ToSigned)) {
418 // Not all values of FromType can be represented in ToType.
419 llvm::APSInt InitializerValue;
420 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421
422 // If it's value-dependent, we can't tell whether it's narrowing.
423 if (Initializer->isValueDependent())
424 return NK_Dependent_Narrowing;
425
426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427 // Such conversions on variables are always narrowing.
428 return NK_Variable_Narrowing;
429 }
430 bool Narrowing = false;
431 if (FromWidth < ToWidth) {
432 // Negative -> unsigned is narrowing. Otherwise, more bits is never
433 // narrowing.
434 if (InitializerValue.isSigned() && InitializerValue.isNegative())
435 Narrowing = true;
436 } else {
437 // Add a bit to the InitializerValue so we don't have to worry about
438 // signed vs. unsigned comparisons.
439 InitializerValue = InitializerValue.extend(
440 InitializerValue.getBitWidth() + 1);
441 // Convert the initializer to and from the target width and signed-ness.
442 llvm::APSInt ConvertedValue = InitializerValue;
443 ConvertedValue = ConvertedValue.trunc(ToWidth);
444 ConvertedValue.setIsSigned(ToSigned);
445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446 ConvertedValue.setIsSigned(InitializerValue.isSigned());
447 // If the result is different, this was a narrowing conversion.
448 if (ConvertedValue != InitializerValue)
449 Narrowing = true;
450 }
451 if (Narrowing) {
452 ConstantType = Initializer->getType();
453 ConstantValue = APValue(InitializerValue);
454 return NK_Constant_Narrowing;
455 }
456 }
457 return NK_Not_Narrowing;
458 }
459
460 default:
461 // Other kinds of conversions are not narrowings.
462 return NK_Not_Narrowing;
463 }
464 }
465
466 /// dump - Print this standard conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
dump() const468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
469 raw_ostream &OS = llvm::errs();
470 bool PrintedSomething = false;
471 if (First != ICK_Identity) {
472 OS << GetImplicitConversionName(First);
473 PrintedSomething = true;
474 }
475
476 if (Second != ICK_Identity) {
477 if (PrintedSomething) {
478 OS << " -> ";
479 }
480 OS << GetImplicitConversionName(Second);
481
482 if (CopyConstructor) {
483 OS << " (by copy constructor)";
484 } else if (DirectBinding) {
485 OS << " (direct reference binding)";
486 } else if (ReferenceBinding) {
487 OS << " (reference binding)";
488 }
489 PrintedSomething = true;
490 }
491
492 if (Third != ICK_Identity) {
493 if (PrintedSomething) {
494 OS << " -> ";
495 }
496 OS << GetImplicitConversionName(Third);
497 PrintedSomething = true;
498 }
499
500 if (!PrintedSomething) {
501 OS << "No conversions required";
502 }
503 }
504
505 /// dump - Print this user-defined conversion sequence to standard
506 /// error. Useful for debugging overloading issues.
dump() const507 void UserDefinedConversionSequence::dump() const {
508 raw_ostream &OS = llvm::errs();
509 if (Before.First || Before.Second || Before.Third) {
510 Before.dump();
511 OS << " -> ";
512 }
513 if (ConversionFunction)
514 OS << '\'' << *ConversionFunction << '\'';
515 else
516 OS << "aggregate initialization";
517 if (After.First || After.Second || After.Third) {
518 OS << " -> ";
519 After.dump();
520 }
521 }
522
523 /// dump - Print this implicit conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
dump() const525 void ImplicitConversionSequence::dump() const {
526 raw_ostream &OS = llvm::errs();
527 if (isStdInitializerListElement())
528 OS << "Worst std::initializer_list element conversion: ";
529 switch (ConversionKind) {
530 case StandardConversion:
531 OS << "Standard conversion: ";
532 Standard.dump();
533 break;
534 case UserDefinedConversion:
535 OS << "User-defined conversion: ";
536 UserDefined.dump();
537 break;
538 case EllipsisConversion:
539 OS << "Ellipsis conversion";
540 break;
541 case AmbiguousConversion:
542 OS << "Ambiguous conversion";
543 break;
544 case BadConversion:
545 OS << "Bad conversion";
546 break;
547 }
548
549 OS << "\n";
550 }
551
construct()552 void AmbiguousConversionSequence::construct() {
553 new (&conversions()) ConversionSet();
554 }
555
destruct()556 void AmbiguousConversionSequence::destruct() {
557 conversions().~ConversionSet();
558 }
559
560 void
copyFrom(const AmbiguousConversionSequence & O)561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562 FromTypePtr = O.FromTypePtr;
563 ToTypePtr = O.ToTypePtr;
564 new (&conversions()) ConversionSet(O.conversions());
565 }
566
567 namespace {
568 // Structure used by DeductionFailureInfo to store
569 // template argument information.
570 struct DFIArguments {
571 TemplateArgument FirstArg;
572 TemplateArgument SecondArg;
573 };
574 // Structure used by DeductionFailureInfo to store
575 // template parameter and template argument information.
576 struct DFIParamWithArguments : DFIArguments {
577 TemplateParameter Param;
578 };
579 // Structure used by DeductionFailureInfo to store template argument
580 // information and the index of the problematic call argument.
581 struct DFIDeducedMismatchArgs : DFIArguments {
582 TemplateArgumentList *TemplateArgs;
583 unsigned CallArgIndex;
584 };
585 }
586
587 /// Convert from Sema's representation of template deduction information
588 /// to the form used in overload-candidate information.
589 DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)590 clang::MakeDeductionFailureInfo(ASTContext &Context,
591 Sema::TemplateDeductionResult TDK,
592 TemplateDeductionInfo &Info) {
593 DeductionFailureInfo Result;
594 Result.Result = static_cast<unsigned>(TDK);
595 Result.HasDiagnostic = false;
596 switch (TDK) {
597 case Sema::TDK_Invalid:
598 case Sema::TDK_InstantiationDepth:
599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
601 case Sema::TDK_MiscellaneousDeductionFailure:
602 case Sema::TDK_CUDATargetMismatch:
603 Result.Data = nullptr;
604 break;
605
606 case Sema::TDK_Incomplete:
607 case Sema::TDK_InvalidExplicitArguments:
608 Result.Data = Info.Param.getOpaqueValue();
609 break;
610
611 case Sema::TDK_DeducedMismatch:
612 case Sema::TDK_DeducedMismatchNested: {
613 // FIXME: Should allocate from normal heap so that we can free this later.
614 auto *Saved = new (Context) DFIDeducedMismatchArgs;
615 Saved->FirstArg = Info.FirstArg;
616 Saved->SecondArg = Info.SecondArg;
617 Saved->TemplateArgs = Info.take();
618 Saved->CallArgIndex = Info.CallArgIndex;
619 Result.Data = Saved;
620 break;
621 }
622
623 case Sema::TDK_NonDeducedMismatch: {
624 // FIXME: Should allocate from normal heap so that we can free this later.
625 DFIArguments *Saved = new (Context) DFIArguments;
626 Saved->FirstArg = Info.FirstArg;
627 Saved->SecondArg = Info.SecondArg;
628 Result.Data = Saved;
629 break;
630 }
631
632 case Sema::TDK_IncompletePack:
633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634 case Sema::TDK_Inconsistent:
635 case Sema::TDK_Underqualified: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638 Saved->Param = Info.Param;
639 Saved->FirstArg = Info.FirstArg;
640 Saved->SecondArg = Info.SecondArg;
641 Result.Data = Saved;
642 break;
643 }
644
645 case Sema::TDK_SubstitutionFailure:
646 Result.Data = Info.take();
647 if (Info.hasSFINAEDiagnostic()) {
648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649 SourceLocation(), PartialDiagnostic::NullDiagnostic());
650 Info.takeSFINAEDiagnostic(*Diag);
651 Result.HasDiagnostic = true;
652 }
653 break;
654
655 case Sema::TDK_Success:
656 case Sema::TDK_NonDependentConversionFailure:
657 llvm_unreachable("not a deduction failure");
658 }
659
660 return Result;
661 }
662
Destroy()663 void DeductionFailureInfo::Destroy() {
664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
666 case Sema::TDK_Invalid:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_Incomplete:
669 case Sema::TDK_TooManyArguments:
670 case Sema::TDK_TooFewArguments:
671 case Sema::TDK_InvalidExplicitArguments:
672 case Sema::TDK_CUDATargetMismatch:
673 case Sema::TDK_NonDependentConversionFailure:
674 break;
675
676 case Sema::TDK_IncompletePack:
677 case Sema::TDK_Inconsistent:
678 case Sema::TDK_Underqualified:
679 case Sema::TDK_DeducedMismatch:
680 case Sema::TDK_DeducedMismatchNested:
681 case Sema::TDK_NonDeducedMismatch:
682 // FIXME: Destroy the data?
683 Data = nullptr;
684 break;
685
686 case Sema::TDK_SubstitutionFailure:
687 // FIXME: Destroy the template argument list?
688 Data = nullptr;
689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690 Diag->~PartialDiagnosticAt();
691 HasDiagnostic = false;
692 }
693 break;
694
695 // Unhandled
696 case Sema::TDK_MiscellaneousDeductionFailure:
697 break;
698 }
699 }
700
getSFINAEDiagnostic()701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702 if (HasDiagnostic)
703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704 return nullptr;
705 }
706
getTemplateParameter()707 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
710 case Sema::TDK_Invalid:
711 case Sema::TDK_InstantiationDepth:
712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
714 case Sema::TDK_SubstitutionFailure:
715 case Sema::TDK_DeducedMismatch:
716 case Sema::TDK_DeducedMismatchNested:
717 case Sema::TDK_NonDeducedMismatch:
718 case Sema::TDK_CUDATargetMismatch:
719 case Sema::TDK_NonDependentConversionFailure:
720 return TemplateParameter();
721
722 case Sema::TDK_Incomplete:
723 case Sema::TDK_InvalidExplicitArguments:
724 return TemplateParameter::getFromOpaqueValue(Data);
725
726 case Sema::TDK_IncompletePack:
727 case Sema::TDK_Inconsistent:
728 case Sema::TDK_Underqualified:
729 return static_cast<DFIParamWithArguments*>(Data)->Param;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735
736 return TemplateParameter();
737 }
738
getTemplateArgumentList()739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741 case Sema::TDK_Success:
742 case Sema::TDK_Invalid:
743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_TooManyArguments:
745 case Sema::TDK_TooFewArguments:
746 case Sema::TDK_Incomplete:
747 case Sema::TDK_IncompletePack:
748 case Sema::TDK_InvalidExplicitArguments:
749 case Sema::TDK_Inconsistent:
750 case Sema::TDK_Underqualified:
751 case Sema::TDK_NonDeducedMismatch:
752 case Sema::TDK_CUDATargetMismatch:
753 case Sema::TDK_NonDependentConversionFailure:
754 return nullptr;
755
756 case Sema::TDK_DeducedMismatch:
757 case Sema::TDK_DeducedMismatchNested:
758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
760 case Sema::TDK_SubstitutionFailure:
761 return static_cast<TemplateArgumentList*>(Data);
762
763 // Unhandled
764 case Sema::TDK_MiscellaneousDeductionFailure:
765 break;
766 }
767
768 return nullptr;
769 }
770
getFirstArg()771 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
774 case Sema::TDK_Invalid:
775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
779 case Sema::TDK_InvalidExplicitArguments:
780 case Sema::TDK_SubstitutionFailure:
781 case Sema::TDK_CUDATargetMismatch:
782 case Sema::TDK_NonDependentConversionFailure:
783 return nullptr;
784
785 case Sema::TDK_IncompletePack:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_DeducedMismatch:
789 case Sema::TDK_DeducedMismatchNested:
790 case Sema::TDK_NonDeducedMismatch:
791 return &static_cast<DFIArguments*>(Data)->FirstArg;
792
793 // Unhandled
794 case Sema::TDK_MiscellaneousDeductionFailure:
795 break;
796 }
797
798 return nullptr;
799 }
800
getSecondArg()801 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803 case Sema::TDK_Success:
804 case Sema::TDK_Invalid:
805 case Sema::TDK_InstantiationDepth:
806 case Sema::TDK_Incomplete:
807 case Sema::TDK_IncompletePack:
808 case Sema::TDK_TooManyArguments:
809 case Sema::TDK_TooFewArguments:
810 case Sema::TDK_InvalidExplicitArguments:
811 case Sema::TDK_SubstitutionFailure:
812 case Sema::TDK_CUDATargetMismatch:
813 case Sema::TDK_NonDependentConversionFailure:
814 return nullptr;
815
816 case Sema::TDK_Inconsistent:
817 case Sema::TDK_Underqualified:
818 case Sema::TDK_DeducedMismatch:
819 case Sema::TDK_DeducedMismatchNested:
820 case Sema::TDK_NonDeducedMismatch:
821 return &static_cast<DFIArguments*>(Data)->SecondArg;
822
823 // Unhandled
824 case Sema::TDK_MiscellaneousDeductionFailure:
825 break;
826 }
827
828 return nullptr;
829 }
830
getCallArgIndex()831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
837 default:
838 return llvm::None;
839 }
840 }
841
destroyCandidates()842 void OverloadCandidateSet::destroyCandidates() {
843 for (iterator i = begin(), e = end(); i != e; ++i) {
844 for (auto &C : i->Conversions)
845 C.~ImplicitConversionSequence();
846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847 i->DeductionFailure.Destroy();
848 }
849 }
850
clear(CandidateSetKind CSK)851 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852 destroyCandidates();
853 SlabAllocator.Reset();
854 NumInlineBytesUsed = 0;
855 Candidates.clear();
856 Functions.clear();
857 Kind = CSK;
858 }
859
860 namespace {
861 class UnbridgedCastsSet {
862 struct Entry {
863 Expr **Addr;
864 Expr *Saved;
865 };
866 SmallVector<Entry, 2> Entries;
867
868 public:
save(Sema & S,Expr * & E)869 void save(Sema &S, Expr *&E) {
870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871 Entry entry = { &E, E };
872 Entries.push_back(entry);
873 E = S.stripARCUnbridgedCast(E);
874 }
875
restore()876 void restore() {
877 for (SmallVectorImpl<Entry>::iterator
878 i = Entries.begin(), e = Entries.end(); i != e; ++i)
879 *i->Addr = i->Saved;
880 }
881 };
882 }
883
884 /// checkPlaceholderForOverload - Do any interesting placeholder-like
885 /// preprocessing on the given expression.
886 ///
887 /// \param unbridgedCasts a collection to which to add unbridged casts;
888 /// without this, they will be immediately diagnosed as errors
889 ///
890 /// Return true on unrecoverable error.
891 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)892 checkPlaceholderForOverload(Sema &S, Expr *&E,
893 UnbridgedCastsSet *unbridgedCasts = nullptr) {
894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
895 // We can't handle overloaded expressions here because overload
896 // resolution might reasonably tweak them.
897 if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899 // If the context potentially accepts unbridged ARC casts, strip
900 // the unbridged cast and add it to the collection for later restoration.
901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902 unbridgedCasts) {
903 unbridgedCasts->save(S, E);
904 return false;
905 }
906
907 // Go ahead and check everything else.
908 ExprResult result = S.CheckPlaceholderExpr(E);
909 if (result.isInvalid())
910 return true;
911
912 E = result.get();
913 return false;
914 }
915
916 // Nothing to do.
917 return false;
918 }
919
920 /// checkArgPlaceholdersForOverload - Check a set of call operands for
921 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)922 static bool checkArgPlaceholdersForOverload(Sema &S,
923 MultiExprArg Args,
924 UnbridgedCastsSet &unbridged) {
925 for (unsigned i = 0, e = Args.size(); i != e; ++i)
926 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927 return true;
928
929 return false;
930 }
931
932 /// Determine whether the given New declaration is an overload of the
933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934 /// New and Old cannot be overloaded, e.g., if New has the same signature as
935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936 /// functions (or function templates) at all. When it does return Ovl_Match or
937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939 /// declaration.
940 ///
941 /// Example: Given the following input:
942 ///
943 /// void f(int, float); // #1
944 /// void f(int, int); // #2
945 /// int f(int, int); // #3
946 ///
947 /// When we process #1, there is no previous declaration of "f", so IsOverload
948 /// will not be used.
949 ///
950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951 /// the parameter types, we see that #1 and #2 are overloaded (since they have
952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953 /// unchanged.
954 ///
955 /// When we process #3, Old is an overload set containing #1 and #2. We compare
956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958 /// functions are not part of the signature), IsOverload returns Ovl_Match and
959 /// MatchedDecl will be set to point to the FunctionDecl for #2.
960 ///
961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962 /// by a using declaration. The rules for whether to hide shadow declarations
963 /// ignore some properties which otherwise figure into a function template's
964 /// signature.
965 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967 NamedDecl *&Match, bool NewIsUsingDecl) {
968 for (LookupResult::iterator I = Old.begin(), E = Old.end();
969 I != E; ++I) {
970 NamedDecl *OldD = *I;
971
972 bool OldIsUsingDecl = false;
973 if (isa<UsingShadowDecl>(OldD)) {
974 OldIsUsingDecl = true;
975
976 // We can always introduce two using declarations into the same
977 // context, even if they have identical signatures.
978 if (NewIsUsingDecl) continue;
979
980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981 }
982
983 // A using-declaration does not conflict with another declaration
984 // if one of them is hidden.
985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986 continue;
987
988 // If either declaration was introduced by a using declaration,
989 // we'll need to use slightly different rules for matching.
990 // Essentially, these rules are the normal rules, except that
991 // function templates hide function templates with different
992 // return types or template parameter lists.
993 bool UseMemberUsingDeclRules =
994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995 !New->getFriendObjectKind();
996
997 if (FunctionDecl *OldF = OldD->getAsFunction()) {
998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 continue;
1002 }
1003
1004 if (!isa<FunctionTemplateDecl>(OldD) &&
1005 !shouldLinkPossiblyHiddenDecl(*I, New))
1006 continue;
1007
1008 Match = *I;
1009 return Ovl_Match;
1010 }
1011
1012 // Builtins that have custom typechecking or have a reference should
1013 // not be overloadable or redeclarable.
1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019 // We can overload with these, which can show up when doing
1020 // redeclaration checks for UsingDecls.
1021 assert(Old.getLookupKind() == LookupUsingDeclName);
1022 } else if (isa<TagDecl>(OldD)) {
1023 // We can always overload with tags by hiding them.
1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025 // Optimistically assume that an unresolved using decl will
1026 // overload; if it doesn't, we'll have to diagnose during
1027 // template instantiation.
1028 //
1029 // Exception: if the scope is dependent and this is not a class
1030 // member, the using declaration can only introduce an enumerator.
1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
1035 } else {
1036 // (C++ 13p1):
1037 // Only function declarations can be overloaded; object and type
1038 // declarations cannot be overloaded.
1039 Match = *I;
1040 return Ovl_NonFunction;
1041 }
1042 }
1043
1044 // C++ [temp.friend]p1:
1045 // For a friend function declaration that is not a template declaration:
1046 // -- if the name of the friend is a qualified or unqualified template-id,
1047 // [...], otherwise
1048 // -- if the name of the friend is a qualified-id and a matching
1049 // non-template function is found in the specified class or namespace,
1050 // the friend declaration refers to that function, otherwise,
1051 // -- if the name of the friend is a qualified-id and a matching function
1052 // template is found in the specified class or namespace, the friend
1053 // declaration refers to the deduced specialization of that function
1054 // template, otherwise
1055 // -- the name shall be an unqualified-id [...]
1056 // If we get here for a qualified friend declaration, we've just reached the
1057 // third bullet. If the type of the friend is dependent, skip this lookup
1058 // until instantiation.
1059 if (New->getFriendObjectKind() && New->getQualifier() &&
1060 !New->getDependentSpecializationInfo() &&
1061 !New->getType()->isDependentType()) {
1062 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1063 TemplateSpecResult.addAllDecls(Old);
1064 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1065 /*QualifiedFriend*/true)) {
1066 New->setInvalidDecl();
1067 return Ovl_Overload;
1068 }
1069
1070 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1071 return Ovl_Match;
1072 }
1073
1074 return Ovl_Overload;
1075 }
1076
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)1077 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1078 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1079 // C++ [basic.start.main]p2: This function shall not be overloaded.
1080 if (New->isMain())
1081 return false;
1082
1083 // MSVCRT user defined entry points cannot be overloaded.
1084 if (New->isMSVCRTEntryPoint())
1085 return false;
1086
1087 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1088 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1089
1090 // C++ [temp.fct]p2:
1091 // A function template can be overloaded with other function templates
1092 // and with normal (non-template) functions.
1093 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1094 return true;
1095
1096 // Is the function New an overload of the function Old?
1097 QualType OldQType = Context.getCanonicalType(Old->getType());
1098 QualType NewQType = Context.getCanonicalType(New->getType());
1099
1100 // Compare the signatures (C++ 1.3.10) of the two functions to
1101 // determine whether they are overloads. If we find any mismatch
1102 // in the signature, they are overloads.
1103
1104 // If either of these functions is a K&R-style function (no
1105 // prototype), then we consider them to have matching signatures.
1106 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1107 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1108 return false;
1109
1110 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1111 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1112
1113 // The signature of a function includes the types of its
1114 // parameters (C++ 1.3.10), which includes the presence or absence
1115 // of the ellipsis; see C++ DR 357).
1116 if (OldQType != NewQType &&
1117 (OldType->getNumParams() != NewType->getNumParams() ||
1118 OldType->isVariadic() != NewType->isVariadic() ||
1119 !FunctionParamTypesAreEqual(OldType, NewType)))
1120 return true;
1121
1122 // C++ [temp.over.link]p4:
1123 // The signature of a function template consists of its function
1124 // signature, its return type and its template parameter list. The names
1125 // of the template parameters are significant only for establishing the
1126 // relationship between the template parameters and the rest of the
1127 // signature.
1128 //
1129 // We check the return type and template parameter lists for function
1130 // templates first; the remaining checks follow.
1131 //
1132 // However, we don't consider either of these when deciding whether
1133 // a member introduced by a shadow declaration is hidden.
1134 if (!UseMemberUsingDeclRules && NewTemplate &&
1135 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1136 OldTemplate->getTemplateParameters(),
1137 false, TPL_TemplateMatch) ||
1138 !Context.hasSameType(Old->getDeclaredReturnType(),
1139 New->getDeclaredReturnType())))
1140 return true;
1141
1142 // If the function is a class member, its signature includes the
1143 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1144 //
1145 // As part of this, also check whether one of the member functions
1146 // is static, in which case they are not overloads (C++
1147 // 13.1p2). While not part of the definition of the signature,
1148 // this check is important to determine whether these functions
1149 // can be overloaded.
1150 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1151 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1152 if (OldMethod && NewMethod &&
1153 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1154 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1155 if (!UseMemberUsingDeclRules &&
1156 (OldMethod->getRefQualifier() == RQ_None ||
1157 NewMethod->getRefQualifier() == RQ_None)) {
1158 // C++0x [over.load]p2:
1159 // - Member function declarations with the same name and the same
1160 // parameter-type-list as well as member function template
1161 // declarations with the same name, the same parameter-type-list, and
1162 // the same template parameter lists cannot be overloaded if any of
1163 // them, but not all, have a ref-qualifier (8.3.5).
1164 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1165 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1166 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1167 }
1168 return true;
1169 }
1170
1171 // We may not have applied the implicit const for a constexpr member
1172 // function yet (because we haven't yet resolved whether this is a static
1173 // or non-static member function). Add it now, on the assumption that this
1174 // is a redeclaration of OldMethod.
1175 // FIXME: OpenCL: Need to consider address spaces
1176 unsigned OldQuals = OldMethod->getTypeQualifiers().getCVRUQualifiers();
1177 unsigned NewQuals = NewMethod->getTypeQualifiers().getCVRUQualifiers();
1178 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1179 !isa<CXXConstructorDecl>(NewMethod))
1180 NewQuals |= Qualifiers::Const;
1181
1182 // We do not allow overloading based off of '__restrict'.
1183 OldQuals &= ~Qualifiers::Restrict;
1184 NewQuals &= ~Qualifiers::Restrict;
1185 if (OldQuals != NewQuals)
1186 return true;
1187 }
1188
1189 // Though pass_object_size is placed on parameters and takes an argument, we
1190 // consider it to be a function-level modifier for the sake of function
1191 // identity. Either the function has one or more parameters with
1192 // pass_object_size or it doesn't.
1193 if (functionHasPassObjectSizeParams(New) !=
1194 functionHasPassObjectSizeParams(Old))
1195 return true;
1196
1197 // enable_if attributes are an order-sensitive part of the signature.
1198 for (specific_attr_iterator<EnableIfAttr>
1199 NewI = New->specific_attr_begin<EnableIfAttr>(),
1200 NewE = New->specific_attr_end<EnableIfAttr>(),
1201 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1202 OldE = Old->specific_attr_end<EnableIfAttr>();
1203 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1204 if (NewI == NewE || OldI == OldE)
1205 return true;
1206 llvm::FoldingSetNodeID NewID, OldID;
1207 NewI->getCond()->Profile(NewID, Context, true);
1208 OldI->getCond()->Profile(OldID, Context, true);
1209 if (NewID != OldID)
1210 return true;
1211 }
1212
1213 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1214 // Don't allow overloading of destructors. (In theory we could, but it
1215 // would be a giant change to clang.)
1216 if (isa<CXXDestructorDecl>(New))
1217 return false;
1218
1219 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1220 OldTarget = IdentifyCUDATarget(Old);
1221 if (NewTarget == CFT_InvalidTarget)
1222 return false;
1223
1224 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1225
1226 // Allow overloading of functions with same signature and different CUDA
1227 // target attributes.
1228 return NewTarget != OldTarget;
1229 }
1230
1231 // The signatures match; this is not an overload.
1232 return false;
1233 }
1234
1235 /// Checks availability of the function depending on the current
1236 /// function context. Inside an unavailable function, unavailability is ignored.
1237 ///
1238 /// \returns true if \arg FD is unavailable and current context is inside
1239 /// an available function, false otherwise.
isFunctionConsideredUnavailable(FunctionDecl * FD)1240 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1241 if (!FD->isUnavailable())
1242 return false;
1243
1244 // Walk up the context of the caller.
1245 Decl *C = cast<Decl>(CurContext);
1246 do {
1247 if (C->isUnavailable())
1248 return false;
1249 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1250 return true;
1251 }
1252
1253 /// Tries a user-defined conversion from From to ToType.
1254 ///
1255 /// Produces an implicit conversion sequence for when a standard conversion
1256 /// is not an option. See TryImplicitConversion for more information.
1257 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1258 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1259 bool SuppressUserConversions,
1260 bool AllowExplicit,
1261 bool InOverloadResolution,
1262 bool CStyle,
1263 bool AllowObjCWritebackConversion,
1264 bool AllowObjCConversionOnExplicit) {
1265 ImplicitConversionSequence ICS;
1266
1267 if (SuppressUserConversions) {
1268 // We're not in the case above, so there is no conversion that
1269 // we can perform.
1270 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1271 return ICS;
1272 }
1273
1274 // Attempt user-defined conversion.
1275 OverloadCandidateSet Conversions(From->getExprLoc(),
1276 OverloadCandidateSet::CSK_Normal);
1277 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1278 Conversions, AllowExplicit,
1279 AllowObjCConversionOnExplicit)) {
1280 case OR_Success:
1281 case OR_Deleted:
1282 ICS.setUserDefined();
1283 // C++ [over.ics.user]p4:
1284 // A conversion of an expression of class type to the same class
1285 // type is given Exact Match rank, and a conversion of an
1286 // expression of class type to a base class of that type is
1287 // given Conversion rank, in spite of the fact that a copy
1288 // constructor (i.e., a user-defined conversion function) is
1289 // called for those cases.
1290 if (CXXConstructorDecl *Constructor
1291 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1292 QualType FromCanon
1293 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1294 QualType ToCanon
1295 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1296 if (Constructor->isCopyConstructor() &&
1297 (FromCanon == ToCanon ||
1298 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1299 // Turn this into a "standard" conversion sequence, so that it
1300 // gets ranked with standard conversion sequences.
1301 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1302 ICS.setStandard();
1303 ICS.Standard.setAsIdentityConversion();
1304 ICS.Standard.setFromType(From->getType());
1305 ICS.Standard.setAllToTypes(ToType);
1306 ICS.Standard.CopyConstructor = Constructor;
1307 ICS.Standard.FoundCopyConstructor = Found;
1308 if (ToCanon != FromCanon)
1309 ICS.Standard.Second = ICK_Derived_To_Base;
1310 }
1311 }
1312 break;
1313
1314 case OR_Ambiguous:
1315 ICS.setAmbiguous();
1316 ICS.Ambiguous.setFromType(From->getType());
1317 ICS.Ambiguous.setToType(ToType);
1318 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1319 Cand != Conversions.end(); ++Cand)
1320 if (Cand->Viable)
1321 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1322 break;
1323
1324 // Fall through.
1325 case OR_No_Viable_Function:
1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327 break;
1328 }
1329
1330 return ICS;
1331 }
1332
1333 /// TryImplicitConversion - Attempt to perform an implicit conversion
1334 /// from the given expression (Expr) to the given type (ToType). This
1335 /// function returns an implicit conversion sequence that can be used
1336 /// to perform the initialization. Given
1337 ///
1338 /// void f(float f);
1339 /// void g(int i) { f(i); }
1340 ///
1341 /// this routine would produce an implicit conversion sequence to
1342 /// describe the initialization of f from i, which will be a standard
1343 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1344 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1345 //
1346 /// Note that this routine only determines how the conversion can be
1347 /// performed; it does not actually perform the conversion. As such,
1348 /// it will not produce any diagnostics if no conversion is available,
1349 /// but will instead return an implicit conversion sequence of kind
1350 /// "BadConversion".
1351 ///
1352 /// If @p SuppressUserConversions, then user-defined conversions are
1353 /// not permitted.
1354 /// If @p AllowExplicit, then explicit user-defined conversions are
1355 /// permitted.
1356 ///
1357 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1358 /// writeback conversion, which allows __autoreleasing id* parameters to
1359 /// be initialized with __strong id* or __weak id* arguments.
1360 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1361 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1362 bool SuppressUserConversions,
1363 bool AllowExplicit,
1364 bool InOverloadResolution,
1365 bool CStyle,
1366 bool AllowObjCWritebackConversion,
1367 bool AllowObjCConversionOnExplicit) {
1368 ImplicitConversionSequence ICS;
1369 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1370 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1371 ICS.setStandard();
1372 return ICS;
1373 }
1374
1375 if (!S.getLangOpts().CPlusPlus) {
1376 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1377 return ICS;
1378 }
1379
1380 // C++ [over.ics.user]p4:
1381 // A conversion of an expression of class type to the same class
1382 // type is given Exact Match rank, and a conversion of an
1383 // expression of class type to a base class of that type is
1384 // given Conversion rank, in spite of the fact that a copy/move
1385 // constructor (i.e., a user-defined conversion function) is
1386 // called for those cases.
1387 QualType FromType = From->getType();
1388 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1389 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1390 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1391 ICS.setStandard();
1392 ICS.Standard.setAsIdentityConversion();
1393 ICS.Standard.setFromType(FromType);
1394 ICS.Standard.setAllToTypes(ToType);
1395
1396 // We don't actually check at this point whether there is a valid
1397 // copy/move constructor, since overloading just assumes that it
1398 // exists. When we actually perform initialization, we'll find the
1399 // appropriate constructor to copy the returned object, if needed.
1400 ICS.Standard.CopyConstructor = nullptr;
1401
1402 // Determine whether this is considered a derived-to-base conversion.
1403 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1404 ICS.Standard.Second = ICK_Derived_To_Base;
1405
1406 return ICS;
1407 }
1408
1409 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1410 AllowExplicit, InOverloadResolution, CStyle,
1411 AllowObjCWritebackConversion,
1412 AllowObjCConversionOnExplicit);
1413 }
1414
1415 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1416 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1417 bool SuppressUserConversions,
1418 bool AllowExplicit,
1419 bool InOverloadResolution,
1420 bool CStyle,
1421 bool AllowObjCWritebackConversion) {
1422 return ::TryImplicitConversion(*this, From, ToType,
1423 SuppressUserConversions, AllowExplicit,
1424 InOverloadResolution, CStyle,
1425 AllowObjCWritebackConversion,
1426 /*AllowObjCConversionOnExplicit=*/false);
1427 }
1428
1429 /// PerformImplicitConversion - Perform an implicit conversion of the
1430 /// expression From to the type ToType. Returns the
1431 /// converted expression. Flavor is the kind of conversion we're
1432 /// performing, used in the error message. If @p AllowExplicit,
1433 /// explicit user-defined conversions are permitted.
1434 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1435 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1436 AssignmentAction Action, bool AllowExplicit) {
1437 ImplicitConversionSequence ICS;
1438 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1439 }
1440
1441 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1442 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1443 AssignmentAction Action, bool AllowExplicit,
1444 ImplicitConversionSequence& ICS) {
1445 if (checkPlaceholderForOverload(*this, From))
1446 return ExprError();
1447
1448 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1449 bool AllowObjCWritebackConversion
1450 = getLangOpts().ObjCAutoRefCount &&
1451 (Action == AA_Passing || Action == AA_Sending);
1452 if (getLangOpts().ObjC)
1453 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1454 From->getType(), From);
1455 ICS = ::TryImplicitConversion(*this, From, ToType,
1456 /*SuppressUserConversions=*/false,
1457 AllowExplicit,
1458 /*InOverloadResolution=*/false,
1459 /*CStyle=*/false,
1460 AllowObjCWritebackConversion,
1461 /*AllowObjCConversionOnExplicit=*/false);
1462 return PerformImplicitConversion(From, ToType, ICS, Action);
1463 }
1464
1465 /// Determine whether the conversion from FromType to ToType is a valid
1466 /// conversion that strips "noexcept" or "noreturn" off the nested function
1467 /// type.
IsFunctionConversion(QualType FromType,QualType ToType,QualType & ResultTy)1468 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1469 QualType &ResultTy) {
1470 if (Context.hasSameUnqualifiedType(FromType, ToType))
1471 return false;
1472
1473 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1474 // or F(t noexcept) -> F(t)
1475 // where F adds one of the following at most once:
1476 // - a pointer
1477 // - a member pointer
1478 // - a block pointer
1479 // Changes here need matching changes in FindCompositePointerType.
1480 CanQualType CanTo = Context.getCanonicalType(ToType);
1481 CanQualType CanFrom = Context.getCanonicalType(FromType);
1482 Type::TypeClass TyClass = CanTo->getTypeClass();
1483 if (TyClass != CanFrom->getTypeClass()) return false;
1484 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1485 if (TyClass == Type::Pointer) {
1486 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1487 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1488 } else if (TyClass == Type::BlockPointer) {
1489 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1490 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1491 } else if (TyClass == Type::MemberPointer) {
1492 auto ToMPT = CanTo.getAs<MemberPointerType>();
1493 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1494 // A function pointer conversion cannot change the class of the function.
1495 if (ToMPT->getClass() != FromMPT->getClass())
1496 return false;
1497 CanTo = ToMPT->getPointeeType();
1498 CanFrom = FromMPT->getPointeeType();
1499 } else {
1500 return false;
1501 }
1502
1503 TyClass = CanTo->getTypeClass();
1504 if (TyClass != CanFrom->getTypeClass()) return false;
1505 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1506 return false;
1507 }
1508
1509 const auto *FromFn = cast<FunctionType>(CanFrom);
1510 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1511
1512 const auto *ToFn = cast<FunctionType>(CanTo);
1513 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1514
1515 bool Changed = false;
1516
1517 // Drop 'noreturn' if not present in target type.
1518 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1519 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1520 Changed = true;
1521 }
1522
1523 // Drop 'noexcept' if not present in target type.
1524 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1525 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1526 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1527 FromFn = cast<FunctionType>(
1528 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1529 EST_None)
1530 .getTypePtr());
1531 Changed = true;
1532 }
1533
1534 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1535 // only if the ExtParameterInfo lists of the two function prototypes can be
1536 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1537 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1538 bool CanUseToFPT, CanUseFromFPT;
1539 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1540 CanUseFromFPT, NewParamInfos) &&
1541 CanUseToFPT && !CanUseFromFPT) {
1542 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1543 ExtInfo.ExtParameterInfos =
1544 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1545 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1546 FromFPT->getParamTypes(), ExtInfo);
1547 FromFn = QT->getAs<FunctionType>();
1548 Changed = true;
1549 }
1550 }
1551
1552 if (!Changed)
1553 return false;
1554
1555 assert(QualType(FromFn, 0).isCanonical());
1556 if (QualType(FromFn, 0) != CanTo) return false;
1557
1558 ResultTy = ToType;
1559 return true;
1560 }
1561
1562 /// Determine whether the conversion from FromType to ToType is a valid
1563 /// vector conversion.
1564 ///
1565 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1566 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1567 static bool IsVectorConversion(Sema &S, QualType FromType,
1568 QualType ToType, ImplicitConversionKind &ICK) {
1569 // We need at least one of these types to be a vector type to have a vector
1570 // conversion.
1571 if (!ToType->isVectorType() && !FromType->isVectorType())
1572 return false;
1573
1574 // Identical types require no conversions.
1575 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1576 return false;
1577
1578 // There are no conversions between extended vector types, only identity.
1579 if (ToType->isExtVectorType()) {
1580 // There are no conversions between extended vector types other than the
1581 // identity conversion.
1582 if (FromType->isExtVectorType())
1583 return false;
1584
1585 // Vector splat from any arithmetic type to a vector.
1586 if (FromType->isArithmeticType()) {
1587 ICK = ICK_Vector_Splat;
1588 return true;
1589 }
1590 }
1591
1592 // We can perform the conversion between vector types in the following cases:
1593 // 1)vector types are equivalent AltiVec and GCC vector types
1594 // 2)lax vector conversions are permitted and the vector types are of the
1595 // same size
1596 if (ToType->isVectorType() && FromType->isVectorType()) {
1597 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1598 S.isLaxVectorConversion(FromType, ToType)) {
1599 ICK = ICK_Vector_Conversion;
1600 return true;
1601 }
1602 }
1603
1604 return false;
1605 }
1606
1607 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1608 bool InOverloadResolution,
1609 StandardConversionSequence &SCS,
1610 bool CStyle);
1611
1612 /// IsStandardConversion - Determines whether there is a standard
1613 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1614 /// expression From to the type ToType. Standard conversion sequences
1615 /// only consider non-class types; for conversions that involve class
1616 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1617 /// contain the standard conversion sequence required to perform this
1618 /// conversion and this routine will return true. Otherwise, this
1619 /// routine will return false and the value of SCS is unspecified.
IsStandardConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle,bool AllowObjCWritebackConversion)1620 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1621 bool InOverloadResolution,
1622 StandardConversionSequence &SCS,
1623 bool CStyle,
1624 bool AllowObjCWritebackConversion) {
1625 QualType FromType = From->getType();
1626
1627 // Standard conversions (C++ [conv])
1628 SCS.setAsIdentityConversion();
1629 SCS.IncompatibleObjC = false;
1630 SCS.setFromType(FromType);
1631 SCS.CopyConstructor = nullptr;
1632
1633 // There are no standard conversions for class types in C++, so
1634 // abort early. When overloading in C, however, we do permit them.
1635 if (S.getLangOpts().CPlusPlus &&
1636 (FromType->isRecordType() || ToType->isRecordType()))
1637 return false;
1638
1639 // The first conversion can be an lvalue-to-rvalue conversion,
1640 // array-to-pointer conversion, or function-to-pointer conversion
1641 // (C++ 4p1).
1642
1643 if (FromType == S.Context.OverloadTy) {
1644 DeclAccessPair AccessPair;
1645 if (FunctionDecl *Fn
1646 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1647 AccessPair)) {
1648 // We were able to resolve the address of the overloaded function,
1649 // so we can convert to the type of that function.
1650 FromType = Fn->getType();
1651 SCS.setFromType(FromType);
1652
1653 // we can sometimes resolve &foo<int> regardless of ToType, so check
1654 // if the type matches (identity) or we are converting to bool
1655 if (!S.Context.hasSameUnqualifiedType(
1656 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1657 QualType resultTy;
1658 // if the function type matches except for [[noreturn]], it's ok
1659 if (!S.IsFunctionConversion(FromType,
1660 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1661 // otherwise, only a boolean conversion is standard
1662 if (!ToType->isBooleanType())
1663 return false;
1664 }
1665
1666 // Check if the "from" expression is taking the address of an overloaded
1667 // function and recompute the FromType accordingly. Take advantage of the
1668 // fact that non-static member functions *must* have such an address-of
1669 // expression.
1670 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1671 if (Method && !Method->isStatic()) {
1672 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1673 "Non-unary operator on non-static member address");
1674 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1675 == UO_AddrOf &&
1676 "Non-address-of operator on non-static member address");
1677 const Type *ClassType
1678 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1679 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1680 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1681 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1682 UO_AddrOf &&
1683 "Non-address-of operator for overloaded function expression");
1684 FromType = S.Context.getPointerType(FromType);
1685 }
1686
1687 // Check that we've computed the proper type after overload resolution.
1688 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1689 // be calling it from within an NDEBUG block.
1690 assert(S.Context.hasSameType(
1691 FromType,
1692 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1693 } else {
1694 return false;
1695 }
1696 }
1697 // Lvalue-to-rvalue conversion (C++11 4.1):
1698 // A glvalue (3.10) of a non-function, non-array type T can
1699 // be converted to a prvalue.
1700 bool argIsLValue = From->isGLValue();
1701 if (argIsLValue &&
1702 !FromType->isFunctionType() && !FromType->isArrayType() &&
1703 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1704 SCS.First = ICK_Lvalue_To_Rvalue;
1705
1706 // C11 6.3.2.1p2:
1707 // ... if the lvalue has atomic type, the value has the non-atomic version
1708 // of the type of the lvalue ...
1709 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1710 FromType = Atomic->getValueType();
1711
1712 // If T is a non-class type, the type of the rvalue is the
1713 // cv-unqualified version of T. Otherwise, the type of the rvalue
1714 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1715 // just strip the qualifiers because they don't matter.
1716 FromType = FromType.getUnqualifiedType();
1717 } else if (FromType->isArrayType()) {
1718 // Array-to-pointer conversion (C++ 4.2)
1719 SCS.First = ICK_Array_To_Pointer;
1720
1721 // An lvalue or rvalue of type "array of N T" or "array of unknown
1722 // bound of T" can be converted to an rvalue of type "pointer to
1723 // T" (C++ 4.2p1).
1724 FromType = S.Context.getArrayDecayedType(FromType);
1725
1726 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1727 // This conversion is deprecated in C++03 (D.4)
1728 SCS.DeprecatedStringLiteralToCharPtr = true;
1729
1730 // For the purpose of ranking in overload resolution
1731 // (13.3.3.1.1), this conversion is considered an
1732 // array-to-pointer conversion followed by a qualification
1733 // conversion (4.4). (C++ 4.2p2)
1734 SCS.Second = ICK_Identity;
1735 SCS.Third = ICK_Qualification;
1736 SCS.QualificationIncludesObjCLifetime = false;
1737 SCS.setAllToTypes(FromType);
1738 return true;
1739 }
1740 } else if (FromType->isFunctionType() && argIsLValue) {
1741 // Function-to-pointer conversion (C++ 4.3).
1742 SCS.First = ICK_Function_To_Pointer;
1743
1744 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1745 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1746 if (!S.checkAddressOfFunctionIsAvailable(FD))
1747 return false;
1748
1749 // An lvalue of function type T can be converted to an rvalue of
1750 // type "pointer to T." The result is a pointer to the
1751 // function. (C++ 4.3p1).
1752 FromType = S.Context.getPointerType(FromType);
1753 } else {
1754 // We don't require any conversions for the first step.
1755 SCS.First = ICK_Identity;
1756 }
1757 SCS.setToType(0, FromType);
1758
1759 // The second conversion can be an integral promotion, floating
1760 // point promotion, integral conversion, floating point conversion,
1761 // floating-integral conversion, pointer conversion,
1762 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1763 // For overloading in C, this can also be a "compatible-type"
1764 // conversion.
1765 bool IncompatibleObjC = false;
1766 ImplicitConversionKind SecondICK = ICK_Identity;
1767 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1768 // The unqualified versions of the types are the same: there's no
1769 // conversion to do.
1770 SCS.Second = ICK_Identity;
1771 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1772 // Integral promotion (C++ 4.5).
1773 SCS.Second = ICK_Integral_Promotion;
1774 FromType = ToType.getUnqualifiedType();
1775 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1776 // Floating point promotion (C++ 4.6).
1777 SCS.Second = ICK_Floating_Promotion;
1778 FromType = ToType.getUnqualifiedType();
1779 } else if (S.IsComplexPromotion(FromType, ToType)) {
1780 // Complex promotion (Clang extension)
1781 SCS.Second = ICK_Complex_Promotion;
1782 FromType = ToType.getUnqualifiedType();
1783 } else if (ToType->isBooleanType() &&
1784 (FromType->isArithmeticType() ||
1785 FromType->isAnyPointerType() ||
1786 FromType->isBlockPointerType() ||
1787 FromType->isMemberPointerType() ||
1788 FromType->isNullPtrType())) {
1789 // Boolean conversions (C++ 4.12).
1790 SCS.Second = ICK_Boolean_Conversion;
1791 FromType = S.Context.BoolTy;
1792 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1793 ToType->isIntegralType(S.Context)) {
1794 // Integral conversions (C++ 4.7).
1795 SCS.Second = ICK_Integral_Conversion;
1796 FromType = ToType.getUnqualifiedType();
1797 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1798 // Complex conversions (C99 6.3.1.6)
1799 SCS.Second = ICK_Complex_Conversion;
1800 FromType = ToType.getUnqualifiedType();
1801 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1802 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1803 // Complex-real conversions (C99 6.3.1.7)
1804 SCS.Second = ICK_Complex_Real;
1805 FromType = ToType.getUnqualifiedType();
1806 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1807 // FIXME: disable conversions between long double and __float128 if
1808 // their representation is different until there is back end support
1809 // We of course allow this conversion if long double is really double.
1810 if (&S.Context.getFloatTypeSemantics(FromType) !=
1811 &S.Context.getFloatTypeSemantics(ToType)) {
1812 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1813 ToType == S.Context.LongDoubleTy) ||
1814 (FromType == S.Context.LongDoubleTy &&
1815 ToType == S.Context.Float128Ty));
1816 if (Float128AndLongDouble &&
1817 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1818 &llvm::APFloat::PPCDoubleDouble()))
1819 return false;
1820 }
1821 // Floating point conversions (C++ 4.8).
1822 SCS.Second = ICK_Floating_Conversion;
1823 FromType = ToType.getUnqualifiedType();
1824 } else if ((FromType->isRealFloatingType() &&
1825 ToType->isIntegralType(S.Context)) ||
1826 (FromType->isIntegralOrUnscopedEnumerationType() &&
1827 ToType->isRealFloatingType())) {
1828 // Floating-integral conversions (C++ 4.9).
1829 SCS.Second = ICK_Floating_Integral;
1830 FromType = ToType.getUnqualifiedType();
1831 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1832 SCS.Second = ICK_Block_Pointer_Conversion;
1833 } else if (AllowObjCWritebackConversion &&
1834 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1835 SCS.Second = ICK_Writeback_Conversion;
1836 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1837 FromType, IncompatibleObjC)) {
1838 // Pointer conversions (C++ 4.10).
1839 SCS.Second = ICK_Pointer_Conversion;
1840 SCS.IncompatibleObjC = IncompatibleObjC;
1841 FromType = FromType.getUnqualifiedType();
1842 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1843 InOverloadResolution, FromType)) {
1844 // Pointer to member conversions (4.11).
1845 SCS.Second = ICK_Pointer_Member;
1846 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1847 SCS.Second = SecondICK;
1848 FromType = ToType.getUnqualifiedType();
1849 } else if (!S.getLangOpts().CPlusPlus &&
1850 S.Context.typesAreCompatible(ToType, FromType)) {
1851 // Compatible conversions (Clang extension for C function overloading)
1852 SCS.Second = ICK_Compatible_Conversion;
1853 FromType = ToType.getUnqualifiedType();
1854 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1855 InOverloadResolution,
1856 SCS, CStyle)) {
1857 SCS.Second = ICK_TransparentUnionConversion;
1858 FromType = ToType;
1859 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1860 CStyle)) {
1861 // tryAtomicConversion has updated the standard conversion sequence
1862 // appropriately.
1863 return true;
1864 } else if (ToType->isEventT() &&
1865 From->isIntegerConstantExpr(S.getASTContext()) &&
1866 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1867 SCS.Second = ICK_Zero_Event_Conversion;
1868 FromType = ToType;
1869 } else if (ToType->isQueueT() &&
1870 From->isIntegerConstantExpr(S.getASTContext()) &&
1871 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1872 SCS.Second = ICK_Zero_Queue_Conversion;
1873 FromType = ToType;
1874 } else {
1875 // No second conversion required.
1876 SCS.Second = ICK_Identity;
1877 }
1878 SCS.setToType(1, FromType);
1879
1880 // The third conversion can be a function pointer conversion or a
1881 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1882 bool ObjCLifetimeConversion;
1883 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1884 // Function pointer conversions (removing 'noexcept') including removal of
1885 // 'noreturn' (Clang extension).
1886 SCS.Third = ICK_Function_Conversion;
1887 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1888 ObjCLifetimeConversion)) {
1889 SCS.Third = ICK_Qualification;
1890 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1891 FromType = ToType;
1892 } else {
1893 // No conversion required
1894 SCS.Third = ICK_Identity;
1895 }
1896
1897 // C++ [over.best.ics]p6:
1898 // [...] Any difference in top-level cv-qualification is
1899 // subsumed by the initialization itself and does not constitute
1900 // a conversion. [...]
1901 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1902 QualType CanonTo = S.Context.getCanonicalType(ToType);
1903 if (CanonFrom.getLocalUnqualifiedType()
1904 == CanonTo.getLocalUnqualifiedType() &&
1905 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1906 FromType = ToType;
1907 CanonFrom = CanonTo;
1908 }
1909
1910 SCS.setToType(2, FromType);
1911
1912 if (CanonFrom == CanonTo)
1913 return true;
1914
1915 // If we have not converted the argument type to the parameter type,
1916 // this is a bad conversion sequence, unless we're resolving an overload in C.
1917 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1918 return false;
1919
1920 ExprResult ER = ExprResult{From};
1921 Sema::AssignConvertType Conv =
1922 S.CheckSingleAssignmentConstraints(ToType, ER,
1923 /*Diagnose=*/false,
1924 /*DiagnoseCFAudited=*/false,
1925 /*ConvertRHS=*/false);
1926 ImplicitConversionKind SecondConv;
1927 switch (Conv) {
1928 case Sema::Compatible:
1929 SecondConv = ICK_C_Only_Conversion;
1930 break;
1931 // For our purposes, discarding qualifiers is just as bad as using an
1932 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1933 // qualifiers, as well.
1934 case Sema::CompatiblePointerDiscardsQualifiers:
1935 case Sema::IncompatiblePointer:
1936 case Sema::IncompatiblePointerSign:
1937 SecondConv = ICK_Incompatible_Pointer_Conversion;
1938 break;
1939 default:
1940 return false;
1941 }
1942
1943 // First can only be an lvalue conversion, so we pretend that this was the
1944 // second conversion. First should already be valid from earlier in the
1945 // function.
1946 SCS.Second = SecondConv;
1947 SCS.setToType(1, ToType);
1948
1949 // Third is Identity, because Second should rank us worse than any other
1950 // conversion. This could also be ICK_Qualification, but it's simpler to just
1951 // lump everything in with the second conversion, and we don't gain anything
1952 // from making this ICK_Qualification.
1953 SCS.Third = ICK_Identity;
1954 SCS.setToType(2, ToType);
1955 return true;
1956 }
1957
1958 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)1959 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1960 QualType &ToType,
1961 bool InOverloadResolution,
1962 StandardConversionSequence &SCS,
1963 bool CStyle) {
1964
1965 const RecordType *UT = ToType->getAsUnionType();
1966 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1967 return false;
1968 // The field to initialize within the transparent union.
1969 RecordDecl *UD = UT->getDecl();
1970 // It's compatible if the expression matches any of the fields.
1971 for (const auto *it : UD->fields()) {
1972 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1973 CStyle, /*ObjCWritebackConversion=*/false)) {
1974 ToType = it->getType();
1975 return true;
1976 }
1977 }
1978 return false;
1979 }
1980
1981 /// IsIntegralPromotion - Determines whether the conversion from the
1982 /// expression From (whose potentially-adjusted type is FromType) to
1983 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1984 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)1985 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1986 const BuiltinType *To = ToType->getAs<BuiltinType>();
1987 // All integers are built-in.
1988 if (!To) {
1989 return false;
1990 }
1991
1992 // An rvalue of type char, signed char, unsigned char, short int, or
1993 // unsigned short int can be converted to an rvalue of type int if
1994 // int can represent all the values of the source type; otherwise,
1995 // the source rvalue can be converted to an rvalue of type unsigned
1996 // int (C++ 4.5p1).
1997 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1998 !FromType->isEnumeralType()) {
1999 if (// We can promote any signed, promotable integer type to an int
2000 (FromType->isSignedIntegerType() ||
2001 // We can promote any unsigned integer type whose size is
2002 // less than int to an int.
2003 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2004 return To->getKind() == BuiltinType::Int;
2005 }
2006
2007 return To->getKind() == BuiltinType::UInt;
2008 }
2009
2010 // C++11 [conv.prom]p3:
2011 // A prvalue of an unscoped enumeration type whose underlying type is not
2012 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2013 // following types that can represent all the values of the enumeration
2014 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2015 // unsigned int, long int, unsigned long int, long long int, or unsigned
2016 // long long int. If none of the types in that list can represent all the
2017 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2018 // type can be converted to an rvalue a prvalue of the extended integer type
2019 // with lowest integer conversion rank (4.13) greater than the rank of long
2020 // long in which all the values of the enumeration can be represented. If
2021 // there are two such extended types, the signed one is chosen.
2022 // C++11 [conv.prom]p4:
2023 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2024 // can be converted to a prvalue of its underlying type. Moreover, if
2025 // integral promotion can be applied to its underlying type, a prvalue of an
2026 // unscoped enumeration type whose underlying type is fixed can also be
2027 // converted to a prvalue of the promoted underlying type.
2028 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2029 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2030 // provided for a scoped enumeration.
2031 if (FromEnumType->getDecl()->isScoped())
2032 return false;
2033
2034 // We can perform an integral promotion to the underlying type of the enum,
2035 // even if that's not the promoted type. Note that the check for promoting
2036 // the underlying type is based on the type alone, and does not consider
2037 // the bitfield-ness of the actual source expression.
2038 if (FromEnumType->getDecl()->isFixed()) {
2039 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2040 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2041 IsIntegralPromotion(nullptr, Underlying, ToType);
2042 }
2043
2044 // We have already pre-calculated the promotion type, so this is trivial.
2045 if (ToType->isIntegerType() &&
2046 isCompleteType(From->getBeginLoc(), FromType))
2047 return Context.hasSameUnqualifiedType(
2048 ToType, FromEnumType->getDecl()->getPromotionType());
2049
2050 // C++ [conv.prom]p5:
2051 // If the bit-field has an enumerated type, it is treated as any other
2052 // value of that type for promotion purposes.
2053 //
2054 // ... so do not fall through into the bit-field checks below in C++.
2055 if (getLangOpts().CPlusPlus)
2056 return false;
2057 }
2058
2059 // C++0x [conv.prom]p2:
2060 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2061 // to an rvalue a prvalue of the first of the following types that can
2062 // represent all the values of its underlying type: int, unsigned int,
2063 // long int, unsigned long int, long long int, or unsigned long long int.
2064 // If none of the types in that list can represent all the values of its
2065 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2066 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2067 // type.
2068 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2069 ToType->isIntegerType()) {
2070 // Determine whether the type we're converting from is signed or
2071 // unsigned.
2072 bool FromIsSigned = FromType->isSignedIntegerType();
2073 uint64_t FromSize = Context.getTypeSize(FromType);
2074
2075 // The types we'll try to promote to, in the appropriate
2076 // order. Try each of these types.
2077 QualType PromoteTypes[6] = {
2078 Context.IntTy, Context.UnsignedIntTy,
2079 Context.LongTy, Context.UnsignedLongTy ,
2080 Context.LongLongTy, Context.UnsignedLongLongTy
2081 };
2082 for (int Idx = 0; Idx < 6; ++Idx) {
2083 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2084 if (FromSize < ToSize ||
2085 (FromSize == ToSize &&
2086 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2087 // We found the type that we can promote to. If this is the
2088 // type we wanted, we have a promotion. Otherwise, no
2089 // promotion.
2090 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2091 }
2092 }
2093 }
2094
2095 // An rvalue for an integral bit-field (9.6) can be converted to an
2096 // rvalue of type int if int can represent all the values of the
2097 // bit-field; otherwise, it can be converted to unsigned int if
2098 // unsigned int can represent all the values of the bit-field. If
2099 // the bit-field is larger yet, no integral promotion applies to
2100 // it. If the bit-field has an enumerated type, it is treated as any
2101 // other value of that type for promotion purposes (C++ 4.5p3).
2102 // FIXME: We should delay checking of bit-fields until we actually perform the
2103 // conversion.
2104 //
2105 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2106 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2107 // bit-fields and those whose underlying type is larger than int) for GCC
2108 // compatibility.
2109 if (From) {
2110 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2111 llvm::APSInt BitWidth;
2112 if (FromType->isIntegralType(Context) &&
2113 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2114 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2115 ToSize = Context.getTypeSize(ToType);
2116
2117 // Are we promoting to an int from a bitfield that fits in an int?
2118 if (BitWidth < ToSize ||
2119 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2120 return To->getKind() == BuiltinType::Int;
2121 }
2122
2123 // Are we promoting to an unsigned int from an unsigned bitfield
2124 // that fits into an unsigned int?
2125 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2126 return To->getKind() == BuiltinType::UInt;
2127 }
2128
2129 return false;
2130 }
2131 }
2132 }
2133
2134 // An rvalue of type bool can be converted to an rvalue of type int,
2135 // with false becoming zero and true becoming one (C++ 4.5p4).
2136 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2137 return true;
2138 }
2139
2140 return false;
2141 }
2142
2143 /// IsFloatingPointPromotion - Determines whether the conversion from
2144 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2145 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)2146 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2147 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2148 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2149 /// An rvalue of type float can be converted to an rvalue of type
2150 /// double. (C++ 4.6p1).
2151 if (FromBuiltin->getKind() == BuiltinType::Float &&
2152 ToBuiltin->getKind() == BuiltinType::Double)
2153 return true;
2154
2155 // C99 6.3.1.5p1:
2156 // When a float is promoted to double or long double, or a
2157 // double is promoted to long double [...].
2158 if (!getLangOpts().CPlusPlus &&
2159 (FromBuiltin->getKind() == BuiltinType::Float ||
2160 FromBuiltin->getKind() == BuiltinType::Double) &&
2161 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2162 ToBuiltin->getKind() == BuiltinType::Float128))
2163 return true;
2164
2165 // Half can be promoted to float.
2166 if (!getLangOpts().NativeHalfType &&
2167 FromBuiltin->getKind() == BuiltinType::Half &&
2168 ToBuiltin->getKind() == BuiltinType::Float)
2169 return true;
2170 }
2171
2172 return false;
2173 }
2174
2175 /// Determine if a conversion is a complex promotion.
2176 ///
2177 /// A complex promotion is defined as a complex -> complex conversion
2178 /// where the conversion between the underlying real types is a
2179 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)2180 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2181 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2182 if (!FromComplex)
2183 return false;
2184
2185 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2186 if (!ToComplex)
2187 return false;
2188
2189 return IsFloatingPointPromotion(FromComplex->getElementType(),
2190 ToComplex->getElementType()) ||
2191 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2192 ToComplex->getElementType());
2193 }
2194
2195 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2196 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2197 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2198 /// if non-empty, will be a pointer to ToType that may or may not have
2199 /// the right set of qualifiers on its pointee.
2200 ///
2201 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)2202 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2203 QualType ToPointee, QualType ToType,
2204 ASTContext &Context,
2205 bool StripObjCLifetime = false) {
2206 assert((FromPtr->getTypeClass() == Type::Pointer ||
2207 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2208 "Invalid similarly-qualified pointer type");
2209
2210 /// Conversions to 'id' subsume cv-qualifier conversions.
2211 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2212 return ToType.getUnqualifiedType();
2213
2214 QualType CanonFromPointee
2215 = Context.getCanonicalType(FromPtr->getPointeeType());
2216 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2217 Qualifiers Quals = CanonFromPointee.getQualifiers();
2218
2219 if (StripObjCLifetime)
2220 Quals.removeObjCLifetime();
2221
2222 // Exact qualifier match -> return the pointer type we're converting to.
2223 if (CanonToPointee.getLocalQualifiers() == Quals) {
2224 // ToType is exactly what we need. Return it.
2225 if (!ToType.isNull())
2226 return ToType.getUnqualifiedType();
2227
2228 // Build a pointer to ToPointee. It has the right qualifiers
2229 // already.
2230 if (isa<ObjCObjectPointerType>(ToType))
2231 return Context.getObjCObjectPointerType(ToPointee);
2232 return Context.getPointerType(ToPointee);
2233 }
2234
2235 // Just build a canonical type that has the right qualifiers.
2236 QualType QualifiedCanonToPointee
2237 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2238
2239 if (isa<ObjCObjectPointerType>(ToType))
2240 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2241 return Context.getPointerType(QualifiedCanonToPointee);
2242 }
2243
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)2244 static bool isNullPointerConstantForConversion(Expr *Expr,
2245 bool InOverloadResolution,
2246 ASTContext &Context) {
2247 // Handle value-dependent integral null pointer constants correctly.
2248 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2249 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2250 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2251 return !InOverloadResolution;
2252
2253 return Expr->isNullPointerConstant(Context,
2254 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2255 : Expr::NPC_ValueDependentIsNull);
2256 }
2257
2258 /// IsPointerConversion - Determines whether the conversion of the
2259 /// expression From, which has the (possibly adjusted) type FromType,
2260 /// can be converted to the type ToType via a pointer conversion (C++
2261 /// 4.10). If so, returns true and places the converted type (that
2262 /// might differ from ToType in its cv-qualifiers at some level) into
2263 /// ConvertedType.
2264 ///
2265 /// This routine also supports conversions to and from block pointers
2266 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2267 /// pointers to interfaces. FIXME: Once we've determined the
2268 /// appropriate overloading rules for Objective-C, we may want to
2269 /// split the Objective-C checks into a different routine; however,
2270 /// GCC seems to consider all of these conversions to be pointer
2271 /// conversions, so for now they live here. IncompatibleObjC will be
2272 /// set if the conversion is an allowed Objective-C conversion that
2273 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2274 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2275 bool InOverloadResolution,
2276 QualType& ConvertedType,
2277 bool &IncompatibleObjC) {
2278 IncompatibleObjC = false;
2279 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2280 IncompatibleObjC))
2281 return true;
2282
2283 // Conversion from a null pointer constant to any Objective-C pointer type.
2284 if (ToType->isObjCObjectPointerType() &&
2285 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2286 ConvertedType = ToType;
2287 return true;
2288 }
2289
2290 // Blocks: Block pointers can be converted to void*.
2291 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2292 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2293 ConvertedType = ToType;
2294 return true;
2295 }
2296 // Blocks: A null pointer constant can be converted to a block
2297 // pointer type.
2298 if (ToType->isBlockPointerType() &&
2299 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2300 ConvertedType = ToType;
2301 return true;
2302 }
2303
2304 // If the left-hand-side is nullptr_t, the right side can be a null
2305 // pointer constant.
2306 if (ToType->isNullPtrType() &&
2307 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2308 ConvertedType = ToType;
2309 return true;
2310 }
2311
2312 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2313 if (!ToTypePtr)
2314 return false;
2315
2316 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2317 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2318 ConvertedType = ToType;
2319 return true;
2320 }
2321
2322 // Beyond this point, both types need to be pointers
2323 // , including objective-c pointers.
2324 QualType ToPointeeType = ToTypePtr->getPointeeType();
2325 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2326 !getLangOpts().ObjCAutoRefCount) {
2327 ConvertedType = BuildSimilarlyQualifiedPointerType(
2328 FromType->getAs<ObjCObjectPointerType>(),
2329 ToPointeeType,
2330 ToType, Context);
2331 return true;
2332 }
2333 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2334 if (!FromTypePtr)
2335 return false;
2336
2337 QualType FromPointeeType = FromTypePtr->getPointeeType();
2338
2339 // If the unqualified pointee types are the same, this can't be a
2340 // pointer conversion, so don't do all of the work below.
2341 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2342 return false;
2343
2344 // An rvalue of type "pointer to cv T," where T is an object type,
2345 // can be converted to an rvalue of type "pointer to cv void" (C++
2346 // 4.10p2).
2347 if (FromPointeeType->isIncompleteOrObjectType() &&
2348 ToPointeeType->isVoidType()) {
2349 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2350 ToPointeeType,
2351 ToType, Context,
2352 /*StripObjCLifetime=*/true);
2353 return true;
2354 }
2355
2356 // MSVC allows implicit function to void* type conversion.
2357 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2358 ToPointeeType->isVoidType()) {
2359 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2360 ToPointeeType,
2361 ToType, Context);
2362 return true;
2363 }
2364
2365 // When we're overloading in C, we allow a special kind of pointer
2366 // conversion for compatible-but-not-identical pointee types.
2367 if (!getLangOpts().CPlusPlus &&
2368 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2370 ToPointeeType,
2371 ToType, Context);
2372 return true;
2373 }
2374
2375 // C++ [conv.ptr]p3:
2376 //
2377 // An rvalue of type "pointer to cv D," where D is a class type,
2378 // can be converted to an rvalue of type "pointer to cv B," where
2379 // B is a base class (clause 10) of D. If B is an inaccessible
2380 // (clause 11) or ambiguous (10.2) base class of D, a program that
2381 // necessitates this conversion is ill-formed. The result of the
2382 // conversion is a pointer to the base class sub-object of the
2383 // derived class object. The null pointer value is converted to
2384 // the null pointer value of the destination type.
2385 //
2386 // Note that we do not check for ambiguity or inaccessibility
2387 // here. That is handled by CheckPointerConversion.
2388 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2389 ToPointeeType->isRecordType() &&
2390 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2391 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2392 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2393 ToPointeeType,
2394 ToType, Context);
2395 return true;
2396 }
2397
2398 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2399 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2400 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2401 ToPointeeType,
2402 ToType, Context);
2403 return true;
2404 }
2405
2406 return false;
2407 }
2408
2409 /// Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2410 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2411 Qualifiers TQs = T.getQualifiers();
2412
2413 // Check whether qualifiers already match.
2414 if (TQs == Qs)
2415 return T;
2416
2417 if (Qs.compatiblyIncludes(TQs))
2418 return Context.getQualifiedType(T, Qs);
2419
2420 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2421 }
2422
2423 /// isObjCPointerConversion - Determines whether this is an
2424 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2425 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2426 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2427 QualType& ConvertedType,
2428 bool &IncompatibleObjC) {
2429 if (!getLangOpts().ObjC)
2430 return false;
2431
2432 // The set of qualifiers on the type we're converting from.
2433 Qualifiers FromQualifiers = FromType.getQualifiers();
2434
2435 // First, we handle all conversions on ObjC object pointer types.
2436 const ObjCObjectPointerType* ToObjCPtr =
2437 ToType->getAs<ObjCObjectPointerType>();
2438 const ObjCObjectPointerType *FromObjCPtr =
2439 FromType->getAs<ObjCObjectPointerType>();
2440
2441 if (ToObjCPtr && FromObjCPtr) {
2442 // If the pointee types are the same (ignoring qualifications),
2443 // then this is not a pointer conversion.
2444 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2445 FromObjCPtr->getPointeeType()))
2446 return false;
2447
2448 // Conversion between Objective-C pointers.
2449 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2450 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2451 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2452 if (getLangOpts().CPlusPlus && LHS && RHS &&
2453 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2454 FromObjCPtr->getPointeeType()))
2455 return false;
2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2457 ToObjCPtr->getPointeeType(),
2458 ToType, Context);
2459 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2460 return true;
2461 }
2462
2463 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2464 // Okay: this is some kind of implicit downcast of Objective-C
2465 // interfaces, which is permitted. However, we're going to
2466 // complain about it.
2467 IncompatibleObjC = true;
2468 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2469 ToObjCPtr->getPointeeType(),
2470 ToType, Context);
2471 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2472 return true;
2473 }
2474 }
2475 // Beyond this point, both types need to be C pointers or block pointers.
2476 QualType ToPointeeType;
2477 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2478 ToPointeeType = ToCPtr->getPointeeType();
2479 else if (const BlockPointerType *ToBlockPtr =
2480 ToType->getAs<BlockPointerType>()) {
2481 // Objective C++: We're able to convert from a pointer to any object
2482 // to a block pointer type.
2483 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2484 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2485 return true;
2486 }
2487 ToPointeeType = ToBlockPtr->getPointeeType();
2488 }
2489 else if (FromType->getAs<BlockPointerType>() &&
2490 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2491 // Objective C++: We're able to convert from a block pointer type to a
2492 // pointer to any object.
2493 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2494 return true;
2495 }
2496 else
2497 return false;
2498
2499 QualType FromPointeeType;
2500 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2501 FromPointeeType = FromCPtr->getPointeeType();
2502 else if (const BlockPointerType *FromBlockPtr =
2503 FromType->getAs<BlockPointerType>())
2504 FromPointeeType = FromBlockPtr->getPointeeType();
2505 else
2506 return false;
2507
2508 // If we have pointers to pointers, recursively check whether this
2509 // is an Objective-C conversion.
2510 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2511 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2512 IncompatibleObjC)) {
2513 // We always complain about this conversion.
2514 IncompatibleObjC = true;
2515 ConvertedType = Context.getPointerType(ConvertedType);
2516 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2517 return true;
2518 }
2519 // Allow conversion of pointee being objective-c pointer to another one;
2520 // as in I* to id.
2521 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2522 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2523 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2524 IncompatibleObjC)) {
2525
2526 ConvertedType = Context.getPointerType(ConvertedType);
2527 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2528 return true;
2529 }
2530
2531 // If we have pointers to functions or blocks, check whether the only
2532 // differences in the argument and result types are in Objective-C
2533 // pointer conversions. If so, we permit the conversion (but
2534 // complain about it).
2535 const FunctionProtoType *FromFunctionType
2536 = FromPointeeType->getAs<FunctionProtoType>();
2537 const FunctionProtoType *ToFunctionType
2538 = ToPointeeType->getAs<FunctionProtoType>();
2539 if (FromFunctionType && ToFunctionType) {
2540 // If the function types are exactly the same, this isn't an
2541 // Objective-C pointer conversion.
2542 if (Context.getCanonicalType(FromPointeeType)
2543 == Context.getCanonicalType(ToPointeeType))
2544 return false;
2545
2546 // Perform the quick checks that will tell us whether these
2547 // function types are obviously different.
2548 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2549 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2550 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2551 return false;
2552
2553 bool HasObjCConversion = false;
2554 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2555 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2556 // Okay, the types match exactly. Nothing to do.
2557 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2558 ToFunctionType->getReturnType(),
2559 ConvertedType, IncompatibleObjC)) {
2560 // Okay, we have an Objective-C pointer conversion.
2561 HasObjCConversion = true;
2562 } else {
2563 // Function types are too different. Abort.
2564 return false;
2565 }
2566
2567 // Check argument types.
2568 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2569 ArgIdx != NumArgs; ++ArgIdx) {
2570 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2571 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2572 if (Context.getCanonicalType(FromArgType)
2573 == Context.getCanonicalType(ToArgType)) {
2574 // Okay, the types match exactly. Nothing to do.
2575 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2576 ConvertedType, IncompatibleObjC)) {
2577 // Okay, we have an Objective-C pointer conversion.
2578 HasObjCConversion = true;
2579 } else {
2580 // Argument types are too different. Abort.
2581 return false;
2582 }
2583 }
2584
2585 if (HasObjCConversion) {
2586 // We had an Objective-C conversion. Allow this pointer
2587 // conversion, but complain about it.
2588 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2589 IncompatibleObjC = true;
2590 return true;
2591 }
2592 }
2593
2594 return false;
2595 }
2596
2597 /// Determine whether this is an Objective-C writeback conversion,
2598 /// used for parameter passing when performing automatic reference counting.
2599 ///
2600 /// \param FromType The type we're converting form.
2601 ///
2602 /// \param ToType The type we're converting to.
2603 ///
2604 /// \param ConvertedType The type that will be produced after applying
2605 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2606 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2607 QualType &ConvertedType) {
2608 if (!getLangOpts().ObjCAutoRefCount ||
2609 Context.hasSameUnqualifiedType(FromType, ToType))
2610 return false;
2611
2612 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2613 QualType ToPointee;
2614 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2615 ToPointee = ToPointer->getPointeeType();
2616 else
2617 return false;
2618
2619 Qualifiers ToQuals = ToPointee.getQualifiers();
2620 if (!ToPointee->isObjCLifetimeType() ||
2621 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2622 !ToQuals.withoutObjCLifetime().empty())
2623 return false;
2624
2625 // Argument must be a pointer to __strong to __weak.
2626 QualType FromPointee;
2627 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2628 FromPointee = FromPointer->getPointeeType();
2629 else
2630 return false;
2631
2632 Qualifiers FromQuals = FromPointee.getQualifiers();
2633 if (!FromPointee->isObjCLifetimeType() ||
2634 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2635 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2636 return false;
2637
2638 // Make sure that we have compatible qualifiers.
2639 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2640 if (!ToQuals.compatiblyIncludes(FromQuals))
2641 return false;
2642
2643 // Remove qualifiers from the pointee type we're converting from; they
2644 // aren't used in the compatibility check belong, and we'll be adding back
2645 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2646 FromPointee = FromPointee.getUnqualifiedType();
2647
2648 // The unqualified form of the pointee types must be compatible.
2649 ToPointee = ToPointee.getUnqualifiedType();
2650 bool IncompatibleObjC;
2651 if (Context.typesAreCompatible(FromPointee, ToPointee))
2652 FromPointee = ToPointee;
2653 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2654 IncompatibleObjC))
2655 return false;
2656
2657 /// Construct the type we're converting to, which is a pointer to
2658 /// __autoreleasing pointee.
2659 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2660 ConvertedType = Context.getPointerType(FromPointee);
2661 return true;
2662 }
2663
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2664 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2665 QualType& ConvertedType) {
2666 QualType ToPointeeType;
2667 if (const BlockPointerType *ToBlockPtr =
2668 ToType->getAs<BlockPointerType>())
2669 ToPointeeType = ToBlockPtr->getPointeeType();
2670 else
2671 return false;
2672
2673 QualType FromPointeeType;
2674 if (const BlockPointerType *FromBlockPtr =
2675 FromType->getAs<BlockPointerType>())
2676 FromPointeeType = FromBlockPtr->getPointeeType();
2677 else
2678 return false;
2679 // We have pointer to blocks, check whether the only
2680 // differences in the argument and result types are in Objective-C
2681 // pointer conversions. If so, we permit the conversion.
2682
2683 const FunctionProtoType *FromFunctionType
2684 = FromPointeeType->getAs<FunctionProtoType>();
2685 const FunctionProtoType *ToFunctionType
2686 = ToPointeeType->getAs<FunctionProtoType>();
2687
2688 if (!FromFunctionType || !ToFunctionType)
2689 return false;
2690
2691 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2692 return true;
2693
2694 // Perform the quick checks that will tell us whether these
2695 // function types are obviously different.
2696 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2697 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2698 return false;
2699
2700 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2701 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2702 if (FromEInfo != ToEInfo)
2703 return false;
2704
2705 bool IncompatibleObjC = false;
2706 if (Context.hasSameType(FromFunctionType->getReturnType(),
2707 ToFunctionType->getReturnType())) {
2708 // Okay, the types match exactly. Nothing to do.
2709 } else {
2710 QualType RHS = FromFunctionType->getReturnType();
2711 QualType LHS = ToFunctionType->getReturnType();
2712 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2713 !RHS.hasQualifiers() && LHS.hasQualifiers())
2714 LHS = LHS.getUnqualifiedType();
2715
2716 if (Context.hasSameType(RHS,LHS)) {
2717 // OK exact match.
2718 } else if (isObjCPointerConversion(RHS, LHS,
2719 ConvertedType, IncompatibleObjC)) {
2720 if (IncompatibleObjC)
2721 return false;
2722 // Okay, we have an Objective-C pointer conversion.
2723 }
2724 else
2725 return false;
2726 }
2727
2728 // Check argument types.
2729 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2730 ArgIdx != NumArgs; ++ArgIdx) {
2731 IncompatibleObjC = false;
2732 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2733 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2734 if (Context.hasSameType(FromArgType, ToArgType)) {
2735 // Okay, the types match exactly. Nothing to do.
2736 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2737 ConvertedType, IncompatibleObjC)) {
2738 if (IncompatibleObjC)
2739 return false;
2740 // Okay, we have an Objective-C pointer conversion.
2741 } else
2742 // Argument types are too different. Abort.
2743 return false;
2744 }
2745
2746 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2747 bool CanUseToFPT, CanUseFromFPT;
2748 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2749 CanUseToFPT, CanUseFromFPT,
2750 NewParamInfos))
2751 return false;
2752
2753 ConvertedType = ToType;
2754 return true;
2755 }
2756
2757 enum {
2758 ft_default,
2759 ft_different_class,
2760 ft_parameter_arity,
2761 ft_parameter_mismatch,
2762 ft_return_type,
2763 ft_qualifer_mismatch,
2764 ft_noexcept
2765 };
2766
2767 /// Attempts to get the FunctionProtoType from a Type. Handles
2768 /// MemberFunctionPointers properly.
tryGetFunctionProtoType(QualType FromType)2769 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2770 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2771 return FPT;
2772
2773 if (auto *MPT = FromType->getAs<MemberPointerType>())
2774 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2775
2776 return nullptr;
2777 }
2778
2779 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2780 /// function types. Catches different number of parameter, mismatch in
2781 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2782 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2783 QualType FromType, QualType ToType) {
2784 // If either type is not valid, include no extra info.
2785 if (FromType.isNull() || ToType.isNull()) {
2786 PDiag << ft_default;
2787 return;
2788 }
2789
2790 // Get the function type from the pointers.
2791 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2792 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2793 *ToMember = ToType->getAs<MemberPointerType>();
2794 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2795 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2796 << QualType(FromMember->getClass(), 0);
2797 return;
2798 }
2799 FromType = FromMember->getPointeeType();
2800 ToType = ToMember->getPointeeType();
2801 }
2802
2803 if (FromType->isPointerType())
2804 FromType = FromType->getPointeeType();
2805 if (ToType->isPointerType())
2806 ToType = ToType->getPointeeType();
2807
2808 // Remove references.
2809 FromType = FromType.getNonReferenceType();
2810 ToType = ToType.getNonReferenceType();
2811
2812 // Don't print extra info for non-specialized template functions.
2813 if (FromType->isInstantiationDependentType() &&
2814 !FromType->getAs<TemplateSpecializationType>()) {
2815 PDiag << ft_default;
2816 return;
2817 }
2818
2819 // No extra info for same types.
2820 if (Context.hasSameType(FromType, ToType)) {
2821 PDiag << ft_default;
2822 return;
2823 }
2824
2825 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2826 *ToFunction = tryGetFunctionProtoType(ToType);
2827
2828 // Both types need to be function types.
2829 if (!FromFunction || !ToFunction) {
2830 PDiag << ft_default;
2831 return;
2832 }
2833
2834 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2835 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2836 << FromFunction->getNumParams();
2837 return;
2838 }
2839
2840 // Handle different parameter types.
2841 unsigned ArgPos;
2842 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2843 PDiag << ft_parameter_mismatch << ArgPos + 1
2844 << ToFunction->getParamType(ArgPos)
2845 << FromFunction->getParamType(ArgPos);
2846 return;
2847 }
2848
2849 // Handle different return type.
2850 if (!Context.hasSameType(FromFunction->getReturnType(),
2851 ToFunction->getReturnType())) {
2852 PDiag << ft_return_type << ToFunction->getReturnType()
2853 << FromFunction->getReturnType();
2854 return;
2855 }
2856
2857 if (FromFunction->getTypeQuals() != ToFunction->getTypeQuals()) {
2858 PDiag << ft_qualifer_mismatch << ToFunction->getTypeQuals()
2859 << FromFunction->getTypeQuals();
2860 return;
2861 }
2862
2863 // Handle exception specification differences on canonical type (in C++17
2864 // onwards).
2865 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2866 ->isNothrow() !=
2867 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2868 ->isNothrow()) {
2869 PDiag << ft_noexcept;
2870 return;
2871 }
2872
2873 // Unable to find a difference, so add no extra info.
2874 PDiag << ft_default;
2875 }
2876
2877 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2878 /// for equality of their argument types. Caller has already checked that
2879 /// they have same number of arguments. If the parameters are different,
2880 /// ArgPos will have the parameter index of the first different parameter.
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2881 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2882 const FunctionProtoType *NewType,
2883 unsigned *ArgPos) {
2884 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2885 N = NewType->param_type_begin(),
2886 E = OldType->param_type_end();
2887 O && (O != E); ++O, ++N) {
2888 if (!Context.hasSameType(O->getUnqualifiedType(),
2889 N->getUnqualifiedType())) {
2890 if (ArgPos)
2891 *ArgPos = O - OldType->param_type_begin();
2892 return false;
2893 }
2894 }
2895 return true;
2896 }
2897
2898 /// CheckPointerConversion - Check the pointer conversion from the
2899 /// expression From to the type ToType. This routine checks for
2900 /// ambiguous or inaccessible derived-to-base pointer
2901 /// conversions for which IsPointerConversion has already returned
2902 /// true. It returns true and produces a diagnostic if there was an
2903 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess,bool Diagnose)2904 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2905 CastKind &Kind,
2906 CXXCastPath& BasePath,
2907 bool IgnoreBaseAccess,
2908 bool Diagnose) {
2909 QualType FromType = From->getType();
2910 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2911
2912 Kind = CK_BitCast;
2913
2914 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2915 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2916 Expr::NPCK_ZeroExpression) {
2917 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2918 DiagRuntimeBehavior(From->getExprLoc(), From,
2919 PDiag(diag::warn_impcast_bool_to_null_pointer)
2920 << ToType << From->getSourceRange());
2921 else if (!isUnevaluatedContext())
2922 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2923 << ToType << From->getSourceRange();
2924 }
2925 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2926 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2927 QualType FromPointeeType = FromPtrType->getPointeeType(),
2928 ToPointeeType = ToPtrType->getPointeeType();
2929
2930 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2931 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2932 // We must have a derived-to-base conversion. Check an
2933 // ambiguous or inaccessible conversion.
2934 unsigned InaccessibleID = 0;
2935 unsigned AmbigiousID = 0;
2936 if (Diagnose) {
2937 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2938 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2939 }
2940 if (CheckDerivedToBaseConversion(
2941 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2942 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2943 &BasePath, IgnoreBaseAccess))
2944 return true;
2945
2946 // The conversion was successful.
2947 Kind = CK_DerivedToBase;
2948 }
2949
2950 if (Diagnose && !IsCStyleOrFunctionalCast &&
2951 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2952 assert(getLangOpts().MSVCCompat &&
2953 "this should only be possible with MSVCCompat!");
2954 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2955 << From->getSourceRange();
2956 }
2957 }
2958 } else if (const ObjCObjectPointerType *ToPtrType =
2959 ToType->getAs<ObjCObjectPointerType>()) {
2960 if (const ObjCObjectPointerType *FromPtrType =
2961 FromType->getAs<ObjCObjectPointerType>()) {
2962 // Objective-C++ conversions are always okay.
2963 // FIXME: We should have a different class of conversions for the
2964 // Objective-C++ implicit conversions.
2965 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2966 return false;
2967 } else if (FromType->isBlockPointerType()) {
2968 Kind = CK_BlockPointerToObjCPointerCast;
2969 } else {
2970 Kind = CK_CPointerToObjCPointerCast;
2971 }
2972 } else if (ToType->isBlockPointerType()) {
2973 if (!FromType->isBlockPointerType())
2974 Kind = CK_AnyPointerToBlockPointerCast;
2975 }
2976
2977 // We shouldn't fall into this case unless it's valid for other
2978 // reasons.
2979 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2980 Kind = CK_NullToPointer;
2981
2982 return false;
2983 }
2984
2985 /// IsMemberPointerConversion - Determines whether the conversion of the
2986 /// expression From, which has the (possibly adjusted) type FromType, can be
2987 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2988 /// If so, returns true and places the converted type (that might differ from
2989 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)2990 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2991 QualType ToType,
2992 bool InOverloadResolution,
2993 QualType &ConvertedType) {
2994 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2995 if (!ToTypePtr)
2996 return false;
2997
2998 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2999 if (From->isNullPointerConstant(Context,
3000 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3001 : Expr::NPC_ValueDependentIsNull)) {
3002 ConvertedType = ToType;
3003 return true;
3004 }
3005
3006 // Otherwise, both types have to be member pointers.
3007 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3008 if (!FromTypePtr)
3009 return false;
3010
3011 // A pointer to member of B can be converted to a pointer to member of D,
3012 // where D is derived from B (C++ 4.11p2).
3013 QualType FromClass(FromTypePtr->getClass(), 0);
3014 QualType ToClass(ToTypePtr->getClass(), 0);
3015
3016 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3017 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3018 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3019 ToClass.getTypePtr());
3020 return true;
3021 }
3022
3023 return false;
3024 }
3025
3026 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3027 /// expression From to the type ToType. This routine checks for ambiguous or
3028 /// virtual or inaccessible base-to-derived member pointer conversions
3029 /// for which IsMemberPointerConversion has already returned true. It returns
3030 /// true and produces a diagnostic if there was an error, or returns false
3031 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)3032 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3033 CastKind &Kind,
3034 CXXCastPath &BasePath,
3035 bool IgnoreBaseAccess) {
3036 QualType FromType = From->getType();
3037 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3038 if (!FromPtrType) {
3039 // This must be a null pointer to member pointer conversion
3040 assert(From->isNullPointerConstant(Context,
3041 Expr::NPC_ValueDependentIsNull) &&
3042 "Expr must be null pointer constant!");
3043 Kind = CK_NullToMemberPointer;
3044 return false;
3045 }
3046
3047 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3048 assert(ToPtrType && "No member pointer cast has a target type "
3049 "that is not a member pointer.");
3050
3051 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3052 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3053
3054 // FIXME: What about dependent types?
3055 assert(FromClass->isRecordType() && "Pointer into non-class.");
3056 assert(ToClass->isRecordType() && "Pointer into non-class.");
3057
3058 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3059 /*DetectVirtual=*/true);
3060 bool DerivationOkay =
3061 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3062 assert(DerivationOkay &&
3063 "Should not have been called if derivation isn't OK.");
3064 (void)DerivationOkay;
3065
3066 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3067 getUnqualifiedType())) {
3068 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3069 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3070 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3071 return true;
3072 }
3073
3074 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3075 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3076 << FromClass << ToClass << QualType(VBase, 0)
3077 << From->getSourceRange();
3078 return true;
3079 }
3080
3081 if (!IgnoreBaseAccess)
3082 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3083 Paths.front(),
3084 diag::err_downcast_from_inaccessible_base);
3085
3086 // Must be a base to derived member conversion.
3087 BuildBasePathArray(Paths, BasePath);
3088 Kind = CK_BaseToDerivedMemberPointer;
3089 return false;
3090 }
3091
3092 /// Determine whether the lifetime conversion between the two given
3093 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)3094 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3095 Qualifiers ToQuals) {
3096 // Converting anything to const __unsafe_unretained is trivial.
3097 if (ToQuals.hasConst() &&
3098 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3099 return false;
3100
3101 return true;
3102 }
3103
3104 /// IsQualificationConversion - Determines whether the conversion from
3105 /// an rvalue of type FromType to ToType is a qualification conversion
3106 /// (C++ 4.4).
3107 ///
3108 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3109 /// when the qualification conversion involves a change in the Objective-C
3110 /// object lifetime.
3111 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)3112 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3113 bool CStyle, bool &ObjCLifetimeConversion) {
3114 FromType = Context.getCanonicalType(FromType);
3115 ToType = Context.getCanonicalType(ToType);
3116 ObjCLifetimeConversion = false;
3117
3118 // If FromType and ToType are the same type, this is not a
3119 // qualification conversion.
3120 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3121 return false;
3122
3123 // (C++ 4.4p4):
3124 // A conversion can add cv-qualifiers at levels other than the first
3125 // in multi-level pointers, subject to the following rules: [...]
3126 bool PreviousToQualsIncludeConst = true;
3127 bool UnwrappedAnyPointer = false;
3128 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3129 // Within each iteration of the loop, we check the qualifiers to
3130 // determine if this still looks like a qualification
3131 // conversion. Then, if all is well, we unwrap one more level of
3132 // pointers or pointers-to-members and do it all again
3133 // until there are no more pointers or pointers-to-members left to
3134 // unwrap.
3135 UnwrappedAnyPointer = true;
3136
3137 Qualifiers FromQuals = FromType.getQualifiers();
3138 Qualifiers ToQuals = ToType.getQualifiers();
3139
3140 // Ignore __unaligned qualifier if this type is void.
3141 if (ToType.getUnqualifiedType()->isVoidType())
3142 FromQuals.removeUnaligned();
3143
3144 // Objective-C ARC:
3145 // Check Objective-C lifetime conversions.
3146 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3147 UnwrappedAnyPointer) {
3148 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3149 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3150 ObjCLifetimeConversion = true;
3151 FromQuals.removeObjCLifetime();
3152 ToQuals.removeObjCLifetime();
3153 } else {
3154 // Qualification conversions cannot cast between different
3155 // Objective-C lifetime qualifiers.
3156 return false;
3157 }
3158 }
3159
3160 // Allow addition/removal of GC attributes but not changing GC attributes.
3161 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3162 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3163 FromQuals.removeObjCGCAttr();
3164 ToQuals.removeObjCGCAttr();
3165 }
3166
3167 // -- for every j > 0, if const is in cv 1,j then const is in cv
3168 // 2,j, and similarly for volatile.
3169 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3170 return false;
3171
3172 // -- if the cv 1,j and cv 2,j are different, then const is in
3173 // every cv for 0 < k < j.
3174 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3175 && !PreviousToQualsIncludeConst)
3176 return false;
3177
3178 // Keep track of whether all prior cv-qualifiers in the "to" type
3179 // include const.
3180 PreviousToQualsIncludeConst
3181 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3182 }
3183
3184 // Allows address space promotion by language rules implemented in
3185 // Type::Qualifiers::isAddressSpaceSupersetOf.
3186 Qualifiers FromQuals = FromType.getQualifiers();
3187 Qualifiers ToQuals = ToType.getQualifiers();
3188 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3189 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3190 return false;
3191 }
3192
3193 // We are left with FromType and ToType being the pointee types
3194 // after unwrapping the original FromType and ToType the same number
3195 // of types. If we unwrapped any pointers, and if FromType and
3196 // ToType have the same unqualified type (since we checked
3197 // qualifiers above), then this is a qualification conversion.
3198 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3199 }
3200
3201 /// - Determine whether this is a conversion from a scalar type to an
3202 /// atomic type.
3203 ///
3204 /// If successful, updates \c SCS's second and third steps in the conversion
3205 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)3206 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3207 bool InOverloadResolution,
3208 StandardConversionSequence &SCS,
3209 bool CStyle) {
3210 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3211 if (!ToAtomic)
3212 return false;
3213
3214 StandardConversionSequence InnerSCS;
3215 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3216 InOverloadResolution, InnerSCS,
3217 CStyle, /*AllowObjCWritebackConversion=*/false))
3218 return false;
3219
3220 SCS.Second = InnerSCS.Second;
3221 SCS.setToType(1, InnerSCS.getToType(1));
3222 SCS.Third = InnerSCS.Third;
3223 SCS.QualificationIncludesObjCLifetime
3224 = InnerSCS.QualificationIncludesObjCLifetime;
3225 SCS.setToType(2, InnerSCS.getToType(2));
3226 return true;
3227 }
3228
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)3229 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3230 CXXConstructorDecl *Constructor,
3231 QualType Type) {
3232 const FunctionProtoType *CtorType =
3233 Constructor->getType()->getAs<FunctionProtoType>();
3234 if (CtorType->getNumParams() > 0) {
3235 QualType FirstArg = CtorType->getParamType(0);
3236 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3237 return true;
3238 }
3239 return false;
3240 }
3241
3242 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3243 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3244 CXXRecordDecl *To,
3245 UserDefinedConversionSequence &User,
3246 OverloadCandidateSet &CandidateSet,
3247 bool AllowExplicit) {
3248 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3249 for (auto *D : S.LookupConstructors(To)) {
3250 auto Info = getConstructorInfo(D);
3251 if (!Info)
3252 continue;
3253
3254 bool Usable = !Info.Constructor->isInvalidDecl() &&
3255 S.isInitListConstructor(Info.Constructor) &&
3256 (AllowExplicit || !Info.Constructor->isExplicit());
3257 if (Usable) {
3258 // If the first argument is (a reference to) the target type,
3259 // suppress conversions.
3260 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3261 S.Context, Info.Constructor, ToType);
3262 if (Info.ConstructorTmpl)
3263 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3264 /*ExplicitArgs*/ nullptr, From,
3265 CandidateSet, SuppressUserConversions);
3266 else
3267 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3268 CandidateSet, SuppressUserConversions);
3269 }
3270 }
3271
3272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3273
3274 OverloadCandidateSet::iterator Best;
3275 switch (auto Result =
3276 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3277 case OR_Deleted:
3278 case OR_Success: {
3279 // Record the standard conversion we used and the conversion function.
3280 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3281 QualType ThisType = Constructor->getThisType();
3282 // Initializer lists don't have conversions as such.
3283 User.Before.setAsIdentityConversion();
3284 User.HadMultipleCandidates = HadMultipleCandidates;
3285 User.ConversionFunction = Constructor;
3286 User.FoundConversionFunction = Best->FoundDecl;
3287 User.After.setAsIdentityConversion();
3288 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3289 User.After.setAllToTypes(ToType);
3290 return Result;
3291 }
3292
3293 case OR_No_Viable_Function:
3294 return OR_No_Viable_Function;
3295 case OR_Ambiguous:
3296 return OR_Ambiguous;
3297 }
3298
3299 llvm_unreachable("Invalid OverloadResult!");
3300 }
3301
3302 /// Determines whether there is a user-defined conversion sequence
3303 /// (C++ [over.ics.user]) that converts expression From to the type
3304 /// ToType. If such a conversion exists, User will contain the
3305 /// user-defined conversion sequence that performs such a conversion
3306 /// and this routine will return true. Otherwise, this routine returns
3307 /// false and User is unspecified.
3308 ///
3309 /// \param AllowExplicit true if the conversion should consider C++0x
3310 /// "explicit" conversion functions as well as non-explicit conversion
3311 /// functions (C++0x [class.conv.fct]p2).
3312 ///
3313 /// \param AllowObjCConversionOnExplicit true if the conversion should
3314 /// allow an extra Objective-C pointer conversion on uses of explicit
3315 /// constructors. Requires \c AllowExplicit to also be set.
3316 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit,bool AllowObjCConversionOnExplicit)3317 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3318 UserDefinedConversionSequence &User,
3319 OverloadCandidateSet &CandidateSet,
3320 bool AllowExplicit,
3321 bool AllowObjCConversionOnExplicit) {
3322 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3323 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3324
3325 // Whether we will only visit constructors.
3326 bool ConstructorsOnly = false;
3327
3328 // If the type we are conversion to is a class type, enumerate its
3329 // constructors.
3330 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3331 // C++ [over.match.ctor]p1:
3332 // When objects of class type are direct-initialized (8.5), or
3333 // copy-initialized from an expression of the same or a
3334 // derived class type (8.5), overload resolution selects the
3335 // constructor. [...] For copy-initialization, the candidate
3336 // functions are all the converting constructors (12.3.1) of
3337 // that class. The argument list is the expression-list within
3338 // the parentheses of the initializer.
3339 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3340 (From->getType()->getAs<RecordType>() &&
3341 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3342 ConstructorsOnly = true;
3343
3344 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3345 // We're not going to find any constructors.
3346 } else if (CXXRecordDecl *ToRecordDecl
3347 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3348
3349 Expr **Args = &From;
3350 unsigned NumArgs = 1;
3351 bool ListInitializing = false;
3352 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3353 // But first, see if there is an init-list-constructor that will work.
3354 OverloadingResult Result = IsInitializerListConstructorConversion(
3355 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3356 if (Result != OR_No_Viable_Function)
3357 return Result;
3358 // Never mind.
3359 CandidateSet.clear(
3360 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3361
3362 // If we're list-initializing, we pass the individual elements as
3363 // arguments, not the entire list.
3364 Args = InitList->getInits();
3365 NumArgs = InitList->getNumInits();
3366 ListInitializing = true;
3367 }
3368
3369 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3370 auto Info = getConstructorInfo(D);
3371 if (!Info)
3372 continue;
3373
3374 bool Usable = !Info.Constructor->isInvalidDecl();
3375 if (ListInitializing)
3376 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3377 else
3378 Usable = Usable &&
3379 Info.Constructor->isConvertingConstructor(AllowExplicit);
3380 if (Usable) {
3381 bool SuppressUserConversions = !ConstructorsOnly;
3382 if (SuppressUserConversions && ListInitializing) {
3383 SuppressUserConversions = false;
3384 if (NumArgs == 1) {
3385 // If the first argument is (a reference to) the target type,
3386 // suppress conversions.
3387 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3388 S.Context, Info.Constructor, ToType);
3389 }
3390 }
3391 if (Info.ConstructorTmpl)
3392 S.AddTemplateOverloadCandidate(
3393 Info.ConstructorTmpl, Info.FoundDecl,
3394 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3395 CandidateSet, SuppressUserConversions);
3396 else
3397 // Allow one user-defined conversion when user specifies a
3398 // From->ToType conversion via an static cast (c-style, etc).
3399 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3400 llvm::makeArrayRef(Args, NumArgs),
3401 CandidateSet, SuppressUserConversions);
3402 }
3403 }
3404 }
3405 }
3406
3407 // Enumerate conversion functions, if we're allowed to.
3408 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3409 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3410 // No conversion functions from incomplete types.
3411 } else if (const RecordType *FromRecordType =
3412 From->getType()->getAs<RecordType>()) {
3413 if (CXXRecordDecl *FromRecordDecl
3414 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3415 // Add all of the conversion functions as candidates.
3416 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3417 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3418 DeclAccessPair FoundDecl = I.getPair();
3419 NamedDecl *D = FoundDecl.getDecl();
3420 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3421 if (isa<UsingShadowDecl>(D))
3422 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3423
3424 CXXConversionDecl *Conv;
3425 FunctionTemplateDecl *ConvTemplate;
3426 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3427 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3428 else
3429 Conv = cast<CXXConversionDecl>(D);
3430
3431 if (AllowExplicit || !Conv->isExplicit()) {
3432 if (ConvTemplate)
3433 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3434 ActingContext, From, ToType,
3435 CandidateSet,
3436 AllowObjCConversionOnExplicit);
3437 else
3438 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3439 From, ToType, CandidateSet,
3440 AllowObjCConversionOnExplicit);
3441 }
3442 }
3443 }
3444 }
3445
3446 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3447
3448 OverloadCandidateSet::iterator Best;
3449 switch (auto Result =
3450 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3451 case OR_Success:
3452 case OR_Deleted:
3453 // Record the standard conversion we used and the conversion function.
3454 if (CXXConstructorDecl *Constructor
3455 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3456 // C++ [over.ics.user]p1:
3457 // If the user-defined conversion is specified by a
3458 // constructor (12.3.1), the initial standard conversion
3459 // sequence converts the source type to the type required by
3460 // the argument of the constructor.
3461 //
3462 QualType ThisType = Constructor->getThisType();
3463 if (isa<InitListExpr>(From)) {
3464 // Initializer lists don't have conversions as such.
3465 User.Before.setAsIdentityConversion();
3466 } else {
3467 if (Best->Conversions[0].isEllipsis())
3468 User.EllipsisConversion = true;
3469 else {
3470 User.Before = Best->Conversions[0].Standard;
3471 User.EllipsisConversion = false;
3472 }
3473 }
3474 User.HadMultipleCandidates = HadMultipleCandidates;
3475 User.ConversionFunction = Constructor;
3476 User.FoundConversionFunction = Best->FoundDecl;
3477 User.After.setAsIdentityConversion();
3478 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3479 User.After.setAllToTypes(ToType);
3480 return Result;
3481 }
3482 if (CXXConversionDecl *Conversion
3483 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3484 // C++ [over.ics.user]p1:
3485 //
3486 // [...] If the user-defined conversion is specified by a
3487 // conversion function (12.3.2), the initial standard
3488 // conversion sequence converts the source type to the
3489 // implicit object parameter of the conversion function.
3490 User.Before = Best->Conversions[0].Standard;
3491 User.HadMultipleCandidates = HadMultipleCandidates;
3492 User.ConversionFunction = Conversion;
3493 User.FoundConversionFunction = Best->FoundDecl;
3494 User.EllipsisConversion = false;
3495
3496 // C++ [over.ics.user]p2:
3497 // The second standard conversion sequence converts the
3498 // result of the user-defined conversion to the target type
3499 // for the sequence. Since an implicit conversion sequence
3500 // is an initialization, the special rules for
3501 // initialization by user-defined conversion apply when
3502 // selecting the best user-defined conversion for a
3503 // user-defined conversion sequence (see 13.3.3 and
3504 // 13.3.3.1).
3505 User.After = Best->FinalConversion;
3506 return Result;
3507 }
3508 llvm_unreachable("Not a constructor or conversion function?");
3509
3510 case OR_No_Viable_Function:
3511 return OR_No_Viable_Function;
3512
3513 case OR_Ambiguous:
3514 return OR_Ambiguous;
3515 }
3516
3517 llvm_unreachable("Invalid OverloadResult!");
3518 }
3519
3520 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3521 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3522 ImplicitConversionSequence ICS;
3523 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3524 OverloadCandidateSet::CSK_Normal);
3525 OverloadingResult OvResult =
3526 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3527 CandidateSet, false, false);
3528 if (OvResult == OR_Ambiguous)
3529 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3530 << From->getType() << ToType << From->getSourceRange();
3531 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3532 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3533 diag::err_typecheck_nonviable_condition_incomplete,
3534 From->getType(), From->getSourceRange()))
3535 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3536 << false << From->getType() << From->getSourceRange() << ToType;
3537 } else
3538 return false;
3539 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3540 return true;
3541 }
3542
3543 /// Compare the user-defined conversion functions or constructors
3544 /// of two user-defined conversion sequences to determine whether any ordering
3545 /// is possible.
3546 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3547 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3548 FunctionDecl *Function2) {
3549 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3550 return ImplicitConversionSequence::Indistinguishable;
3551
3552 // Objective-C++:
3553 // If both conversion functions are implicitly-declared conversions from
3554 // a lambda closure type to a function pointer and a block pointer,
3555 // respectively, always prefer the conversion to a function pointer,
3556 // because the function pointer is more lightweight and is more likely
3557 // to keep code working.
3558 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3559 if (!Conv1)
3560 return ImplicitConversionSequence::Indistinguishable;
3561
3562 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3563 if (!Conv2)
3564 return ImplicitConversionSequence::Indistinguishable;
3565
3566 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3567 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3568 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3569 if (Block1 != Block2)
3570 return Block1 ? ImplicitConversionSequence::Worse
3571 : ImplicitConversionSequence::Better;
3572 }
3573
3574 return ImplicitConversionSequence::Indistinguishable;
3575 }
3576
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)3577 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3578 const ImplicitConversionSequence &ICS) {
3579 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3580 (ICS.isUserDefined() &&
3581 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3582 }
3583
3584 /// CompareImplicitConversionSequences - Compare two implicit
3585 /// conversion sequences to determine whether one is better than the
3586 /// other or if they are indistinguishable (C++ 13.3.3.2).
3587 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,SourceLocation Loc,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3588 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3589 const ImplicitConversionSequence& ICS1,
3590 const ImplicitConversionSequence& ICS2)
3591 {
3592 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3593 // conversion sequences (as defined in 13.3.3.1)
3594 // -- a standard conversion sequence (13.3.3.1.1) is a better
3595 // conversion sequence than a user-defined conversion sequence or
3596 // an ellipsis conversion sequence, and
3597 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3598 // conversion sequence than an ellipsis conversion sequence
3599 // (13.3.3.1.3).
3600 //
3601 // C++0x [over.best.ics]p10:
3602 // For the purpose of ranking implicit conversion sequences as
3603 // described in 13.3.3.2, the ambiguous conversion sequence is
3604 // treated as a user-defined sequence that is indistinguishable
3605 // from any other user-defined conversion sequence.
3606
3607 // String literal to 'char *' conversion has been deprecated in C++03. It has
3608 // been removed from C++11. We still accept this conversion, if it happens at
3609 // the best viable function. Otherwise, this conversion is considered worse
3610 // than ellipsis conversion. Consider this as an extension; this is not in the
3611 // standard. For example:
3612 //
3613 // int &f(...); // #1
3614 // void f(char*); // #2
3615 // void g() { int &r = f("foo"); }
3616 //
3617 // In C++03, we pick #2 as the best viable function.
3618 // In C++11, we pick #1 as the best viable function, because ellipsis
3619 // conversion is better than string-literal to char* conversion (since there
3620 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3621 // convert arguments, #2 would be the best viable function in C++11.
3622 // If the best viable function has this conversion, a warning will be issued
3623 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3624
3625 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3626 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3627 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3628 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3629 ? ImplicitConversionSequence::Worse
3630 : ImplicitConversionSequence::Better;
3631
3632 if (ICS1.getKindRank() < ICS2.getKindRank())
3633 return ImplicitConversionSequence::Better;
3634 if (ICS2.getKindRank() < ICS1.getKindRank())
3635 return ImplicitConversionSequence::Worse;
3636
3637 // The following checks require both conversion sequences to be of
3638 // the same kind.
3639 if (ICS1.getKind() != ICS2.getKind())
3640 return ImplicitConversionSequence::Indistinguishable;
3641
3642 ImplicitConversionSequence::CompareKind Result =
3643 ImplicitConversionSequence::Indistinguishable;
3644
3645 // Two implicit conversion sequences of the same form are
3646 // indistinguishable conversion sequences unless one of the
3647 // following rules apply: (C++ 13.3.3.2p3):
3648
3649 // List-initialization sequence L1 is a better conversion sequence than
3650 // list-initialization sequence L2 if:
3651 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3652 // if not that,
3653 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3654 // and N1 is smaller than N2.,
3655 // even if one of the other rules in this paragraph would otherwise apply.
3656 if (!ICS1.isBad()) {
3657 if (ICS1.isStdInitializerListElement() &&
3658 !ICS2.isStdInitializerListElement())
3659 return ImplicitConversionSequence::Better;
3660 if (!ICS1.isStdInitializerListElement() &&
3661 ICS2.isStdInitializerListElement())
3662 return ImplicitConversionSequence::Worse;
3663 }
3664
3665 if (ICS1.isStandard())
3666 // Standard conversion sequence S1 is a better conversion sequence than
3667 // standard conversion sequence S2 if [...]
3668 Result = CompareStandardConversionSequences(S, Loc,
3669 ICS1.Standard, ICS2.Standard);
3670 else if (ICS1.isUserDefined()) {
3671 // User-defined conversion sequence U1 is a better conversion
3672 // sequence than another user-defined conversion sequence U2 if
3673 // they contain the same user-defined conversion function or
3674 // constructor and if the second standard conversion sequence of
3675 // U1 is better than the second standard conversion sequence of
3676 // U2 (C++ 13.3.3.2p3).
3677 if (ICS1.UserDefined.ConversionFunction ==
3678 ICS2.UserDefined.ConversionFunction)
3679 Result = CompareStandardConversionSequences(S, Loc,
3680 ICS1.UserDefined.After,
3681 ICS2.UserDefined.After);
3682 else
3683 Result = compareConversionFunctions(S,
3684 ICS1.UserDefined.ConversionFunction,
3685 ICS2.UserDefined.ConversionFunction);
3686 }
3687
3688 return Result;
3689 }
3690
3691 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3692 // determine if one is a proper subset of the other.
3693 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3694 compareStandardConversionSubsets(ASTContext &Context,
3695 const StandardConversionSequence& SCS1,
3696 const StandardConversionSequence& SCS2) {
3697 ImplicitConversionSequence::CompareKind Result
3698 = ImplicitConversionSequence::Indistinguishable;
3699
3700 // the identity conversion sequence is considered to be a subsequence of
3701 // any non-identity conversion sequence
3702 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3703 return ImplicitConversionSequence::Better;
3704 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3705 return ImplicitConversionSequence::Worse;
3706
3707 if (SCS1.Second != SCS2.Second) {
3708 if (SCS1.Second == ICK_Identity)
3709 Result = ImplicitConversionSequence::Better;
3710 else if (SCS2.Second == ICK_Identity)
3711 Result = ImplicitConversionSequence::Worse;
3712 else
3713 return ImplicitConversionSequence::Indistinguishable;
3714 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3715 return ImplicitConversionSequence::Indistinguishable;
3716
3717 if (SCS1.Third == SCS2.Third) {
3718 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3719 : ImplicitConversionSequence::Indistinguishable;
3720 }
3721
3722 if (SCS1.Third == ICK_Identity)
3723 return Result == ImplicitConversionSequence::Worse
3724 ? ImplicitConversionSequence::Indistinguishable
3725 : ImplicitConversionSequence::Better;
3726
3727 if (SCS2.Third == ICK_Identity)
3728 return Result == ImplicitConversionSequence::Better
3729 ? ImplicitConversionSequence::Indistinguishable
3730 : ImplicitConversionSequence::Worse;
3731
3732 return ImplicitConversionSequence::Indistinguishable;
3733 }
3734
3735 /// Determine whether one of the given reference bindings is better
3736 /// than the other based on what kind of bindings they are.
3737 static bool
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3738 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3739 const StandardConversionSequence &SCS2) {
3740 // C++0x [over.ics.rank]p3b4:
3741 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3742 // implicit object parameter of a non-static member function declared
3743 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3744 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3745 // lvalue reference to a function lvalue and S2 binds an rvalue
3746 // reference*.
3747 //
3748 // FIXME: Rvalue references. We're going rogue with the above edits,
3749 // because the semantics in the current C++0x working paper (N3225 at the
3750 // time of this writing) break the standard definition of std::forward
3751 // and std::reference_wrapper when dealing with references to functions.
3752 // Proposed wording changes submitted to CWG for consideration.
3753 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3754 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3755 return false;
3756
3757 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3758 SCS2.IsLvalueReference) ||
3759 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3760 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3761 }
3762
3763 /// CompareStandardConversionSequences - Compare two standard
3764 /// conversion sequences to determine whether one is better than the
3765 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3766 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3767 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3768 const StandardConversionSequence& SCS1,
3769 const StandardConversionSequence& SCS2)
3770 {
3771 // Standard conversion sequence S1 is a better conversion sequence
3772 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3773
3774 // -- S1 is a proper subsequence of S2 (comparing the conversion
3775 // sequences in the canonical form defined by 13.3.3.1.1,
3776 // excluding any Lvalue Transformation; the identity conversion
3777 // sequence is considered to be a subsequence of any
3778 // non-identity conversion sequence) or, if not that,
3779 if (ImplicitConversionSequence::CompareKind CK
3780 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3781 return CK;
3782
3783 // -- the rank of S1 is better than the rank of S2 (by the rules
3784 // defined below), or, if not that,
3785 ImplicitConversionRank Rank1 = SCS1.getRank();
3786 ImplicitConversionRank Rank2 = SCS2.getRank();
3787 if (Rank1 < Rank2)
3788 return ImplicitConversionSequence::Better;
3789 else if (Rank2 < Rank1)
3790 return ImplicitConversionSequence::Worse;
3791
3792 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3793 // are indistinguishable unless one of the following rules
3794 // applies:
3795
3796 // A conversion that is not a conversion of a pointer, or
3797 // pointer to member, to bool is better than another conversion
3798 // that is such a conversion.
3799 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3800 return SCS2.isPointerConversionToBool()
3801 ? ImplicitConversionSequence::Better
3802 : ImplicitConversionSequence::Worse;
3803
3804 // C++ [over.ics.rank]p4b2:
3805 //
3806 // If class B is derived directly or indirectly from class A,
3807 // conversion of B* to A* is better than conversion of B* to
3808 // void*, and conversion of A* to void* is better than conversion
3809 // of B* to void*.
3810 bool SCS1ConvertsToVoid
3811 = SCS1.isPointerConversionToVoidPointer(S.Context);
3812 bool SCS2ConvertsToVoid
3813 = SCS2.isPointerConversionToVoidPointer(S.Context);
3814 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3815 // Exactly one of the conversion sequences is a conversion to
3816 // a void pointer; it's the worse conversion.
3817 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3818 : ImplicitConversionSequence::Worse;
3819 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3820 // Neither conversion sequence converts to a void pointer; compare
3821 // their derived-to-base conversions.
3822 if (ImplicitConversionSequence::CompareKind DerivedCK
3823 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3824 return DerivedCK;
3825 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3826 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3827 // Both conversion sequences are conversions to void
3828 // pointers. Compare the source types to determine if there's an
3829 // inheritance relationship in their sources.
3830 QualType FromType1 = SCS1.getFromType();
3831 QualType FromType2 = SCS2.getFromType();
3832
3833 // Adjust the types we're converting from via the array-to-pointer
3834 // conversion, if we need to.
3835 if (SCS1.First == ICK_Array_To_Pointer)
3836 FromType1 = S.Context.getArrayDecayedType(FromType1);
3837 if (SCS2.First == ICK_Array_To_Pointer)
3838 FromType2 = S.Context.getArrayDecayedType(FromType2);
3839
3840 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3841 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3842
3843 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3844 return ImplicitConversionSequence::Better;
3845 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3846 return ImplicitConversionSequence::Worse;
3847
3848 // Objective-C++: If one interface is more specific than the
3849 // other, it is the better one.
3850 const ObjCObjectPointerType* FromObjCPtr1
3851 = FromType1->getAs<ObjCObjectPointerType>();
3852 const ObjCObjectPointerType* FromObjCPtr2
3853 = FromType2->getAs<ObjCObjectPointerType>();
3854 if (FromObjCPtr1 && FromObjCPtr2) {
3855 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3856 FromObjCPtr2);
3857 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3858 FromObjCPtr1);
3859 if (AssignLeft != AssignRight) {
3860 return AssignLeft? ImplicitConversionSequence::Better
3861 : ImplicitConversionSequence::Worse;
3862 }
3863 }
3864 }
3865
3866 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3867 // bullet 3).
3868 if (ImplicitConversionSequence::CompareKind QualCK
3869 = CompareQualificationConversions(S, SCS1, SCS2))
3870 return QualCK;
3871
3872 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3873 // Check for a better reference binding based on the kind of bindings.
3874 if (isBetterReferenceBindingKind(SCS1, SCS2))
3875 return ImplicitConversionSequence::Better;
3876 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3877 return ImplicitConversionSequence::Worse;
3878
3879 // C++ [over.ics.rank]p3b4:
3880 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3881 // which the references refer are the same type except for
3882 // top-level cv-qualifiers, and the type to which the reference
3883 // initialized by S2 refers is more cv-qualified than the type
3884 // to which the reference initialized by S1 refers.
3885 QualType T1 = SCS1.getToType(2);
3886 QualType T2 = SCS2.getToType(2);
3887 T1 = S.Context.getCanonicalType(T1);
3888 T2 = S.Context.getCanonicalType(T2);
3889 Qualifiers T1Quals, T2Quals;
3890 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3891 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3892 if (UnqualT1 == UnqualT2) {
3893 // Objective-C++ ARC: If the references refer to objects with different
3894 // lifetimes, prefer bindings that don't change lifetime.
3895 if (SCS1.ObjCLifetimeConversionBinding !=
3896 SCS2.ObjCLifetimeConversionBinding) {
3897 return SCS1.ObjCLifetimeConversionBinding
3898 ? ImplicitConversionSequence::Worse
3899 : ImplicitConversionSequence::Better;
3900 }
3901
3902 // If the type is an array type, promote the element qualifiers to the
3903 // type for comparison.
3904 if (isa<ArrayType>(T1) && T1Quals)
3905 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3906 if (isa<ArrayType>(T2) && T2Quals)
3907 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3908 if (T2.isMoreQualifiedThan(T1))
3909 return ImplicitConversionSequence::Better;
3910 else if (T1.isMoreQualifiedThan(T2))
3911 return ImplicitConversionSequence::Worse;
3912 }
3913 }
3914
3915 // In Microsoft mode, prefer an integral conversion to a
3916 // floating-to-integral conversion if the integral conversion
3917 // is between types of the same size.
3918 // For example:
3919 // void f(float);
3920 // void f(int);
3921 // int main {
3922 // long a;
3923 // f(a);
3924 // }
3925 // Here, MSVC will call f(int) instead of generating a compile error
3926 // as clang will do in standard mode.
3927 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3928 SCS2.Second == ICK_Floating_Integral &&
3929 S.Context.getTypeSize(SCS1.getFromType()) ==
3930 S.Context.getTypeSize(SCS1.getToType(2)))
3931 return ImplicitConversionSequence::Better;
3932
3933 // Prefer a compatible vector conversion over a lax vector conversion
3934 // For example:
3935 //
3936 // typedef float __v4sf __attribute__((__vector_size__(16)));
3937 // void f(vector float);
3938 // void f(vector signed int);
3939 // int main() {
3940 // __v4sf a;
3941 // f(a);
3942 // }
3943 // Here, we'd like to choose f(vector float) and not
3944 // report an ambiguous call error
3945 if (SCS1.Second == ICK_Vector_Conversion &&
3946 SCS2.Second == ICK_Vector_Conversion) {
3947 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3948 SCS1.getFromType(), SCS1.getToType(2));
3949 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3950 SCS2.getFromType(), SCS2.getToType(2));
3951
3952 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3953 return SCS1IsCompatibleVectorConversion
3954 ? ImplicitConversionSequence::Better
3955 : ImplicitConversionSequence::Worse;
3956 }
3957
3958 return ImplicitConversionSequence::Indistinguishable;
3959 }
3960
3961 /// CompareQualificationConversions - Compares two standard conversion
3962 /// sequences to determine whether they can be ranked based on their
3963 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3964 static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3965 CompareQualificationConversions(Sema &S,
3966 const StandardConversionSequence& SCS1,
3967 const StandardConversionSequence& SCS2) {
3968 // C++ 13.3.3.2p3:
3969 // -- S1 and S2 differ only in their qualification conversion and
3970 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3971 // cv-qualification signature of type T1 is a proper subset of
3972 // the cv-qualification signature of type T2, and S1 is not the
3973 // deprecated string literal array-to-pointer conversion (4.2).
3974 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3975 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3976 return ImplicitConversionSequence::Indistinguishable;
3977
3978 // FIXME: the example in the standard doesn't use a qualification
3979 // conversion (!)
3980 QualType T1 = SCS1.getToType(2);
3981 QualType T2 = SCS2.getToType(2);
3982 T1 = S.Context.getCanonicalType(T1);
3983 T2 = S.Context.getCanonicalType(T2);
3984 Qualifiers T1Quals, T2Quals;
3985 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3986 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3987
3988 // If the types are the same, we won't learn anything by unwrapped
3989 // them.
3990 if (UnqualT1 == UnqualT2)
3991 return ImplicitConversionSequence::Indistinguishable;
3992
3993 // If the type is an array type, promote the element qualifiers to the type
3994 // for comparison.
3995 if (isa<ArrayType>(T1) && T1Quals)
3996 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3997 if (isa<ArrayType>(T2) && T2Quals)
3998 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3999
4000 ImplicitConversionSequence::CompareKind Result
4001 = ImplicitConversionSequence::Indistinguishable;
4002
4003 // Objective-C++ ARC:
4004 // Prefer qualification conversions not involving a change in lifetime
4005 // to qualification conversions that do not change lifetime.
4006 if (SCS1.QualificationIncludesObjCLifetime !=
4007 SCS2.QualificationIncludesObjCLifetime) {
4008 Result = SCS1.QualificationIncludesObjCLifetime
4009 ? ImplicitConversionSequence::Worse
4010 : ImplicitConversionSequence::Better;
4011 }
4012
4013 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4014 // Within each iteration of the loop, we check the qualifiers to
4015 // determine if this still looks like a qualification
4016 // conversion. Then, if all is well, we unwrap one more level of
4017 // pointers or pointers-to-members and do it all again
4018 // until there are no more pointers or pointers-to-members left
4019 // to unwrap. This essentially mimics what
4020 // IsQualificationConversion does, but here we're checking for a
4021 // strict subset of qualifiers.
4022 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4023 // The qualifiers are the same, so this doesn't tell us anything
4024 // about how the sequences rank.
4025 ;
4026 else if (T2.isMoreQualifiedThan(T1)) {
4027 // T1 has fewer qualifiers, so it could be the better sequence.
4028 if (Result == ImplicitConversionSequence::Worse)
4029 // Neither has qualifiers that are a subset of the other's
4030 // qualifiers.
4031 return ImplicitConversionSequence::Indistinguishable;
4032
4033 Result = ImplicitConversionSequence::Better;
4034 } else if (T1.isMoreQualifiedThan(T2)) {
4035 // T2 has fewer qualifiers, so it could be the better sequence.
4036 if (Result == ImplicitConversionSequence::Better)
4037 // Neither has qualifiers that are a subset of the other's
4038 // qualifiers.
4039 return ImplicitConversionSequence::Indistinguishable;
4040
4041 Result = ImplicitConversionSequence::Worse;
4042 } else {
4043 // Qualifiers are disjoint.
4044 return ImplicitConversionSequence::Indistinguishable;
4045 }
4046
4047 // If the types after this point are equivalent, we're done.
4048 if (S.Context.hasSameUnqualifiedType(T1, T2))
4049 break;
4050 }
4051
4052 // Check that the winning standard conversion sequence isn't using
4053 // the deprecated string literal array to pointer conversion.
4054 switch (Result) {
4055 case ImplicitConversionSequence::Better:
4056 if (SCS1.DeprecatedStringLiteralToCharPtr)
4057 Result = ImplicitConversionSequence::Indistinguishable;
4058 break;
4059
4060 case ImplicitConversionSequence::Indistinguishable:
4061 break;
4062
4063 case ImplicitConversionSequence::Worse:
4064 if (SCS2.DeprecatedStringLiteralToCharPtr)
4065 Result = ImplicitConversionSequence::Indistinguishable;
4066 break;
4067 }
4068
4069 return Result;
4070 }
4071
4072 /// CompareDerivedToBaseConversions - Compares two standard conversion
4073 /// sequences to determine whether they can be ranked based on their
4074 /// various kinds of derived-to-base conversions (C++
4075 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4076 /// conversions between Objective-C interface types.
4077 static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4078 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4079 const StandardConversionSequence& SCS1,
4080 const StandardConversionSequence& SCS2) {
4081 QualType FromType1 = SCS1.getFromType();
4082 QualType ToType1 = SCS1.getToType(1);
4083 QualType FromType2 = SCS2.getFromType();
4084 QualType ToType2 = SCS2.getToType(1);
4085
4086 // Adjust the types we're converting from via the array-to-pointer
4087 // conversion, if we need to.
4088 if (SCS1.First == ICK_Array_To_Pointer)
4089 FromType1 = S.Context.getArrayDecayedType(FromType1);
4090 if (SCS2.First == ICK_Array_To_Pointer)
4091 FromType2 = S.Context.getArrayDecayedType(FromType2);
4092
4093 // Canonicalize all of the types.
4094 FromType1 = S.Context.getCanonicalType(FromType1);
4095 ToType1 = S.Context.getCanonicalType(ToType1);
4096 FromType2 = S.Context.getCanonicalType(FromType2);
4097 ToType2 = S.Context.getCanonicalType(ToType2);
4098
4099 // C++ [over.ics.rank]p4b3:
4100 //
4101 // If class B is derived directly or indirectly from class A and
4102 // class C is derived directly or indirectly from B,
4103 //
4104 // Compare based on pointer conversions.
4105 if (SCS1.Second == ICK_Pointer_Conversion &&
4106 SCS2.Second == ICK_Pointer_Conversion &&
4107 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4108 FromType1->isPointerType() && FromType2->isPointerType() &&
4109 ToType1->isPointerType() && ToType2->isPointerType()) {
4110 QualType FromPointee1
4111 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112 QualType ToPointee1
4113 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114 QualType FromPointee2
4115 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116 QualType ToPointee2
4117 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4118
4119 // -- conversion of C* to B* is better than conversion of C* to A*,
4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4122 return ImplicitConversionSequence::Better;
4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4124 return ImplicitConversionSequence::Worse;
4125 }
4126
4127 // -- conversion of B* to A* is better than conversion of C* to A*,
4128 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4129 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4130 return ImplicitConversionSequence::Better;
4131 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4132 return ImplicitConversionSequence::Worse;
4133 }
4134 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4135 SCS2.Second == ICK_Pointer_Conversion) {
4136 const ObjCObjectPointerType *FromPtr1
4137 = FromType1->getAs<ObjCObjectPointerType>();
4138 const ObjCObjectPointerType *FromPtr2
4139 = FromType2->getAs<ObjCObjectPointerType>();
4140 const ObjCObjectPointerType *ToPtr1
4141 = ToType1->getAs<ObjCObjectPointerType>();
4142 const ObjCObjectPointerType *ToPtr2
4143 = ToType2->getAs<ObjCObjectPointerType>();
4144
4145 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4146 // Apply the same conversion ranking rules for Objective-C pointer types
4147 // that we do for C++ pointers to class types. However, we employ the
4148 // Objective-C pseudo-subtyping relationship used for assignment of
4149 // Objective-C pointer types.
4150 bool FromAssignLeft
4151 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4152 bool FromAssignRight
4153 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4154 bool ToAssignLeft
4155 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4156 bool ToAssignRight
4157 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4158
4159 // A conversion to an a non-id object pointer type or qualified 'id'
4160 // type is better than a conversion to 'id'.
4161 if (ToPtr1->isObjCIdType() &&
4162 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4163 return ImplicitConversionSequence::Worse;
4164 if (ToPtr2->isObjCIdType() &&
4165 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4166 return ImplicitConversionSequence::Better;
4167
4168 // A conversion to a non-id object pointer type is better than a
4169 // conversion to a qualified 'id' type
4170 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4171 return ImplicitConversionSequence::Worse;
4172 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4173 return ImplicitConversionSequence::Better;
4174
4175 // A conversion to an a non-Class object pointer type or qualified 'Class'
4176 // type is better than a conversion to 'Class'.
4177 if (ToPtr1->isObjCClassType() &&
4178 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4179 return ImplicitConversionSequence::Worse;
4180 if (ToPtr2->isObjCClassType() &&
4181 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4182 return ImplicitConversionSequence::Better;
4183
4184 // A conversion to a non-Class object pointer type is better than a
4185 // conversion to a qualified 'Class' type.
4186 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4187 return ImplicitConversionSequence::Worse;
4188 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4189 return ImplicitConversionSequence::Better;
4190
4191 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4192 if (S.Context.hasSameType(FromType1, FromType2) &&
4193 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4194 (ToAssignLeft != ToAssignRight)) {
4195 if (FromPtr1->isSpecialized()) {
4196 // "conversion of B<A> * to B * is better than conversion of B * to
4197 // C *.
4198 bool IsFirstSame =
4199 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4200 bool IsSecondSame =
4201 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4202 if (IsFirstSame) {
4203 if (!IsSecondSame)
4204 return ImplicitConversionSequence::Better;
4205 } else if (IsSecondSame)
4206 return ImplicitConversionSequence::Worse;
4207 }
4208 return ToAssignLeft? ImplicitConversionSequence::Worse
4209 : ImplicitConversionSequence::Better;
4210 }
4211
4212 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4213 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4214 (FromAssignLeft != FromAssignRight))
4215 return FromAssignLeft? ImplicitConversionSequence::Better
4216 : ImplicitConversionSequence::Worse;
4217 }
4218 }
4219
4220 // Ranking of member-pointer types.
4221 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4222 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4223 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4224 const MemberPointerType * FromMemPointer1 =
4225 FromType1->getAs<MemberPointerType>();
4226 const MemberPointerType * ToMemPointer1 =
4227 ToType1->getAs<MemberPointerType>();
4228 const MemberPointerType * FromMemPointer2 =
4229 FromType2->getAs<MemberPointerType>();
4230 const MemberPointerType * ToMemPointer2 =
4231 ToType2->getAs<MemberPointerType>();
4232 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4233 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4234 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4235 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4236 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4237 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4238 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4239 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4240 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4241 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4242 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4243 return ImplicitConversionSequence::Worse;
4244 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4245 return ImplicitConversionSequence::Better;
4246 }
4247 // conversion of B::* to C::* is better than conversion of A::* to C::*
4248 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4249 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4250 return ImplicitConversionSequence::Better;
4251 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4252 return ImplicitConversionSequence::Worse;
4253 }
4254 }
4255
4256 if (SCS1.Second == ICK_Derived_To_Base) {
4257 // -- conversion of C to B is better than conversion of C to A,
4258 // -- binding of an expression of type C to a reference of type
4259 // B& is better than binding an expression of type C to a
4260 // reference of type A&,
4261 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4262 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4263 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4264 return ImplicitConversionSequence::Better;
4265 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4266 return ImplicitConversionSequence::Worse;
4267 }
4268
4269 // -- conversion of B to A is better than conversion of C to A.
4270 // -- binding of an expression of type B to a reference of type
4271 // A& is better than binding an expression of type C to a
4272 // reference of type A&,
4273 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4274 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4275 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4276 return ImplicitConversionSequence::Better;
4277 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4278 return ImplicitConversionSequence::Worse;
4279 }
4280 }
4281
4282 return ImplicitConversionSequence::Indistinguishable;
4283 }
4284
4285 /// Determine whether the given type is valid, e.g., it is not an invalid
4286 /// C++ class.
isTypeValid(QualType T)4287 static bool isTypeValid(QualType T) {
4288 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4289 return !Record->isInvalidDecl();
4290
4291 return true;
4292 }
4293
4294 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4295 /// determine whether they are reference-related,
4296 /// reference-compatible, reference-compatible with added
4297 /// qualification, or incompatible, for use in C++ initialization by
4298 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4299 /// type, and the first type (T1) is the pointee type of the reference
4300 /// type being initialized.
4301 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,bool & DerivedToBase,bool & ObjCConversion,bool & ObjCLifetimeConversion)4302 Sema::CompareReferenceRelationship(SourceLocation Loc,
4303 QualType OrigT1, QualType OrigT2,
4304 bool &DerivedToBase,
4305 bool &ObjCConversion,
4306 bool &ObjCLifetimeConversion) {
4307 assert(!OrigT1->isReferenceType() &&
4308 "T1 must be the pointee type of the reference type");
4309 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4310
4311 QualType T1 = Context.getCanonicalType(OrigT1);
4312 QualType T2 = Context.getCanonicalType(OrigT2);
4313 Qualifiers T1Quals, T2Quals;
4314 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4315 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4316
4317 // C++ [dcl.init.ref]p4:
4318 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4319 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4320 // T1 is a base class of T2.
4321 DerivedToBase = false;
4322 ObjCConversion = false;
4323 ObjCLifetimeConversion = false;
4324 QualType ConvertedT2;
4325 if (UnqualT1 == UnqualT2) {
4326 // Nothing to do.
4327 } else if (isCompleteType(Loc, OrigT2) &&
4328 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4329 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4330 DerivedToBase = true;
4331 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4332 UnqualT2->isObjCObjectOrInterfaceType() &&
4333 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4334 ObjCConversion = true;
4335 else if (UnqualT2->isFunctionType() &&
4336 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4337 // C++1z [dcl.init.ref]p4:
4338 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4339 // function" and T1 is "function"
4340 //
4341 // We extend this to also apply to 'noreturn', so allow any function
4342 // conversion between function types.
4343 return Ref_Compatible;
4344 else
4345 return Ref_Incompatible;
4346
4347 // At this point, we know that T1 and T2 are reference-related (at
4348 // least).
4349
4350 // If the type is an array type, promote the element qualifiers to the type
4351 // for comparison.
4352 if (isa<ArrayType>(T1) && T1Quals)
4353 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4354 if (isa<ArrayType>(T2) && T2Quals)
4355 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4356
4357 // C++ [dcl.init.ref]p4:
4358 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4359 // reference-related to T2 and cv1 is the same cv-qualification
4360 // as, or greater cv-qualification than, cv2. For purposes of
4361 // overload resolution, cases for which cv1 is greater
4362 // cv-qualification than cv2 are identified as
4363 // reference-compatible with added qualification (see 13.3.3.2).
4364 //
4365 // Note that we also require equivalence of Objective-C GC and address-space
4366 // qualifiers when performing these computations, so that e.g., an int in
4367 // address space 1 is not reference-compatible with an int in address
4368 // space 2.
4369 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4370 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4371 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4372 ObjCLifetimeConversion = true;
4373
4374 T1Quals.removeObjCLifetime();
4375 T2Quals.removeObjCLifetime();
4376 }
4377
4378 // MS compiler ignores __unaligned qualifier for references; do the same.
4379 T1Quals.removeUnaligned();
4380 T2Quals.removeUnaligned();
4381
4382 if (T1Quals.compatiblyIncludes(T2Quals))
4383 return Ref_Compatible;
4384 else
4385 return Ref_Related;
4386 }
4387
4388 /// Look for a user-defined conversion to a value reference-compatible
4389 /// with DeclType. Return true if something definite is found.
4390 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4391 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4392 QualType DeclType, SourceLocation DeclLoc,
4393 Expr *Init, QualType T2, bool AllowRvalues,
4394 bool AllowExplicit) {
4395 assert(T2->isRecordType() && "Can only find conversions of record types.");
4396 CXXRecordDecl *T2RecordDecl
4397 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4398
4399 OverloadCandidateSet CandidateSet(
4400 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4401 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4402 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4403 NamedDecl *D = *I;
4404 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4405 if (isa<UsingShadowDecl>(D))
4406 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4407
4408 FunctionTemplateDecl *ConvTemplate
4409 = dyn_cast<FunctionTemplateDecl>(D);
4410 CXXConversionDecl *Conv;
4411 if (ConvTemplate)
4412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4413 else
4414 Conv = cast<CXXConversionDecl>(D);
4415
4416 // If this is an explicit conversion, and we're not allowed to consider
4417 // explicit conversions, skip it.
4418 if (!AllowExplicit && Conv->isExplicit())
4419 continue;
4420
4421 if (AllowRvalues) {
4422 bool DerivedToBase = false;
4423 bool ObjCConversion = false;
4424 bool ObjCLifetimeConversion = false;
4425
4426 // If we are initializing an rvalue reference, don't permit conversion
4427 // functions that return lvalues.
4428 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4429 const ReferenceType *RefType
4430 = Conv->getConversionType()->getAs<LValueReferenceType>();
4431 if (RefType && !RefType->getPointeeType()->isFunctionType())
4432 continue;
4433 }
4434
4435 if (!ConvTemplate &&
4436 S.CompareReferenceRelationship(
4437 DeclLoc,
4438 Conv->getConversionType().getNonReferenceType()
4439 .getUnqualifiedType(),
4440 DeclType.getNonReferenceType().getUnqualifiedType(),
4441 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4442 Sema::Ref_Incompatible)
4443 continue;
4444 } else {
4445 // If the conversion function doesn't return a reference type,
4446 // it can't be considered for this conversion. An rvalue reference
4447 // is only acceptable if its referencee is a function type.
4448
4449 const ReferenceType *RefType =
4450 Conv->getConversionType()->getAs<ReferenceType>();
4451 if (!RefType ||
4452 (!RefType->isLValueReferenceType() &&
4453 !RefType->getPointeeType()->isFunctionType()))
4454 continue;
4455 }
4456
4457 if (ConvTemplate)
4458 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4459 Init, DeclType, CandidateSet,
4460 /*AllowObjCConversionOnExplicit=*/false);
4461 else
4462 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4463 DeclType, CandidateSet,
4464 /*AllowObjCConversionOnExplicit=*/false);
4465 }
4466
4467 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4468
4469 OverloadCandidateSet::iterator Best;
4470 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4471 case OR_Success:
4472 // C++ [over.ics.ref]p1:
4473 //
4474 // [...] If the parameter binds directly to the result of
4475 // applying a conversion function to the argument
4476 // expression, the implicit conversion sequence is a
4477 // user-defined conversion sequence (13.3.3.1.2), with the
4478 // second standard conversion sequence either an identity
4479 // conversion or, if the conversion function returns an
4480 // entity of a type that is a derived class of the parameter
4481 // type, a derived-to-base Conversion.
4482 if (!Best->FinalConversion.DirectBinding)
4483 return false;
4484
4485 ICS.setUserDefined();
4486 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4487 ICS.UserDefined.After = Best->FinalConversion;
4488 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4489 ICS.UserDefined.ConversionFunction = Best->Function;
4490 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4491 ICS.UserDefined.EllipsisConversion = false;
4492 assert(ICS.UserDefined.After.ReferenceBinding &&
4493 ICS.UserDefined.After.DirectBinding &&
4494 "Expected a direct reference binding!");
4495 return true;
4496
4497 case OR_Ambiguous:
4498 ICS.setAmbiguous();
4499 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4500 Cand != CandidateSet.end(); ++Cand)
4501 if (Cand->Viable)
4502 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4503 return true;
4504
4505 case OR_No_Viable_Function:
4506 case OR_Deleted:
4507 // There was no suitable conversion, or we found a deleted
4508 // conversion; continue with other checks.
4509 return false;
4510 }
4511
4512 llvm_unreachable("Invalid OverloadResult!");
4513 }
4514
4515 /// Compute an implicit conversion sequence for reference
4516 /// initialization.
4517 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4518 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4519 SourceLocation DeclLoc,
4520 bool SuppressUserConversions,
4521 bool AllowExplicit) {
4522 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4523
4524 // Most paths end in a failed conversion.
4525 ImplicitConversionSequence ICS;
4526 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4527
4528 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4529 QualType T2 = Init->getType();
4530
4531 // If the initializer is the address of an overloaded function, try
4532 // to resolve the overloaded function. If all goes well, T2 is the
4533 // type of the resulting function.
4534 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4535 DeclAccessPair Found;
4536 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4537 false, Found))
4538 T2 = Fn->getType();
4539 }
4540
4541 // Compute some basic properties of the types and the initializer.
4542 bool isRValRef = DeclType->isRValueReferenceType();
4543 bool DerivedToBase = false;
4544 bool ObjCConversion = false;
4545 bool ObjCLifetimeConversion = false;
4546 Expr::Classification InitCategory = Init->Classify(S.Context);
4547 Sema::ReferenceCompareResult RefRelationship
4548 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4549 ObjCConversion, ObjCLifetimeConversion);
4550
4551
4552 // C++0x [dcl.init.ref]p5:
4553 // A reference to type "cv1 T1" is initialized by an expression
4554 // of type "cv2 T2" as follows:
4555
4556 // -- If reference is an lvalue reference and the initializer expression
4557 if (!isRValRef) {
4558 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4559 // reference-compatible with "cv2 T2," or
4560 //
4561 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4562 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4563 // C++ [over.ics.ref]p1:
4564 // When a parameter of reference type binds directly (8.5.3)
4565 // to an argument expression, the implicit conversion sequence
4566 // is the identity conversion, unless the argument expression
4567 // has a type that is a derived class of the parameter type,
4568 // in which case the implicit conversion sequence is a
4569 // derived-to-base Conversion (13.3.3.1).
4570 ICS.setStandard();
4571 ICS.Standard.First = ICK_Identity;
4572 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4573 : ObjCConversion? ICK_Compatible_Conversion
4574 : ICK_Identity;
4575 ICS.Standard.Third = ICK_Identity;
4576 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4577 ICS.Standard.setToType(0, T2);
4578 ICS.Standard.setToType(1, T1);
4579 ICS.Standard.setToType(2, T1);
4580 ICS.Standard.ReferenceBinding = true;
4581 ICS.Standard.DirectBinding = true;
4582 ICS.Standard.IsLvalueReference = !isRValRef;
4583 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4584 ICS.Standard.BindsToRvalue = false;
4585 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4586 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4587 ICS.Standard.CopyConstructor = nullptr;
4588 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4589
4590 // Nothing more to do: the inaccessibility/ambiguity check for
4591 // derived-to-base conversions is suppressed when we're
4592 // computing the implicit conversion sequence (C++
4593 // [over.best.ics]p2).
4594 return ICS;
4595 }
4596
4597 // -- has a class type (i.e., T2 is a class type), where T1 is
4598 // not reference-related to T2, and can be implicitly
4599 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4600 // is reference-compatible with "cv3 T3" 92) (this
4601 // conversion is selected by enumerating the applicable
4602 // conversion functions (13.3.1.6) and choosing the best
4603 // one through overload resolution (13.3)),
4604 if (!SuppressUserConversions && T2->isRecordType() &&
4605 S.isCompleteType(DeclLoc, T2) &&
4606 RefRelationship == Sema::Ref_Incompatible) {
4607 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4608 Init, T2, /*AllowRvalues=*/false,
4609 AllowExplicit))
4610 return ICS;
4611 }
4612 }
4613
4614 // -- Otherwise, the reference shall be an lvalue reference to a
4615 // non-volatile const type (i.e., cv1 shall be const), or the reference
4616 // shall be an rvalue reference.
4617 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4618 return ICS;
4619
4620 // -- If the initializer expression
4621 //
4622 // -- is an xvalue, class prvalue, array prvalue or function
4623 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4624 if (RefRelationship == Sema::Ref_Compatible &&
4625 (InitCategory.isXValue() ||
4626 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4627 (InitCategory.isLValue() && T2->isFunctionType()))) {
4628 ICS.setStandard();
4629 ICS.Standard.First = ICK_Identity;
4630 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4631 : ObjCConversion? ICK_Compatible_Conversion
4632 : ICK_Identity;
4633 ICS.Standard.Third = ICK_Identity;
4634 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4635 ICS.Standard.setToType(0, T2);
4636 ICS.Standard.setToType(1, T1);
4637 ICS.Standard.setToType(2, T1);
4638 ICS.Standard.ReferenceBinding = true;
4639 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4640 // binding unless we're binding to a class prvalue.
4641 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4642 // allow the use of rvalue references in C++98/03 for the benefit of
4643 // standard library implementors; therefore, we need the xvalue check here.
4644 ICS.Standard.DirectBinding =
4645 S.getLangOpts().CPlusPlus11 ||
4646 !(InitCategory.isPRValue() || T2->isRecordType());
4647 ICS.Standard.IsLvalueReference = !isRValRef;
4648 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4649 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4650 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4651 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4652 ICS.Standard.CopyConstructor = nullptr;
4653 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4654 return ICS;
4655 }
4656
4657 // -- has a class type (i.e., T2 is a class type), where T1 is not
4658 // reference-related to T2, and can be implicitly converted to
4659 // an xvalue, class prvalue, or function lvalue of type
4660 // "cv3 T3", where "cv1 T1" is reference-compatible with
4661 // "cv3 T3",
4662 //
4663 // then the reference is bound to the value of the initializer
4664 // expression in the first case and to the result of the conversion
4665 // in the second case (or, in either case, to an appropriate base
4666 // class subobject).
4667 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4668 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4669 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4670 Init, T2, /*AllowRvalues=*/true,
4671 AllowExplicit)) {
4672 // In the second case, if the reference is an rvalue reference
4673 // and the second standard conversion sequence of the
4674 // user-defined conversion sequence includes an lvalue-to-rvalue
4675 // conversion, the program is ill-formed.
4676 if (ICS.isUserDefined() && isRValRef &&
4677 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4678 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4679
4680 return ICS;
4681 }
4682
4683 // A temporary of function type cannot be created; don't even try.
4684 if (T1->isFunctionType())
4685 return ICS;
4686
4687 // -- Otherwise, a temporary of type "cv1 T1" is created and
4688 // initialized from the initializer expression using the
4689 // rules for a non-reference copy initialization (8.5). The
4690 // reference is then bound to the temporary. If T1 is
4691 // reference-related to T2, cv1 must be the same
4692 // cv-qualification as, or greater cv-qualification than,
4693 // cv2; otherwise, the program is ill-formed.
4694 if (RefRelationship == Sema::Ref_Related) {
4695 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4696 // we would be reference-compatible or reference-compatible with
4697 // added qualification. But that wasn't the case, so the reference
4698 // initialization fails.
4699 //
4700 // Note that we only want to check address spaces and cvr-qualifiers here.
4701 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4702 Qualifiers T1Quals = T1.getQualifiers();
4703 Qualifiers T2Quals = T2.getQualifiers();
4704 T1Quals.removeObjCGCAttr();
4705 T1Quals.removeObjCLifetime();
4706 T2Quals.removeObjCGCAttr();
4707 T2Quals.removeObjCLifetime();
4708 // MS compiler ignores __unaligned qualifier for references; do the same.
4709 T1Quals.removeUnaligned();
4710 T2Quals.removeUnaligned();
4711 if (!T1Quals.compatiblyIncludes(T2Quals))
4712 return ICS;
4713 }
4714
4715 // If at least one of the types is a class type, the types are not
4716 // related, and we aren't allowed any user conversions, the
4717 // reference binding fails. This case is important for breaking
4718 // recursion, since TryImplicitConversion below will attempt to
4719 // create a temporary through the use of a copy constructor.
4720 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4721 (T1->isRecordType() || T2->isRecordType()))
4722 return ICS;
4723
4724 // If T1 is reference-related to T2 and the reference is an rvalue
4725 // reference, the initializer expression shall not be an lvalue.
4726 if (RefRelationship >= Sema::Ref_Related &&
4727 isRValRef && Init->Classify(S.Context).isLValue())
4728 return ICS;
4729
4730 // C++ [over.ics.ref]p2:
4731 // When a parameter of reference type is not bound directly to
4732 // an argument expression, the conversion sequence is the one
4733 // required to convert the argument expression to the
4734 // underlying type of the reference according to
4735 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4736 // to copy-initializing a temporary of the underlying type with
4737 // the argument expression. Any difference in top-level
4738 // cv-qualification is subsumed by the initialization itself
4739 // and does not constitute a conversion.
4740 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4741 /*AllowExplicit=*/false,
4742 /*InOverloadResolution=*/false,
4743 /*CStyle=*/false,
4744 /*AllowObjCWritebackConversion=*/false,
4745 /*AllowObjCConversionOnExplicit=*/false);
4746
4747 // Of course, that's still a reference binding.
4748 if (ICS.isStandard()) {
4749 ICS.Standard.ReferenceBinding = true;
4750 ICS.Standard.IsLvalueReference = !isRValRef;
4751 ICS.Standard.BindsToFunctionLvalue = false;
4752 ICS.Standard.BindsToRvalue = true;
4753 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4754 ICS.Standard.ObjCLifetimeConversionBinding = false;
4755 } else if (ICS.isUserDefined()) {
4756 const ReferenceType *LValRefType =
4757 ICS.UserDefined.ConversionFunction->getReturnType()
4758 ->getAs<LValueReferenceType>();
4759
4760 // C++ [over.ics.ref]p3:
4761 // Except for an implicit object parameter, for which see 13.3.1, a
4762 // standard conversion sequence cannot be formed if it requires [...]
4763 // binding an rvalue reference to an lvalue other than a function
4764 // lvalue.
4765 // Note that the function case is not possible here.
4766 if (DeclType->isRValueReferenceType() && LValRefType) {
4767 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4768 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4769 // reference to an rvalue!
4770 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4771 return ICS;
4772 }
4773
4774 ICS.UserDefined.After.ReferenceBinding = true;
4775 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4776 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4777 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4778 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4779 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4780 }
4781
4782 return ICS;
4783 }
4784
4785 static ImplicitConversionSequence
4786 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4787 bool SuppressUserConversions,
4788 bool InOverloadResolution,
4789 bool AllowObjCWritebackConversion,
4790 bool AllowExplicit = false);
4791
4792 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4793 /// initializer list From.
4794 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4795 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4796 bool SuppressUserConversions,
4797 bool InOverloadResolution,
4798 bool AllowObjCWritebackConversion) {
4799 // C++11 [over.ics.list]p1:
4800 // When an argument is an initializer list, it is not an expression and
4801 // special rules apply for converting it to a parameter type.
4802
4803 ImplicitConversionSequence Result;
4804 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4805
4806 // We need a complete type for what follows. Incomplete types can never be
4807 // initialized from init lists.
4808 if (!S.isCompleteType(From->getBeginLoc(), ToType))
4809 return Result;
4810
4811 // Per DR1467:
4812 // If the parameter type is a class X and the initializer list has a single
4813 // element of type cv U, where U is X or a class derived from X, the
4814 // implicit conversion sequence is the one required to convert the element
4815 // to the parameter type.
4816 //
4817 // Otherwise, if the parameter type is a character array [... ]
4818 // and the initializer list has a single element that is an
4819 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4820 // implicit conversion sequence is the identity conversion.
4821 if (From->getNumInits() == 1) {
4822 if (ToType->isRecordType()) {
4823 QualType InitType = From->getInit(0)->getType();
4824 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4825 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4826 return TryCopyInitialization(S, From->getInit(0), ToType,
4827 SuppressUserConversions,
4828 InOverloadResolution,
4829 AllowObjCWritebackConversion);
4830 }
4831 // FIXME: Check the other conditions here: array of character type,
4832 // initializer is a string literal.
4833 if (ToType->isArrayType()) {
4834 InitializedEntity Entity =
4835 InitializedEntity::InitializeParameter(S.Context, ToType,
4836 /*Consumed=*/false);
4837 if (S.CanPerformCopyInitialization(Entity, From)) {
4838 Result.setStandard();
4839 Result.Standard.setAsIdentityConversion();
4840 Result.Standard.setFromType(ToType);
4841 Result.Standard.setAllToTypes(ToType);
4842 return Result;
4843 }
4844 }
4845 }
4846
4847 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4848 // C++11 [over.ics.list]p2:
4849 // If the parameter type is std::initializer_list<X> or "array of X" and
4850 // all the elements can be implicitly converted to X, the implicit
4851 // conversion sequence is the worst conversion necessary to convert an
4852 // element of the list to X.
4853 //
4854 // C++14 [over.ics.list]p3:
4855 // Otherwise, if the parameter type is "array of N X", if the initializer
4856 // list has exactly N elements or if it has fewer than N elements and X is
4857 // default-constructible, and if all the elements of the initializer list
4858 // can be implicitly converted to X, the implicit conversion sequence is
4859 // the worst conversion necessary to convert an element of the list to X.
4860 //
4861 // FIXME: We're missing a lot of these checks.
4862 bool toStdInitializerList = false;
4863 QualType X;
4864 if (ToType->isArrayType())
4865 X = S.Context.getAsArrayType(ToType)->getElementType();
4866 else
4867 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4868 if (!X.isNull()) {
4869 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4870 Expr *Init = From->getInit(i);
4871 ImplicitConversionSequence ICS =
4872 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4873 InOverloadResolution,
4874 AllowObjCWritebackConversion);
4875 // If a single element isn't convertible, fail.
4876 if (ICS.isBad()) {
4877 Result = ICS;
4878 break;
4879 }
4880 // Otherwise, look for the worst conversion.
4881 if (Result.isBad() || CompareImplicitConversionSequences(
4882 S, From->getBeginLoc(), ICS, Result) ==
4883 ImplicitConversionSequence::Worse)
4884 Result = ICS;
4885 }
4886
4887 // For an empty list, we won't have computed any conversion sequence.
4888 // Introduce the identity conversion sequence.
4889 if (From->getNumInits() == 0) {
4890 Result.setStandard();
4891 Result.Standard.setAsIdentityConversion();
4892 Result.Standard.setFromType(ToType);
4893 Result.Standard.setAllToTypes(ToType);
4894 }
4895
4896 Result.setStdInitializerListElement(toStdInitializerList);
4897 return Result;
4898 }
4899
4900 // C++14 [over.ics.list]p4:
4901 // C++11 [over.ics.list]p3:
4902 // Otherwise, if the parameter is a non-aggregate class X and overload
4903 // resolution chooses a single best constructor [...] the implicit
4904 // conversion sequence is a user-defined conversion sequence. If multiple
4905 // constructors are viable but none is better than the others, the
4906 // implicit conversion sequence is a user-defined conversion sequence.
4907 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4908 // This function can deal with initializer lists.
4909 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4910 /*AllowExplicit=*/false,
4911 InOverloadResolution, /*CStyle=*/false,
4912 AllowObjCWritebackConversion,
4913 /*AllowObjCConversionOnExplicit=*/false);
4914 }
4915
4916 // C++14 [over.ics.list]p5:
4917 // C++11 [over.ics.list]p4:
4918 // Otherwise, if the parameter has an aggregate type which can be
4919 // initialized from the initializer list [...] the implicit conversion
4920 // sequence is a user-defined conversion sequence.
4921 if (ToType->isAggregateType()) {
4922 // Type is an aggregate, argument is an init list. At this point it comes
4923 // down to checking whether the initialization works.
4924 // FIXME: Find out whether this parameter is consumed or not.
4925 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4926 // need to call into the initialization code here; overload resolution
4927 // should not be doing that.
4928 InitializedEntity Entity =
4929 InitializedEntity::InitializeParameter(S.Context, ToType,
4930 /*Consumed=*/false);
4931 if (S.CanPerformCopyInitialization(Entity, From)) {
4932 Result.setUserDefined();
4933 Result.UserDefined.Before.setAsIdentityConversion();
4934 // Initializer lists don't have a type.
4935 Result.UserDefined.Before.setFromType(QualType());
4936 Result.UserDefined.Before.setAllToTypes(QualType());
4937
4938 Result.UserDefined.After.setAsIdentityConversion();
4939 Result.UserDefined.After.setFromType(ToType);
4940 Result.UserDefined.After.setAllToTypes(ToType);
4941 Result.UserDefined.ConversionFunction = nullptr;
4942 }
4943 return Result;
4944 }
4945
4946 // C++14 [over.ics.list]p6:
4947 // C++11 [over.ics.list]p5:
4948 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4949 if (ToType->isReferenceType()) {
4950 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4951 // mention initializer lists in any way. So we go by what list-
4952 // initialization would do and try to extrapolate from that.
4953
4954 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4955
4956 // If the initializer list has a single element that is reference-related
4957 // to the parameter type, we initialize the reference from that.
4958 if (From->getNumInits() == 1) {
4959 Expr *Init = From->getInit(0);
4960
4961 QualType T2 = Init->getType();
4962
4963 // If the initializer is the address of an overloaded function, try
4964 // to resolve the overloaded function. If all goes well, T2 is the
4965 // type of the resulting function.
4966 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4967 DeclAccessPair Found;
4968 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4969 Init, ToType, false, Found))
4970 T2 = Fn->getType();
4971 }
4972
4973 // Compute some basic properties of the types and the initializer.
4974 bool dummy1 = false;
4975 bool dummy2 = false;
4976 bool dummy3 = false;
4977 Sema::ReferenceCompareResult RefRelationship =
4978 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4979 dummy2, dummy3);
4980
4981 if (RefRelationship >= Sema::Ref_Related) {
4982 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4983 SuppressUserConversions,
4984 /*AllowExplicit=*/false);
4985 }
4986 }
4987
4988 // Otherwise, we bind the reference to a temporary created from the
4989 // initializer list.
4990 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4991 InOverloadResolution,
4992 AllowObjCWritebackConversion);
4993 if (Result.isFailure())
4994 return Result;
4995 assert(!Result.isEllipsis() &&
4996 "Sub-initialization cannot result in ellipsis conversion.");
4997
4998 // Can we even bind to a temporary?
4999 if (ToType->isRValueReferenceType() ||
5000 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5001 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5002 Result.UserDefined.After;
5003 SCS.ReferenceBinding = true;
5004 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5005 SCS.BindsToRvalue = true;
5006 SCS.BindsToFunctionLvalue = false;
5007 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5008 SCS.ObjCLifetimeConversionBinding = false;
5009 } else
5010 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5011 From, ToType);
5012 return Result;
5013 }
5014
5015 // C++14 [over.ics.list]p7:
5016 // C++11 [over.ics.list]p6:
5017 // Otherwise, if the parameter type is not a class:
5018 if (!ToType->isRecordType()) {
5019 // - if the initializer list has one element that is not itself an
5020 // initializer list, the implicit conversion sequence is the one
5021 // required to convert the element to the parameter type.
5022 unsigned NumInits = From->getNumInits();
5023 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5024 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5025 SuppressUserConversions,
5026 InOverloadResolution,
5027 AllowObjCWritebackConversion);
5028 // - if the initializer list has no elements, the implicit conversion
5029 // sequence is the identity conversion.
5030 else if (NumInits == 0) {
5031 Result.setStandard();
5032 Result.Standard.setAsIdentityConversion();
5033 Result.Standard.setFromType(ToType);
5034 Result.Standard.setAllToTypes(ToType);
5035 }
5036 return Result;
5037 }
5038
5039 // C++14 [over.ics.list]p8:
5040 // C++11 [over.ics.list]p7:
5041 // In all cases other than those enumerated above, no conversion is possible
5042 return Result;
5043 }
5044
5045 /// TryCopyInitialization - Try to copy-initialize a value of type
5046 /// ToType from the expression From. Return the implicit conversion
5047 /// sequence required to pass this argument, which may be a bad
5048 /// conversion sequence (meaning that the argument cannot be passed to
5049 /// a parameter of this type). If @p SuppressUserConversions, then we
5050 /// do not permit any user-defined conversion sequences.
5051 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)5052 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5053 bool SuppressUserConversions,
5054 bool InOverloadResolution,
5055 bool AllowObjCWritebackConversion,
5056 bool AllowExplicit) {
5057 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5058 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5059 InOverloadResolution,AllowObjCWritebackConversion);
5060
5061 if (ToType->isReferenceType())
5062 return TryReferenceInit(S, From, ToType,
5063 /*FIXME:*/ From->getBeginLoc(),
5064 SuppressUserConversions, AllowExplicit);
5065
5066 return TryImplicitConversion(S, From, ToType,
5067 SuppressUserConversions,
5068 /*AllowExplicit=*/false,
5069 InOverloadResolution,
5070 /*CStyle=*/false,
5071 AllowObjCWritebackConversion,
5072 /*AllowObjCConversionOnExplicit=*/false);
5073 }
5074
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)5075 static bool TryCopyInitialization(const CanQualType FromQTy,
5076 const CanQualType ToQTy,
5077 Sema &S,
5078 SourceLocation Loc,
5079 ExprValueKind FromVK) {
5080 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5081 ImplicitConversionSequence ICS =
5082 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5083
5084 return !ICS.isBad();
5085 }
5086
5087 /// TryObjectArgumentInitialization - Try to initialize the object
5088 /// parameter of the given member function (@c Method) from the
5089 /// expression @p From.
5090 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,SourceLocation Loc,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)5091 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5092 Expr::Classification FromClassification,
5093 CXXMethodDecl *Method,
5094 CXXRecordDecl *ActingContext) {
5095 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5096 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5097 // const volatile object.
5098 Qualifiers Quals;
5099 if (isa<CXXDestructorDecl>(Method)) {
5100 Quals.addConst();
5101 Quals.addVolatile();
5102 } else {
5103 Quals = Method->getTypeQualifiers();
5104 }
5105
5106 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5107
5108 // Set up the conversion sequence as a "bad" conversion, to allow us
5109 // to exit early.
5110 ImplicitConversionSequence ICS;
5111
5112 // We need to have an object of class type.
5113 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5114 FromType = PT->getPointeeType();
5115
5116 // When we had a pointer, it's implicitly dereferenced, so we
5117 // better have an lvalue.
5118 assert(FromClassification.isLValue());
5119 }
5120
5121 assert(FromType->isRecordType());
5122
5123 // C++0x [over.match.funcs]p4:
5124 // For non-static member functions, the type of the implicit object
5125 // parameter is
5126 //
5127 // - "lvalue reference to cv X" for functions declared without a
5128 // ref-qualifier or with the & ref-qualifier
5129 // - "rvalue reference to cv X" for functions declared with the &&
5130 // ref-qualifier
5131 //
5132 // where X is the class of which the function is a member and cv is the
5133 // cv-qualification on the member function declaration.
5134 //
5135 // However, when finding an implicit conversion sequence for the argument, we
5136 // are not allowed to perform user-defined conversions
5137 // (C++ [over.match.funcs]p5). We perform a simplified version of
5138 // reference binding here, that allows class rvalues to bind to
5139 // non-constant references.
5140
5141 // First check the qualifiers.
5142 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5143 if (ImplicitParamType.getCVRQualifiers()
5144 != FromTypeCanon.getLocalCVRQualifiers() &&
5145 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5146 ICS.setBad(BadConversionSequence::bad_qualifiers,
5147 FromType, ImplicitParamType);
5148 return ICS;
5149 }
5150
5151 // Check that we have either the same type or a derived type. It
5152 // affects the conversion rank.
5153 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5154 ImplicitConversionKind SecondKind;
5155 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5156 SecondKind = ICK_Identity;
5157 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5158 SecondKind = ICK_Derived_To_Base;
5159 else {
5160 ICS.setBad(BadConversionSequence::unrelated_class,
5161 FromType, ImplicitParamType);
5162 return ICS;
5163 }
5164
5165 // Check the ref-qualifier.
5166 switch (Method->getRefQualifier()) {
5167 case RQ_None:
5168 // Do nothing; we don't care about lvalueness or rvalueness.
5169 break;
5170
5171 case RQ_LValue:
5172 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5173 // non-const lvalue reference cannot bind to an rvalue
5174 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5175 ImplicitParamType);
5176 return ICS;
5177 }
5178 break;
5179
5180 case RQ_RValue:
5181 if (!FromClassification.isRValue()) {
5182 // rvalue reference cannot bind to an lvalue
5183 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5184 ImplicitParamType);
5185 return ICS;
5186 }
5187 break;
5188 }
5189
5190 // Success. Mark this as a reference binding.
5191 ICS.setStandard();
5192 ICS.Standard.setAsIdentityConversion();
5193 ICS.Standard.Second = SecondKind;
5194 ICS.Standard.setFromType(FromType);
5195 ICS.Standard.setAllToTypes(ImplicitParamType);
5196 ICS.Standard.ReferenceBinding = true;
5197 ICS.Standard.DirectBinding = true;
5198 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5199 ICS.Standard.BindsToFunctionLvalue = false;
5200 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5201 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5202 = (Method->getRefQualifier() == RQ_None);
5203 return ICS;
5204 }
5205
5206 /// PerformObjectArgumentInitialization - Perform initialization of
5207 /// the implicit object parameter for the given Method with the given
5208 /// expression.
5209 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)5210 Sema::PerformObjectArgumentInitialization(Expr *From,
5211 NestedNameSpecifier *Qualifier,
5212 NamedDecl *FoundDecl,
5213 CXXMethodDecl *Method) {
5214 QualType FromRecordType, DestType;
5215 QualType ImplicitParamRecordType =
5216 Method->getThisType()->getAs<PointerType>()->getPointeeType();
5217
5218 Expr::Classification FromClassification;
5219 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5220 FromRecordType = PT->getPointeeType();
5221 DestType = Method->getThisType();
5222 FromClassification = Expr::Classification::makeSimpleLValue();
5223 } else {
5224 FromRecordType = From->getType();
5225 DestType = ImplicitParamRecordType;
5226 FromClassification = From->Classify(Context);
5227
5228 // When performing member access on an rvalue, materialize a temporary.
5229 if (From->isRValue()) {
5230 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5231 Method->getRefQualifier() !=
5232 RefQualifierKind::RQ_RValue);
5233 }
5234 }
5235
5236 // Note that we always use the true parent context when performing
5237 // the actual argument initialization.
5238 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5239 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5240 Method->getParent());
5241 if (ICS.isBad()) {
5242 switch (ICS.Bad.Kind) {
5243 case BadConversionSequence::bad_qualifiers: {
5244 Qualifiers FromQs = FromRecordType.getQualifiers();
5245 Qualifiers ToQs = DestType.getQualifiers();
5246 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5247 if (CVR) {
5248 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5249 << Method->getDeclName() << FromRecordType << (CVR - 1)
5250 << From->getSourceRange();
5251 Diag(Method->getLocation(), diag::note_previous_decl)
5252 << Method->getDeclName();
5253 return ExprError();
5254 }
5255 break;
5256 }
5257
5258 case BadConversionSequence::lvalue_ref_to_rvalue:
5259 case BadConversionSequence::rvalue_ref_to_lvalue: {
5260 bool IsRValueQualified =
5261 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5262 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5263 << Method->getDeclName() << FromClassification.isRValue()
5264 << IsRValueQualified;
5265 Diag(Method->getLocation(), diag::note_previous_decl)
5266 << Method->getDeclName();
5267 return ExprError();
5268 }
5269
5270 case BadConversionSequence::no_conversion:
5271 case BadConversionSequence::unrelated_class:
5272 break;
5273 }
5274
5275 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5276 << ImplicitParamRecordType << FromRecordType
5277 << From->getSourceRange();
5278 }
5279
5280 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5281 ExprResult FromRes =
5282 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5283 if (FromRes.isInvalid())
5284 return ExprError();
5285 From = FromRes.get();
5286 }
5287
5288 if (!Context.hasSameType(From->getType(), DestType)) {
5289 if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5290 From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5291 From->getValueKind()).get();
5292 else
5293 From = ImpCastExprToType(From, DestType, CK_NoOp,
5294 From->getValueKind()).get();
5295 }
5296 return From;
5297 }
5298
5299 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5300 /// expression From to bool (C++0x [conv]p3).
5301 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)5302 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5303 return TryImplicitConversion(S, From, S.Context.BoolTy,
5304 /*SuppressUserConversions=*/false,
5305 /*AllowExplicit=*/true,
5306 /*InOverloadResolution=*/false,
5307 /*CStyle=*/false,
5308 /*AllowObjCWritebackConversion=*/false,
5309 /*AllowObjCConversionOnExplicit=*/false);
5310 }
5311
5312 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5313 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)5314 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5315 if (checkPlaceholderForOverload(*this, From))
5316 return ExprError();
5317
5318 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5319 if (!ICS.isBad())
5320 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5321
5322 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5323 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5324 << From->getType() << From->getSourceRange();
5325 return ExprError();
5326 }
5327
5328 /// Check that the specified conversion is permitted in a converted constant
5329 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5330 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)5331 static bool CheckConvertedConstantConversions(Sema &S,
5332 StandardConversionSequence &SCS) {
5333 // Since we know that the target type is an integral or unscoped enumeration
5334 // type, most conversion kinds are impossible. All possible First and Third
5335 // conversions are fine.
5336 switch (SCS.Second) {
5337 case ICK_Identity:
5338 case ICK_Function_Conversion:
5339 case ICK_Integral_Promotion:
5340 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5341 case ICK_Zero_Queue_Conversion:
5342 return true;
5343
5344 case ICK_Boolean_Conversion:
5345 // Conversion from an integral or unscoped enumeration type to bool is
5346 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5347 // conversion, so we allow it in a converted constant expression.
5348 //
5349 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5350 // a lot of popular code. We should at least add a warning for this
5351 // (non-conforming) extension.
5352 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5353 SCS.getToType(2)->isBooleanType();
5354
5355 case ICK_Pointer_Conversion:
5356 case ICK_Pointer_Member:
5357 // C++1z: null pointer conversions and null member pointer conversions are
5358 // only permitted if the source type is std::nullptr_t.
5359 return SCS.getFromType()->isNullPtrType();
5360
5361 case ICK_Floating_Promotion:
5362 case ICK_Complex_Promotion:
5363 case ICK_Floating_Conversion:
5364 case ICK_Complex_Conversion:
5365 case ICK_Floating_Integral:
5366 case ICK_Compatible_Conversion:
5367 case ICK_Derived_To_Base:
5368 case ICK_Vector_Conversion:
5369 case ICK_Vector_Splat:
5370 case ICK_Complex_Real:
5371 case ICK_Block_Pointer_Conversion:
5372 case ICK_TransparentUnionConversion:
5373 case ICK_Writeback_Conversion:
5374 case ICK_Zero_Event_Conversion:
5375 case ICK_C_Only_Conversion:
5376 case ICK_Incompatible_Pointer_Conversion:
5377 return false;
5378
5379 case ICK_Lvalue_To_Rvalue:
5380 case ICK_Array_To_Pointer:
5381 case ICK_Function_To_Pointer:
5382 llvm_unreachable("found a first conversion kind in Second");
5383
5384 case ICK_Qualification:
5385 llvm_unreachable("found a third conversion kind in Second");
5386
5387 case ICK_Num_Conversion_Kinds:
5388 break;
5389 }
5390
5391 llvm_unreachable("unknown conversion kind");
5392 }
5393
5394 /// CheckConvertedConstantExpression - Check that the expression From is a
5395 /// converted constant expression of type T, perform the conversion and produce
5396 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Sema & S,Expr * From,QualType T,APValue & Value,Sema::CCEKind CCE,bool RequireInt)5397 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5398 QualType T, APValue &Value,
5399 Sema::CCEKind CCE,
5400 bool RequireInt) {
5401 assert(S.getLangOpts().CPlusPlus11 &&
5402 "converted constant expression outside C++11");
5403
5404 if (checkPlaceholderForOverload(S, From))
5405 return ExprError();
5406
5407 // C++1z [expr.const]p3:
5408 // A converted constant expression of type T is an expression,
5409 // implicitly converted to type T, where the converted
5410 // expression is a constant expression and the implicit conversion
5411 // sequence contains only [... list of conversions ...].
5412 // C++1z [stmt.if]p2:
5413 // If the if statement is of the form if constexpr, the value of the
5414 // condition shall be a contextually converted constant expression of type
5415 // bool.
5416 ImplicitConversionSequence ICS =
5417 CCE == Sema::CCEK_ConstexprIf
5418 ? TryContextuallyConvertToBool(S, From)
5419 : TryCopyInitialization(S, From, T,
5420 /*SuppressUserConversions=*/false,
5421 /*InOverloadResolution=*/false,
5422 /*AllowObjcWritebackConversion=*/false,
5423 /*AllowExplicit=*/false);
5424 StandardConversionSequence *SCS = nullptr;
5425 switch (ICS.getKind()) {
5426 case ImplicitConversionSequence::StandardConversion:
5427 SCS = &ICS.Standard;
5428 break;
5429 case ImplicitConversionSequence::UserDefinedConversion:
5430 // We are converting to a non-class type, so the Before sequence
5431 // must be trivial.
5432 SCS = &ICS.UserDefined.After;
5433 break;
5434 case ImplicitConversionSequence::AmbiguousConversion:
5435 case ImplicitConversionSequence::BadConversion:
5436 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5437 return S.Diag(From->getBeginLoc(),
5438 diag::err_typecheck_converted_constant_expression)
5439 << From->getType() << From->getSourceRange() << T;
5440 return ExprError();
5441
5442 case ImplicitConversionSequence::EllipsisConversion:
5443 llvm_unreachable("ellipsis conversion in converted constant expression");
5444 }
5445
5446 // Check that we would only use permitted conversions.
5447 if (!CheckConvertedConstantConversions(S, *SCS)) {
5448 return S.Diag(From->getBeginLoc(),
5449 diag::err_typecheck_converted_constant_expression_disallowed)
5450 << From->getType() << From->getSourceRange() << T;
5451 }
5452 // [...] and where the reference binding (if any) binds directly.
5453 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5454 return S.Diag(From->getBeginLoc(),
5455 diag::err_typecheck_converted_constant_expression_indirect)
5456 << From->getType() << From->getSourceRange() << T;
5457 }
5458
5459 ExprResult Result =
5460 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5461 if (Result.isInvalid())
5462 return Result;
5463
5464 // Check for a narrowing implicit conversion.
5465 APValue PreNarrowingValue;
5466 QualType PreNarrowingType;
5467 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5468 PreNarrowingType)) {
5469 case NK_Dependent_Narrowing:
5470 // Implicit conversion to a narrower type, but the expression is
5471 // value-dependent so we can't tell whether it's actually narrowing.
5472 case NK_Variable_Narrowing:
5473 // Implicit conversion to a narrower type, and the value is not a constant
5474 // expression. We'll diagnose this in a moment.
5475 case NK_Not_Narrowing:
5476 break;
5477
5478 case NK_Constant_Narrowing:
5479 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5480 << CCE << /*Constant*/ 1
5481 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5482 break;
5483
5484 case NK_Type_Narrowing:
5485 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5486 << CCE << /*Constant*/ 0 << From->getType() << T;
5487 break;
5488 }
5489
5490 if (Result.get()->isValueDependent()) {
5491 Value = APValue();
5492 return Result;
5493 }
5494
5495 // Check the expression is a constant expression.
5496 SmallVector<PartialDiagnosticAt, 8> Notes;
5497 Expr::EvalResult Eval;
5498 Eval.Diag = &Notes;
5499 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5500 ? Expr::EvaluateForMangling
5501 : Expr::EvaluateForCodeGen;
5502
5503 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5504 (RequireInt && !Eval.Val.isInt())) {
5505 // The expression can't be folded, so we can't keep it at this position in
5506 // the AST.
5507 Result = ExprError();
5508 } else {
5509 Value = Eval.Val;
5510
5511 if (Notes.empty()) {
5512 // It's a constant expression.
5513 return ConstantExpr::Create(S.Context, Result.get());
5514 }
5515 }
5516
5517 // It's not a constant expression. Produce an appropriate diagnostic.
5518 if (Notes.size() == 1 &&
5519 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5520 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5521 else {
5522 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5523 << CCE << From->getSourceRange();
5524 for (unsigned I = 0; I < Notes.size(); ++I)
5525 S.Diag(Notes[I].first, Notes[I].second);
5526 }
5527 return ExprError();
5528 }
5529
CheckConvertedConstantExpression(Expr * From,QualType T,APValue & Value,CCEKind CCE)5530 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5531 APValue &Value, CCEKind CCE) {
5532 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5533 }
5534
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)5535 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5536 llvm::APSInt &Value,
5537 CCEKind CCE) {
5538 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5539
5540 APValue V;
5541 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5542 if (!R.isInvalid() && !R.get()->isValueDependent())
5543 Value = V.getInt();
5544 return R;
5545 }
5546
5547
5548 /// dropPointerConversions - If the given standard conversion sequence
5549 /// involves any pointer conversions, remove them. This may change
5550 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)5551 static void dropPointerConversion(StandardConversionSequence &SCS) {
5552 if (SCS.Second == ICK_Pointer_Conversion) {
5553 SCS.Second = ICK_Identity;
5554 SCS.Third = ICK_Identity;
5555 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5556 }
5557 }
5558
5559 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5560 /// convert the expression From to an Objective-C pointer type.
5561 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)5562 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5563 // Do an implicit conversion to 'id'.
5564 QualType Ty = S.Context.getObjCIdType();
5565 ImplicitConversionSequence ICS
5566 = TryImplicitConversion(S, From, Ty,
5567 // FIXME: Are these flags correct?
5568 /*SuppressUserConversions=*/false,
5569 /*AllowExplicit=*/true,
5570 /*InOverloadResolution=*/false,
5571 /*CStyle=*/false,
5572 /*AllowObjCWritebackConversion=*/false,
5573 /*AllowObjCConversionOnExplicit=*/true);
5574
5575 // Strip off any final conversions to 'id'.
5576 switch (ICS.getKind()) {
5577 case ImplicitConversionSequence::BadConversion:
5578 case ImplicitConversionSequence::AmbiguousConversion:
5579 case ImplicitConversionSequence::EllipsisConversion:
5580 break;
5581
5582 case ImplicitConversionSequence::UserDefinedConversion:
5583 dropPointerConversion(ICS.UserDefined.After);
5584 break;
5585
5586 case ImplicitConversionSequence::StandardConversion:
5587 dropPointerConversion(ICS.Standard);
5588 break;
5589 }
5590
5591 return ICS;
5592 }
5593
5594 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5595 /// conversion of the expression From to an Objective-C pointer type.
5596 /// Returns a valid but null ExprResult if no conversion sequence exists.
PerformContextuallyConvertToObjCPointer(Expr * From)5597 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5598 if (checkPlaceholderForOverload(*this, From))
5599 return ExprError();
5600
5601 QualType Ty = Context.getObjCIdType();
5602 ImplicitConversionSequence ICS =
5603 TryContextuallyConvertToObjCPointer(*this, From);
5604 if (!ICS.isBad())
5605 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5606 return ExprResult();
5607 }
5608
5609 /// Determine whether the provided type is an integral type, or an enumeration
5610 /// type of a permitted flavor.
match(QualType T)5611 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5612 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5613 : T->isIntegralOrUnscopedEnumerationType();
5614 }
5615
5616 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)5617 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5618 Sema::ContextualImplicitConverter &Converter,
5619 QualType T, UnresolvedSetImpl &ViableConversions) {
5620
5621 if (Converter.Suppress)
5622 return ExprError();
5623
5624 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5625 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5626 CXXConversionDecl *Conv =
5627 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5628 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5629 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5630 }
5631 return From;
5632 }
5633
5634 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)5635 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5636 Sema::ContextualImplicitConverter &Converter,
5637 QualType T, bool HadMultipleCandidates,
5638 UnresolvedSetImpl &ExplicitConversions) {
5639 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5640 DeclAccessPair Found = ExplicitConversions[0];
5641 CXXConversionDecl *Conversion =
5642 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5643
5644 // The user probably meant to invoke the given explicit
5645 // conversion; use it.
5646 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5647 std::string TypeStr;
5648 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5649
5650 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5651 << FixItHint::CreateInsertion(From->getBeginLoc(),
5652 "static_cast<" + TypeStr + ">(")
5653 << FixItHint::CreateInsertion(
5654 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5655 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5656
5657 // If we aren't in a SFINAE context, build a call to the
5658 // explicit conversion function.
5659 if (SemaRef.isSFINAEContext())
5660 return true;
5661
5662 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5663 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5664 HadMultipleCandidates);
5665 if (Result.isInvalid())
5666 return true;
5667 // Record usage of conversion in an implicit cast.
5668 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5669 CK_UserDefinedConversion, Result.get(),
5670 nullptr, Result.get()->getValueKind());
5671 }
5672 return false;
5673 }
5674
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)5675 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5676 Sema::ContextualImplicitConverter &Converter,
5677 QualType T, bool HadMultipleCandidates,
5678 DeclAccessPair &Found) {
5679 CXXConversionDecl *Conversion =
5680 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5681 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5682
5683 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5684 if (!Converter.SuppressConversion) {
5685 if (SemaRef.isSFINAEContext())
5686 return true;
5687
5688 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5689 << From->getSourceRange();
5690 }
5691
5692 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5693 HadMultipleCandidates);
5694 if (Result.isInvalid())
5695 return true;
5696 // Record usage of conversion in an implicit cast.
5697 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5698 CK_UserDefinedConversion, Result.get(),
5699 nullptr, Result.get()->getValueKind());
5700 return false;
5701 }
5702
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)5703 static ExprResult finishContextualImplicitConversion(
5704 Sema &SemaRef, SourceLocation Loc, Expr *From,
5705 Sema::ContextualImplicitConverter &Converter) {
5706 if (!Converter.match(From->getType()) && !Converter.Suppress)
5707 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5708 << From->getSourceRange();
5709
5710 return SemaRef.DefaultLvalueConversion(From);
5711 }
5712
5713 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)5714 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5715 UnresolvedSetImpl &ViableConversions,
5716 OverloadCandidateSet &CandidateSet) {
5717 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5718 DeclAccessPair FoundDecl = ViableConversions[I];
5719 NamedDecl *D = FoundDecl.getDecl();
5720 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5721 if (isa<UsingShadowDecl>(D))
5722 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5723
5724 CXXConversionDecl *Conv;
5725 FunctionTemplateDecl *ConvTemplate;
5726 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5727 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5728 else
5729 Conv = cast<CXXConversionDecl>(D);
5730
5731 if (ConvTemplate)
5732 SemaRef.AddTemplateConversionCandidate(
5733 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5734 /*AllowObjCConversionOnExplicit=*/false);
5735 else
5736 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5737 ToType, CandidateSet,
5738 /*AllowObjCConversionOnExplicit=*/false);
5739 }
5740 }
5741
5742 /// Attempt to convert the given expression to a type which is accepted
5743 /// by the given converter.
5744 ///
5745 /// This routine will attempt to convert an expression of class type to a
5746 /// type accepted by the specified converter. In C++11 and before, the class
5747 /// must have a single non-explicit conversion function converting to a matching
5748 /// type. In C++1y, there can be multiple such conversion functions, but only
5749 /// one target type.
5750 ///
5751 /// \param Loc The source location of the construct that requires the
5752 /// conversion.
5753 ///
5754 /// \param From The expression we're converting from.
5755 ///
5756 /// \param Converter Used to control and diagnose the conversion process.
5757 ///
5758 /// \returns The expression, converted to an integral or enumeration type if
5759 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)5760 ExprResult Sema::PerformContextualImplicitConversion(
5761 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5762 // We can't perform any more checking for type-dependent expressions.
5763 if (From->isTypeDependent())
5764 return From;
5765
5766 // Process placeholders immediately.
5767 if (From->hasPlaceholderType()) {
5768 ExprResult result = CheckPlaceholderExpr(From);
5769 if (result.isInvalid())
5770 return result;
5771 From = result.get();
5772 }
5773
5774 // If the expression already has a matching type, we're golden.
5775 QualType T = From->getType();
5776 if (Converter.match(T))
5777 return DefaultLvalueConversion(From);
5778
5779 // FIXME: Check for missing '()' if T is a function type?
5780
5781 // We can only perform contextual implicit conversions on objects of class
5782 // type.
5783 const RecordType *RecordTy = T->getAs<RecordType>();
5784 if (!RecordTy || !getLangOpts().CPlusPlus) {
5785 if (!Converter.Suppress)
5786 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5787 return From;
5788 }
5789
5790 // We must have a complete class type.
5791 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5792 ContextualImplicitConverter &Converter;
5793 Expr *From;
5794
5795 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5796 : Converter(Converter), From(From) {}
5797
5798 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5799 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5800 }
5801 } IncompleteDiagnoser(Converter, From);
5802
5803 if (Converter.Suppress ? !isCompleteType(Loc, T)
5804 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5805 return From;
5806
5807 // Look for a conversion to an integral or enumeration type.
5808 UnresolvedSet<4>
5809 ViableConversions; // These are *potentially* viable in C++1y.
5810 UnresolvedSet<4> ExplicitConversions;
5811 const auto &Conversions =
5812 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5813
5814 bool HadMultipleCandidates =
5815 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5816
5817 // To check that there is only one target type, in C++1y:
5818 QualType ToType;
5819 bool HasUniqueTargetType = true;
5820
5821 // Collect explicit or viable (potentially in C++1y) conversions.
5822 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5823 NamedDecl *D = (*I)->getUnderlyingDecl();
5824 CXXConversionDecl *Conversion;
5825 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5826 if (ConvTemplate) {
5827 if (getLangOpts().CPlusPlus14)
5828 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5829 else
5830 continue; // C++11 does not consider conversion operator templates(?).
5831 } else
5832 Conversion = cast<CXXConversionDecl>(D);
5833
5834 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5835 "Conversion operator templates are considered potentially "
5836 "viable in C++1y");
5837
5838 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5839 if (Converter.match(CurToType) || ConvTemplate) {
5840
5841 if (Conversion->isExplicit()) {
5842 // FIXME: For C++1y, do we need this restriction?
5843 // cf. diagnoseNoViableConversion()
5844 if (!ConvTemplate)
5845 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5846 } else {
5847 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5848 if (ToType.isNull())
5849 ToType = CurToType.getUnqualifiedType();
5850 else if (HasUniqueTargetType &&
5851 (CurToType.getUnqualifiedType() != ToType))
5852 HasUniqueTargetType = false;
5853 }
5854 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5855 }
5856 }
5857 }
5858
5859 if (getLangOpts().CPlusPlus14) {
5860 // C++1y [conv]p6:
5861 // ... An expression e of class type E appearing in such a context
5862 // is said to be contextually implicitly converted to a specified
5863 // type T and is well-formed if and only if e can be implicitly
5864 // converted to a type T that is determined as follows: E is searched
5865 // for conversion functions whose return type is cv T or reference to
5866 // cv T such that T is allowed by the context. There shall be
5867 // exactly one such T.
5868
5869 // If no unique T is found:
5870 if (ToType.isNull()) {
5871 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5872 HadMultipleCandidates,
5873 ExplicitConversions))
5874 return ExprError();
5875 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5876 }
5877
5878 // If more than one unique Ts are found:
5879 if (!HasUniqueTargetType)
5880 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5881 ViableConversions);
5882
5883 // If one unique T is found:
5884 // First, build a candidate set from the previously recorded
5885 // potentially viable conversions.
5886 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5887 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5888 CandidateSet);
5889
5890 // Then, perform overload resolution over the candidate set.
5891 OverloadCandidateSet::iterator Best;
5892 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5893 case OR_Success: {
5894 // Apply this conversion.
5895 DeclAccessPair Found =
5896 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5897 if (recordConversion(*this, Loc, From, Converter, T,
5898 HadMultipleCandidates, Found))
5899 return ExprError();
5900 break;
5901 }
5902 case OR_Ambiguous:
5903 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5904 ViableConversions);
5905 case OR_No_Viable_Function:
5906 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5907 HadMultipleCandidates,
5908 ExplicitConversions))
5909 return ExprError();
5910 LLVM_FALLTHROUGH;
5911 case OR_Deleted:
5912 // We'll complain below about a non-integral condition type.
5913 break;
5914 }
5915 } else {
5916 switch (ViableConversions.size()) {
5917 case 0: {
5918 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5919 HadMultipleCandidates,
5920 ExplicitConversions))
5921 return ExprError();
5922
5923 // We'll complain below about a non-integral condition type.
5924 break;
5925 }
5926 case 1: {
5927 // Apply this conversion.
5928 DeclAccessPair Found = ViableConversions[0];
5929 if (recordConversion(*this, Loc, From, Converter, T,
5930 HadMultipleCandidates, Found))
5931 return ExprError();
5932 break;
5933 }
5934 default:
5935 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5936 ViableConversions);
5937 }
5938 }
5939
5940 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5941 }
5942
5943 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5944 /// an acceptable non-member overloaded operator for a call whose
5945 /// arguments have types T1 (and, if non-empty, T2). This routine
5946 /// implements the check in C++ [over.match.oper]p3b2 concerning
5947 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)5948 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5949 FunctionDecl *Fn,
5950 ArrayRef<Expr *> Args) {
5951 QualType T1 = Args[0]->getType();
5952 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5953
5954 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5955 return true;
5956
5957 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5958 return true;
5959
5960 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5961 if (Proto->getNumParams() < 1)
5962 return false;
5963
5964 if (T1->isEnumeralType()) {
5965 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5966 if (Context.hasSameUnqualifiedType(T1, ArgType))
5967 return true;
5968 }
5969
5970 if (Proto->getNumParams() < 2)
5971 return false;
5972
5973 if (!T2.isNull() && T2->isEnumeralType()) {
5974 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5975 if (Context.hasSameUnqualifiedType(T2, ArgType))
5976 return true;
5977 }
5978
5979 return false;
5980 }
5981
5982 /// AddOverloadCandidate - Adds the given function to the set of
5983 /// candidate functions, using the given function call arguments. If
5984 /// @p SuppressUserConversions, then don't allow user-defined
5985 /// conversions via constructors or conversion operators.
5986 ///
5987 /// \param PartialOverloading true if we are performing "partial" overloading
5988 /// based on an incomplete set of function arguments. This feature is used by
5989 /// code completion.
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,ADLCallKind IsADLCandidate,ConversionSequenceList EarlyConversions)5990 void Sema::AddOverloadCandidate(FunctionDecl *Function,
5991 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5992 OverloadCandidateSet &CandidateSet,
5993 bool SuppressUserConversions,
5994 bool PartialOverloading, bool AllowExplicit,
5995 ADLCallKind IsADLCandidate,
5996 ConversionSequenceList EarlyConversions) {
5997 const FunctionProtoType *Proto
5998 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5999 assert(Proto && "Functions without a prototype cannot be overloaded");
6000 assert(!Function->getDescribedFunctionTemplate() &&
6001 "Use AddTemplateOverloadCandidate for function templates");
6002
6003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6004 if (!isa<CXXConstructorDecl>(Method)) {
6005 // If we get here, it's because we're calling a member function
6006 // that is named without a member access expression (e.g.,
6007 // "this->f") that was either written explicitly or created
6008 // implicitly. This can happen with a qualified call to a member
6009 // function, e.g., X::f(). We use an empty type for the implied
6010 // object argument (C++ [over.call.func]p3), and the acting context
6011 // is irrelevant.
6012 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6013 Expr::Classification::makeSimpleLValue(), Args,
6014 CandidateSet, SuppressUserConversions,
6015 PartialOverloading, EarlyConversions);
6016 return;
6017 }
6018 // We treat a constructor like a non-member function, since its object
6019 // argument doesn't participate in overload resolution.
6020 }
6021
6022 if (!CandidateSet.isNewCandidate(Function))
6023 return;
6024
6025 // C++ [over.match.oper]p3:
6026 // if no operand has a class type, only those non-member functions in the
6027 // lookup set that have a first parameter of type T1 or "reference to
6028 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6029 // is a right operand) a second parameter of type T2 or "reference to
6030 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6031 // candidate functions.
6032 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6033 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6034 return;
6035
6036 // C++11 [class.copy]p11: [DR1402]
6037 // A defaulted move constructor that is defined as deleted is ignored by
6038 // overload resolution.
6039 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6040 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6041 Constructor->isMoveConstructor())
6042 return;
6043
6044 // Overload resolution is always an unevaluated context.
6045 EnterExpressionEvaluationContext Unevaluated(
6046 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6047
6048 // Add this candidate
6049 OverloadCandidate &Candidate =
6050 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6051 Candidate.FoundDecl = FoundDecl;
6052 Candidate.Function = Function;
6053 Candidate.Viable = true;
6054 Candidate.IsSurrogate = false;
6055 Candidate.IsADLCandidate = IsADLCandidate;
6056 Candidate.IgnoreObjectArgument = false;
6057 Candidate.ExplicitCallArguments = Args.size();
6058
6059 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6060 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6061 Candidate.Viable = false;
6062 Candidate.FailureKind = ovl_non_default_multiversion_function;
6063 return;
6064 }
6065
6066 if (Constructor) {
6067 // C++ [class.copy]p3:
6068 // A member function template is never instantiated to perform the copy
6069 // of a class object to an object of its class type.
6070 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6071 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6072 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6073 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6074 ClassType))) {
6075 Candidate.Viable = false;
6076 Candidate.FailureKind = ovl_fail_illegal_constructor;
6077 return;
6078 }
6079
6080 // C++ [over.match.funcs]p8: (proposed DR resolution)
6081 // A constructor inherited from class type C that has a first parameter
6082 // of type "reference to P" (including such a constructor instantiated
6083 // from a template) is excluded from the set of candidate functions when
6084 // constructing an object of type cv D if the argument list has exactly
6085 // one argument and D is reference-related to P and P is reference-related
6086 // to C.
6087 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6088 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6089 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6090 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6091 QualType C = Context.getRecordType(Constructor->getParent());
6092 QualType D = Context.getRecordType(Shadow->getParent());
6093 SourceLocation Loc = Args.front()->getExprLoc();
6094 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6095 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6096 Candidate.Viable = false;
6097 Candidate.FailureKind = ovl_fail_inhctor_slice;
6098 return;
6099 }
6100 }
6101 }
6102
6103 unsigned NumParams = Proto->getNumParams();
6104
6105 // (C++ 13.3.2p2): A candidate function having fewer than m
6106 // parameters is viable only if it has an ellipsis in its parameter
6107 // list (8.3.5).
6108 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6109 !Proto->isVariadic()) {
6110 Candidate.Viable = false;
6111 Candidate.FailureKind = ovl_fail_too_many_arguments;
6112 return;
6113 }
6114
6115 // (C++ 13.3.2p2): A candidate function having more than m parameters
6116 // is viable only if the (m+1)st parameter has a default argument
6117 // (8.3.6). For the purposes of overload resolution, the
6118 // parameter list is truncated on the right, so that there are
6119 // exactly m parameters.
6120 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6121 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6122 // Not enough arguments.
6123 Candidate.Viable = false;
6124 Candidate.FailureKind = ovl_fail_too_few_arguments;
6125 return;
6126 }
6127
6128 // (CUDA B.1): Check for invalid calls between targets.
6129 if (getLangOpts().CUDA)
6130 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6131 // Skip the check for callers that are implicit members, because in this
6132 // case we may not yet know what the member's target is; the target is
6133 // inferred for the member automatically, based on the bases and fields of
6134 // the class.
6135 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6136 Candidate.Viable = false;
6137 Candidate.FailureKind = ovl_fail_bad_target;
6138 return;
6139 }
6140
6141 // Determine the implicit conversion sequences for each of the
6142 // arguments.
6143 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6144 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6145 // We already formed a conversion sequence for this parameter during
6146 // template argument deduction.
6147 } else if (ArgIdx < NumParams) {
6148 // (C++ 13.3.2p3): for F to be a viable function, there shall
6149 // exist for each argument an implicit conversion sequence
6150 // (13.3.3.1) that converts that argument to the corresponding
6151 // parameter of F.
6152 QualType ParamType = Proto->getParamType(ArgIdx);
6153 Candidate.Conversions[ArgIdx]
6154 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6155 SuppressUserConversions,
6156 /*InOverloadResolution=*/true,
6157 /*AllowObjCWritebackConversion=*/
6158 getLangOpts().ObjCAutoRefCount,
6159 AllowExplicit);
6160 if (Candidate.Conversions[ArgIdx].isBad()) {
6161 Candidate.Viable = false;
6162 Candidate.FailureKind = ovl_fail_bad_conversion;
6163 return;
6164 }
6165 } else {
6166 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6167 // argument for which there is no corresponding parameter is
6168 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6169 Candidate.Conversions[ArgIdx].setEllipsis();
6170 }
6171 }
6172
6173 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6174 Candidate.Viable = false;
6175 Candidate.FailureKind = ovl_fail_enable_if;
6176 Candidate.DeductionFailure.Data = FailedAttr;
6177 return;
6178 }
6179
6180 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6181 Candidate.Viable = false;
6182 Candidate.FailureKind = ovl_fail_ext_disabled;
6183 return;
6184 }
6185 }
6186
6187 ObjCMethodDecl *
SelectBestMethod(Selector Sel,MultiExprArg Args,bool IsInstance,SmallVectorImpl<ObjCMethodDecl * > & Methods)6188 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6189 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6190 if (Methods.size() <= 1)
6191 return nullptr;
6192
6193 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6194 bool Match = true;
6195 ObjCMethodDecl *Method = Methods[b];
6196 unsigned NumNamedArgs = Sel.getNumArgs();
6197 // Method might have more arguments than selector indicates. This is due
6198 // to addition of c-style arguments in method.
6199 if (Method->param_size() > NumNamedArgs)
6200 NumNamedArgs = Method->param_size();
6201 if (Args.size() < NumNamedArgs)
6202 continue;
6203
6204 for (unsigned i = 0; i < NumNamedArgs; i++) {
6205 // We can't do any type-checking on a type-dependent argument.
6206 if (Args[i]->isTypeDependent()) {
6207 Match = false;
6208 break;
6209 }
6210
6211 ParmVarDecl *param = Method->parameters()[i];
6212 Expr *argExpr = Args[i];
6213 assert(argExpr && "SelectBestMethod(): missing expression");
6214
6215 // Strip the unbridged-cast placeholder expression off unless it's
6216 // a consumed argument.
6217 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6218 !param->hasAttr<CFConsumedAttr>())
6219 argExpr = stripARCUnbridgedCast(argExpr);
6220
6221 // If the parameter is __unknown_anytype, move on to the next method.
6222 if (param->getType() == Context.UnknownAnyTy) {
6223 Match = false;
6224 break;
6225 }
6226
6227 ImplicitConversionSequence ConversionState
6228 = TryCopyInitialization(*this, argExpr, param->getType(),
6229 /*SuppressUserConversions*/false,
6230 /*InOverloadResolution=*/true,
6231 /*AllowObjCWritebackConversion=*/
6232 getLangOpts().ObjCAutoRefCount,
6233 /*AllowExplicit*/false);
6234 // This function looks for a reasonably-exact match, so we consider
6235 // incompatible pointer conversions to be a failure here.
6236 if (ConversionState.isBad() ||
6237 (ConversionState.isStandard() &&
6238 ConversionState.Standard.Second ==
6239 ICK_Incompatible_Pointer_Conversion)) {
6240 Match = false;
6241 break;
6242 }
6243 }
6244 // Promote additional arguments to variadic methods.
6245 if (Match && Method->isVariadic()) {
6246 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6247 if (Args[i]->isTypeDependent()) {
6248 Match = false;
6249 break;
6250 }
6251 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6252 nullptr);
6253 if (Arg.isInvalid()) {
6254 Match = false;
6255 break;
6256 }
6257 }
6258 } else {
6259 // Check for extra arguments to non-variadic methods.
6260 if (Args.size() != NumNamedArgs)
6261 Match = false;
6262 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6263 // Special case when selectors have no argument. In this case, select
6264 // one with the most general result type of 'id'.
6265 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6266 QualType ReturnT = Methods[b]->getReturnType();
6267 if (ReturnT->isObjCIdType())
6268 return Methods[b];
6269 }
6270 }
6271 }
6272
6273 if (Match)
6274 return Method;
6275 }
6276 return nullptr;
6277 }
6278
6279 static bool
convertArgsForAvailabilityChecks(Sema & S,FunctionDecl * Function,Expr * ThisArg,ArrayRef<Expr * > Args,Sema::SFINAETrap & Trap,bool MissingImplicitThis,Expr * & ConvertedThis,SmallVectorImpl<Expr * > & ConvertedArgs)6280 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6281 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6282 bool MissingImplicitThis, Expr *&ConvertedThis,
6283 SmallVectorImpl<Expr *> &ConvertedArgs) {
6284 if (ThisArg) {
6285 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6286 assert(!isa<CXXConstructorDecl>(Method) &&
6287 "Shouldn't have `this` for ctors!");
6288 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6289 ExprResult R = S.PerformObjectArgumentInitialization(
6290 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6291 if (R.isInvalid())
6292 return false;
6293 ConvertedThis = R.get();
6294 } else {
6295 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6296 (void)MD;
6297 assert((MissingImplicitThis || MD->isStatic() ||
6298 isa<CXXConstructorDecl>(MD)) &&
6299 "Expected `this` for non-ctor instance methods");
6300 }
6301 ConvertedThis = nullptr;
6302 }
6303
6304 // Ignore any variadic arguments. Converting them is pointless, since the
6305 // user can't refer to them in the function condition.
6306 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6307
6308 // Convert the arguments.
6309 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6310 ExprResult R;
6311 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6312 S.Context, Function->getParamDecl(I)),
6313 SourceLocation(), Args[I]);
6314
6315 if (R.isInvalid())
6316 return false;
6317
6318 ConvertedArgs.push_back(R.get());
6319 }
6320
6321 if (Trap.hasErrorOccurred())
6322 return false;
6323
6324 // Push default arguments if needed.
6325 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6326 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6327 ParmVarDecl *P = Function->getParamDecl(i);
6328 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6329 ? P->getUninstantiatedDefaultArg()
6330 : P->getDefaultArg();
6331 // This can only happen in code completion, i.e. when PartialOverloading
6332 // is true.
6333 if (!DefArg)
6334 return false;
6335 ExprResult R =
6336 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6337 S.Context, Function->getParamDecl(i)),
6338 SourceLocation(), DefArg);
6339 if (R.isInvalid())
6340 return false;
6341 ConvertedArgs.push_back(R.get());
6342 }
6343
6344 if (Trap.hasErrorOccurred())
6345 return false;
6346 }
6347 return true;
6348 }
6349
CheckEnableIf(FunctionDecl * Function,ArrayRef<Expr * > Args,bool MissingImplicitThis)6350 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6351 bool MissingImplicitThis) {
6352 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6353 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6354 return nullptr;
6355
6356 SFINAETrap Trap(*this);
6357 SmallVector<Expr *, 16> ConvertedArgs;
6358 // FIXME: We should look into making enable_if late-parsed.
6359 Expr *DiscardedThis;
6360 if (!convertArgsForAvailabilityChecks(
6361 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6362 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6363 return *EnableIfAttrs.begin();
6364
6365 for (auto *EIA : EnableIfAttrs) {
6366 APValue Result;
6367 // FIXME: This doesn't consider value-dependent cases, because doing so is
6368 // very difficult. Ideally, we should handle them more gracefully.
6369 if (!EIA->getCond()->EvaluateWithSubstitution(
6370 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6371 return EIA;
6372
6373 if (!Result.isInt() || !Result.getInt().getBoolValue())
6374 return EIA;
6375 }
6376 return nullptr;
6377 }
6378
6379 template <typename CheckFn>
diagnoseDiagnoseIfAttrsWith(Sema & S,const NamedDecl * ND,bool ArgDependent,SourceLocation Loc,CheckFn && IsSuccessful)6380 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6381 bool ArgDependent, SourceLocation Loc,
6382 CheckFn &&IsSuccessful) {
6383 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6384 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6385 if (ArgDependent == DIA->getArgDependent())
6386 Attrs.push_back(DIA);
6387 }
6388
6389 // Common case: No diagnose_if attributes, so we can quit early.
6390 if (Attrs.empty())
6391 return false;
6392
6393 auto WarningBegin = std::stable_partition(
6394 Attrs.begin(), Attrs.end(),
6395 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6396
6397 // Note that diagnose_if attributes are late-parsed, so they appear in the
6398 // correct order (unlike enable_if attributes).
6399 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6400 IsSuccessful);
6401 if (ErrAttr != WarningBegin) {
6402 const DiagnoseIfAttr *DIA = *ErrAttr;
6403 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6404 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6405 << DIA->getParent() << DIA->getCond()->getSourceRange();
6406 return true;
6407 }
6408
6409 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6410 if (IsSuccessful(DIA)) {
6411 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6412 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6413 << DIA->getParent() << DIA->getCond()->getSourceRange();
6414 }
6415
6416 return false;
6417 }
6418
diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl * Function,const Expr * ThisArg,ArrayRef<const Expr * > Args,SourceLocation Loc)6419 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6420 const Expr *ThisArg,
6421 ArrayRef<const Expr *> Args,
6422 SourceLocation Loc) {
6423 return diagnoseDiagnoseIfAttrsWith(
6424 *this, Function, /*ArgDependent=*/true, Loc,
6425 [&](const DiagnoseIfAttr *DIA) {
6426 APValue Result;
6427 // It's sane to use the same Args for any redecl of this function, since
6428 // EvaluateWithSubstitution only cares about the position of each
6429 // argument in the arg list, not the ParmVarDecl* it maps to.
6430 if (!DIA->getCond()->EvaluateWithSubstitution(
6431 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6432 return false;
6433 return Result.isInt() && Result.getInt().getBoolValue();
6434 });
6435 }
6436
diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl * ND,SourceLocation Loc)6437 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6438 SourceLocation Loc) {
6439 return diagnoseDiagnoseIfAttrsWith(
6440 *this, ND, /*ArgDependent=*/false, Loc,
6441 [&](const DiagnoseIfAttr *DIA) {
6442 bool Result;
6443 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6444 Result;
6445 });
6446 }
6447
6448 /// Add all of the function declarations in the given function set to
6449 /// the overload candidate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs,bool SuppressUserConversions,bool PartialOverloading,bool FirstArgumentIsBase)6450 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6451 ArrayRef<Expr *> Args,
6452 OverloadCandidateSet &CandidateSet,
6453 TemplateArgumentListInfo *ExplicitTemplateArgs,
6454 bool SuppressUserConversions,
6455 bool PartialOverloading,
6456 bool FirstArgumentIsBase) {
6457 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6458 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6459 ArrayRef<Expr *> FunctionArgs = Args;
6460
6461 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6462 FunctionDecl *FD =
6463 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6464
6465 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6466 QualType ObjectType;
6467 Expr::Classification ObjectClassification;
6468 if (Args.size() > 0) {
6469 if (Expr *E = Args[0]) {
6470 // Use the explicit base to restrict the lookup:
6471 ObjectType = E->getType();
6472 // Pointers in the object arguments are implicitly dereferenced, so we
6473 // always classify them as l-values.
6474 if (!ObjectType.isNull() && ObjectType->isPointerType())
6475 ObjectClassification = Expr::Classification::makeSimpleLValue();
6476 else
6477 ObjectClassification = E->Classify(Context);
6478 } // .. else there is an implicit base.
6479 FunctionArgs = Args.slice(1);
6480 }
6481 if (FunTmpl) {
6482 AddMethodTemplateCandidate(
6483 FunTmpl, F.getPair(),
6484 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6485 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6486 FunctionArgs, CandidateSet, SuppressUserConversions,
6487 PartialOverloading);
6488 } else {
6489 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6490 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6491 ObjectClassification, FunctionArgs, CandidateSet,
6492 SuppressUserConversions, PartialOverloading);
6493 }
6494 } else {
6495 // This branch handles both standalone functions and static methods.
6496
6497 // Slice the first argument (which is the base) when we access
6498 // static method as non-static.
6499 if (Args.size() > 0 &&
6500 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6501 !isa<CXXConstructorDecl>(FD)))) {
6502 assert(cast<CXXMethodDecl>(FD)->isStatic());
6503 FunctionArgs = Args.slice(1);
6504 }
6505 if (FunTmpl) {
6506 AddTemplateOverloadCandidate(
6507 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6508 CandidateSet, SuppressUserConversions, PartialOverloading);
6509 } else {
6510 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6511 SuppressUserConversions, PartialOverloading);
6512 }
6513 }
6514 }
6515 }
6516
6517 /// AddMethodCandidate - Adds a named decl (which is some kind of
6518 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)6519 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6520 QualType ObjectType,
6521 Expr::Classification ObjectClassification,
6522 ArrayRef<Expr *> Args,
6523 OverloadCandidateSet& CandidateSet,
6524 bool SuppressUserConversions) {
6525 NamedDecl *Decl = FoundDecl.getDecl();
6526 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6527
6528 if (isa<UsingShadowDecl>(Decl))
6529 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6530
6531 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6532 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6533 "Expected a member function template");
6534 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6535 /*ExplicitArgs*/ nullptr, ObjectType,
6536 ObjectClassification, Args, CandidateSet,
6537 SuppressUserConversions);
6538 } else {
6539 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6540 ObjectType, ObjectClassification, Args, CandidateSet,
6541 SuppressUserConversions);
6542 }
6543 }
6544
6545 /// AddMethodCandidate - Adds the given C++ member function to the set
6546 /// of candidate functions, using the given function call arguments
6547 /// and the object argument (@c Object). For example, in a call
6548 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6549 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6550 /// allow user-defined conversions via constructors or conversion
6551 /// operators.
6552 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,ConversionSequenceList EarlyConversions)6553 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6554 CXXRecordDecl *ActingContext, QualType ObjectType,
6555 Expr::Classification ObjectClassification,
6556 ArrayRef<Expr *> Args,
6557 OverloadCandidateSet &CandidateSet,
6558 bool SuppressUserConversions,
6559 bool PartialOverloading,
6560 ConversionSequenceList EarlyConversions) {
6561 const FunctionProtoType *Proto
6562 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6563 assert(Proto && "Methods without a prototype cannot be overloaded");
6564 assert(!isa<CXXConstructorDecl>(Method) &&
6565 "Use AddOverloadCandidate for constructors");
6566
6567 if (!CandidateSet.isNewCandidate(Method))
6568 return;
6569
6570 // C++11 [class.copy]p23: [DR1402]
6571 // A defaulted move assignment operator that is defined as deleted is
6572 // ignored by overload resolution.
6573 if (Method->isDefaulted() && Method->isDeleted() &&
6574 Method->isMoveAssignmentOperator())
6575 return;
6576
6577 // Overload resolution is always an unevaluated context.
6578 EnterExpressionEvaluationContext Unevaluated(
6579 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6580
6581 // Add this candidate
6582 OverloadCandidate &Candidate =
6583 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6584 Candidate.FoundDecl = FoundDecl;
6585 Candidate.Function = Method;
6586 Candidate.IsSurrogate = false;
6587 Candidate.IgnoreObjectArgument = false;
6588 Candidate.ExplicitCallArguments = Args.size();
6589
6590 unsigned NumParams = Proto->getNumParams();
6591
6592 // (C++ 13.3.2p2): A candidate function having fewer than m
6593 // parameters is viable only if it has an ellipsis in its parameter
6594 // list (8.3.5).
6595 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6596 !Proto->isVariadic()) {
6597 Candidate.Viable = false;
6598 Candidate.FailureKind = ovl_fail_too_many_arguments;
6599 return;
6600 }
6601
6602 // (C++ 13.3.2p2): A candidate function having more than m parameters
6603 // is viable only if the (m+1)st parameter has a default argument
6604 // (8.3.6). For the purposes of overload resolution, the
6605 // parameter list is truncated on the right, so that there are
6606 // exactly m parameters.
6607 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6608 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6609 // Not enough arguments.
6610 Candidate.Viable = false;
6611 Candidate.FailureKind = ovl_fail_too_few_arguments;
6612 return;
6613 }
6614
6615 Candidate.Viable = true;
6616
6617 if (Method->isStatic() || ObjectType.isNull())
6618 // The implicit object argument is ignored.
6619 Candidate.IgnoreObjectArgument = true;
6620 else {
6621 // Determine the implicit conversion sequence for the object
6622 // parameter.
6623 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6624 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6625 Method, ActingContext);
6626 if (Candidate.Conversions[0].isBad()) {
6627 Candidate.Viable = false;
6628 Candidate.FailureKind = ovl_fail_bad_conversion;
6629 return;
6630 }
6631 }
6632
6633 // (CUDA B.1): Check for invalid calls between targets.
6634 if (getLangOpts().CUDA)
6635 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6636 if (!IsAllowedCUDACall(Caller, Method)) {
6637 Candidate.Viable = false;
6638 Candidate.FailureKind = ovl_fail_bad_target;
6639 return;
6640 }
6641
6642 // Determine the implicit conversion sequences for each of the
6643 // arguments.
6644 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6645 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6646 // We already formed a conversion sequence for this parameter during
6647 // template argument deduction.
6648 } else if (ArgIdx < NumParams) {
6649 // (C++ 13.3.2p3): for F to be a viable function, there shall
6650 // exist for each argument an implicit conversion sequence
6651 // (13.3.3.1) that converts that argument to the corresponding
6652 // parameter of F.
6653 QualType ParamType = Proto->getParamType(ArgIdx);
6654 Candidate.Conversions[ArgIdx + 1]
6655 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6656 SuppressUserConversions,
6657 /*InOverloadResolution=*/true,
6658 /*AllowObjCWritebackConversion=*/
6659 getLangOpts().ObjCAutoRefCount);
6660 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6661 Candidate.Viable = false;
6662 Candidate.FailureKind = ovl_fail_bad_conversion;
6663 return;
6664 }
6665 } else {
6666 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6667 // argument for which there is no corresponding parameter is
6668 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6669 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6670 }
6671 }
6672
6673 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6674 Candidate.Viable = false;
6675 Candidate.FailureKind = ovl_fail_enable_if;
6676 Candidate.DeductionFailure.Data = FailedAttr;
6677 return;
6678 }
6679
6680 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6681 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6682 Candidate.Viable = false;
6683 Candidate.FailureKind = ovl_non_default_multiversion_function;
6684 }
6685 }
6686
6687 /// Add a C++ member function template as a candidate to the candidate
6688 /// set, using template argument deduction to produce an appropriate member
6689 /// function template specialization.
6690 void
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading)6691 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6692 DeclAccessPair FoundDecl,
6693 CXXRecordDecl *ActingContext,
6694 TemplateArgumentListInfo *ExplicitTemplateArgs,
6695 QualType ObjectType,
6696 Expr::Classification ObjectClassification,
6697 ArrayRef<Expr *> Args,
6698 OverloadCandidateSet& CandidateSet,
6699 bool SuppressUserConversions,
6700 bool PartialOverloading) {
6701 if (!CandidateSet.isNewCandidate(MethodTmpl))
6702 return;
6703
6704 // C++ [over.match.funcs]p7:
6705 // In each case where a candidate is a function template, candidate
6706 // function template specializations are generated using template argument
6707 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6708 // candidate functions in the usual way.113) A given name can refer to one
6709 // or more function templates and also to a set of overloaded non-template
6710 // functions. In such a case, the candidate functions generated from each
6711 // function template are combined with the set of non-template candidate
6712 // functions.
6713 TemplateDeductionInfo Info(CandidateSet.getLocation());
6714 FunctionDecl *Specialization = nullptr;
6715 ConversionSequenceList Conversions;
6716 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6717 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6718 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6719 return CheckNonDependentConversions(
6720 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6721 SuppressUserConversions, ActingContext, ObjectType,
6722 ObjectClassification);
6723 })) {
6724 OverloadCandidate &Candidate =
6725 CandidateSet.addCandidate(Conversions.size(), Conversions);
6726 Candidate.FoundDecl = FoundDecl;
6727 Candidate.Function = MethodTmpl->getTemplatedDecl();
6728 Candidate.Viable = false;
6729 Candidate.IsSurrogate = false;
6730 Candidate.IgnoreObjectArgument =
6731 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6732 ObjectType.isNull();
6733 Candidate.ExplicitCallArguments = Args.size();
6734 if (Result == TDK_NonDependentConversionFailure)
6735 Candidate.FailureKind = ovl_fail_bad_conversion;
6736 else {
6737 Candidate.FailureKind = ovl_fail_bad_deduction;
6738 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6739 Info);
6740 }
6741 return;
6742 }
6743
6744 // Add the function template specialization produced by template argument
6745 // deduction as a candidate.
6746 assert(Specialization && "Missing member function template specialization?");
6747 assert(isa<CXXMethodDecl>(Specialization) &&
6748 "Specialization is not a member function?");
6749 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6750 ActingContext, ObjectType, ObjectClassification, Args,
6751 CandidateSet, SuppressUserConversions, PartialOverloading,
6752 Conversions);
6753 }
6754
6755 /// Add a C++ function template specialization as a candidate
6756 /// in the candidate set, using template argument deduction to produce
6757 /// an appropriate function template specialization.
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,ADLCallKind IsADLCandidate)6758 void Sema::AddTemplateOverloadCandidate(
6759 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6760 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6761 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6762 bool PartialOverloading, ADLCallKind IsADLCandidate) {
6763 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6764 return;
6765
6766 // C++ [over.match.funcs]p7:
6767 // In each case where a candidate is a function template, candidate
6768 // function template specializations are generated using template argument
6769 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6770 // candidate functions in the usual way.113) A given name can refer to one
6771 // or more function templates and also to a set of overloaded non-template
6772 // functions. In such a case, the candidate functions generated from each
6773 // function template are combined with the set of non-template candidate
6774 // functions.
6775 TemplateDeductionInfo Info(CandidateSet.getLocation());
6776 FunctionDecl *Specialization = nullptr;
6777 ConversionSequenceList Conversions;
6778 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6779 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6780 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6781 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6782 Args, CandidateSet, Conversions,
6783 SuppressUserConversions);
6784 })) {
6785 OverloadCandidate &Candidate =
6786 CandidateSet.addCandidate(Conversions.size(), Conversions);
6787 Candidate.FoundDecl = FoundDecl;
6788 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6789 Candidate.Viable = false;
6790 Candidate.IsSurrogate = false;
6791 Candidate.IsADLCandidate = IsADLCandidate;
6792 // Ignore the object argument if there is one, since we don't have an object
6793 // type.
6794 Candidate.IgnoreObjectArgument =
6795 isa<CXXMethodDecl>(Candidate.Function) &&
6796 !isa<CXXConstructorDecl>(Candidate.Function);
6797 Candidate.ExplicitCallArguments = Args.size();
6798 if (Result == TDK_NonDependentConversionFailure)
6799 Candidate.FailureKind = ovl_fail_bad_conversion;
6800 else {
6801 Candidate.FailureKind = ovl_fail_bad_deduction;
6802 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6803 Info);
6804 }
6805 return;
6806 }
6807
6808 // Add the function template specialization produced by template argument
6809 // deduction as a candidate.
6810 assert(Specialization && "Missing function template specialization?");
6811 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6812 SuppressUserConversions, PartialOverloading,
6813 /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6814 }
6815
6816 /// Check that implicit conversion sequences can be formed for each argument
6817 /// whose corresponding parameter has a non-dependent type, per DR1391's
6818 /// [temp.deduct.call]p10.
CheckNonDependentConversions(FunctionTemplateDecl * FunctionTemplate,ArrayRef<QualType> ParamTypes,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,ConversionSequenceList & Conversions,bool SuppressUserConversions,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification)6819 bool Sema::CheckNonDependentConversions(
6820 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6821 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6822 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6823 CXXRecordDecl *ActingContext, QualType ObjectType,
6824 Expr::Classification ObjectClassification) {
6825 // FIXME: The cases in which we allow explicit conversions for constructor
6826 // arguments never consider calling a constructor template. It's not clear
6827 // that is correct.
6828 const bool AllowExplicit = false;
6829
6830 auto *FD = FunctionTemplate->getTemplatedDecl();
6831 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6832 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6833 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6834
6835 Conversions =
6836 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6837
6838 // Overload resolution is always an unevaluated context.
6839 EnterExpressionEvaluationContext Unevaluated(
6840 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6841
6842 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6843 // require that, but this check should never result in a hard error, and
6844 // overload resolution is permitted to sidestep instantiations.
6845 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6846 !ObjectType.isNull()) {
6847 Conversions[0] = TryObjectArgumentInitialization(
6848 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6849 Method, ActingContext);
6850 if (Conversions[0].isBad())
6851 return true;
6852 }
6853
6854 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6855 ++I) {
6856 QualType ParamType = ParamTypes[I];
6857 if (!ParamType->isDependentType()) {
6858 Conversions[ThisConversions + I]
6859 = TryCopyInitialization(*this, Args[I], ParamType,
6860 SuppressUserConversions,
6861 /*InOverloadResolution=*/true,
6862 /*AllowObjCWritebackConversion=*/
6863 getLangOpts().ObjCAutoRefCount,
6864 AllowExplicit);
6865 if (Conversions[ThisConversions + I].isBad())
6866 return true;
6867 }
6868 }
6869
6870 return false;
6871 }
6872
6873 /// Determine whether this is an allowable conversion from the result
6874 /// of an explicit conversion operator to the expected type, per C++
6875 /// [over.match.conv]p1 and [over.match.ref]p1.
6876 ///
6877 /// \param ConvType The return type of the conversion function.
6878 ///
6879 /// \param ToType The type we are converting to.
6880 ///
6881 /// \param AllowObjCPointerConversion Allow a conversion from one
6882 /// Objective-C pointer to another.
6883 ///
6884 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)6885 static bool isAllowableExplicitConversion(Sema &S,
6886 QualType ConvType, QualType ToType,
6887 bool AllowObjCPointerConversion) {
6888 QualType ToNonRefType = ToType.getNonReferenceType();
6889
6890 // Easy case: the types are the same.
6891 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6892 return true;
6893
6894 // Allow qualification conversions.
6895 bool ObjCLifetimeConversion;
6896 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6897 ObjCLifetimeConversion))
6898 return true;
6899
6900 // If we're not allowed to consider Objective-C pointer conversions,
6901 // we're done.
6902 if (!AllowObjCPointerConversion)
6903 return false;
6904
6905 // Is this an Objective-C pointer conversion?
6906 bool IncompatibleObjC = false;
6907 QualType ConvertedType;
6908 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6909 IncompatibleObjC);
6910 }
6911
6912 /// AddConversionCandidate - Add a C++ conversion function as a
6913 /// candidate in the candidate set (C++ [over.match.conv],
6914 /// C++ [over.match.copy]). From is the expression we're converting from,
6915 /// and ToType is the type that we're eventually trying to convert to
6916 /// (which may or may not be the same type as the type that the
6917 /// conversion function produces).
6918 void
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowResultConversion)6919 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6920 DeclAccessPair FoundDecl,
6921 CXXRecordDecl *ActingContext,
6922 Expr *From, QualType ToType,
6923 OverloadCandidateSet& CandidateSet,
6924 bool AllowObjCConversionOnExplicit,
6925 bool AllowResultConversion) {
6926 assert(!Conversion->getDescribedFunctionTemplate() &&
6927 "Conversion function templates use AddTemplateConversionCandidate");
6928 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6929 if (!CandidateSet.isNewCandidate(Conversion))
6930 return;
6931
6932 // If the conversion function has an undeduced return type, trigger its
6933 // deduction now.
6934 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6935 if (DeduceReturnType(Conversion, From->getExprLoc()))
6936 return;
6937 ConvType = Conversion->getConversionType().getNonReferenceType();
6938 }
6939
6940 // If we don't allow any conversion of the result type, ignore conversion
6941 // functions that don't convert to exactly (possibly cv-qualified) T.
6942 if (!AllowResultConversion &&
6943 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6944 return;
6945
6946 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6947 // operator is only a candidate if its return type is the target type or
6948 // can be converted to the target type with a qualification conversion.
6949 if (Conversion->isExplicit() &&
6950 !isAllowableExplicitConversion(*this, ConvType, ToType,
6951 AllowObjCConversionOnExplicit))
6952 return;
6953
6954 // Overload resolution is always an unevaluated context.
6955 EnterExpressionEvaluationContext Unevaluated(
6956 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6957
6958 // Add this candidate
6959 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6960 Candidate.FoundDecl = FoundDecl;
6961 Candidate.Function = Conversion;
6962 Candidate.IsSurrogate = false;
6963 Candidate.IgnoreObjectArgument = false;
6964 Candidate.FinalConversion.setAsIdentityConversion();
6965 Candidate.FinalConversion.setFromType(ConvType);
6966 Candidate.FinalConversion.setAllToTypes(ToType);
6967 Candidate.Viable = true;
6968 Candidate.ExplicitCallArguments = 1;
6969
6970 // C++ [over.match.funcs]p4:
6971 // For conversion functions, the function is considered to be a member of
6972 // the class of the implicit implied object argument for the purpose of
6973 // defining the type of the implicit object parameter.
6974 //
6975 // Determine the implicit conversion sequence for the implicit
6976 // object parameter.
6977 QualType ImplicitParamType = From->getType();
6978 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6979 ImplicitParamType = FromPtrType->getPointeeType();
6980 CXXRecordDecl *ConversionContext
6981 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6982
6983 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6984 *this, CandidateSet.getLocation(), From->getType(),
6985 From->Classify(Context), Conversion, ConversionContext);
6986
6987 if (Candidate.Conversions[0].isBad()) {
6988 Candidate.Viable = false;
6989 Candidate.FailureKind = ovl_fail_bad_conversion;
6990 return;
6991 }
6992
6993 // We won't go through a user-defined type conversion function to convert a
6994 // derived to base as such conversions are given Conversion Rank. They only
6995 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6996 QualType FromCanon
6997 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6998 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6999 if (FromCanon == ToCanon ||
7000 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7001 Candidate.Viable = false;
7002 Candidate.FailureKind = ovl_fail_trivial_conversion;
7003 return;
7004 }
7005
7006 // To determine what the conversion from the result of calling the
7007 // conversion function to the type we're eventually trying to
7008 // convert to (ToType), we need to synthesize a call to the
7009 // conversion function and attempt copy initialization from it. This
7010 // makes sure that we get the right semantics with respect to
7011 // lvalues/rvalues and the type. Fortunately, we can allocate this
7012 // call on the stack and we don't need its arguments to be
7013 // well-formed.
7014 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7015 VK_LValue, From->getBeginLoc());
7016 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7017 Context.getPointerType(Conversion->getType()),
7018 CK_FunctionToPointerDecay,
7019 &ConversionRef, VK_RValue);
7020
7021 QualType ConversionType = Conversion->getConversionType();
7022 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7023 Candidate.Viable = false;
7024 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7025 return;
7026 }
7027
7028 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7029
7030 // Note that it is safe to allocate CallExpr on the stack here because
7031 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7032 // allocator).
7033 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7034
7035 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7036 Buffer;
7037 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7038 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7039
7040 ImplicitConversionSequence ICS =
7041 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7042 /*SuppressUserConversions=*/true,
7043 /*InOverloadResolution=*/false,
7044 /*AllowObjCWritebackConversion=*/false);
7045
7046 switch (ICS.getKind()) {
7047 case ImplicitConversionSequence::StandardConversion:
7048 Candidate.FinalConversion = ICS.Standard;
7049
7050 // C++ [over.ics.user]p3:
7051 // If the user-defined conversion is specified by a specialization of a
7052 // conversion function template, the second standard conversion sequence
7053 // shall have exact match rank.
7054 if (Conversion->getPrimaryTemplate() &&
7055 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7056 Candidate.Viable = false;
7057 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7058 return;
7059 }
7060
7061 // C++0x [dcl.init.ref]p5:
7062 // In the second case, if the reference is an rvalue reference and
7063 // the second standard conversion sequence of the user-defined
7064 // conversion sequence includes an lvalue-to-rvalue conversion, the
7065 // program is ill-formed.
7066 if (ToType->isRValueReferenceType() &&
7067 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7068 Candidate.Viable = false;
7069 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7070 return;
7071 }
7072 break;
7073
7074 case ImplicitConversionSequence::BadConversion:
7075 Candidate.Viable = false;
7076 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7077 return;
7078
7079 default:
7080 llvm_unreachable(
7081 "Can only end up with a standard conversion sequence or failure");
7082 }
7083
7084 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7085 Candidate.Viable = false;
7086 Candidate.FailureKind = ovl_fail_enable_if;
7087 Candidate.DeductionFailure.Data = FailedAttr;
7088 return;
7089 }
7090
7091 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7092 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7093 Candidate.Viable = false;
7094 Candidate.FailureKind = ovl_non_default_multiversion_function;
7095 }
7096 }
7097
7098 /// Adds a conversion function template specialization
7099 /// candidate to the overload set, using template argument deduction
7100 /// to deduce the template arguments of the conversion function
7101 /// template from the type that we are converting to (C++
7102 /// [temp.deduct.conv]).
7103 void
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowResultConversion)7104 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7105 DeclAccessPair FoundDecl,
7106 CXXRecordDecl *ActingDC,
7107 Expr *From, QualType ToType,
7108 OverloadCandidateSet &CandidateSet,
7109 bool AllowObjCConversionOnExplicit,
7110 bool AllowResultConversion) {
7111 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7112 "Only conversion function templates permitted here");
7113
7114 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7115 return;
7116
7117 TemplateDeductionInfo Info(CandidateSet.getLocation());
7118 CXXConversionDecl *Specialization = nullptr;
7119 if (TemplateDeductionResult Result
7120 = DeduceTemplateArguments(FunctionTemplate, ToType,
7121 Specialization, Info)) {
7122 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7123 Candidate.FoundDecl = FoundDecl;
7124 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7125 Candidate.Viable = false;
7126 Candidate.FailureKind = ovl_fail_bad_deduction;
7127 Candidate.IsSurrogate = false;
7128 Candidate.IgnoreObjectArgument = false;
7129 Candidate.ExplicitCallArguments = 1;
7130 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7131 Info);
7132 return;
7133 }
7134
7135 // Add the conversion function template specialization produced by
7136 // template argument deduction as a candidate.
7137 assert(Specialization && "Missing function template specialization?");
7138 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7139 CandidateSet, AllowObjCConversionOnExplicit,
7140 AllowResultConversion);
7141 }
7142
7143 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7144 /// converts the given @c Object to a function pointer via the
7145 /// conversion function @c Conversion, and then attempts to call it
7146 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7147 /// the type of function that we'll eventually be calling.
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7148 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7149 DeclAccessPair FoundDecl,
7150 CXXRecordDecl *ActingContext,
7151 const FunctionProtoType *Proto,
7152 Expr *Object,
7153 ArrayRef<Expr *> Args,
7154 OverloadCandidateSet& CandidateSet) {
7155 if (!CandidateSet.isNewCandidate(Conversion))
7156 return;
7157
7158 // Overload resolution is always an unevaluated context.
7159 EnterExpressionEvaluationContext Unevaluated(
7160 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7161
7162 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7163 Candidate.FoundDecl = FoundDecl;
7164 Candidate.Function = nullptr;
7165 Candidate.Surrogate = Conversion;
7166 Candidate.Viable = true;
7167 Candidate.IsSurrogate = true;
7168 Candidate.IgnoreObjectArgument = false;
7169 Candidate.ExplicitCallArguments = Args.size();
7170
7171 // Determine the implicit conversion sequence for the implicit
7172 // object parameter.
7173 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7174 *this, CandidateSet.getLocation(), Object->getType(),
7175 Object->Classify(Context), Conversion, ActingContext);
7176 if (ObjectInit.isBad()) {
7177 Candidate.Viable = false;
7178 Candidate.FailureKind = ovl_fail_bad_conversion;
7179 Candidate.Conversions[0] = ObjectInit;
7180 return;
7181 }
7182
7183 // The first conversion is actually a user-defined conversion whose
7184 // first conversion is ObjectInit's standard conversion (which is
7185 // effectively a reference binding). Record it as such.
7186 Candidate.Conversions[0].setUserDefined();
7187 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7188 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7189 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7190 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7191 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7192 Candidate.Conversions[0].UserDefined.After
7193 = Candidate.Conversions[0].UserDefined.Before;
7194 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7195
7196 // Find the
7197 unsigned NumParams = Proto->getNumParams();
7198
7199 // (C++ 13.3.2p2): A candidate function having fewer than m
7200 // parameters is viable only if it has an ellipsis in its parameter
7201 // list (8.3.5).
7202 if (Args.size() > NumParams && !Proto->isVariadic()) {
7203 Candidate.Viable = false;
7204 Candidate.FailureKind = ovl_fail_too_many_arguments;
7205 return;
7206 }
7207
7208 // Function types don't have any default arguments, so just check if
7209 // we have enough arguments.
7210 if (Args.size() < NumParams) {
7211 // Not enough arguments.
7212 Candidate.Viable = false;
7213 Candidate.FailureKind = ovl_fail_too_few_arguments;
7214 return;
7215 }
7216
7217 // Determine the implicit conversion sequences for each of the
7218 // arguments.
7219 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7220 if (ArgIdx < NumParams) {
7221 // (C++ 13.3.2p3): for F to be a viable function, there shall
7222 // exist for each argument an implicit conversion sequence
7223 // (13.3.3.1) that converts that argument to the corresponding
7224 // parameter of F.
7225 QualType ParamType = Proto->getParamType(ArgIdx);
7226 Candidate.Conversions[ArgIdx + 1]
7227 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7228 /*SuppressUserConversions=*/false,
7229 /*InOverloadResolution=*/false,
7230 /*AllowObjCWritebackConversion=*/
7231 getLangOpts().ObjCAutoRefCount);
7232 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7233 Candidate.Viable = false;
7234 Candidate.FailureKind = ovl_fail_bad_conversion;
7235 return;
7236 }
7237 } else {
7238 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7239 // argument for which there is no corresponding parameter is
7240 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7241 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7242 }
7243 }
7244
7245 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7246 Candidate.Viable = false;
7247 Candidate.FailureKind = ovl_fail_enable_if;
7248 Candidate.DeductionFailure.Data = FailedAttr;
7249 return;
7250 }
7251 }
7252
7253 /// Add overload candidates for overloaded operators that are
7254 /// member functions.
7255 ///
7256 /// Add the overloaded operator candidates that are member functions
7257 /// for the operator Op that was used in an operator expression such
7258 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7259 /// CandidateSet will store the added overload candidates. (C++
7260 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,SourceRange OpRange)7261 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7262 SourceLocation OpLoc,
7263 ArrayRef<Expr *> Args,
7264 OverloadCandidateSet& CandidateSet,
7265 SourceRange OpRange) {
7266 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7267
7268 // C++ [over.match.oper]p3:
7269 // For a unary operator @ with an operand of a type whose
7270 // cv-unqualified version is T1, and for a binary operator @ with
7271 // a left operand of a type whose cv-unqualified version is T1 and
7272 // a right operand of a type whose cv-unqualified version is T2,
7273 // three sets of candidate functions, designated member
7274 // candidates, non-member candidates and built-in candidates, are
7275 // constructed as follows:
7276 QualType T1 = Args[0]->getType();
7277
7278 // -- If T1 is a complete class type or a class currently being
7279 // defined, the set of member candidates is the result of the
7280 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7281 // the set of member candidates is empty.
7282 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7283 // Complete the type if it can be completed.
7284 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7285 return;
7286 // If the type is neither complete nor being defined, bail out now.
7287 if (!T1Rec->getDecl()->getDefinition())
7288 return;
7289
7290 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7291 LookupQualifiedName(Operators, T1Rec->getDecl());
7292 Operators.suppressDiagnostics();
7293
7294 for (LookupResult::iterator Oper = Operators.begin(),
7295 OperEnd = Operators.end();
7296 Oper != OperEnd;
7297 ++Oper)
7298 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7299 Args[0]->Classify(Context), Args.slice(1),
7300 CandidateSet, /*SuppressUserConversions=*/false);
7301 }
7302 }
7303
7304 /// AddBuiltinCandidate - Add a candidate for a built-in
7305 /// operator. ResultTy and ParamTys are the result and parameter types
7306 /// of the built-in candidate, respectively. Args and NumArgs are the
7307 /// arguments being passed to the candidate. IsAssignmentOperator
7308 /// should be true when this built-in candidate is an assignment
7309 /// operator. NumContextualBoolArguments is the number of arguments
7310 /// (at the beginning of the argument list) that will be contextually
7311 /// converted to bool.
AddBuiltinCandidate(QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)7312 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7313 OverloadCandidateSet& CandidateSet,
7314 bool IsAssignmentOperator,
7315 unsigned NumContextualBoolArguments) {
7316 // Overload resolution is always an unevaluated context.
7317 EnterExpressionEvaluationContext Unevaluated(
7318 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7319
7320 // Add this candidate
7321 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7322 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7323 Candidate.Function = nullptr;
7324 Candidate.IsSurrogate = false;
7325 Candidate.IgnoreObjectArgument = false;
7326 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7327
7328 // Determine the implicit conversion sequences for each of the
7329 // arguments.
7330 Candidate.Viable = true;
7331 Candidate.ExplicitCallArguments = Args.size();
7332 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7333 // C++ [over.match.oper]p4:
7334 // For the built-in assignment operators, conversions of the
7335 // left operand are restricted as follows:
7336 // -- no temporaries are introduced to hold the left operand, and
7337 // -- no user-defined conversions are applied to the left
7338 // operand to achieve a type match with the left-most
7339 // parameter of a built-in candidate.
7340 //
7341 // We block these conversions by turning off user-defined
7342 // conversions, since that is the only way that initialization of
7343 // a reference to a non-class type can occur from something that
7344 // is not of the same type.
7345 if (ArgIdx < NumContextualBoolArguments) {
7346 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7347 "Contextual conversion to bool requires bool type");
7348 Candidate.Conversions[ArgIdx]
7349 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7350 } else {
7351 Candidate.Conversions[ArgIdx]
7352 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7353 ArgIdx == 0 && IsAssignmentOperator,
7354 /*InOverloadResolution=*/false,
7355 /*AllowObjCWritebackConversion=*/
7356 getLangOpts().ObjCAutoRefCount);
7357 }
7358 if (Candidate.Conversions[ArgIdx].isBad()) {
7359 Candidate.Viable = false;
7360 Candidate.FailureKind = ovl_fail_bad_conversion;
7361 break;
7362 }
7363 }
7364 }
7365
7366 namespace {
7367
7368 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7369 /// candidate operator functions for built-in operators (C++
7370 /// [over.built]). The types are separated into pointer types and
7371 /// enumeration types.
7372 class BuiltinCandidateTypeSet {
7373 /// TypeSet - A set of types.
7374 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7375 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7376
7377 /// PointerTypes - The set of pointer types that will be used in the
7378 /// built-in candidates.
7379 TypeSet PointerTypes;
7380
7381 /// MemberPointerTypes - The set of member pointer types that will be
7382 /// used in the built-in candidates.
7383 TypeSet MemberPointerTypes;
7384
7385 /// EnumerationTypes - The set of enumeration types that will be
7386 /// used in the built-in candidates.
7387 TypeSet EnumerationTypes;
7388
7389 /// The set of vector types that will be used in the built-in
7390 /// candidates.
7391 TypeSet VectorTypes;
7392
7393 /// A flag indicating non-record types are viable candidates
7394 bool HasNonRecordTypes;
7395
7396 /// A flag indicating whether either arithmetic or enumeration types
7397 /// were present in the candidate set.
7398 bool HasArithmeticOrEnumeralTypes;
7399
7400 /// A flag indicating whether the nullptr type was present in the
7401 /// candidate set.
7402 bool HasNullPtrType;
7403
7404 /// Sema - The semantic analysis instance where we are building the
7405 /// candidate type set.
7406 Sema &SemaRef;
7407
7408 /// Context - The AST context in which we will build the type sets.
7409 ASTContext &Context;
7410
7411 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7412 const Qualifiers &VisibleQuals);
7413 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7414
7415 public:
7416 /// iterator - Iterates through the types that are part of the set.
7417 typedef TypeSet::iterator iterator;
7418
BuiltinCandidateTypeSet(Sema & SemaRef)7419 BuiltinCandidateTypeSet(Sema &SemaRef)
7420 : HasNonRecordTypes(false),
7421 HasArithmeticOrEnumeralTypes(false),
7422 HasNullPtrType(false),
7423 SemaRef(SemaRef),
7424 Context(SemaRef.Context) { }
7425
7426 void AddTypesConvertedFrom(QualType Ty,
7427 SourceLocation Loc,
7428 bool AllowUserConversions,
7429 bool AllowExplicitConversions,
7430 const Qualifiers &VisibleTypeConversionsQuals);
7431
7432 /// pointer_begin - First pointer type found;
pointer_begin()7433 iterator pointer_begin() { return PointerTypes.begin(); }
7434
7435 /// pointer_end - Past the last pointer type found;
pointer_end()7436 iterator pointer_end() { return PointerTypes.end(); }
7437
7438 /// member_pointer_begin - First member pointer type found;
member_pointer_begin()7439 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7440
7441 /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()7442 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7443
7444 /// enumeration_begin - First enumeration type found;
enumeration_begin()7445 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7446
7447 /// enumeration_end - Past the last enumeration type found;
enumeration_end()7448 iterator enumeration_end() { return EnumerationTypes.end(); }
7449
vector_begin()7450 iterator vector_begin() { return VectorTypes.begin(); }
vector_end()7451 iterator vector_end() { return VectorTypes.end(); }
7452
hasNonRecordTypes()7453 bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()7454 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const7455 bool hasNullPtrType() const { return HasNullPtrType; }
7456 };
7457
7458 } // end anonymous namespace
7459
7460 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7461 /// the set of pointer types along with any more-qualified variants of
7462 /// that type. For example, if @p Ty is "int const *", this routine
7463 /// will add "int const *", "int const volatile *", "int const
7464 /// restrict *", and "int const volatile restrict *" to the set of
7465 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7466 /// false otherwise.
7467 ///
7468 /// FIXME: what to do about extended qualifiers?
7469 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)7470 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7471 const Qualifiers &VisibleQuals) {
7472
7473 // Insert this type.
7474 if (!PointerTypes.insert(Ty))
7475 return false;
7476
7477 QualType PointeeTy;
7478 const PointerType *PointerTy = Ty->getAs<PointerType>();
7479 bool buildObjCPtr = false;
7480 if (!PointerTy) {
7481 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7482 PointeeTy = PTy->getPointeeType();
7483 buildObjCPtr = true;
7484 } else {
7485 PointeeTy = PointerTy->getPointeeType();
7486 }
7487
7488 // Don't add qualified variants of arrays. For one, they're not allowed
7489 // (the qualifier would sink to the element type), and for another, the
7490 // only overload situation where it matters is subscript or pointer +- int,
7491 // and those shouldn't have qualifier variants anyway.
7492 if (PointeeTy->isArrayType())
7493 return true;
7494
7495 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7496 bool hasVolatile = VisibleQuals.hasVolatile();
7497 bool hasRestrict = VisibleQuals.hasRestrict();
7498
7499 // Iterate through all strict supersets of BaseCVR.
7500 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7501 if ((CVR | BaseCVR) != CVR) continue;
7502 // Skip over volatile if no volatile found anywhere in the types.
7503 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7504
7505 // Skip over restrict if no restrict found anywhere in the types, or if
7506 // the type cannot be restrict-qualified.
7507 if ((CVR & Qualifiers::Restrict) &&
7508 (!hasRestrict ||
7509 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7510 continue;
7511
7512 // Build qualified pointee type.
7513 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7514
7515 // Build qualified pointer type.
7516 QualType QPointerTy;
7517 if (!buildObjCPtr)
7518 QPointerTy = Context.getPointerType(QPointeeTy);
7519 else
7520 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7521
7522 // Insert qualified pointer type.
7523 PointerTypes.insert(QPointerTy);
7524 }
7525
7526 return true;
7527 }
7528
7529 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7530 /// to the set of pointer types along with any more-qualified variants of
7531 /// that type. For example, if @p Ty is "int const *", this routine
7532 /// will add "int const *", "int const volatile *", "int const
7533 /// restrict *", and "int const volatile restrict *" to the set of
7534 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7535 /// false otherwise.
7536 ///
7537 /// FIXME: what to do about extended qualifiers?
7538 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)7539 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7540 QualType Ty) {
7541 // Insert this type.
7542 if (!MemberPointerTypes.insert(Ty))
7543 return false;
7544
7545 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7546 assert(PointerTy && "type was not a member pointer type!");
7547
7548 QualType PointeeTy = PointerTy->getPointeeType();
7549 // Don't add qualified variants of arrays. For one, they're not allowed
7550 // (the qualifier would sink to the element type), and for another, the
7551 // only overload situation where it matters is subscript or pointer +- int,
7552 // and those shouldn't have qualifier variants anyway.
7553 if (PointeeTy->isArrayType())
7554 return true;
7555 const Type *ClassTy = PointerTy->getClass();
7556
7557 // Iterate through all strict supersets of the pointee type's CVR
7558 // qualifiers.
7559 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7560 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7561 if ((CVR | BaseCVR) != CVR) continue;
7562
7563 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7564 MemberPointerTypes.insert(
7565 Context.getMemberPointerType(QPointeeTy, ClassTy));
7566 }
7567
7568 return true;
7569 }
7570
7571 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7572 /// Ty can be implicit converted to the given set of @p Types. We're
7573 /// primarily interested in pointer types and enumeration types. We also
7574 /// take member pointer types, for the conditional operator.
7575 /// AllowUserConversions is true if we should look at the conversion
7576 /// functions of a class type, and AllowExplicitConversions if we
7577 /// should also include the explicit conversion functions of a class
7578 /// type.
7579 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)7580 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7581 SourceLocation Loc,
7582 bool AllowUserConversions,
7583 bool AllowExplicitConversions,
7584 const Qualifiers &VisibleQuals) {
7585 // Only deal with canonical types.
7586 Ty = Context.getCanonicalType(Ty);
7587
7588 // Look through reference types; they aren't part of the type of an
7589 // expression for the purposes of conversions.
7590 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7591 Ty = RefTy->getPointeeType();
7592
7593 // If we're dealing with an array type, decay to the pointer.
7594 if (Ty->isArrayType())
7595 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7596
7597 // Otherwise, we don't care about qualifiers on the type.
7598 Ty = Ty.getLocalUnqualifiedType();
7599
7600 // Flag if we ever add a non-record type.
7601 const RecordType *TyRec = Ty->getAs<RecordType>();
7602 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7603
7604 // Flag if we encounter an arithmetic type.
7605 HasArithmeticOrEnumeralTypes =
7606 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7607
7608 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7609 PointerTypes.insert(Ty);
7610 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7611 // Insert our type, and its more-qualified variants, into the set
7612 // of types.
7613 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7614 return;
7615 } else if (Ty->isMemberPointerType()) {
7616 // Member pointers are far easier, since the pointee can't be converted.
7617 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7618 return;
7619 } else if (Ty->isEnumeralType()) {
7620 HasArithmeticOrEnumeralTypes = true;
7621 EnumerationTypes.insert(Ty);
7622 } else if (Ty->isVectorType()) {
7623 // We treat vector types as arithmetic types in many contexts as an
7624 // extension.
7625 HasArithmeticOrEnumeralTypes = true;
7626 VectorTypes.insert(Ty);
7627 } else if (Ty->isNullPtrType()) {
7628 HasNullPtrType = true;
7629 } else if (AllowUserConversions && TyRec) {
7630 // No conversion functions in incomplete types.
7631 if (!SemaRef.isCompleteType(Loc, Ty))
7632 return;
7633
7634 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7635 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7636 if (isa<UsingShadowDecl>(D))
7637 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7638
7639 // Skip conversion function templates; they don't tell us anything
7640 // about which builtin types we can convert to.
7641 if (isa<FunctionTemplateDecl>(D))
7642 continue;
7643
7644 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7645 if (AllowExplicitConversions || !Conv->isExplicit()) {
7646 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7647 VisibleQuals);
7648 }
7649 }
7650 }
7651 }
7652
7653 /// Helper function for AddBuiltinOperatorCandidates() that adds
7654 /// the volatile- and non-volatile-qualified assignment operators for the
7655 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7656 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7657 QualType T,
7658 ArrayRef<Expr *> Args,
7659 OverloadCandidateSet &CandidateSet) {
7660 QualType ParamTypes[2];
7661
7662 // T& operator=(T&, T)
7663 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7664 ParamTypes[1] = T;
7665 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7666 /*IsAssignmentOperator=*/true);
7667
7668 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7669 // volatile T& operator=(volatile T&, T)
7670 ParamTypes[0]
7671 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7672 ParamTypes[1] = T;
7673 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7674 /*IsAssignmentOperator=*/true);
7675 }
7676 }
7677
7678 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7679 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)7680 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7681 Qualifiers VRQuals;
7682 const RecordType *TyRec;
7683 if (const MemberPointerType *RHSMPType =
7684 ArgExpr->getType()->getAs<MemberPointerType>())
7685 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7686 else
7687 TyRec = ArgExpr->getType()->getAs<RecordType>();
7688 if (!TyRec) {
7689 // Just to be safe, assume the worst case.
7690 VRQuals.addVolatile();
7691 VRQuals.addRestrict();
7692 return VRQuals;
7693 }
7694
7695 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7696 if (!ClassDecl->hasDefinition())
7697 return VRQuals;
7698
7699 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7700 if (isa<UsingShadowDecl>(D))
7701 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7702 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7703 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7704 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7705 CanTy = ResTypeRef->getPointeeType();
7706 // Need to go down the pointer/mempointer chain and add qualifiers
7707 // as see them.
7708 bool done = false;
7709 while (!done) {
7710 if (CanTy.isRestrictQualified())
7711 VRQuals.addRestrict();
7712 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7713 CanTy = ResTypePtr->getPointeeType();
7714 else if (const MemberPointerType *ResTypeMPtr =
7715 CanTy->getAs<MemberPointerType>())
7716 CanTy = ResTypeMPtr->getPointeeType();
7717 else
7718 done = true;
7719 if (CanTy.isVolatileQualified())
7720 VRQuals.addVolatile();
7721 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7722 return VRQuals;
7723 }
7724 }
7725 }
7726 return VRQuals;
7727 }
7728
7729 namespace {
7730
7731 /// Helper class to manage the addition of builtin operator overload
7732 /// candidates. It provides shared state and utility methods used throughout
7733 /// the process, as well as a helper method to add each group of builtin
7734 /// operator overloads from the standard to a candidate set.
7735 class BuiltinOperatorOverloadBuilder {
7736 // Common instance state available to all overload candidate addition methods.
7737 Sema &S;
7738 ArrayRef<Expr *> Args;
7739 Qualifiers VisibleTypeConversionsQuals;
7740 bool HasArithmeticOrEnumeralCandidateType;
7741 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7742 OverloadCandidateSet &CandidateSet;
7743
7744 static constexpr int ArithmeticTypesCap = 24;
7745 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7746
7747 // Define some indices used to iterate over the arithemetic types in
7748 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7749 // types are that preserved by promotion (C++ [over.built]p2).
7750 unsigned FirstIntegralType,
7751 LastIntegralType;
7752 unsigned FirstPromotedIntegralType,
7753 LastPromotedIntegralType;
7754 unsigned FirstPromotedArithmeticType,
7755 LastPromotedArithmeticType;
7756 unsigned NumArithmeticTypes;
7757
InitArithmeticTypes()7758 void InitArithmeticTypes() {
7759 // Start of promoted types.
7760 FirstPromotedArithmeticType = 0;
7761 ArithmeticTypes.push_back(S.Context.FloatTy);
7762 ArithmeticTypes.push_back(S.Context.DoubleTy);
7763 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7764 if (S.Context.getTargetInfo().hasFloat128Type())
7765 ArithmeticTypes.push_back(S.Context.Float128Ty);
7766
7767 // Start of integral types.
7768 FirstIntegralType = ArithmeticTypes.size();
7769 FirstPromotedIntegralType = ArithmeticTypes.size();
7770 ArithmeticTypes.push_back(S.Context.IntTy);
7771 ArithmeticTypes.push_back(S.Context.LongTy);
7772 ArithmeticTypes.push_back(S.Context.LongLongTy);
7773 if (S.Context.getTargetInfo().hasInt128Type())
7774 ArithmeticTypes.push_back(S.Context.Int128Ty);
7775 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7776 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7777 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7778 if (S.Context.getTargetInfo().hasInt128Type())
7779 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7780 LastPromotedIntegralType = ArithmeticTypes.size();
7781 LastPromotedArithmeticType = ArithmeticTypes.size();
7782 // End of promoted types.
7783
7784 ArithmeticTypes.push_back(S.Context.BoolTy);
7785 ArithmeticTypes.push_back(S.Context.CharTy);
7786 ArithmeticTypes.push_back(S.Context.WCharTy);
7787 if (S.Context.getLangOpts().Char8)
7788 ArithmeticTypes.push_back(S.Context.Char8Ty);
7789 ArithmeticTypes.push_back(S.Context.Char16Ty);
7790 ArithmeticTypes.push_back(S.Context.Char32Ty);
7791 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7792 ArithmeticTypes.push_back(S.Context.ShortTy);
7793 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7794 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7795 LastIntegralType = ArithmeticTypes.size();
7796 NumArithmeticTypes = ArithmeticTypes.size();
7797 // End of integral types.
7798 // FIXME: What about complex? What about half?
7799
7800 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7801 "Enough inline storage for all arithmetic types.");
7802 }
7803
7804 /// Helper method to factor out the common pattern of adding overloads
7805 /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)7806 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7807 bool HasVolatile,
7808 bool HasRestrict) {
7809 QualType ParamTypes[2] = {
7810 S.Context.getLValueReferenceType(CandidateTy),
7811 S.Context.IntTy
7812 };
7813
7814 // Non-volatile version.
7815 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7816
7817 // Use a heuristic to reduce number of builtin candidates in the set:
7818 // add volatile version only if there are conversions to a volatile type.
7819 if (HasVolatile) {
7820 ParamTypes[0] =
7821 S.Context.getLValueReferenceType(
7822 S.Context.getVolatileType(CandidateTy));
7823 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7824 }
7825
7826 // Add restrict version only if there are conversions to a restrict type
7827 // and our candidate type is a non-restrict-qualified pointer.
7828 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7829 !CandidateTy.isRestrictQualified()) {
7830 ParamTypes[0]
7831 = S.Context.getLValueReferenceType(
7832 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7833 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7834
7835 if (HasVolatile) {
7836 ParamTypes[0]
7837 = S.Context.getLValueReferenceType(
7838 S.Context.getCVRQualifiedType(CandidateTy,
7839 (Qualifiers::Volatile |
7840 Qualifiers::Restrict)));
7841 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7842 }
7843 }
7844
7845 }
7846
7847 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)7848 BuiltinOperatorOverloadBuilder(
7849 Sema &S, ArrayRef<Expr *> Args,
7850 Qualifiers VisibleTypeConversionsQuals,
7851 bool HasArithmeticOrEnumeralCandidateType,
7852 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7853 OverloadCandidateSet &CandidateSet)
7854 : S(S), Args(Args),
7855 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7856 HasArithmeticOrEnumeralCandidateType(
7857 HasArithmeticOrEnumeralCandidateType),
7858 CandidateTypes(CandidateTypes),
7859 CandidateSet(CandidateSet) {
7860
7861 InitArithmeticTypes();
7862 }
7863
7864 // Increment is deprecated for bool since C++17.
7865 //
7866 // C++ [over.built]p3:
7867 //
7868 // For every pair (T, VQ), where T is an arithmetic type other
7869 // than bool, and VQ is either volatile or empty, there exist
7870 // candidate operator functions of the form
7871 //
7872 // VQ T& operator++(VQ T&);
7873 // T operator++(VQ T&, int);
7874 //
7875 // C++ [over.built]p4:
7876 //
7877 // For every pair (T, VQ), where T is an arithmetic type other
7878 // than bool, and VQ is either volatile or empty, there exist
7879 // candidate operator functions of the form
7880 //
7881 // VQ T& operator--(VQ T&);
7882 // T operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)7883 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7884 if (!HasArithmeticOrEnumeralCandidateType)
7885 return;
7886
7887 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7888 const auto TypeOfT = ArithmeticTypes[Arith];
7889 if (TypeOfT == S.Context.BoolTy) {
7890 if (Op == OO_MinusMinus)
7891 continue;
7892 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7893 continue;
7894 }
7895 addPlusPlusMinusMinusStyleOverloads(
7896 TypeOfT,
7897 VisibleTypeConversionsQuals.hasVolatile(),
7898 VisibleTypeConversionsQuals.hasRestrict());
7899 }
7900 }
7901
7902 // C++ [over.built]p5:
7903 //
7904 // For every pair (T, VQ), where T is a cv-qualified or
7905 // cv-unqualified object type, and VQ is either volatile or
7906 // empty, there exist candidate operator functions of the form
7907 //
7908 // T*VQ& operator++(T*VQ&);
7909 // T*VQ& operator--(T*VQ&);
7910 // T* operator++(T*VQ&, int);
7911 // T* operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()7912 void addPlusPlusMinusMinusPointerOverloads() {
7913 for (BuiltinCandidateTypeSet::iterator
7914 Ptr = CandidateTypes[0].pointer_begin(),
7915 PtrEnd = CandidateTypes[0].pointer_end();
7916 Ptr != PtrEnd; ++Ptr) {
7917 // Skip pointer types that aren't pointers to object types.
7918 if (!(*Ptr)->getPointeeType()->isObjectType())
7919 continue;
7920
7921 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7922 (!(*Ptr).isVolatileQualified() &&
7923 VisibleTypeConversionsQuals.hasVolatile()),
7924 (!(*Ptr).isRestrictQualified() &&
7925 VisibleTypeConversionsQuals.hasRestrict()));
7926 }
7927 }
7928
7929 // C++ [over.built]p6:
7930 // For every cv-qualified or cv-unqualified object type T, there
7931 // exist candidate operator functions of the form
7932 //
7933 // T& operator*(T*);
7934 //
7935 // C++ [over.built]p7:
7936 // For every function type T that does not have cv-qualifiers or a
7937 // ref-qualifier, there exist candidate operator functions of the form
7938 // T& operator*(T*);
addUnaryStarPointerOverloads()7939 void addUnaryStarPointerOverloads() {
7940 for (BuiltinCandidateTypeSet::iterator
7941 Ptr = CandidateTypes[0].pointer_begin(),
7942 PtrEnd = CandidateTypes[0].pointer_end();
7943 Ptr != PtrEnd; ++Ptr) {
7944 QualType ParamTy = *Ptr;
7945 QualType PointeeTy = ParamTy->getPointeeType();
7946 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7947 continue;
7948
7949 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7950 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7951 continue;
7952
7953 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7954 }
7955 }
7956
7957 // C++ [over.built]p9:
7958 // For every promoted arithmetic type T, there exist candidate
7959 // operator functions of the form
7960 //
7961 // T operator+(T);
7962 // T operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()7963 void addUnaryPlusOrMinusArithmeticOverloads() {
7964 if (!HasArithmeticOrEnumeralCandidateType)
7965 return;
7966
7967 for (unsigned Arith = FirstPromotedArithmeticType;
7968 Arith < LastPromotedArithmeticType; ++Arith) {
7969 QualType ArithTy = ArithmeticTypes[Arith];
7970 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7971 }
7972
7973 // Extension: We also add these operators for vector types.
7974 for (BuiltinCandidateTypeSet::iterator
7975 Vec = CandidateTypes[0].vector_begin(),
7976 VecEnd = CandidateTypes[0].vector_end();
7977 Vec != VecEnd; ++Vec) {
7978 QualType VecTy = *Vec;
7979 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7980 }
7981 }
7982
7983 // C++ [over.built]p8:
7984 // For every type T, there exist candidate operator functions of
7985 // the form
7986 //
7987 // T* operator+(T*);
addUnaryPlusPointerOverloads()7988 void addUnaryPlusPointerOverloads() {
7989 for (BuiltinCandidateTypeSet::iterator
7990 Ptr = CandidateTypes[0].pointer_begin(),
7991 PtrEnd = CandidateTypes[0].pointer_end();
7992 Ptr != PtrEnd; ++Ptr) {
7993 QualType ParamTy = *Ptr;
7994 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7995 }
7996 }
7997
7998 // C++ [over.built]p10:
7999 // For every promoted integral type T, there exist candidate
8000 // operator functions of the form
8001 //
8002 // T operator~(T);
addUnaryTildePromotedIntegralOverloads()8003 void addUnaryTildePromotedIntegralOverloads() {
8004 if (!HasArithmeticOrEnumeralCandidateType)
8005 return;
8006
8007 for (unsigned Int = FirstPromotedIntegralType;
8008 Int < LastPromotedIntegralType; ++Int) {
8009 QualType IntTy = ArithmeticTypes[Int];
8010 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8011 }
8012
8013 // Extension: We also add this operator for vector types.
8014 for (BuiltinCandidateTypeSet::iterator
8015 Vec = CandidateTypes[0].vector_begin(),
8016 VecEnd = CandidateTypes[0].vector_end();
8017 Vec != VecEnd; ++Vec) {
8018 QualType VecTy = *Vec;
8019 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8020 }
8021 }
8022
8023 // C++ [over.match.oper]p16:
8024 // For every pointer to member type T or type std::nullptr_t, there
8025 // exist candidate operator functions of the form
8026 //
8027 // bool operator==(T,T);
8028 // bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads()8029 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8030 /// Set of (canonical) types that we've already handled.
8031 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8032
8033 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8034 for (BuiltinCandidateTypeSet::iterator
8035 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8036 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8037 MemPtr != MemPtrEnd;
8038 ++MemPtr) {
8039 // Don't add the same builtin candidate twice.
8040 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8041 continue;
8042
8043 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8044 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8045 }
8046
8047 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8048 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8049 if (AddedTypes.insert(NullPtrTy).second) {
8050 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8051 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8052 }
8053 }
8054 }
8055 }
8056
8057 // C++ [over.built]p15:
8058 //
8059 // For every T, where T is an enumeration type or a pointer type,
8060 // there exist candidate operator functions of the form
8061 //
8062 // bool operator<(T, T);
8063 // bool operator>(T, T);
8064 // bool operator<=(T, T);
8065 // bool operator>=(T, T);
8066 // bool operator==(T, T);
8067 // bool operator!=(T, T);
8068 // R operator<=>(T, T)
addGenericBinaryPointerOrEnumeralOverloads()8069 void addGenericBinaryPointerOrEnumeralOverloads() {
8070 // C++ [over.match.oper]p3:
8071 // [...]the built-in candidates include all of the candidate operator
8072 // functions defined in 13.6 that, compared to the given operator, [...]
8073 // do not have the same parameter-type-list as any non-template non-member
8074 // candidate.
8075 //
8076 // Note that in practice, this only affects enumeration types because there
8077 // aren't any built-in candidates of record type, and a user-defined operator
8078 // must have an operand of record or enumeration type. Also, the only other
8079 // overloaded operator with enumeration arguments, operator=,
8080 // cannot be overloaded for enumeration types, so this is the only place
8081 // where we must suppress candidates like this.
8082 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8083 UserDefinedBinaryOperators;
8084
8085 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8086 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8087 CandidateTypes[ArgIdx].enumeration_end()) {
8088 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8089 CEnd = CandidateSet.end();
8090 C != CEnd; ++C) {
8091 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8092 continue;
8093
8094 if (C->Function->isFunctionTemplateSpecialization())
8095 continue;
8096
8097 QualType FirstParamType =
8098 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8099 QualType SecondParamType =
8100 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8101
8102 // Skip if either parameter isn't of enumeral type.
8103 if (!FirstParamType->isEnumeralType() ||
8104 !SecondParamType->isEnumeralType())
8105 continue;
8106
8107 // Add this operator to the set of known user-defined operators.
8108 UserDefinedBinaryOperators.insert(
8109 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8110 S.Context.getCanonicalType(SecondParamType)));
8111 }
8112 }
8113 }
8114
8115 /// Set of (canonical) types that we've already handled.
8116 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8117
8118 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8119 for (BuiltinCandidateTypeSet::iterator
8120 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8121 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8122 Ptr != PtrEnd; ++Ptr) {
8123 // Don't add the same builtin candidate twice.
8124 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8125 continue;
8126
8127 QualType ParamTypes[2] = { *Ptr, *Ptr };
8128 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129 }
8130 for (BuiltinCandidateTypeSet::iterator
8131 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8132 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8133 Enum != EnumEnd; ++Enum) {
8134 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8135
8136 // Don't add the same builtin candidate twice, or if a user defined
8137 // candidate exists.
8138 if (!AddedTypes.insert(CanonType).second ||
8139 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8140 CanonType)))
8141 continue;
8142 QualType ParamTypes[2] = { *Enum, *Enum };
8143 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8144 }
8145 }
8146 }
8147
8148 // C++ [over.built]p13:
8149 //
8150 // For every cv-qualified or cv-unqualified object type T
8151 // there exist candidate operator functions of the form
8152 //
8153 // T* operator+(T*, ptrdiff_t);
8154 // T& operator[](T*, ptrdiff_t); [BELOW]
8155 // T* operator-(T*, ptrdiff_t);
8156 // T* operator+(ptrdiff_t, T*);
8157 // T& operator[](ptrdiff_t, T*); [BELOW]
8158 //
8159 // C++ [over.built]p14:
8160 //
8161 // For every T, where T is a pointer to object type, there
8162 // exist candidate operator functions of the form
8163 //
8164 // ptrdiff_t operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)8165 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8166 /// Set of (canonical) types that we've already handled.
8167 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8168
8169 for (int Arg = 0; Arg < 2; ++Arg) {
8170 QualType AsymmetricParamTypes[2] = {
8171 S.Context.getPointerDiffType(),
8172 S.Context.getPointerDiffType(),
8173 };
8174 for (BuiltinCandidateTypeSet::iterator
8175 Ptr = CandidateTypes[Arg].pointer_begin(),
8176 PtrEnd = CandidateTypes[Arg].pointer_end();
8177 Ptr != PtrEnd; ++Ptr) {
8178 QualType PointeeTy = (*Ptr)->getPointeeType();
8179 if (!PointeeTy->isObjectType())
8180 continue;
8181
8182 AsymmetricParamTypes[Arg] = *Ptr;
8183 if (Arg == 0 || Op == OO_Plus) {
8184 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8185 // T* operator+(ptrdiff_t, T*);
8186 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8187 }
8188 if (Op == OO_Minus) {
8189 // ptrdiff_t operator-(T, T);
8190 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8191 continue;
8192
8193 QualType ParamTypes[2] = { *Ptr, *Ptr };
8194 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8195 }
8196 }
8197 }
8198 }
8199
8200 // C++ [over.built]p12:
8201 //
8202 // For every pair of promoted arithmetic types L and R, there
8203 // exist candidate operator functions of the form
8204 //
8205 // LR operator*(L, R);
8206 // LR operator/(L, R);
8207 // LR operator+(L, R);
8208 // LR operator-(L, R);
8209 // bool operator<(L, R);
8210 // bool operator>(L, R);
8211 // bool operator<=(L, R);
8212 // bool operator>=(L, R);
8213 // bool operator==(L, R);
8214 // bool operator!=(L, R);
8215 //
8216 // where LR is the result of the usual arithmetic conversions
8217 // between types L and R.
8218 //
8219 // C++ [over.built]p24:
8220 //
8221 // For every pair of promoted arithmetic types L and R, there exist
8222 // candidate operator functions of the form
8223 //
8224 // LR operator?(bool, L, R);
8225 //
8226 // where LR is the result of the usual arithmetic conversions
8227 // between types L and R.
8228 // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads()8229 void addGenericBinaryArithmeticOverloads() {
8230 if (!HasArithmeticOrEnumeralCandidateType)
8231 return;
8232
8233 for (unsigned Left = FirstPromotedArithmeticType;
8234 Left < LastPromotedArithmeticType; ++Left) {
8235 for (unsigned Right = FirstPromotedArithmeticType;
8236 Right < LastPromotedArithmeticType; ++Right) {
8237 QualType LandR[2] = { ArithmeticTypes[Left],
8238 ArithmeticTypes[Right] };
8239 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8240 }
8241 }
8242
8243 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8244 // conditional operator for vector types.
8245 for (BuiltinCandidateTypeSet::iterator
8246 Vec1 = CandidateTypes[0].vector_begin(),
8247 Vec1End = CandidateTypes[0].vector_end();
8248 Vec1 != Vec1End; ++Vec1) {
8249 for (BuiltinCandidateTypeSet::iterator
8250 Vec2 = CandidateTypes[1].vector_begin(),
8251 Vec2End = CandidateTypes[1].vector_end();
8252 Vec2 != Vec2End; ++Vec2) {
8253 QualType LandR[2] = { *Vec1, *Vec2 };
8254 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8255 }
8256 }
8257 }
8258
8259 // C++2a [over.built]p14:
8260 //
8261 // For every integral type T there exists a candidate operator function
8262 // of the form
8263 //
8264 // std::strong_ordering operator<=>(T, T)
8265 //
8266 // C++2a [over.built]p15:
8267 //
8268 // For every pair of floating-point types L and R, there exists a candidate
8269 // operator function of the form
8270 //
8271 // std::partial_ordering operator<=>(L, R);
8272 //
8273 // FIXME: The current specification for integral types doesn't play nice with
8274 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8275 // comparisons. Under the current spec this can lead to ambiguity during
8276 // overload resolution. For example:
8277 //
8278 // enum A : int {a};
8279 // auto x = (a <=> (long)42);
8280 //
8281 // error: call is ambiguous for arguments 'A' and 'long'.
8282 // note: candidate operator<=>(int, int)
8283 // note: candidate operator<=>(long, long)
8284 //
8285 // To avoid this error, this function deviates from the specification and adds
8286 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8287 // arithmetic types (the same as the generic relational overloads).
8288 //
8289 // For now this function acts as a placeholder.
addThreeWayArithmeticOverloads()8290 void addThreeWayArithmeticOverloads() {
8291 addGenericBinaryArithmeticOverloads();
8292 }
8293
8294 // C++ [over.built]p17:
8295 //
8296 // For every pair of promoted integral types L and R, there
8297 // exist candidate operator functions of the form
8298 //
8299 // LR operator%(L, R);
8300 // LR operator&(L, R);
8301 // LR operator^(L, R);
8302 // LR operator|(L, R);
8303 // L operator<<(L, R);
8304 // L operator>>(L, R);
8305 //
8306 // where LR is the result of the usual arithmetic conversions
8307 // between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)8308 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8309 if (!HasArithmeticOrEnumeralCandidateType)
8310 return;
8311
8312 for (unsigned Left = FirstPromotedIntegralType;
8313 Left < LastPromotedIntegralType; ++Left) {
8314 for (unsigned Right = FirstPromotedIntegralType;
8315 Right < LastPromotedIntegralType; ++Right) {
8316 QualType LandR[2] = { ArithmeticTypes[Left],
8317 ArithmeticTypes[Right] };
8318 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8319 }
8320 }
8321 }
8322
8323 // C++ [over.built]p20:
8324 //
8325 // For every pair (T, VQ), where T is an enumeration or
8326 // pointer to member type and VQ is either volatile or
8327 // empty, there exist candidate operator functions of the form
8328 //
8329 // VQ T& operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()8330 void addAssignmentMemberPointerOrEnumeralOverloads() {
8331 /// Set of (canonical) types that we've already handled.
8332 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8333
8334 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8335 for (BuiltinCandidateTypeSet::iterator
8336 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8337 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8338 Enum != EnumEnd; ++Enum) {
8339 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8340 continue;
8341
8342 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8343 }
8344
8345 for (BuiltinCandidateTypeSet::iterator
8346 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8347 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8348 MemPtr != MemPtrEnd; ++MemPtr) {
8349 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8350 continue;
8351
8352 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8353 }
8354 }
8355 }
8356
8357 // C++ [over.built]p19:
8358 //
8359 // For every pair (T, VQ), where T is any type and VQ is either
8360 // volatile or empty, there exist candidate operator functions
8361 // of the form
8362 //
8363 // T*VQ& operator=(T*VQ&, T*);
8364 //
8365 // C++ [over.built]p21:
8366 //
8367 // For every pair (T, VQ), where T is a cv-qualified or
8368 // cv-unqualified object type and VQ is either volatile or
8369 // empty, there exist candidate operator functions of the form
8370 //
8371 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8372 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)8373 void addAssignmentPointerOverloads(bool isEqualOp) {
8374 /// Set of (canonical) types that we've already handled.
8375 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8376
8377 for (BuiltinCandidateTypeSet::iterator
8378 Ptr = CandidateTypes[0].pointer_begin(),
8379 PtrEnd = CandidateTypes[0].pointer_end();
8380 Ptr != PtrEnd; ++Ptr) {
8381 // If this is operator=, keep track of the builtin candidates we added.
8382 if (isEqualOp)
8383 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8384 else if (!(*Ptr)->getPointeeType()->isObjectType())
8385 continue;
8386
8387 // non-volatile version
8388 QualType ParamTypes[2] = {
8389 S.Context.getLValueReferenceType(*Ptr),
8390 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8391 };
8392 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8393 /*IsAssigmentOperator=*/ isEqualOp);
8394
8395 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8396 VisibleTypeConversionsQuals.hasVolatile();
8397 if (NeedVolatile) {
8398 // volatile version
8399 ParamTypes[0] =
8400 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402 /*IsAssigmentOperator=*/isEqualOp);
8403 }
8404
8405 if (!(*Ptr).isRestrictQualified() &&
8406 VisibleTypeConversionsQuals.hasRestrict()) {
8407 // restrict version
8408 ParamTypes[0]
8409 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8411 /*IsAssigmentOperator=*/isEqualOp);
8412
8413 if (NeedVolatile) {
8414 // volatile restrict version
8415 ParamTypes[0]
8416 = S.Context.getLValueReferenceType(
8417 S.Context.getCVRQualifiedType(*Ptr,
8418 (Qualifiers::Volatile |
8419 Qualifiers::Restrict)));
8420 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421 /*IsAssigmentOperator=*/isEqualOp);
8422 }
8423 }
8424 }
8425
8426 if (isEqualOp) {
8427 for (BuiltinCandidateTypeSet::iterator
8428 Ptr = CandidateTypes[1].pointer_begin(),
8429 PtrEnd = CandidateTypes[1].pointer_end();
8430 Ptr != PtrEnd; ++Ptr) {
8431 // Make sure we don't add the same candidate twice.
8432 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8433 continue;
8434
8435 QualType ParamTypes[2] = {
8436 S.Context.getLValueReferenceType(*Ptr),
8437 *Ptr,
8438 };
8439
8440 // non-volatile version
8441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8442 /*IsAssigmentOperator=*/true);
8443
8444 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8445 VisibleTypeConversionsQuals.hasVolatile();
8446 if (NeedVolatile) {
8447 // volatile version
8448 ParamTypes[0] =
8449 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8450 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8451 /*IsAssigmentOperator=*/true);
8452 }
8453
8454 if (!(*Ptr).isRestrictQualified() &&
8455 VisibleTypeConversionsQuals.hasRestrict()) {
8456 // restrict version
8457 ParamTypes[0]
8458 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8459 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8460 /*IsAssigmentOperator=*/true);
8461
8462 if (NeedVolatile) {
8463 // volatile restrict version
8464 ParamTypes[0]
8465 = S.Context.getLValueReferenceType(
8466 S.Context.getCVRQualifiedType(*Ptr,
8467 (Qualifiers::Volatile |
8468 Qualifiers::Restrict)));
8469 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8470 /*IsAssigmentOperator=*/true);
8471 }
8472 }
8473 }
8474 }
8475 }
8476
8477 // C++ [over.built]p18:
8478 //
8479 // For every triple (L, VQ, R), where L is an arithmetic type,
8480 // VQ is either volatile or empty, and R is a promoted
8481 // arithmetic type, there exist candidate operator functions of
8482 // the form
8483 //
8484 // VQ L& operator=(VQ L&, R);
8485 // VQ L& operator*=(VQ L&, R);
8486 // VQ L& operator/=(VQ L&, R);
8487 // VQ L& operator+=(VQ L&, R);
8488 // VQ L& operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)8489 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8490 if (!HasArithmeticOrEnumeralCandidateType)
8491 return;
8492
8493 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8494 for (unsigned Right = FirstPromotedArithmeticType;
8495 Right < LastPromotedArithmeticType; ++Right) {
8496 QualType ParamTypes[2];
8497 ParamTypes[1] = ArithmeticTypes[Right];
8498
8499 // Add this built-in operator as a candidate (VQ is empty).
8500 ParamTypes[0] =
8501 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8503 /*IsAssigmentOperator=*/isEqualOp);
8504
8505 // Add this built-in operator as a candidate (VQ is 'volatile').
8506 if (VisibleTypeConversionsQuals.hasVolatile()) {
8507 ParamTypes[0] =
8508 S.Context.getVolatileType(ArithmeticTypes[Left]);
8509 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8510 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8511 /*IsAssigmentOperator=*/isEqualOp);
8512 }
8513 }
8514 }
8515
8516 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8517 for (BuiltinCandidateTypeSet::iterator
8518 Vec1 = CandidateTypes[0].vector_begin(),
8519 Vec1End = CandidateTypes[0].vector_end();
8520 Vec1 != Vec1End; ++Vec1) {
8521 for (BuiltinCandidateTypeSet::iterator
8522 Vec2 = CandidateTypes[1].vector_begin(),
8523 Vec2End = CandidateTypes[1].vector_end();
8524 Vec2 != Vec2End; ++Vec2) {
8525 QualType ParamTypes[2];
8526 ParamTypes[1] = *Vec2;
8527 // Add this built-in operator as a candidate (VQ is empty).
8528 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8529 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8530 /*IsAssigmentOperator=*/isEqualOp);
8531
8532 // Add this built-in operator as a candidate (VQ is 'volatile').
8533 if (VisibleTypeConversionsQuals.hasVolatile()) {
8534 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8535 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8536 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8537 /*IsAssigmentOperator=*/isEqualOp);
8538 }
8539 }
8540 }
8541 }
8542
8543 // C++ [over.built]p22:
8544 //
8545 // For every triple (L, VQ, R), where L is an integral type, VQ
8546 // is either volatile or empty, and R is a promoted integral
8547 // type, there exist candidate operator functions of the form
8548 //
8549 // VQ L& operator%=(VQ L&, R);
8550 // VQ L& operator<<=(VQ L&, R);
8551 // VQ L& operator>>=(VQ L&, R);
8552 // VQ L& operator&=(VQ L&, R);
8553 // VQ L& operator^=(VQ L&, R);
8554 // VQ L& operator|=(VQ L&, R);
addAssignmentIntegralOverloads()8555 void addAssignmentIntegralOverloads() {
8556 if (!HasArithmeticOrEnumeralCandidateType)
8557 return;
8558
8559 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8560 for (unsigned Right = FirstPromotedIntegralType;
8561 Right < LastPromotedIntegralType; ++Right) {
8562 QualType ParamTypes[2];
8563 ParamTypes[1] = ArithmeticTypes[Right];
8564
8565 // Add this built-in operator as a candidate (VQ is empty).
8566 ParamTypes[0] =
8567 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8568 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8569 if (VisibleTypeConversionsQuals.hasVolatile()) {
8570 // Add this built-in operator as a candidate (VQ is 'volatile').
8571 ParamTypes[0] = ArithmeticTypes[Left];
8572 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8573 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8574 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8575 }
8576 }
8577 }
8578 }
8579
8580 // C++ [over.operator]p23:
8581 //
8582 // There also exist candidate operator functions of the form
8583 //
8584 // bool operator!(bool);
8585 // bool operator&&(bool, bool);
8586 // bool operator||(bool, bool);
addExclaimOverload()8587 void addExclaimOverload() {
8588 QualType ParamTy = S.Context.BoolTy;
8589 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8590 /*IsAssignmentOperator=*/false,
8591 /*NumContextualBoolArguments=*/1);
8592 }
addAmpAmpOrPipePipeOverload()8593 void addAmpAmpOrPipePipeOverload() {
8594 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8595 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8596 /*IsAssignmentOperator=*/false,
8597 /*NumContextualBoolArguments=*/2);
8598 }
8599
8600 // C++ [over.built]p13:
8601 //
8602 // For every cv-qualified or cv-unqualified object type T there
8603 // exist candidate operator functions of the form
8604 //
8605 // T* operator+(T*, ptrdiff_t); [ABOVE]
8606 // T& operator[](T*, ptrdiff_t);
8607 // T* operator-(T*, ptrdiff_t); [ABOVE]
8608 // T* operator+(ptrdiff_t, T*); [ABOVE]
8609 // T& operator[](ptrdiff_t, T*);
addSubscriptOverloads()8610 void addSubscriptOverloads() {
8611 for (BuiltinCandidateTypeSet::iterator
8612 Ptr = CandidateTypes[0].pointer_begin(),
8613 PtrEnd = CandidateTypes[0].pointer_end();
8614 Ptr != PtrEnd; ++Ptr) {
8615 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8616 QualType PointeeType = (*Ptr)->getPointeeType();
8617 if (!PointeeType->isObjectType())
8618 continue;
8619
8620 // T& operator[](T*, ptrdiff_t)
8621 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8622 }
8623
8624 for (BuiltinCandidateTypeSet::iterator
8625 Ptr = CandidateTypes[1].pointer_begin(),
8626 PtrEnd = CandidateTypes[1].pointer_end();
8627 Ptr != PtrEnd; ++Ptr) {
8628 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8629 QualType PointeeType = (*Ptr)->getPointeeType();
8630 if (!PointeeType->isObjectType())
8631 continue;
8632
8633 // T& operator[](ptrdiff_t, T*)
8634 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8635 }
8636 }
8637
8638 // C++ [over.built]p11:
8639 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8640 // C1 is the same type as C2 or is a derived class of C2, T is an object
8641 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8642 // there exist candidate operator functions of the form
8643 //
8644 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8645 //
8646 // where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()8647 void addArrowStarOverloads() {
8648 for (BuiltinCandidateTypeSet::iterator
8649 Ptr = CandidateTypes[0].pointer_begin(),
8650 PtrEnd = CandidateTypes[0].pointer_end();
8651 Ptr != PtrEnd; ++Ptr) {
8652 QualType C1Ty = (*Ptr);
8653 QualType C1;
8654 QualifierCollector Q1;
8655 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8656 if (!isa<RecordType>(C1))
8657 continue;
8658 // heuristic to reduce number of builtin candidates in the set.
8659 // Add volatile/restrict version only if there are conversions to a
8660 // volatile/restrict type.
8661 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8662 continue;
8663 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8664 continue;
8665 for (BuiltinCandidateTypeSet::iterator
8666 MemPtr = CandidateTypes[1].member_pointer_begin(),
8667 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8668 MemPtr != MemPtrEnd; ++MemPtr) {
8669 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8670 QualType C2 = QualType(mptr->getClass(), 0);
8671 C2 = C2.getUnqualifiedType();
8672 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8673 break;
8674 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8675 // build CV12 T&
8676 QualType T = mptr->getPointeeType();
8677 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8678 T.isVolatileQualified())
8679 continue;
8680 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8681 T.isRestrictQualified())
8682 continue;
8683 T = Q1.apply(S.Context, T);
8684 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8685 }
8686 }
8687 }
8688
8689 // Note that we don't consider the first argument, since it has been
8690 // contextually converted to bool long ago. The candidates below are
8691 // therefore added as binary.
8692 //
8693 // C++ [over.built]p25:
8694 // For every type T, where T is a pointer, pointer-to-member, or scoped
8695 // enumeration type, there exist candidate operator functions of the form
8696 //
8697 // T operator?(bool, T, T);
8698 //
addConditionalOperatorOverloads()8699 void addConditionalOperatorOverloads() {
8700 /// Set of (canonical) types that we've already handled.
8701 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8702
8703 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8704 for (BuiltinCandidateTypeSet::iterator
8705 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8706 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8707 Ptr != PtrEnd; ++Ptr) {
8708 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8709 continue;
8710
8711 QualType ParamTypes[2] = { *Ptr, *Ptr };
8712 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8713 }
8714
8715 for (BuiltinCandidateTypeSet::iterator
8716 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8717 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8718 MemPtr != MemPtrEnd; ++MemPtr) {
8719 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8720 continue;
8721
8722 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8723 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8724 }
8725
8726 if (S.getLangOpts().CPlusPlus11) {
8727 for (BuiltinCandidateTypeSet::iterator
8728 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8729 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8730 Enum != EnumEnd; ++Enum) {
8731 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8732 continue;
8733
8734 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8735 continue;
8736
8737 QualType ParamTypes[2] = { *Enum, *Enum };
8738 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8739 }
8740 }
8741 }
8742 }
8743 };
8744
8745 } // end anonymous namespace
8746
8747 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8748 /// operator overloads to the candidate set (C++ [over.built]), based
8749 /// on the operator @p Op and the arguments given. For example, if the
8750 /// operator is a binary '+', this routine might add "int
8751 /// operator+(int, int)" to cover integer addition.
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)8752 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8753 SourceLocation OpLoc,
8754 ArrayRef<Expr *> Args,
8755 OverloadCandidateSet &CandidateSet) {
8756 // Find all of the types that the arguments can convert to, but only
8757 // if the operator we're looking at has built-in operator candidates
8758 // that make use of these types. Also record whether we encounter non-record
8759 // candidate types or either arithmetic or enumeral candidate types.
8760 Qualifiers VisibleTypeConversionsQuals;
8761 VisibleTypeConversionsQuals.addConst();
8762 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8763 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8764
8765 bool HasNonRecordCandidateType = false;
8766 bool HasArithmeticOrEnumeralCandidateType = false;
8767 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8768 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8769 CandidateTypes.emplace_back(*this);
8770 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8771 OpLoc,
8772 true,
8773 (Op == OO_Exclaim ||
8774 Op == OO_AmpAmp ||
8775 Op == OO_PipePipe),
8776 VisibleTypeConversionsQuals);
8777 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8778 CandidateTypes[ArgIdx].hasNonRecordTypes();
8779 HasArithmeticOrEnumeralCandidateType =
8780 HasArithmeticOrEnumeralCandidateType ||
8781 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8782 }
8783
8784 // Exit early when no non-record types have been added to the candidate set
8785 // for any of the arguments to the operator.
8786 //
8787 // We can't exit early for !, ||, or &&, since there we have always have
8788 // 'bool' overloads.
8789 if (!HasNonRecordCandidateType &&
8790 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8791 return;
8792
8793 // Setup an object to manage the common state for building overloads.
8794 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8795 VisibleTypeConversionsQuals,
8796 HasArithmeticOrEnumeralCandidateType,
8797 CandidateTypes, CandidateSet);
8798
8799 // Dispatch over the operation to add in only those overloads which apply.
8800 switch (Op) {
8801 case OO_None:
8802 case NUM_OVERLOADED_OPERATORS:
8803 llvm_unreachable("Expected an overloaded operator");
8804
8805 case OO_New:
8806 case OO_Delete:
8807 case OO_Array_New:
8808 case OO_Array_Delete:
8809 case OO_Call:
8810 llvm_unreachable(
8811 "Special operators don't use AddBuiltinOperatorCandidates");
8812
8813 case OO_Comma:
8814 case OO_Arrow:
8815 case OO_Coawait:
8816 // C++ [over.match.oper]p3:
8817 // -- For the operator ',', the unary operator '&', the
8818 // operator '->', or the operator 'co_await', the
8819 // built-in candidates set is empty.
8820 break;
8821
8822 case OO_Plus: // '+' is either unary or binary
8823 if (Args.size() == 1)
8824 OpBuilder.addUnaryPlusPointerOverloads();
8825 LLVM_FALLTHROUGH;
8826
8827 case OO_Minus: // '-' is either unary or binary
8828 if (Args.size() == 1) {
8829 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8830 } else {
8831 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8832 OpBuilder.addGenericBinaryArithmeticOverloads();
8833 }
8834 break;
8835
8836 case OO_Star: // '*' is either unary or binary
8837 if (Args.size() == 1)
8838 OpBuilder.addUnaryStarPointerOverloads();
8839 else
8840 OpBuilder.addGenericBinaryArithmeticOverloads();
8841 break;
8842
8843 case OO_Slash:
8844 OpBuilder.addGenericBinaryArithmeticOverloads();
8845 break;
8846
8847 case OO_PlusPlus:
8848 case OO_MinusMinus:
8849 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8850 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8851 break;
8852
8853 case OO_EqualEqual:
8854 case OO_ExclaimEqual:
8855 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8856 LLVM_FALLTHROUGH;
8857
8858 case OO_Less:
8859 case OO_Greater:
8860 case OO_LessEqual:
8861 case OO_GreaterEqual:
8862 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8863 OpBuilder.addGenericBinaryArithmeticOverloads();
8864 break;
8865
8866 case OO_Spaceship:
8867 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8868 OpBuilder.addThreeWayArithmeticOverloads();
8869 break;
8870
8871 case OO_Percent:
8872 case OO_Caret:
8873 case OO_Pipe:
8874 case OO_LessLess:
8875 case OO_GreaterGreater:
8876 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8877 break;
8878
8879 case OO_Amp: // '&' is either unary or binary
8880 if (Args.size() == 1)
8881 // C++ [over.match.oper]p3:
8882 // -- For the operator ',', the unary operator '&', or the
8883 // operator '->', the built-in candidates set is empty.
8884 break;
8885
8886 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8887 break;
8888
8889 case OO_Tilde:
8890 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8891 break;
8892
8893 case OO_Equal:
8894 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8895 LLVM_FALLTHROUGH;
8896
8897 case OO_PlusEqual:
8898 case OO_MinusEqual:
8899 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8900 LLVM_FALLTHROUGH;
8901
8902 case OO_StarEqual:
8903 case OO_SlashEqual:
8904 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8905 break;
8906
8907 case OO_PercentEqual:
8908 case OO_LessLessEqual:
8909 case OO_GreaterGreaterEqual:
8910 case OO_AmpEqual:
8911 case OO_CaretEqual:
8912 case OO_PipeEqual:
8913 OpBuilder.addAssignmentIntegralOverloads();
8914 break;
8915
8916 case OO_Exclaim:
8917 OpBuilder.addExclaimOverload();
8918 break;
8919
8920 case OO_AmpAmp:
8921 case OO_PipePipe:
8922 OpBuilder.addAmpAmpOrPipePipeOverload();
8923 break;
8924
8925 case OO_Subscript:
8926 OpBuilder.addSubscriptOverloads();
8927 break;
8928
8929 case OO_ArrowStar:
8930 OpBuilder.addArrowStarOverloads();
8931 break;
8932
8933 case OO_Conditional:
8934 OpBuilder.addConditionalOperatorOverloads();
8935 OpBuilder.addGenericBinaryArithmeticOverloads();
8936 break;
8937 }
8938 }
8939
8940 /// Add function candidates found via argument-dependent lookup
8941 /// to the set of overloading candidates.
8942 ///
8943 /// This routine performs argument-dependent name lookup based on the
8944 /// given function name (which may also be an operator name) and adds
8945 /// all of the overload candidates found by ADL to the overload
8946 /// candidate set (C++ [basic.lookup.argdep]).
8947 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)8948 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8949 SourceLocation Loc,
8950 ArrayRef<Expr *> Args,
8951 TemplateArgumentListInfo *ExplicitTemplateArgs,
8952 OverloadCandidateSet& CandidateSet,
8953 bool PartialOverloading) {
8954 ADLResult Fns;
8955
8956 // FIXME: This approach for uniquing ADL results (and removing
8957 // redundant candidates from the set) relies on pointer-equality,
8958 // which means we need to key off the canonical decl. However,
8959 // always going back to the canonical decl might not get us the
8960 // right set of default arguments. What default arguments are
8961 // we supposed to consider on ADL candidates, anyway?
8962
8963 // FIXME: Pass in the explicit template arguments?
8964 ArgumentDependentLookup(Name, Loc, Args, Fns);
8965
8966 // Erase all of the candidates we already knew about.
8967 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8968 CandEnd = CandidateSet.end();
8969 Cand != CandEnd; ++Cand)
8970 if (Cand->Function) {
8971 Fns.erase(Cand->Function);
8972 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8973 Fns.erase(FunTmpl);
8974 }
8975
8976 // For each of the ADL candidates we found, add it to the overload
8977 // set.
8978 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8979 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8980
8981 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8982 if (ExplicitTemplateArgs)
8983 continue;
8984
8985 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8986 /*SupressUserConversions=*/false, PartialOverloading,
8987 /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8988 } else {
8989 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8990 ExplicitTemplateArgs, Args, CandidateSet,
8991 /*SupressUserConversions=*/false,
8992 PartialOverloading, ADLCallKind::UsesADL);
8993 }
8994 }
8995 }
8996
8997 namespace {
8998 enum class Comparison { Equal, Better, Worse };
8999 }
9000
9001 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9002 /// overload resolution.
9003 ///
9004 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9005 /// Cand1's first N enable_if attributes have precisely the same conditions as
9006 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9007 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9008 ///
9009 /// Note that you can have a pair of candidates such that Cand1's enable_if
9010 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9011 /// worse than Cand1's.
compareEnableIfAttrs(const Sema & S,const FunctionDecl * Cand1,const FunctionDecl * Cand2)9012 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9013 const FunctionDecl *Cand2) {
9014 // Common case: One (or both) decls don't have enable_if attrs.
9015 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9016 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9017 if (!Cand1Attr || !Cand2Attr) {
9018 if (Cand1Attr == Cand2Attr)
9019 return Comparison::Equal;
9020 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9021 }
9022
9023 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9024 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9025
9026 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9027 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9028 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9029 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9030
9031 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9032 // has fewer enable_if attributes than Cand2, and vice versa.
9033 if (!Cand1A)
9034 return Comparison::Worse;
9035 if (!Cand2A)
9036 return Comparison::Better;
9037
9038 Cand1ID.clear();
9039 Cand2ID.clear();
9040
9041 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9042 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9043 if (Cand1ID != Cand2ID)
9044 return Comparison::Worse;
9045 }
9046
9047 return Comparison::Equal;
9048 }
9049
isBetterMultiversionCandidate(const OverloadCandidate & Cand1,const OverloadCandidate & Cand2)9050 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9051 const OverloadCandidate &Cand2) {
9052 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9053 !Cand2.Function->isMultiVersion())
9054 return false;
9055
9056 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9057 // is obviously better.
9058 if (Cand1.Function->isInvalidDecl()) return false;
9059 if (Cand2.Function->isInvalidDecl()) return true;
9060
9061 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9062 // cpu_dispatch, else arbitrarily based on the identifiers.
9063 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9064 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9065 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9066 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9067
9068 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9069 return false;
9070
9071 if (Cand1CPUDisp && !Cand2CPUDisp)
9072 return true;
9073 if (Cand2CPUDisp && !Cand1CPUDisp)
9074 return false;
9075
9076 if (Cand1CPUSpec && Cand2CPUSpec) {
9077 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9078 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9079
9080 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9081 FirstDiff = std::mismatch(
9082 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9083 Cand2CPUSpec->cpus_begin(),
9084 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9085 return LHS->getName() == RHS->getName();
9086 });
9087
9088 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9089 "Two different cpu-specific versions should not have the same "
9090 "identifier list, otherwise they'd be the same decl!");
9091 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9092 }
9093 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9094 }
9095
9096 /// isBetterOverloadCandidate - Determines whether the first overload
9097 /// candidate is a better candidate than the second (C++ 13.3.3p1).
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,OverloadCandidateSet::CandidateSetKind Kind)9098 bool clang::isBetterOverloadCandidate(
9099 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9100 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9101 // Define viable functions to be better candidates than non-viable
9102 // functions.
9103 if (!Cand2.Viable)
9104 return Cand1.Viable;
9105 else if (!Cand1.Viable)
9106 return false;
9107
9108 // C++ [over.match.best]p1:
9109 //
9110 // -- if F is a static member function, ICS1(F) is defined such
9111 // that ICS1(F) is neither better nor worse than ICS1(G) for
9112 // any function G, and, symmetrically, ICS1(G) is neither
9113 // better nor worse than ICS1(F).
9114 unsigned StartArg = 0;
9115 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9116 StartArg = 1;
9117
9118 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9119 // We don't allow incompatible pointer conversions in C++.
9120 if (!S.getLangOpts().CPlusPlus)
9121 return ICS.isStandard() &&
9122 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9123
9124 // The only ill-formed conversion we allow in C++ is the string literal to
9125 // char* conversion, which is only considered ill-formed after C++11.
9126 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9127 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9128 };
9129
9130 // Define functions that don't require ill-formed conversions for a given
9131 // argument to be better candidates than functions that do.
9132 unsigned NumArgs = Cand1.Conversions.size();
9133 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9134 bool HasBetterConversion = false;
9135 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9136 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9137 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9138 if (Cand1Bad != Cand2Bad) {
9139 if (Cand1Bad)
9140 return false;
9141 HasBetterConversion = true;
9142 }
9143 }
9144
9145 if (HasBetterConversion)
9146 return true;
9147
9148 // C++ [over.match.best]p1:
9149 // A viable function F1 is defined to be a better function than another
9150 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9151 // conversion sequence than ICSi(F2), and then...
9152 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9153 switch (CompareImplicitConversionSequences(S, Loc,
9154 Cand1.Conversions[ArgIdx],
9155 Cand2.Conversions[ArgIdx])) {
9156 case ImplicitConversionSequence::Better:
9157 // Cand1 has a better conversion sequence.
9158 HasBetterConversion = true;
9159 break;
9160
9161 case ImplicitConversionSequence::Worse:
9162 // Cand1 can't be better than Cand2.
9163 return false;
9164
9165 case ImplicitConversionSequence::Indistinguishable:
9166 // Do nothing.
9167 break;
9168 }
9169 }
9170
9171 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9172 // ICSj(F2), or, if not that,
9173 if (HasBetterConversion)
9174 return true;
9175
9176 // -- the context is an initialization by user-defined conversion
9177 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9178 // from the return type of F1 to the destination type (i.e.,
9179 // the type of the entity being initialized) is a better
9180 // conversion sequence than the standard conversion sequence
9181 // from the return type of F2 to the destination type.
9182 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9183 Cand1.Function && Cand2.Function &&
9184 isa<CXXConversionDecl>(Cand1.Function) &&
9185 isa<CXXConversionDecl>(Cand2.Function)) {
9186 // First check whether we prefer one of the conversion functions over the
9187 // other. This only distinguishes the results in non-standard, extension
9188 // cases such as the conversion from a lambda closure type to a function
9189 // pointer or block.
9190 ImplicitConversionSequence::CompareKind Result =
9191 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9192 if (Result == ImplicitConversionSequence::Indistinguishable)
9193 Result = CompareStandardConversionSequences(S, Loc,
9194 Cand1.FinalConversion,
9195 Cand2.FinalConversion);
9196
9197 if (Result != ImplicitConversionSequence::Indistinguishable)
9198 return Result == ImplicitConversionSequence::Better;
9199
9200 // FIXME: Compare kind of reference binding if conversion functions
9201 // convert to a reference type used in direct reference binding, per
9202 // C++14 [over.match.best]p1 section 2 bullet 3.
9203 }
9204
9205 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9206 // as combined with the resolution to CWG issue 243.
9207 //
9208 // When the context is initialization by constructor ([over.match.ctor] or
9209 // either phase of [over.match.list]), a constructor is preferred over
9210 // a conversion function.
9211 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9212 Cand1.Function && Cand2.Function &&
9213 isa<CXXConstructorDecl>(Cand1.Function) !=
9214 isa<CXXConstructorDecl>(Cand2.Function))
9215 return isa<CXXConstructorDecl>(Cand1.Function);
9216
9217 // -- F1 is a non-template function and F2 is a function template
9218 // specialization, or, if not that,
9219 bool Cand1IsSpecialization = Cand1.Function &&
9220 Cand1.Function->getPrimaryTemplate();
9221 bool Cand2IsSpecialization = Cand2.Function &&
9222 Cand2.Function->getPrimaryTemplate();
9223 if (Cand1IsSpecialization != Cand2IsSpecialization)
9224 return Cand2IsSpecialization;
9225
9226 // -- F1 and F2 are function template specializations, and the function
9227 // template for F1 is more specialized than the template for F2
9228 // according to the partial ordering rules described in 14.5.5.2, or,
9229 // if not that,
9230 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9231 if (FunctionTemplateDecl *BetterTemplate
9232 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9233 Cand2.Function->getPrimaryTemplate(),
9234 Loc,
9235 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9236 : TPOC_Call,
9237 Cand1.ExplicitCallArguments,
9238 Cand2.ExplicitCallArguments))
9239 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9240 }
9241
9242 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9243 // A derived-class constructor beats an (inherited) base class constructor.
9244 bool Cand1IsInherited =
9245 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9246 bool Cand2IsInherited =
9247 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9248 if (Cand1IsInherited != Cand2IsInherited)
9249 return Cand2IsInherited;
9250 else if (Cand1IsInherited) {
9251 assert(Cand2IsInherited);
9252 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9253 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9254 if (Cand1Class->isDerivedFrom(Cand2Class))
9255 return true;
9256 if (Cand2Class->isDerivedFrom(Cand1Class))
9257 return false;
9258 // Inherited from sibling base classes: still ambiguous.
9259 }
9260
9261 // Check C++17 tie-breakers for deduction guides.
9262 {
9263 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9264 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9265 if (Guide1 && Guide2) {
9266 // -- F1 is generated from a deduction-guide and F2 is not
9267 if (Guide1->isImplicit() != Guide2->isImplicit())
9268 return Guide2->isImplicit();
9269
9270 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9271 if (Guide1->isCopyDeductionCandidate())
9272 return true;
9273 }
9274 }
9275
9276 // Check for enable_if value-based overload resolution.
9277 if (Cand1.Function && Cand2.Function) {
9278 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9279 if (Cmp != Comparison::Equal)
9280 return Cmp == Comparison::Better;
9281 }
9282
9283 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9284 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9285 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9286 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9287 }
9288
9289 bool HasPS1 = Cand1.Function != nullptr &&
9290 functionHasPassObjectSizeParams(Cand1.Function);
9291 bool HasPS2 = Cand2.Function != nullptr &&
9292 functionHasPassObjectSizeParams(Cand2.Function);
9293 if (HasPS1 != HasPS2 && HasPS1)
9294 return true;
9295
9296 return isBetterMultiversionCandidate(Cand1, Cand2);
9297 }
9298
9299 /// Determine whether two declarations are "equivalent" for the purposes of
9300 /// name lookup and overload resolution. This applies when the same internal/no
9301 /// linkage entity is defined by two modules (probably by textually including
9302 /// the same header). In such a case, we don't consider the declarations to
9303 /// declare the same entity, but we also don't want lookups with both
9304 /// declarations visible to be ambiguous in some cases (this happens when using
9305 /// a modularized libstdc++).
isEquivalentInternalLinkageDeclaration(const NamedDecl * A,const NamedDecl * B)9306 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9307 const NamedDecl *B) {
9308 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9309 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9310 if (!VA || !VB)
9311 return false;
9312
9313 // The declarations must be declaring the same name as an internal linkage
9314 // entity in different modules.
9315 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9316 VB->getDeclContext()->getRedeclContext()) ||
9317 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9318 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9319 VA->isExternallyVisible() || VB->isExternallyVisible())
9320 return false;
9321
9322 // Check that the declarations appear to be equivalent.
9323 //
9324 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9325 // For constants and functions, we should check the initializer or body is
9326 // the same. For non-constant variables, we shouldn't allow it at all.
9327 if (Context.hasSameType(VA->getType(), VB->getType()))
9328 return true;
9329
9330 // Enum constants within unnamed enumerations will have different types, but
9331 // may still be similar enough to be interchangeable for our purposes.
9332 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9333 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9334 // Only handle anonymous enums. If the enumerations were named and
9335 // equivalent, they would have been merged to the same type.
9336 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9337 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9338 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9339 !Context.hasSameType(EnumA->getIntegerType(),
9340 EnumB->getIntegerType()))
9341 return false;
9342 // Allow this only if the value is the same for both enumerators.
9343 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9344 }
9345 }
9346
9347 // Nothing else is sufficiently similar.
9348 return false;
9349 }
9350
diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc,const NamedDecl * D,ArrayRef<const NamedDecl * > Equiv)9351 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9352 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9353 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9354
9355 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9356 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9357 << !M << (M ? M->getFullModuleName() : "");
9358
9359 for (auto *E : Equiv) {
9360 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9361 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9362 << !M << (M ? M->getFullModuleName() : "");
9363 }
9364 }
9365
9366 /// Computes the best viable function (C++ 13.3.3)
9367 /// within an overload candidate set.
9368 ///
9369 /// \param Loc The location of the function name (or operator symbol) for
9370 /// which overload resolution occurs.
9371 ///
9372 /// \param Best If overload resolution was successful or found a deleted
9373 /// function, \p Best points to the candidate function found.
9374 ///
9375 /// \returns The result of overload resolution.
9376 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best)9377 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9378 iterator &Best) {
9379 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9380 std::transform(begin(), end(), std::back_inserter(Candidates),
9381 [](OverloadCandidate &Cand) { return &Cand; });
9382
9383 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9384 // are accepted by both clang and NVCC. However, during a particular
9385 // compilation mode only one call variant is viable. We need to
9386 // exclude non-viable overload candidates from consideration based
9387 // only on their host/device attributes. Specifically, if one
9388 // candidate call is WrongSide and the other is SameSide, we ignore
9389 // the WrongSide candidate.
9390 if (S.getLangOpts().CUDA) {
9391 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9392 bool ContainsSameSideCandidate =
9393 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9394 return Cand->Function &&
9395 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9396 Sema::CFP_SameSide;
9397 });
9398 if (ContainsSameSideCandidate) {
9399 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9400 return Cand->Function &&
9401 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9402 Sema::CFP_WrongSide;
9403 };
9404 llvm::erase_if(Candidates, IsWrongSideCandidate);
9405 }
9406 }
9407
9408 // Find the best viable function.
9409 Best = end();
9410 for (auto *Cand : Candidates)
9411 if (Cand->Viable)
9412 if (Best == end() ||
9413 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9414 Best = Cand;
9415
9416 // If we didn't find any viable functions, abort.
9417 if (Best == end())
9418 return OR_No_Viable_Function;
9419
9420 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9421
9422 // Make sure that this function is better than every other viable
9423 // function. If not, we have an ambiguity.
9424 for (auto *Cand : Candidates) {
9425 if (Cand->Viable && Cand != Best &&
9426 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9427 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9428 Cand->Function)) {
9429 EquivalentCands.push_back(Cand->Function);
9430 continue;
9431 }
9432
9433 Best = end();
9434 return OR_Ambiguous;
9435 }
9436 }
9437
9438 // Best is the best viable function.
9439 if (Best->Function &&
9440 (Best->Function->isDeleted() ||
9441 S.isFunctionConsideredUnavailable(Best->Function)))
9442 return OR_Deleted;
9443
9444 if (!EquivalentCands.empty())
9445 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9446 EquivalentCands);
9447
9448 return OR_Success;
9449 }
9450
9451 namespace {
9452
9453 enum OverloadCandidateKind {
9454 oc_function,
9455 oc_method,
9456 oc_constructor,
9457 oc_implicit_default_constructor,
9458 oc_implicit_copy_constructor,
9459 oc_implicit_move_constructor,
9460 oc_implicit_copy_assignment,
9461 oc_implicit_move_assignment,
9462 oc_inherited_constructor
9463 };
9464
9465 enum OverloadCandidateSelect {
9466 ocs_non_template,
9467 ocs_template,
9468 ocs_described_template,
9469 };
9470
9471 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
ClassifyOverloadCandidate(Sema & S,NamedDecl * Found,FunctionDecl * Fn,std::string & Description)9472 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9473 std::string &Description) {
9474
9475 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9476 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9477 isTemplate = true;
9478 Description = S.getTemplateArgumentBindingsText(
9479 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9480 }
9481
9482 OverloadCandidateSelect Select = [&]() {
9483 if (!Description.empty())
9484 return ocs_described_template;
9485 return isTemplate ? ocs_template : ocs_non_template;
9486 }();
9487
9488 OverloadCandidateKind Kind = [&]() {
9489 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9490 if (!Ctor->isImplicit()) {
9491 if (isa<ConstructorUsingShadowDecl>(Found))
9492 return oc_inherited_constructor;
9493 else
9494 return oc_constructor;
9495 }
9496
9497 if (Ctor->isDefaultConstructor())
9498 return oc_implicit_default_constructor;
9499
9500 if (Ctor->isMoveConstructor())
9501 return oc_implicit_move_constructor;
9502
9503 assert(Ctor->isCopyConstructor() &&
9504 "unexpected sort of implicit constructor");
9505 return oc_implicit_copy_constructor;
9506 }
9507
9508 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9509 // This actually gets spelled 'candidate function' for now, but
9510 // it doesn't hurt to split it out.
9511 if (!Meth->isImplicit())
9512 return oc_method;
9513
9514 if (Meth->isMoveAssignmentOperator())
9515 return oc_implicit_move_assignment;
9516
9517 if (Meth->isCopyAssignmentOperator())
9518 return oc_implicit_copy_assignment;
9519
9520 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9521 return oc_method;
9522 }
9523
9524 return oc_function;
9525 }();
9526
9527 return std::make_pair(Kind, Select);
9528 }
9529
MaybeEmitInheritedConstructorNote(Sema & S,Decl * FoundDecl)9530 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9531 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9532 // set.
9533 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9534 S.Diag(FoundDecl->getLocation(),
9535 diag::note_ovl_candidate_inherited_constructor)
9536 << Shadow->getNominatedBaseClass();
9537 }
9538
9539 } // end anonymous namespace
9540
isFunctionAlwaysEnabled(const ASTContext & Ctx,const FunctionDecl * FD)9541 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9542 const FunctionDecl *FD) {
9543 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9544 bool AlwaysTrue;
9545 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9546 return false;
9547 if (!AlwaysTrue)
9548 return false;
9549 }
9550 return true;
9551 }
9552
9553 /// Returns true if we can take the address of the function.
9554 ///
9555 /// \param Complain - If true, we'll emit a diagnostic
9556 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9557 /// we in overload resolution?
9558 /// \param Loc - The location of the statement we're complaining about. Ignored
9559 /// if we're not complaining, or if we're in overload resolution.
checkAddressOfFunctionIsAvailable(Sema & S,const FunctionDecl * FD,bool Complain,bool InOverloadResolution,SourceLocation Loc)9560 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9561 bool Complain,
9562 bool InOverloadResolution,
9563 SourceLocation Loc) {
9564 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9565 if (Complain) {
9566 if (InOverloadResolution)
9567 S.Diag(FD->getBeginLoc(),
9568 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9569 else
9570 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9571 }
9572 return false;
9573 }
9574
9575 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9576 return P->hasAttr<PassObjectSizeAttr>();
9577 });
9578 if (I == FD->param_end())
9579 return true;
9580
9581 if (Complain) {
9582 // Add one to ParamNo because it's user-facing
9583 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9584 if (InOverloadResolution)
9585 S.Diag(FD->getLocation(),
9586 diag::note_ovl_candidate_has_pass_object_size_params)
9587 << ParamNo;
9588 else
9589 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9590 << FD << ParamNo;
9591 }
9592 return false;
9593 }
9594
checkAddressOfCandidateIsAvailable(Sema & S,const FunctionDecl * FD)9595 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9596 const FunctionDecl *FD) {
9597 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9598 /*InOverloadResolution=*/true,
9599 /*Loc=*/SourceLocation());
9600 }
9601
checkAddressOfFunctionIsAvailable(const FunctionDecl * Function,bool Complain,SourceLocation Loc)9602 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9603 bool Complain,
9604 SourceLocation Loc) {
9605 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9606 /*InOverloadResolution=*/false,
9607 Loc);
9608 }
9609
9610 // Notes the location of an overload candidate.
NoteOverloadCandidate(NamedDecl * Found,FunctionDecl * Fn,QualType DestType,bool TakingAddress)9611 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9612 QualType DestType, bool TakingAddress) {
9613 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9614 return;
9615 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9616 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9617 return;
9618
9619 std::string FnDesc;
9620 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9621 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9622 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9623 << (unsigned)KSPair.first << (unsigned)KSPair.second
9624 << Fn << FnDesc;
9625
9626 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9627 Diag(Fn->getLocation(), PD);
9628 MaybeEmitInheritedConstructorNote(*this, Found);
9629 }
9630
9631 // Notes the location of all overload candidates designated through
9632 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType,bool TakingAddress)9633 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9634 bool TakingAddress) {
9635 assert(OverloadedExpr->getType() == Context.OverloadTy);
9636
9637 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9638 OverloadExpr *OvlExpr = Ovl.Expression;
9639
9640 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9641 IEnd = OvlExpr->decls_end();
9642 I != IEnd; ++I) {
9643 if (FunctionTemplateDecl *FunTmpl =
9644 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9645 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9646 TakingAddress);
9647 } else if (FunctionDecl *Fun
9648 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9649 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9650 }
9651 }
9652 }
9653
9654 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9655 /// "lead" diagnostic; it will be given two arguments, the source and
9656 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const9657 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9658 Sema &S,
9659 SourceLocation CaretLoc,
9660 const PartialDiagnostic &PDiag) const {
9661 S.Diag(CaretLoc, PDiag)
9662 << Ambiguous.getFromType() << Ambiguous.getToType();
9663 // FIXME: The note limiting machinery is borrowed from
9664 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9665 // refactoring here.
9666 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9667 unsigned CandsShown = 0;
9668 AmbiguousConversionSequence::const_iterator I, E;
9669 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9670 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9671 break;
9672 ++CandsShown;
9673 S.NoteOverloadCandidate(I->first, I->second);
9674 }
9675 if (I != E)
9676 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9677 }
9678
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I,bool TakingCandidateAddress)9679 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9680 unsigned I, bool TakingCandidateAddress) {
9681 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9682 assert(Conv.isBad());
9683 assert(Cand->Function && "for now, candidate must be a function");
9684 FunctionDecl *Fn = Cand->Function;
9685
9686 // There's a conversion slot for the object argument if this is a
9687 // non-constructor method. Note that 'I' corresponds the
9688 // conversion-slot index.
9689 bool isObjectArgument = false;
9690 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9691 if (I == 0)
9692 isObjectArgument = true;
9693 else
9694 I--;
9695 }
9696
9697 std::string FnDesc;
9698 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9699 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9700
9701 Expr *FromExpr = Conv.Bad.FromExpr;
9702 QualType FromTy = Conv.Bad.getFromType();
9703 QualType ToTy = Conv.Bad.getToType();
9704
9705 if (FromTy == S.Context.OverloadTy) {
9706 assert(FromExpr && "overload set argument came from implicit argument?");
9707 Expr *E = FromExpr->IgnoreParens();
9708 if (isa<UnaryOperator>(E))
9709 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9710 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9711
9712 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9713 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9714 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9715 << Name << I + 1;
9716 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9717 return;
9718 }
9719
9720 // Do some hand-waving analysis to see if the non-viability is due
9721 // to a qualifier mismatch.
9722 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9723 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9724 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9725 CToTy = RT->getPointeeType();
9726 else {
9727 // TODO: detect and diagnose the full richness of const mismatches.
9728 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9729 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9730 CFromTy = FromPT->getPointeeType();
9731 CToTy = ToPT->getPointeeType();
9732 }
9733 }
9734
9735 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9736 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9737 Qualifiers FromQs = CFromTy.getQualifiers();
9738 Qualifiers ToQs = CToTy.getQualifiers();
9739
9740 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9741 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9742 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9743 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9744 << ToTy << (unsigned)isObjectArgument << I + 1;
9745 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9746 return;
9747 }
9748
9749 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9750 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9751 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9752 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9753 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9754 << (unsigned)isObjectArgument << I + 1;
9755 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9756 return;
9757 }
9758
9759 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9761 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9762 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9763 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9764 << (unsigned)isObjectArgument << I + 1;
9765 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9766 return;
9767 }
9768
9769 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9770 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9771 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9772 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9773 << FromQs.hasUnaligned() << I + 1;
9774 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9775 return;
9776 }
9777
9778 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9779 assert(CVR && "unexpected qualifiers mismatch");
9780
9781 if (isObjectArgument) {
9782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9783 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9785 << (CVR - 1);
9786 } else {
9787 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9788 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9789 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9790 << (CVR - 1) << I + 1;
9791 }
9792 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9793 return;
9794 }
9795
9796 // Special diagnostic for failure to convert an initializer list, since
9797 // telling the user that it has type void is not useful.
9798 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9800 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9802 << ToTy << (unsigned)isObjectArgument << I + 1;
9803 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9804 return;
9805 }
9806
9807 // Diagnose references or pointers to incomplete types differently,
9808 // since it's far from impossible that the incompleteness triggered
9809 // the failure.
9810 QualType TempFromTy = FromTy.getNonReferenceType();
9811 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9812 TempFromTy = PTy->getPointeeType();
9813 if (TempFromTy->isIncompleteType()) {
9814 // Emit the generic diagnostic and, optionally, add the hints to it.
9815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9816 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9818 << ToTy << (unsigned)isObjectArgument << I + 1
9819 << (unsigned)(Cand->Fix.Kind);
9820
9821 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9822 return;
9823 }
9824
9825 // Diagnose base -> derived pointer conversions.
9826 unsigned BaseToDerivedConversion = 0;
9827 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9828 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9829 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9830 FromPtrTy->getPointeeType()) &&
9831 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9832 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9833 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9834 FromPtrTy->getPointeeType()))
9835 BaseToDerivedConversion = 1;
9836 }
9837 } else if (const ObjCObjectPointerType *FromPtrTy
9838 = FromTy->getAs<ObjCObjectPointerType>()) {
9839 if (const ObjCObjectPointerType *ToPtrTy
9840 = ToTy->getAs<ObjCObjectPointerType>())
9841 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9842 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9843 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9844 FromPtrTy->getPointeeType()) &&
9845 FromIface->isSuperClassOf(ToIface))
9846 BaseToDerivedConversion = 2;
9847 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9848 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9849 !FromTy->isIncompleteType() &&
9850 !ToRefTy->getPointeeType()->isIncompleteType() &&
9851 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9852 BaseToDerivedConversion = 3;
9853 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9854 ToTy.getNonReferenceType().getCanonicalType() ==
9855 FromTy.getNonReferenceType().getCanonicalType()) {
9856 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9857 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9858 << (unsigned)isObjectArgument << I + 1
9859 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9860 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9861 return;
9862 }
9863 }
9864
9865 if (BaseToDerivedConversion) {
9866 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9867 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9868 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9869 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9870 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9871 return;
9872 }
9873
9874 if (isa<ObjCObjectPointerType>(CFromTy) &&
9875 isa<PointerType>(CToTy)) {
9876 Qualifiers FromQs = CFromTy.getQualifiers();
9877 Qualifiers ToQs = CToTy.getQualifiers();
9878 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9880 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9881 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9882 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9883 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9884 return;
9885 }
9886 }
9887
9888 if (TakingCandidateAddress &&
9889 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9890 return;
9891
9892 // Emit the generic diagnostic and, optionally, add the hints to it.
9893 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9894 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9895 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9896 << ToTy << (unsigned)isObjectArgument << I + 1
9897 << (unsigned)(Cand->Fix.Kind);
9898
9899 // If we can fix the conversion, suggest the FixIts.
9900 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9901 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9902 FDiag << *HI;
9903 S.Diag(Fn->getLocation(), FDiag);
9904
9905 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9906 }
9907
9908 /// Additional arity mismatch diagnosis specific to a function overload
9909 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9910 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)9911 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9912 unsigned NumArgs) {
9913 FunctionDecl *Fn = Cand->Function;
9914 unsigned MinParams = Fn->getMinRequiredArguments();
9915
9916 // With invalid overloaded operators, it's possible that we think we
9917 // have an arity mismatch when in fact it looks like we have the
9918 // right number of arguments, because only overloaded operators have
9919 // the weird behavior of overloading member and non-member functions.
9920 // Just don't report anything.
9921 if (Fn->isInvalidDecl() &&
9922 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9923 return true;
9924
9925 if (NumArgs < MinParams) {
9926 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9927 (Cand->FailureKind == ovl_fail_bad_deduction &&
9928 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9929 } else {
9930 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9931 (Cand->FailureKind == ovl_fail_bad_deduction &&
9932 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9933 }
9934
9935 return false;
9936 }
9937
9938 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,NamedDecl * Found,Decl * D,unsigned NumFormalArgs)9939 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9940 unsigned NumFormalArgs) {
9941 assert(isa<FunctionDecl>(D) &&
9942 "The templated declaration should at least be a function"
9943 " when diagnosing bad template argument deduction due to too many"
9944 " or too few arguments");
9945
9946 FunctionDecl *Fn = cast<FunctionDecl>(D);
9947
9948 // TODO: treat calls to a missing default constructor as a special case
9949 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9950 unsigned MinParams = Fn->getMinRequiredArguments();
9951
9952 // at least / at most / exactly
9953 unsigned mode, modeCount;
9954 if (NumFormalArgs < MinParams) {
9955 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9956 FnTy->isTemplateVariadic())
9957 mode = 0; // "at least"
9958 else
9959 mode = 2; // "exactly"
9960 modeCount = MinParams;
9961 } else {
9962 if (MinParams != FnTy->getNumParams())
9963 mode = 1; // "at most"
9964 else
9965 mode = 2; // "exactly"
9966 modeCount = FnTy->getNumParams();
9967 }
9968
9969 std::string Description;
9970 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9971 ClassifyOverloadCandidate(S, Found, Fn, Description);
9972
9973 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9974 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9975 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9976 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9977 else
9978 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9979 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9980 << Description << mode << modeCount << NumFormalArgs;
9981
9982 MaybeEmitInheritedConstructorNote(S, Found);
9983 }
9984
9985 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)9986 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9987 unsigned NumFormalArgs) {
9988 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9989 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9990 }
9991
getDescribedTemplate(Decl * Templated)9992 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9993 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9994 return TD;
9995 llvm_unreachable("Unsupported: Getting the described template declaration"
9996 " for bad deduction diagnosis");
9997 }
9998
9999 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,NamedDecl * Found,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs,bool TakingCandidateAddress)10000 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10001 DeductionFailureInfo &DeductionFailure,
10002 unsigned NumArgs,
10003 bool TakingCandidateAddress) {
10004 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10005 NamedDecl *ParamD;
10006 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10007 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10008 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10009 switch (DeductionFailure.Result) {
10010 case Sema::TDK_Success:
10011 llvm_unreachable("TDK_success while diagnosing bad deduction");
10012
10013 case Sema::TDK_Incomplete: {
10014 assert(ParamD && "no parameter found for incomplete deduction result");
10015 S.Diag(Templated->getLocation(),
10016 diag::note_ovl_candidate_incomplete_deduction)
10017 << ParamD->getDeclName();
10018 MaybeEmitInheritedConstructorNote(S, Found);
10019 return;
10020 }
10021
10022 case Sema::TDK_IncompletePack: {
10023 assert(ParamD && "no parameter found for incomplete deduction result");
10024 S.Diag(Templated->getLocation(),
10025 diag::note_ovl_candidate_incomplete_deduction_pack)
10026 << ParamD->getDeclName()
10027 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10028 << *DeductionFailure.getFirstArg();
10029 MaybeEmitInheritedConstructorNote(S, Found);
10030 return;
10031 }
10032
10033 case Sema::TDK_Underqualified: {
10034 assert(ParamD && "no parameter found for bad qualifiers deduction result");
10035 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10036
10037 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10038
10039 // Param will have been canonicalized, but it should just be a
10040 // qualified version of ParamD, so move the qualifiers to that.
10041 QualifierCollector Qs;
10042 Qs.strip(Param);
10043 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10044 assert(S.Context.hasSameType(Param, NonCanonParam));
10045
10046 // Arg has also been canonicalized, but there's nothing we can do
10047 // about that. It also doesn't matter as much, because it won't
10048 // have any template parameters in it (because deduction isn't
10049 // done on dependent types).
10050 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10051
10052 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10053 << ParamD->getDeclName() << Arg << NonCanonParam;
10054 MaybeEmitInheritedConstructorNote(S, Found);
10055 return;
10056 }
10057
10058 case Sema::TDK_Inconsistent: {
10059 assert(ParamD && "no parameter found for inconsistent deduction result");
10060 int which = 0;
10061 if (isa<TemplateTypeParmDecl>(ParamD))
10062 which = 0;
10063 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10064 // Deduction might have failed because we deduced arguments of two
10065 // different types for a non-type template parameter.
10066 // FIXME: Use a different TDK value for this.
10067 QualType T1 =
10068 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10069 QualType T2 =
10070 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10071 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10072 S.Diag(Templated->getLocation(),
10073 diag::note_ovl_candidate_inconsistent_deduction_types)
10074 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10075 << *DeductionFailure.getSecondArg() << T2;
10076 MaybeEmitInheritedConstructorNote(S, Found);
10077 return;
10078 }
10079
10080 which = 1;
10081 } else {
10082 which = 2;
10083 }
10084
10085 S.Diag(Templated->getLocation(),
10086 diag::note_ovl_candidate_inconsistent_deduction)
10087 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10088 << *DeductionFailure.getSecondArg();
10089 MaybeEmitInheritedConstructorNote(S, Found);
10090 return;
10091 }
10092
10093 case Sema::TDK_InvalidExplicitArguments:
10094 assert(ParamD && "no parameter found for invalid explicit arguments");
10095 if (ParamD->getDeclName())
10096 S.Diag(Templated->getLocation(),
10097 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10098 << ParamD->getDeclName();
10099 else {
10100 int index = 0;
10101 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10102 index = TTP->getIndex();
10103 else if (NonTypeTemplateParmDecl *NTTP
10104 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10105 index = NTTP->getIndex();
10106 else
10107 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10108 S.Diag(Templated->getLocation(),
10109 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10110 << (index + 1);
10111 }
10112 MaybeEmitInheritedConstructorNote(S, Found);
10113 return;
10114
10115 case Sema::TDK_TooManyArguments:
10116 case Sema::TDK_TooFewArguments:
10117 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10118 return;
10119
10120 case Sema::TDK_InstantiationDepth:
10121 S.Diag(Templated->getLocation(),
10122 diag::note_ovl_candidate_instantiation_depth);
10123 MaybeEmitInheritedConstructorNote(S, Found);
10124 return;
10125
10126 case Sema::TDK_SubstitutionFailure: {
10127 // Format the template argument list into the argument string.
10128 SmallString<128> TemplateArgString;
10129 if (TemplateArgumentList *Args =
10130 DeductionFailure.getTemplateArgumentList()) {
10131 TemplateArgString = " ";
10132 TemplateArgString += S.getTemplateArgumentBindingsText(
10133 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10134 }
10135
10136 // If this candidate was disabled by enable_if, say so.
10137 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10138 if (PDiag && PDiag->second.getDiagID() ==
10139 diag::err_typename_nested_not_found_enable_if) {
10140 // FIXME: Use the source range of the condition, and the fully-qualified
10141 // name of the enable_if template. These are both present in PDiag.
10142 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10143 << "'enable_if'" << TemplateArgString;
10144 return;
10145 }
10146
10147 // We found a specific requirement that disabled the enable_if.
10148 if (PDiag && PDiag->second.getDiagID() ==
10149 diag::err_typename_nested_not_found_requirement) {
10150 S.Diag(Templated->getLocation(),
10151 diag::note_ovl_candidate_disabled_by_requirement)
10152 << PDiag->second.getStringArg(0) << TemplateArgString;
10153 return;
10154 }
10155
10156 // Format the SFINAE diagnostic into the argument string.
10157 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10158 // formatted message in another diagnostic.
10159 SmallString<128> SFINAEArgString;
10160 SourceRange R;
10161 if (PDiag) {
10162 SFINAEArgString = ": ";
10163 R = SourceRange(PDiag->first, PDiag->first);
10164 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10165 }
10166
10167 S.Diag(Templated->getLocation(),
10168 diag::note_ovl_candidate_substitution_failure)
10169 << TemplateArgString << SFINAEArgString << R;
10170 MaybeEmitInheritedConstructorNote(S, Found);
10171 return;
10172 }
10173
10174 case Sema::TDK_DeducedMismatch:
10175 case Sema::TDK_DeducedMismatchNested: {
10176 // Format the template argument list into the argument string.
10177 SmallString<128> TemplateArgString;
10178 if (TemplateArgumentList *Args =
10179 DeductionFailure.getTemplateArgumentList()) {
10180 TemplateArgString = " ";
10181 TemplateArgString += S.getTemplateArgumentBindingsText(
10182 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10183 }
10184
10185 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10186 << (*DeductionFailure.getCallArgIndex() + 1)
10187 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10188 << TemplateArgString
10189 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10190 break;
10191 }
10192
10193 case Sema::TDK_NonDeducedMismatch: {
10194 // FIXME: Provide a source location to indicate what we couldn't match.
10195 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10196 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10197 if (FirstTA.getKind() == TemplateArgument::Template &&
10198 SecondTA.getKind() == TemplateArgument::Template) {
10199 TemplateName FirstTN = FirstTA.getAsTemplate();
10200 TemplateName SecondTN = SecondTA.getAsTemplate();
10201 if (FirstTN.getKind() == TemplateName::Template &&
10202 SecondTN.getKind() == TemplateName::Template) {
10203 if (FirstTN.getAsTemplateDecl()->getName() ==
10204 SecondTN.getAsTemplateDecl()->getName()) {
10205 // FIXME: This fixes a bad diagnostic where both templates are named
10206 // the same. This particular case is a bit difficult since:
10207 // 1) It is passed as a string to the diagnostic printer.
10208 // 2) The diagnostic printer only attempts to find a better
10209 // name for types, not decls.
10210 // Ideally, this should folded into the diagnostic printer.
10211 S.Diag(Templated->getLocation(),
10212 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10213 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10214 return;
10215 }
10216 }
10217 }
10218
10219 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10220 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10221 return;
10222
10223 // FIXME: For generic lambda parameters, check if the function is a lambda
10224 // call operator, and if so, emit a prettier and more informative
10225 // diagnostic that mentions 'auto' and lambda in addition to
10226 // (or instead of?) the canonical template type parameters.
10227 S.Diag(Templated->getLocation(),
10228 diag::note_ovl_candidate_non_deduced_mismatch)
10229 << FirstTA << SecondTA;
10230 return;
10231 }
10232 // TODO: diagnose these individually, then kill off
10233 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10234 case Sema::TDK_MiscellaneousDeductionFailure:
10235 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10236 MaybeEmitInheritedConstructorNote(S, Found);
10237 return;
10238 case Sema::TDK_CUDATargetMismatch:
10239 S.Diag(Templated->getLocation(),
10240 diag::note_cuda_ovl_candidate_target_mismatch);
10241 return;
10242 }
10243 }
10244
10245 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)10246 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10247 unsigned NumArgs,
10248 bool TakingCandidateAddress) {
10249 unsigned TDK = Cand->DeductionFailure.Result;
10250 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10251 if (CheckArityMismatch(S, Cand, NumArgs))
10252 return;
10253 }
10254 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10255 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10256 }
10257
10258 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)10259 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10260 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10261 FunctionDecl *Callee = Cand->Function;
10262
10263 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10264 CalleeTarget = S.IdentifyCUDATarget(Callee);
10265
10266 std::string FnDesc;
10267 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10268 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10269
10270 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10271 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10272 << FnDesc /* Ignored */
10273 << CalleeTarget << CallerTarget;
10274
10275 // This could be an implicit constructor for which we could not infer the
10276 // target due to a collsion. Diagnose that case.
10277 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10278 if (Meth != nullptr && Meth->isImplicit()) {
10279 CXXRecordDecl *ParentClass = Meth->getParent();
10280 Sema::CXXSpecialMember CSM;
10281
10282 switch (FnKindPair.first) {
10283 default:
10284 return;
10285 case oc_implicit_default_constructor:
10286 CSM = Sema::CXXDefaultConstructor;
10287 break;
10288 case oc_implicit_copy_constructor:
10289 CSM = Sema::CXXCopyConstructor;
10290 break;
10291 case oc_implicit_move_constructor:
10292 CSM = Sema::CXXMoveConstructor;
10293 break;
10294 case oc_implicit_copy_assignment:
10295 CSM = Sema::CXXCopyAssignment;
10296 break;
10297 case oc_implicit_move_assignment:
10298 CSM = Sema::CXXMoveAssignment;
10299 break;
10300 };
10301
10302 bool ConstRHS = false;
10303 if (Meth->getNumParams()) {
10304 if (const ReferenceType *RT =
10305 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10306 ConstRHS = RT->getPointeeType().isConstQualified();
10307 }
10308 }
10309
10310 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10311 /* ConstRHS */ ConstRHS,
10312 /* Diagnose */ true);
10313 }
10314 }
10315
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)10316 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10317 FunctionDecl *Callee = Cand->Function;
10318 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10319
10320 S.Diag(Callee->getLocation(),
10321 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10322 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10323 }
10324
DiagnoseOpenCLExtensionDisabled(Sema & S,OverloadCandidate * Cand)10325 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10326 FunctionDecl *Callee = Cand->Function;
10327
10328 S.Diag(Callee->getLocation(),
10329 diag::note_ovl_candidate_disabled_by_extension)
10330 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10331 }
10332
10333 /// Generates a 'note' diagnostic for an overload candidate. We've
10334 /// already generated a primary error at the call site.
10335 ///
10336 /// It really does need to be a single diagnostic with its caret
10337 /// pointed at the candidate declaration. Yes, this creates some
10338 /// major challenges of technical writing. Yes, this makes pointing
10339 /// out problems with specific arguments quite awkward. It's still
10340 /// better than generating twenty screens of text for every failed
10341 /// overload.
10342 ///
10343 /// It would be great to be able to express per-candidate problems
10344 /// more richly for those diagnostic clients that cared, but we'd
10345 /// still have to be just as careful with the default diagnostics.
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)10346 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10347 unsigned NumArgs,
10348 bool TakingCandidateAddress) {
10349 FunctionDecl *Fn = Cand->Function;
10350
10351 // Note deleted candidates, but only if they're viable.
10352 if (Cand->Viable) {
10353 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10354 std::string FnDesc;
10355 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10356 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10357
10358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10359 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10360 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10361 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10362 return;
10363 }
10364
10365 // We don't really have anything else to say about viable candidates.
10366 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10367 return;
10368 }
10369
10370 switch (Cand->FailureKind) {
10371 case ovl_fail_too_many_arguments:
10372 case ovl_fail_too_few_arguments:
10373 return DiagnoseArityMismatch(S, Cand, NumArgs);
10374
10375 case ovl_fail_bad_deduction:
10376 return DiagnoseBadDeduction(S, Cand, NumArgs,
10377 TakingCandidateAddress);
10378
10379 case ovl_fail_illegal_constructor: {
10380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10381 << (Fn->getPrimaryTemplate() ? 1 : 0);
10382 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10383 return;
10384 }
10385
10386 case ovl_fail_trivial_conversion:
10387 case ovl_fail_bad_final_conversion:
10388 case ovl_fail_final_conversion_not_exact:
10389 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10390
10391 case ovl_fail_bad_conversion: {
10392 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10393 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10394 if (Cand->Conversions[I].isBad())
10395 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10396
10397 // FIXME: this currently happens when we're called from SemaInit
10398 // when user-conversion overload fails. Figure out how to handle
10399 // those conditions and diagnose them well.
10400 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10401 }
10402
10403 case ovl_fail_bad_target:
10404 return DiagnoseBadTarget(S, Cand);
10405
10406 case ovl_fail_enable_if:
10407 return DiagnoseFailedEnableIfAttr(S, Cand);
10408
10409 case ovl_fail_ext_disabled:
10410 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10411
10412 case ovl_fail_inhctor_slice:
10413 // It's generally not interesting to note copy/move constructors here.
10414 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10415 return;
10416 S.Diag(Fn->getLocation(),
10417 diag::note_ovl_candidate_inherited_constructor_slice)
10418 << (Fn->getPrimaryTemplate() ? 1 : 0)
10419 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10420 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10421 return;
10422
10423 case ovl_fail_addr_not_available: {
10424 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10425 (void)Available;
10426 assert(!Available);
10427 break;
10428 }
10429 case ovl_non_default_multiversion_function:
10430 // Do nothing, these should simply be ignored.
10431 break;
10432 }
10433 }
10434
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)10435 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10436 // Desugar the type of the surrogate down to a function type,
10437 // retaining as many typedefs as possible while still showing
10438 // the function type (and, therefore, its parameter types).
10439 QualType FnType = Cand->Surrogate->getConversionType();
10440 bool isLValueReference = false;
10441 bool isRValueReference = false;
10442 bool isPointer = false;
10443 if (const LValueReferenceType *FnTypeRef =
10444 FnType->getAs<LValueReferenceType>()) {
10445 FnType = FnTypeRef->getPointeeType();
10446 isLValueReference = true;
10447 } else if (const RValueReferenceType *FnTypeRef =
10448 FnType->getAs<RValueReferenceType>()) {
10449 FnType = FnTypeRef->getPointeeType();
10450 isRValueReference = true;
10451 }
10452 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10453 FnType = FnTypePtr->getPointeeType();
10454 isPointer = true;
10455 }
10456 // Desugar down to a function type.
10457 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10458 // Reconstruct the pointer/reference as appropriate.
10459 if (isPointer) FnType = S.Context.getPointerType(FnType);
10460 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10461 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10462
10463 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10464 << FnType;
10465 }
10466
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)10467 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10468 SourceLocation OpLoc,
10469 OverloadCandidate *Cand) {
10470 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10471 std::string TypeStr("operator");
10472 TypeStr += Opc;
10473 TypeStr += "(";
10474 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10475 if (Cand->Conversions.size() == 1) {
10476 TypeStr += ")";
10477 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10478 } else {
10479 TypeStr += ", ";
10480 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10481 TypeStr += ")";
10482 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10483 }
10484 }
10485
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)10486 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10487 OverloadCandidate *Cand) {
10488 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10489 if (ICS.isBad()) break; // all meaningless after first invalid
10490 if (!ICS.isAmbiguous()) continue;
10491
10492 ICS.DiagnoseAmbiguousConversion(
10493 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10494 }
10495 }
10496
GetLocationForCandidate(const OverloadCandidate * Cand)10497 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10498 if (Cand->Function)
10499 return Cand->Function->getLocation();
10500 if (Cand->IsSurrogate)
10501 return Cand->Surrogate->getLocation();
10502 return SourceLocation();
10503 }
10504
RankDeductionFailure(const DeductionFailureInfo & DFI)10505 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10506 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10507 case Sema::TDK_Success:
10508 case Sema::TDK_NonDependentConversionFailure:
10509 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10510
10511 case Sema::TDK_Invalid:
10512 case Sema::TDK_Incomplete:
10513 case Sema::TDK_IncompletePack:
10514 return 1;
10515
10516 case Sema::TDK_Underqualified:
10517 case Sema::TDK_Inconsistent:
10518 return 2;
10519
10520 case Sema::TDK_SubstitutionFailure:
10521 case Sema::TDK_DeducedMismatch:
10522 case Sema::TDK_DeducedMismatchNested:
10523 case Sema::TDK_NonDeducedMismatch:
10524 case Sema::TDK_MiscellaneousDeductionFailure:
10525 case Sema::TDK_CUDATargetMismatch:
10526 return 3;
10527
10528 case Sema::TDK_InstantiationDepth:
10529 return 4;
10530
10531 case Sema::TDK_InvalidExplicitArguments:
10532 return 5;
10533
10534 case Sema::TDK_TooManyArguments:
10535 case Sema::TDK_TooFewArguments:
10536 return 6;
10537 }
10538 llvm_unreachable("Unhandled deduction result");
10539 }
10540
10541 namespace {
10542 struct CompareOverloadCandidatesForDisplay {
10543 Sema &S;
10544 SourceLocation Loc;
10545 size_t NumArgs;
10546 OverloadCandidateSet::CandidateSetKind CSK;
10547
CompareOverloadCandidatesForDisplay__anon832832a01611::CompareOverloadCandidatesForDisplay10548 CompareOverloadCandidatesForDisplay(
10549 Sema &S, SourceLocation Loc, size_t NArgs,
10550 OverloadCandidateSet::CandidateSetKind CSK)
10551 : S(S), NumArgs(NArgs), CSK(CSK) {}
10552
operator ()__anon832832a01611::CompareOverloadCandidatesForDisplay10553 bool operator()(const OverloadCandidate *L,
10554 const OverloadCandidate *R) {
10555 // Fast-path this check.
10556 if (L == R) return false;
10557
10558 // Order first by viability.
10559 if (L->Viable) {
10560 if (!R->Viable) return true;
10561
10562 // TODO: introduce a tri-valued comparison for overload
10563 // candidates. Would be more worthwhile if we had a sort
10564 // that could exploit it.
10565 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10566 return true;
10567 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10568 return false;
10569 } else if (R->Viable)
10570 return false;
10571
10572 assert(L->Viable == R->Viable);
10573
10574 // Criteria by which we can sort non-viable candidates:
10575 if (!L->Viable) {
10576 // 1. Arity mismatches come after other candidates.
10577 if (L->FailureKind == ovl_fail_too_many_arguments ||
10578 L->FailureKind == ovl_fail_too_few_arguments) {
10579 if (R->FailureKind == ovl_fail_too_many_arguments ||
10580 R->FailureKind == ovl_fail_too_few_arguments) {
10581 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10582 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10583 if (LDist == RDist) {
10584 if (L->FailureKind == R->FailureKind)
10585 // Sort non-surrogates before surrogates.
10586 return !L->IsSurrogate && R->IsSurrogate;
10587 // Sort candidates requiring fewer parameters than there were
10588 // arguments given after candidates requiring more parameters
10589 // than there were arguments given.
10590 return L->FailureKind == ovl_fail_too_many_arguments;
10591 }
10592 return LDist < RDist;
10593 }
10594 return false;
10595 }
10596 if (R->FailureKind == ovl_fail_too_many_arguments ||
10597 R->FailureKind == ovl_fail_too_few_arguments)
10598 return true;
10599
10600 // 2. Bad conversions come first and are ordered by the number
10601 // of bad conversions and quality of good conversions.
10602 if (L->FailureKind == ovl_fail_bad_conversion) {
10603 if (R->FailureKind != ovl_fail_bad_conversion)
10604 return true;
10605
10606 // The conversion that can be fixed with a smaller number of changes,
10607 // comes first.
10608 unsigned numLFixes = L->Fix.NumConversionsFixed;
10609 unsigned numRFixes = R->Fix.NumConversionsFixed;
10610 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10611 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10612 if (numLFixes != numRFixes) {
10613 return numLFixes < numRFixes;
10614 }
10615
10616 // If there's any ordering between the defined conversions...
10617 // FIXME: this might not be transitive.
10618 assert(L->Conversions.size() == R->Conversions.size());
10619
10620 int leftBetter = 0;
10621 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10622 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10623 switch (CompareImplicitConversionSequences(S, Loc,
10624 L->Conversions[I],
10625 R->Conversions[I])) {
10626 case ImplicitConversionSequence::Better:
10627 leftBetter++;
10628 break;
10629
10630 case ImplicitConversionSequence::Worse:
10631 leftBetter--;
10632 break;
10633
10634 case ImplicitConversionSequence::Indistinguishable:
10635 break;
10636 }
10637 }
10638 if (leftBetter > 0) return true;
10639 if (leftBetter < 0) return false;
10640
10641 } else if (R->FailureKind == ovl_fail_bad_conversion)
10642 return false;
10643
10644 if (L->FailureKind == ovl_fail_bad_deduction) {
10645 if (R->FailureKind != ovl_fail_bad_deduction)
10646 return true;
10647
10648 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10649 return RankDeductionFailure(L->DeductionFailure)
10650 < RankDeductionFailure(R->DeductionFailure);
10651 } else if (R->FailureKind == ovl_fail_bad_deduction)
10652 return false;
10653
10654 // TODO: others?
10655 }
10656
10657 // Sort everything else by location.
10658 SourceLocation LLoc = GetLocationForCandidate(L);
10659 SourceLocation RLoc = GetLocationForCandidate(R);
10660
10661 // Put candidates without locations (e.g. builtins) at the end.
10662 if (LLoc.isInvalid()) return false;
10663 if (RLoc.isInvalid()) return true;
10664
10665 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10666 }
10667 };
10668 }
10669
10670 /// CompleteNonViableCandidate - Normally, overload resolution only
10671 /// computes up to the first bad conversion. Produces the FixIt set if
10672 /// possible.
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args)10673 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10674 ArrayRef<Expr *> Args) {
10675 assert(!Cand->Viable);
10676
10677 // Don't do anything on failures other than bad conversion.
10678 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10679
10680 // We only want the FixIts if all the arguments can be corrected.
10681 bool Unfixable = false;
10682 // Use a implicit copy initialization to check conversion fixes.
10683 Cand->Fix.setConversionChecker(TryCopyInitialization);
10684
10685 // Attempt to fix the bad conversion.
10686 unsigned ConvCount = Cand->Conversions.size();
10687 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10688 ++ConvIdx) {
10689 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10690 if (Cand->Conversions[ConvIdx].isInitialized() &&
10691 Cand->Conversions[ConvIdx].isBad()) {
10692 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10693 break;
10694 }
10695 }
10696
10697 // FIXME: this should probably be preserved from the overload
10698 // operation somehow.
10699 bool SuppressUserConversions = false;
10700
10701 unsigned ConvIdx = 0;
10702 ArrayRef<QualType> ParamTypes;
10703
10704 if (Cand->IsSurrogate) {
10705 QualType ConvType
10706 = Cand->Surrogate->getConversionType().getNonReferenceType();
10707 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10708 ConvType = ConvPtrType->getPointeeType();
10709 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10710 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10711 ConvIdx = 1;
10712 } else if (Cand->Function) {
10713 ParamTypes =
10714 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10715 if (isa<CXXMethodDecl>(Cand->Function) &&
10716 !isa<CXXConstructorDecl>(Cand->Function)) {
10717 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10718 ConvIdx = 1;
10719 }
10720 } else {
10721 // Builtin operator.
10722 assert(ConvCount <= 3);
10723 ParamTypes = Cand->BuiltinParamTypes;
10724 }
10725
10726 // Fill in the rest of the conversions.
10727 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10728 if (Cand->Conversions[ConvIdx].isInitialized()) {
10729 // We've already checked this conversion.
10730 } else if (ArgIdx < ParamTypes.size()) {
10731 if (ParamTypes[ArgIdx]->isDependentType())
10732 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10733 Args[ArgIdx]->getType());
10734 else {
10735 Cand->Conversions[ConvIdx] =
10736 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10737 SuppressUserConversions,
10738 /*InOverloadResolution=*/true,
10739 /*AllowObjCWritebackConversion=*/
10740 S.getLangOpts().ObjCAutoRefCount);
10741 // Store the FixIt in the candidate if it exists.
10742 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10743 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10744 }
10745 } else
10746 Cand->Conversions[ConvIdx].setEllipsis();
10747 }
10748 }
10749
10750 /// When overload resolution fails, prints diagnostic messages containing the
10751 /// candidates in the candidate set.
NoteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,StringRef Opc,SourceLocation OpLoc,llvm::function_ref<bool (OverloadCandidate &)> Filter)10752 void OverloadCandidateSet::NoteCandidates(
10753 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10754 StringRef Opc, SourceLocation OpLoc,
10755 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10756 // Sort the candidates by viability and position. Sorting directly would
10757 // be prohibitive, so we make a set of pointers and sort those.
10758 SmallVector<OverloadCandidate*, 32> Cands;
10759 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10760 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10761 if (!Filter(*Cand))
10762 continue;
10763 if (Cand->Viable)
10764 Cands.push_back(Cand);
10765 else if (OCD == OCD_AllCandidates) {
10766 CompleteNonViableCandidate(S, Cand, Args);
10767 if (Cand->Function || Cand->IsSurrogate)
10768 Cands.push_back(Cand);
10769 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10770 // want to list every possible builtin candidate.
10771 }
10772 }
10773
10774 std::stable_sort(Cands.begin(), Cands.end(),
10775 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10776
10777 bool ReportedAmbiguousConversions = false;
10778
10779 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10780 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10781 unsigned CandsShown = 0;
10782 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10783 OverloadCandidate *Cand = *I;
10784
10785 // Set an arbitrary limit on the number of candidate functions we'll spam
10786 // the user with. FIXME: This limit should depend on details of the
10787 // candidate list.
10788 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10789 break;
10790 }
10791 ++CandsShown;
10792
10793 if (Cand->Function)
10794 NoteFunctionCandidate(S, Cand, Args.size(),
10795 /*TakingCandidateAddress=*/false);
10796 else if (Cand->IsSurrogate)
10797 NoteSurrogateCandidate(S, Cand);
10798 else {
10799 assert(Cand->Viable &&
10800 "Non-viable built-in candidates are not added to Cands.");
10801 // Generally we only see ambiguities including viable builtin
10802 // operators if overload resolution got screwed up by an
10803 // ambiguous user-defined conversion.
10804 //
10805 // FIXME: It's quite possible for different conversions to see
10806 // different ambiguities, though.
10807 if (!ReportedAmbiguousConversions) {
10808 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10809 ReportedAmbiguousConversions = true;
10810 }
10811
10812 // If this is a viable builtin, print it.
10813 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10814 }
10815 }
10816
10817 if (I != E)
10818 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10819 }
10820
10821 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)10822 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10823 return Cand->Specialization ? Cand->Specialization->getLocation()
10824 : SourceLocation();
10825 }
10826
10827 namespace {
10828 struct CompareTemplateSpecCandidatesForDisplay {
10829 Sema &S;
CompareTemplateSpecCandidatesForDisplay__anon832832a01711::CompareTemplateSpecCandidatesForDisplay10830 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10831
operator ()__anon832832a01711::CompareTemplateSpecCandidatesForDisplay10832 bool operator()(const TemplateSpecCandidate *L,
10833 const TemplateSpecCandidate *R) {
10834 // Fast-path this check.
10835 if (L == R)
10836 return false;
10837
10838 // Assuming that both candidates are not matches...
10839
10840 // Sort by the ranking of deduction failures.
10841 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10842 return RankDeductionFailure(L->DeductionFailure) <
10843 RankDeductionFailure(R->DeductionFailure);
10844
10845 // Sort everything else by location.
10846 SourceLocation LLoc = GetLocationForCandidate(L);
10847 SourceLocation RLoc = GetLocationForCandidate(R);
10848
10849 // Put candidates without locations (e.g. builtins) at the end.
10850 if (LLoc.isInvalid())
10851 return false;
10852 if (RLoc.isInvalid())
10853 return true;
10854
10855 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10856 }
10857 };
10858 }
10859
10860 /// Diagnose a template argument deduction failure.
10861 /// We are treating these failures as overload failures due to bad
10862 /// deductions.
NoteDeductionFailure(Sema & S,bool ForTakingAddress)10863 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10864 bool ForTakingAddress) {
10865 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10866 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10867 }
10868
destroyCandidates()10869 void TemplateSpecCandidateSet::destroyCandidates() {
10870 for (iterator i = begin(), e = end(); i != e; ++i) {
10871 i->DeductionFailure.Destroy();
10872 }
10873 }
10874
clear()10875 void TemplateSpecCandidateSet::clear() {
10876 destroyCandidates();
10877 Candidates.clear();
10878 }
10879
10880 /// NoteCandidates - When no template specialization match is found, prints
10881 /// diagnostic messages containing the non-matching specializations that form
10882 /// the candidate set.
10883 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10884 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)10885 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10886 // Sort the candidates by position (assuming no candidate is a match).
10887 // Sorting directly would be prohibitive, so we make a set of pointers
10888 // and sort those.
10889 SmallVector<TemplateSpecCandidate *, 32> Cands;
10890 Cands.reserve(size());
10891 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10892 if (Cand->Specialization)
10893 Cands.push_back(Cand);
10894 // Otherwise, this is a non-matching builtin candidate. We do not,
10895 // in general, want to list every possible builtin candidate.
10896 }
10897
10898 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10899
10900 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10901 // for generalization purposes (?).
10902 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10903
10904 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10905 unsigned CandsShown = 0;
10906 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10907 TemplateSpecCandidate *Cand = *I;
10908
10909 // Set an arbitrary limit on the number of candidates we'll spam
10910 // the user with. FIXME: This limit should depend on details of the
10911 // candidate list.
10912 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10913 break;
10914 ++CandsShown;
10915
10916 assert(Cand->Specialization &&
10917 "Non-matching built-in candidates are not added to Cands.");
10918 Cand->NoteDeductionFailure(S, ForTakingAddress);
10919 }
10920
10921 if (I != E)
10922 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10923 }
10924
10925 // [PossiblyAFunctionType] --> [Return]
10926 // NonFunctionType --> NonFunctionType
10927 // R (A) --> R(A)
10928 // R (*)(A) --> R (A)
10929 // R (&)(A) --> R (A)
10930 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)10931 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10932 QualType Ret = PossiblyAFunctionType;
10933 if (const PointerType *ToTypePtr =
10934 PossiblyAFunctionType->getAs<PointerType>())
10935 Ret = ToTypePtr->getPointeeType();
10936 else if (const ReferenceType *ToTypeRef =
10937 PossiblyAFunctionType->getAs<ReferenceType>())
10938 Ret = ToTypeRef->getPointeeType();
10939 else if (const MemberPointerType *MemTypePtr =
10940 PossiblyAFunctionType->getAs<MemberPointerType>())
10941 Ret = MemTypePtr->getPointeeType();
10942 Ret =
10943 Context.getCanonicalType(Ret).getUnqualifiedType();
10944 return Ret;
10945 }
10946
completeFunctionType(Sema & S,FunctionDecl * FD,SourceLocation Loc,bool Complain=true)10947 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10948 bool Complain = true) {
10949 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10950 S.DeduceReturnType(FD, Loc, Complain))
10951 return true;
10952
10953 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10954 if (S.getLangOpts().CPlusPlus17 &&
10955 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10956 !S.ResolveExceptionSpec(Loc, FPT))
10957 return true;
10958
10959 return false;
10960 }
10961
10962 namespace {
10963 // A helper class to help with address of function resolution
10964 // - allows us to avoid passing around all those ugly parameters
10965 class AddressOfFunctionResolver {
10966 Sema& S;
10967 Expr* SourceExpr;
10968 const QualType& TargetType;
10969 QualType TargetFunctionType; // Extracted function type from target type
10970
10971 bool Complain;
10972 //DeclAccessPair& ResultFunctionAccessPair;
10973 ASTContext& Context;
10974
10975 bool TargetTypeIsNonStaticMemberFunction;
10976 bool FoundNonTemplateFunction;
10977 bool StaticMemberFunctionFromBoundPointer;
10978 bool HasComplained;
10979
10980 OverloadExpr::FindResult OvlExprInfo;
10981 OverloadExpr *OvlExpr;
10982 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10983 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10984 TemplateSpecCandidateSet FailedCandidates;
10985
10986 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)10987 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10988 const QualType &TargetType, bool Complain)
10989 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10990 Complain(Complain), Context(S.getASTContext()),
10991 TargetTypeIsNonStaticMemberFunction(
10992 !!TargetType->getAs<MemberPointerType>()),
10993 FoundNonTemplateFunction(false),
10994 StaticMemberFunctionFromBoundPointer(false),
10995 HasComplained(false),
10996 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10997 OvlExpr(OvlExprInfo.Expression),
10998 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10999 ExtractUnqualifiedFunctionTypeFromTargetType();
11000
11001 if (TargetFunctionType->isFunctionType()) {
11002 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11003 if (!UME->isImplicitAccess() &&
11004 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11005 StaticMemberFunctionFromBoundPointer = true;
11006 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11007 DeclAccessPair dap;
11008 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11009 OvlExpr, false, &dap)) {
11010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11011 if (!Method->isStatic()) {
11012 // If the target type is a non-function type and the function found
11013 // is a non-static member function, pretend as if that was the
11014 // target, it's the only possible type to end up with.
11015 TargetTypeIsNonStaticMemberFunction = true;
11016
11017 // And skip adding the function if its not in the proper form.
11018 // We'll diagnose this due to an empty set of functions.
11019 if (!OvlExprInfo.HasFormOfMemberPointer)
11020 return;
11021 }
11022
11023 Matches.push_back(std::make_pair(dap, Fn));
11024 }
11025 return;
11026 }
11027
11028 if (OvlExpr->hasExplicitTemplateArgs())
11029 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11030
11031 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11032 // C++ [over.over]p4:
11033 // If more than one function is selected, [...]
11034 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11035 if (FoundNonTemplateFunction)
11036 EliminateAllTemplateMatches();
11037 else
11038 EliminateAllExceptMostSpecializedTemplate();
11039 }
11040 }
11041
11042 if (S.getLangOpts().CUDA && Matches.size() > 1)
11043 EliminateSuboptimalCudaMatches();
11044 }
11045
hasComplained() const11046 bool hasComplained() const { return HasComplained; }
11047
11048 private:
candidateHasExactlyCorrectType(const FunctionDecl * FD)11049 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11050 QualType Discard;
11051 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11052 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11053 }
11054
11055 /// \return true if A is considered a better overload candidate for the
11056 /// desired type than B.
isBetterCandidate(const FunctionDecl * A,const FunctionDecl * B)11057 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11058 // If A doesn't have exactly the correct type, we don't want to classify it
11059 // as "better" than anything else. This way, the user is required to
11060 // disambiguate for us if there are multiple candidates and no exact match.
11061 return candidateHasExactlyCorrectType(A) &&
11062 (!candidateHasExactlyCorrectType(B) ||
11063 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11064 }
11065
11066 /// \return true if we were able to eliminate all but one overload candidate,
11067 /// false otherwise.
eliminiateSuboptimalOverloadCandidates()11068 bool eliminiateSuboptimalOverloadCandidates() {
11069 // Same algorithm as overload resolution -- one pass to pick the "best",
11070 // another pass to be sure that nothing is better than the best.
11071 auto Best = Matches.begin();
11072 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11073 if (isBetterCandidate(I->second, Best->second))
11074 Best = I;
11075
11076 const FunctionDecl *BestFn = Best->second;
11077 auto IsBestOrInferiorToBest = [this, BestFn](
11078 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11079 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11080 };
11081
11082 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11083 // option, so we can potentially give the user a better error
11084 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11085 return false;
11086 Matches[0] = *Best;
11087 Matches.resize(1);
11088 return true;
11089 }
11090
isTargetTypeAFunction() const11091 bool isTargetTypeAFunction() const {
11092 return TargetFunctionType->isFunctionType();
11093 }
11094
11095 // [ToType] [Return]
11096
11097 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11098 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11099 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()11100 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11101 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11102 }
11103
11104 // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)11105 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11106 const DeclAccessPair& CurAccessFunPair) {
11107 if (CXXMethodDecl *Method
11108 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11109 // Skip non-static function templates when converting to pointer, and
11110 // static when converting to member pointer.
11111 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11112 return false;
11113 }
11114 else if (TargetTypeIsNonStaticMemberFunction)
11115 return false;
11116
11117 // C++ [over.over]p2:
11118 // If the name is a function template, template argument deduction is
11119 // done (14.8.2.2), and if the argument deduction succeeds, the
11120 // resulting template argument list is used to generate a single
11121 // function template specialization, which is added to the set of
11122 // overloaded functions considered.
11123 FunctionDecl *Specialization = nullptr;
11124 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11125 if (Sema::TemplateDeductionResult Result
11126 = S.DeduceTemplateArguments(FunctionTemplate,
11127 &OvlExplicitTemplateArgs,
11128 TargetFunctionType, Specialization,
11129 Info, /*IsAddressOfFunction*/true)) {
11130 // Make a note of the failed deduction for diagnostics.
11131 FailedCandidates.addCandidate()
11132 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11133 MakeDeductionFailureInfo(Context, Result, Info));
11134 return false;
11135 }
11136
11137 // Template argument deduction ensures that we have an exact match or
11138 // compatible pointer-to-function arguments that would be adjusted by ICS.
11139 // This function template specicalization works.
11140 assert(S.isSameOrCompatibleFunctionType(
11141 Context.getCanonicalType(Specialization->getType()),
11142 Context.getCanonicalType(TargetFunctionType)));
11143
11144 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11145 return false;
11146
11147 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11148 return true;
11149 }
11150
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)11151 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11152 const DeclAccessPair& CurAccessFunPair) {
11153 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11154 // Skip non-static functions when converting to pointer, and static
11155 // when converting to member pointer.
11156 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11157 return false;
11158 }
11159 else if (TargetTypeIsNonStaticMemberFunction)
11160 return false;
11161
11162 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11163 if (S.getLangOpts().CUDA)
11164 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11165 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11166 return false;
11167 if (FunDecl->isMultiVersion()) {
11168 const auto *TA = FunDecl->getAttr<TargetAttr>();
11169 if (TA && !TA->isDefaultVersion())
11170 return false;
11171 }
11172
11173 // If any candidate has a placeholder return type, trigger its deduction
11174 // now.
11175 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11176 Complain)) {
11177 HasComplained |= Complain;
11178 return false;
11179 }
11180
11181 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11182 return false;
11183
11184 // If we're in C, we need to support types that aren't exactly identical.
11185 if (!S.getLangOpts().CPlusPlus ||
11186 candidateHasExactlyCorrectType(FunDecl)) {
11187 Matches.push_back(std::make_pair(
11188 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11189 FoundNonTemplateFunction = true;
11190 return true;
11191 }
11192 }
11193
11194 return false;
11195 }
11196
FindAllFunctionsThatMatchTargetTypeExactly()11197 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11198 bool Ret = false;
11199
11200 // If the overload expression doesn't have the form of a pointer to
11201 // member, don't try to convert it to a pointer-to-member type.
11202 if (IsInvalidFormOfPointerToMemberFunction())
11203 return false;
11204
11205 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11206 E = OvlExpr->decls_end();
11207 I != E; ++I) {
11208 // Look through any using declarations to find the underlying function.
11209 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11210
11211 // C++ [over.over]p3:
11212 // Non-member functions and static member functions match
11213 // targets of type "pointer-to-function" or "reference-to-function."
11214 // Nonstatic member functions match targets of
11215 // type "pointer-to-member-function."
11216 // Note that according to DR 247, the containing class does not matter.
11217 if (FunctionTemplateDecl *FunctionTemplate
11218 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11219 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11220 Ret = true;
11221 }
11222 // If we have explicit template arguments supplied, skip non-templates.
11223 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11224 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11225 Ret = true;
11226 }
11227 assert(Ret || Matches.empty());
11228 return Ret;
11229 }
11230
EliminateAllExceptMostSpecializedTemplate()11231 void EliminateAllExceptMostSpecializedTemplate() {
11232 // [...] and any given function template specialization F1 is
11233 // eliminated if the set contains a second function template
11234 // specialization whose function template is more specialized
11235 // than the function template of F1 according to the partial
11236 // ordering rules of 14.5.5.2.
11237
11238 // The algorithm specified above is quadratic. We instead use a
11239 // two-pass algorithm (similar to the one used to identify the
11240 // best viable function in an overload set) that identifies the
11241 // best function template (if it exists).
11242
11243 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11244 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11245 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11246
11247 // TODO: It looks like FailedCandidates does not serve much purpose
11248 // here, since the no_viable diagnostic has index 0.
11249 UnresolvedSetIterator Result = S.getMostSpecialized(
11250 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11251 SourceExpr->getBeginLoc(), S.PDiag(),
11252 S.PDiag(diag::err_addr_ovl_ambiguous)
11253 << Matches[0].second->getDeclName(),
11254 S.PDiag(diag::note_ovl_candidate)
11255 << (unsigned)oc_function << (unsigned)ocs_described_template,
11256 Complain, TargetFunctionType);
11257
11258 if (Result != MatchesCopy.end()) {
11259 // Make it the first and only element
11260 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11261 Matches[0].second = cast<FunctionDecl>(*Result);
11262 Matches.resize(1);
11263 } else
11264 HasComplained |= Complain;
11265 }
11266
EliminateAllTemplateMatches()11267 void EliminateAllTemplateMatches() {
11268 // [...] any function template specializations in the set are
11269 // eliminated if the set also contains a non-template function, [...]
11270 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11271 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11272 ++I;
11273 else {
11274 Matches[I] = Matches[--N];
11275 Matches.resize(N);
11276 }
11277 }
11278 }
11279
EliminateSuboptimalCudaMatches()11280 void EliminateSuboptimalCudaMatches() {
11281 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11282 }
11283
11284 public:
ComplainNoMatchesFound() const11285 void ComplainNoMatchesFound() const {
11286 assert(Matches.empty());
11287 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11288 << OvlExpr->getName() << TargetFunctionType
11289 << OvlExpr->getSourceRange();
11290 if (FailedCandidates.empty())
11291 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11292 /*TakingAddress=*/true);
11293 else {
11294 // We have some deduction failure messages. Use them to diagnose
11295 // the function templates, and diagnose the non-template candidates
11296 // normally.
11297 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11298 IEnd = OvlExpr->decls_end();
11299 I != IEnd; ++I)
11300 if (FunctionDecl *Fun =
11301 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11302 if (!functionHasPassObjectSizeParams(Fun))
11303 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11304 /*TakingAddress=*/true);
11305 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11306 }
11307 }
11308
IsInvalidFormOfPointerToMemberFunction() const11309 bool IsInvalidFormOfPointerToMemberFunction() const {
11310 return TargetTypeIsNonStaticMemberFunction &&
11311 !OvlExprInfo.HasFormOfMemberPointer;
11312 }
11313
ComplainIsInvalidFormOfPointerToMemberFunction() const11314 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11315 // TODO: Should we condition this on whether any functions might
11316 // have matched, or is it more appropriate to do that in callers?
11317 // TODO: a fixit wouldn't hurt.
11318 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11319 << TargetType << OvlExpr->getSourceRange();
11320 }
11321
IsStaticMemberFunctionFromBoundPointer() const11322 bool IsStaticMemberFunctionFromBoundPointer() const {
11323 return StaticMemberFunctionFromBoundPointer;
11324 }
11325
ComplainIsStaticMemberFunctionFromBoundPointer() const11326 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11327 S.Diag(OvlExpr->getBeginLoc(),
11328 diag::err_invalid_form_pointer_member_function)
11329 << OvlExpr->getSourceRange();
11330 }
11331
ComplainOfInvalidConversion() const11332 void ComplainOfInvalidConversion() const {
11333 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11334 << OvlExpr->getName() << TargetType;
11335 }
11336
ComplainMultipleMatchesFound() const11337 void ComplainMultipleMatchesFound() const {
11338 assert(Matches.size() > 1);
11339 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11340 << OvlExpr->getName() << OvlExpr->getSourceRange();
11341 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11342 /*TakingAddress=*/true);
11343 }
11344
hadMultipleCandidates() const11345 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11346
getNumMatches() const11347 int getNumMatches() const { return Matches.size(); }
11348
getMatchingFunctionDecl() const11349 FunctionDecl* getMatchingFunctionDecl() const {
11350 if (Matches.size() != 1) return nullptr;
11351 return Matches[0].second;
11352 }
11353
getMatchingFunctionAccessPair() const11354 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11355 if (Matches.size() != 1) return nullptr;
11356 return &Matches[0].first;
11357 }
11358 };
11359 }
11360
11361 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11362 /// an overloaded function (C++ [over.over]), where @p From is an
11363 /// expression with overloaded function type and @p ToType is the type
11364 /// we're trying to resolve to. For example:
11365 ///
11366 /// @code
11367 /// int f(double);
11368 /// int f(int);
11369 ///
11370 /// int (*pfd)(double) = f; // selects f(double)
11371 /// @endcode
11372 ///
11373 /// This routine returns the resulting FunctionDecl if it could be
11374 /// resolved, and NULL otherwise. When @p Complain is true, this
11375 /// routine will emit diagnostics if there is an error.
11376 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)11377 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11378 QualType TargetType,
11379 bool Complain,
11380 DeclAccessPair &FoundResult,
11381 bool *pHadMultipleCandidates) {
11382 assert(AddressOfExpr->getType() == Context.OverloadTy);
11383
11384 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11385 Complain);
11386 int NumMatches = Resolver.getNumMatches();
11387 FunctionDecl *Fn = nullptr;
11388 bool ShouldComplain = Complain && !Resolver.hasComplained();
11389 if (NumMatches == 0 && ShouldComplain) {
11390 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11391 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11392 else
11393 Resolver.ComplainNoMatchesFound();
11394 }
11395 else if (NumMatches > 1 && ShouldComplain)
11396 Resolver.ComplainMultipleMatchesFound();
11397 else if (NumMatches == 1) {
11398 Fn = Resolver.getMatchingFunctionDecl();
11399 assert(Fn);
11400 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11401 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11402 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11403 if (Complain) {
11404 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11405 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11406 else
11407 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11408 }
11409 }
11410
11411 if (pHadMultipleCandidates)
11412 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11413 return Fn;
11414 }
11415
11416 /// Given an expression that refers to an overloaded function, try to
11417 /// resolve that function to a single function that can have its address taken.
11418 /// This will modify `Pair` iff it returns non-null.
11419 ///
11420 /// This routine can only realistically succeed if all but one candidates in the
11421 /// overload set for SrcExpr cannot have their addresses taken.
11422 FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr * E,DeclAccessPair & Pair)11423 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11424 DeclAccessPair &Pair) {
11425 OverloadExpr::FindResult R = OverloadExpr::find(E);
11426 OverloadExpr *Ovl = R.Expression;
11427 FunctionDecl *Result = nullptr;
11428 DeclAccessPair DAP;
11429 // Don't use the AddressOfResolver because we're specifically looking for
11430 // cases where we have one overload candidate that lacks
11431 // enable_if/pass_object_size/...
11432 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11433 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11434 if (!FD)
11435 return nullptr;
11436
11437 if (!checkAddressOfFunctionIsAvailable(FD))
11438 continue;
11439
11440 // We have more than one result; quit.
11441 if (Result)
11442 return nullptr;
11443 DAP = I.getPair();
11444 Result = FD;
11445 }
11446
11447 if (Result)
11448 Pair = DAP;
11449 return Result;
11450 }
11451
11452 /// Given an overloaded function, tries to turn it into a non-overloaded
11453 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11454 /// will perform access checks, diagnose the use of the resultant decl, and, if
11455 /// requested, potentially perform a function-to-pointer decay.
11456 ///
11457 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11458 /// Otherwise, returns true. This may emit diagnostics and return true.
resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult & SrcExpr,bool DoFunctionPointerConverion)11459 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11460 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11461 Expr *E = SrcExpr.get();
11462 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11463
11464 DeclAccessPair DAP;
11465 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11466 if (!Found || Found->isCPUDispatchMultiVersion() ||
11467 Found->isCPUSpecificMultiVersion())
11468 return false;
11469
11470 // Emitting multiple diagnostics for a function that is both inaccessible and
11471 // unavailable is consistent with our behavior elsewhere. So, always check
11472 // for both.
11473 DiagnoseUseOfDecl(Found, E->getExprLoc());
11474 CheckAddressOfMemberAccess(E, DAP);
11475 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11476 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11477 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11478 else
11479 SrcExpr = Fixed;
11480 return true;
11481 }
11482
11483 /// Given an expression that refers to an overloaded function, try to
11484 /// resolve that overloaded function expression down to a single function.
11485 ///
11486 /// This routine can only resolve template-ids that refer to a single function
11487 /// template, where that template-id refers to a single template whose template
11488 /// arguments are either provided by the template-id or have defaults,
11489 /// as described in C++0x [temp.arg.explicit]p3.
11490 ///
11491 /// If no template-ids are found, no diagnostics are emitted and NULL is
11492 /// returned.
11493 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)11494 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11495 bool Complain,
11496 DeclAccessPair *FoundResult) {
11497 // C++ [over.over]p1:
11498 // [...] [Note: any redundant set of parentheses surrounding the
11499 // overloaded function name is ignored (5.1). ]
11500 // C++ [over.over]p1:
11501 // [...] The overloaded function name can be preceded by the &
11502 // operator.
11503
11504 // If we didn't actually find any template-ids, we're done.
11505 if (!ovl->hasExplicitTemplateArgs())
11506 return nullptr;
11507
11508 TemplateArgumentListInfo ExplicitTemplateArgs;
11509 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11510 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11511
11512 // Look through all of the overloaded functions, searching for one
11513 // whose type matches exactly.
11514 FunctionDecl *Matched = nullptr;
11515 for (UnresolvedSetIterator I = ovl->decls_begin(),
11516 E = ovl->decls_end(); I != E; ++I) {
11517 // C++0x [temp.arg.explicit]p3:
11518 // [...] In contexts where deduction is done and fails, or in contexts
11519 // where deduction is not done, if a template argument list is
11520 // specified and it, along with any default template arguments,
11521 // identifies a single function template specialization, then the
11522 // template-id is an lvalue for the function template specialization.
11523 FunctionTemplateDecl *FunctionTemplate
11524 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11525
11526 // C++ [over.over]p2:
11527 // If the name is a function template, template argument deduction is
11528 // done (14.8.2.2), and if the argument deduction succeeds, the
11529 // resulting template argument list is used to generate a single
11530 // function template specialization, which is added to the set of
11531 // overloaded functions considered.
11532 FunctionDecl *Specialization = nullptr;
11533 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11534 if (TemplateDeductionResult Result
11535 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11536 Specialization, Info,
11537 /*IsAddressOfFunction*/true)) {
11538 // Make a note of the failed deduction for diagnostics.
11539 // TODO: Actually use the failed-deduction info?
11540 FailedCandidates.addCandidate()
11541 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11542 MakeDeductionFailureInfo(Context, Result, Info));
11543 continue;
11544 }
11545
11546 assert(Specialization && "no specialization and no error?");
11547
11548 // Multiple matches; we can't resolve to a single declaration.
11549 if (Matched) {
11550 if (Complain) {
11551 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11552 << ovl->getName();
11553 NoteAllOverloadCandidates(ovl);
11554 }
11555 return nullptr;
11556 }
11557
11558 Matched = Specialization;
11559 if (FoundResult) *FoundResult = I.getPair();
11560 }
11561
11562 if (Matched &&
11563 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11564 return nullptr;
11565
11566 return Matched;
11567 }
11568
11569 // Resolve and fix an overloaded expression that can be resolved
11570 // because it identifies a single function template specialization.
11571 //
11572 // Last three arguments should only be supplied if Complain = true
11573 //
11574 // Return true if it was logically possible to so resolve the
11575 // expression, regardless of whether or not it succeeded. Always
11576 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,SourceRange OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)11577 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11578 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11579 bool complain, SourceRange OpRangeForComplaining,
11580 QualType DestTypeForComplaining,
11581 unsigned DiagIDForComplaining) {
11582 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11583
11584 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11585
11586 DeclAccessPair found;
11587 ExprResult SingleFunctionExpression;
11588 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11589 ovl.Expression, /*complain*/ false, &found)) {
11590 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11591 SrcExpr = ExprError();
11592 return true;
11593 }
11594
11595 // It is only correct to resolve to an instance method if we're
11596 // resolving a form that's permitted to be a pointer to member.
11597 // Otherwise we'll end up making a bound member expression, which
11598 // is illegal in all the contexts we resolve like this.
11599 if (!ovl.HasFormOfMemberPointer &&
11600 isa<CXXMethodDecl>(fn) &&
11601 cast<CXXMethodDecl>(fn)->isInstance()) {
11602 if (!complain) return false;
11603
11604 Diag(ovl.Expression->getExprLoc(),
11605 diag::err_bound_member_function)
11606 << 0 << ovl.Expression->getSourceRange();
11607
11608 // TODO: I believe we only end up here if there's a mix of
11609 // static and non-static candidates (otherwise the expression
11610 // would have 'bound member' type, not 'overload' type).
11611 // Ideally we would note which candidate was chosen and why
11612 // the static candidates were rejected.
11613 SrcExpr = ExprError();
11614 return true;
11615 }
11616
11617 // Fix the expression to refer to 'fn'.
11618 SingleFunctionExpression =
11619 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11620
11621 // If desired, do function-to-pointer decay.
11622 if (doFunctionPointerConverion) {
11623 SingleFunctionExpression =
11624 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11625 if (SingleFunctionExpression.isInvalid()) {
11626 SrcExpr = ExprError();
11627 return true;
11628 }
11629 }
11630 }
11631
11632 if (!SingleFunctionExpression.isUsable()) {
11633 if (complain) {
11634 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11635 << ovl.Expression->getName()
11636 << DestTypeForComplaining
11637 << OpRangeForComplaining
11638 << ovl.Expression->getQualifierLoc().getSourceRange();
11639 NoteAllOverloadCandidates(SrcExpr.get());
11640
11641 SrcExpr = ExprError();
11642 return true;
11643 }
11644
11645 return false;
11646 }
11647
11648 SrcExpr = SingleFunctionExpression;
11649 return true;
11650 }
11651
11652 /// Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)11653 static void AddOverloadedCallCandidate(Sema &S,
11654 DeclAccessPair FoundDecl,
11655 TemplateArgumentListInfo *ExplicitTemplateArgs,
11656 ArrayRef<Expr *> Args,
11657 OverloadCandidateSet &CandidateSet,
11658 bool PartialOverloading,
11659 bool KnownValid) {
11660 NamedDecl *Callee = FoundDecl.getDecl();
11661 if (isa<UsingShadowDecl>(Callee))
11662 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11663
11664 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11665 if (ExplicitTemplateArgs) {
11666 assert(!KnownValid && "Explicit template arguments?");
11667 return;
11668 }
11669 // Prevent ill-formed function decls to be added as overload candidates.
11670 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11671 return;
11672
11673 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11674 /*SuppressUsedConversions=*/false,
11675 PartialOverloading);
11676 return;
11677 }
11678
11679 if (FunctionTemplateDecl *FuncTemplate
11680 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11681 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11682 ExplicitTemplateArgs, Args, CandidateSet,
11683 /*SuppressUsedConversions=*/false,
11684 PartialOverloading);
11685 return;
11686 }
11687
11688 assert(!KnownValid && "unhandled case in overloaded call candidate");
11689 }
11690
11691 /// Add the overload candidates named by callee and/or found by argument
11692 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)11693 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11694 ArrayRef<Expr *> Args,
11695 OverloadCandidateSet &CandidateSet,
11696 bool PartialOverloading) {
11697
11698 #ifndef NDEBUG
11699 // Verify that ArgumentDependentLookup is consistent with the rules
11700 // in C++0x [basic.lookup.argdep]p3:
11701 //
11702 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11703 // and let Y be the lookup set produced by argument dependent
11704 // lookup (defined as follows). If X contains
11705 //
11706 // -- a declaration of a class member, or
11707 //
11708 // -- a block-scope function declaration that is not a
11709 // using-declaration, or
11710 //
11711 // -- a declaration that is neither a function or a function
11712 // template
11713 //
11714 // then Y is empty.
11715
11716 if (ULE->requiresADL()) {
11717 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11718 E = ULE->decls_end(); I != E; ++I) {
11719 assert(!(*I)->getDeclContext()->isRecord());
11720 assert(isa<UsingShadowDecl>(*I) ||
11721 !(*I)->getDeclContext()->isFunctionOrMethod());
11722 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11723 }
11724 }
11725 #endif
11726
11727 // It would be nice to avoid this copy.
11728 TemplateArgumentListInfo TABuffer;
11729 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11730 if (ULE->hasExplicitTemplateArgs()) {
11731 ULE->copyTemplateArgumentsInto(TABuffer);
11732 ExplicitTemplateArgs = &TABuffer;
11733 }
11734
11735 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11736 E = ULE->decls_end(); I != E; ++I)
11737 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11738 CandidateSet, PartialOverloading,
11739 /*KnownValid*/ true);
11740
11741 if (ULE->requiresADL())
11742 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11743 Args, ExplicitTemplateArgs,
11744 CandidateSet, PartialOverloading);
11745 }
11746
11747 /// Determine whether a declaration with the specified name could be moved into
11748 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)11749 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11750 switch (Name.getCXXOverloadedOperator()) {
11751 case OO_New: case OO_Array_New:
11752 case OO_Delete: case OO_Array_Delete:
11753 return false;
11754
11755 default:
11756 return true;
11757 }
11758 }
11759
11760 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11761 /// template, where the non-dependent name was declared after the template
11762 /// was defined. This is common in code written for a compilers which do not
11763 /// correctly implement two-stage name lookup.
11764 ///
11765 /// Returns true if a viable candidate was found and a diagnostic was issued.
11766 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,OverloadCandidateSet::CandidateSetKind CSK,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,bool * DoDiagnoseEmptyLookup=nullptr)11767 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11768 const CXXScopeSpec &SS, LookupResult &R,
11769 OverloadCandidateSet::CandidateSetKind CSK,
11770 TemplateArgumentListInfo *ExplicitTemplateArgs,
11771 ArrayRef<Expr *> Args,
11772 bool *DoDiagnoseEmptyLookup = nullptr) {
11773 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11774 return false;
11775
11776 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11777 if (DC->isTransparentContext())
11778 continue;
11779
11780 SemaRef.LookupQualifiedName(R, DC);
11781
11782 if (!R.empty()) {
11783 R.suppressDiagnostics();
11784
11785 if (isa<CXXRecordDecl>(DC)) {
11786 // Don't diagnose names we find in classes; we get much better
11787 // diagnostics for these from DiagnoseEmptyLookup.
11788 R.clear();
11789 if (DoDiagnoseEmptyLookup)
11790 *DoDiagnoseEmptyLookup = true;
11791 return false;
11792 }
11793
11794 OverloadCandidateSet Candidates(FnLoc, CSK);
11795 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11796 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11797 ExplicitTemplateArgs, Args,
11798 Candidates, false, /*KnownValid*/ false);
11799
11800 OverloadCandidateSet::iterator Best;
11801 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11802 // No viable functions. Don't bother the user with notes for functions
11803 // which don't work and shouldn't be found anyway.
11804 R.clear();
11805 return false;
11806 }
11807
11808 // Find the namespaces where ADL would have looked, and suggest
11809 // declaring the function there instead.
11810 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11811 Sema::AssociatedClassSet AssociatedClasses;
11812 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11813 AssociatedNamespaces,
11814 AssociatedClasses);
11815 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11816 if (canBeDeclaredInNamespace(R.getLookupName())) {
11817 DeclContext *Std = SemaRef.getStdNamespace();
11818 for (Sema::AssociatedNamespaceSet::iterator
11819 it = AssociatedNamespaces.begin(),
11820 end = AssociatedNamespaces.end(); it != end; ++it) {
11821 // Never suggest declaring a function within namespace 'std'.
11822 if (Std && Std->Encloses(*it))
11823 continue;
11824
11825 // Never suggest declaring a function within a namespace with a
11826 // reserved name, like __gnu_cxx.
11827 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11828 if (NS &&
11829 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11830 continue;
11831
11832 SuggestedNamespaces.insert(*it);
11833 }
11834 }
11835
11836 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11837 << R.getLookupName();
11838 if (SuggestedNamespaces.empty()) {
11839 SemaRef.Diag(Best->Function->getLocation(),
11840 diag::note_not_found_by_two_phase_lookup)
11841 << R.getLookupName() << 0;
11842 } else if (SuggestedNamespaces.size() == 1) {
11843 SemaRef.Diag(Best->Function->getLocation(),
11844 diag::note_not_found_by_two_phase_lookup)
11845 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11846 } else {
11847 // FIXME: It would be useful to list the associated namespaces here,
11848 // but the diagnostics infrastructure doesn't provide a way to produce
11849 // a localized representation of a list of items.
11850 SemaRef.Diag(Best->Function->getLocation(),
11851 diag::note_not_found_by_two_phase_lookup)
11852 << R.getLookupName() << 2;
11853 }
11854
11855 // Try to recover by calling this function.
11856 return true;
11857 }
11858
11859 R.clear();
11860 }
11861
11862 return false;
11863 }
11864
11865 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11866 /// template, where the non-dependent operator was declared after the template
11867 /// was defined.
11868 ///
11869 /// Returns true if a viable candidate was found and a diagnostic was issued.
11870 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)11871 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11872 SourceLocation OpLoc,
11873 ArrayRef<Expr *> Args) {
11874 DeclarationName OpName =
11875 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11876 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11877 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11878 OverloadCandidateSet::CSK_Operator,
11879 /*ExplicitTemplateArgs=*/nullptr, Args);
11880 }
11881
11882 namespace {
11883 class BuildRecoveryCallExprRAII {
11884 Sema &SemaRef;
11885 public:
BuildRecoveryCallExprRAII(Sema & S)11886 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11887 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11888 SemaRef.IsBuildingRecoveryCallExpr = true;
11889 }
11890
~BuildRecoveryCallExprRAII()11891 ~BuildRecoveryCallExprRAII() {
11892 SemaRef.IsBuildingRecoveryCallExpr = false;
11893 }
11894 };
11895
11896 }
11897
11898 static std::unique_ptr<CorrectionCandidateCallback>
MakeValidator(Sema & SemaRef,MemberExpr * ME,size_t NumArgs,bool HasTemplateArgs,bool AllowTypoCorrection)11899 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11900 bool HasTemplateArgs, bool AllowTypoCorrection) {
11901 if (!AllowTypoCorrection)
11902 return llvm::make_unique<NoTypoCorrectionCCC>();
11903 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11904 HasTemplateArgs, ME);
11905 }
11906
11907 /// Attempts to recover from a call where no functions were found.
11908 ///
11909 /// Returns true if new candidates were found.
11910 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)11911 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11912 UnresolvedLookupExpr *ULE,
11913 SourceLocation LParenLoc,
11914 MutableArrayRef<Expr *> Args,
11915 SourceLocation RParenLoc,
11916 bool EmptyLookup, bool AllowTypoCorrection) {
11917 // Do not try to recover if it is already building a recovery call.
11918 // This stops infinite loops for template instantiations like
11919 //
11920 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11921 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11922 //
11923 if (SemaRef.IsBuildingRecoveryCallExpr)
11924 return ExprError();
11925 BuildRecoveryCallExprRAII RCE(SemaRef);
11926
11927 CXXScopeSpec SS;
11928 SS.Adopt(ULE->getQualifierLoc());
11929 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11930
11931 TemplateArgumentListInfo TABuffer;
11932 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11933 if (ULE->hasExplicitTemplateArgs()) {
11934 ULE->copyTemplateArgumentsInto(TABuffer);
11935 ExplicitTemplateArgs = &TABuffer;
11936 }
11937
11938 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11939 Sema::LookupOrdinaryName);
11940 bool DoDiagnoseEmptyLookup = EmptyLookup;
11941 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11942 OverloadCandidateSet::CSK_Normal,
11943 ExplicitTemplateArgs, Args,
11944 &DoDiagnoseEmptyLookup) &&
11945 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11946 S, SS, R,
11947 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11948 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11949 ExplicitTemplateArgs, Args)))
11950 return ExprError();
11951
11952 assert(!R.empty() && "lookup results empty despite recovery");
11953
11954 // If recovery created an ambiguity, just bail out.
11955 if (R.isAmbiguous()) {
11956 R.suppressDiagnostics();
11957 return ExprError();
11958 }
11959
11960 // Build an implicit member call if appropriate. Just drop the
11961 // casts and such from the call, we don't really care.
11962 ExprResult NewFn = ExprError();
11963 if ((*R.begin())->isCXXClassMember())
11964 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11965 ExplicitTemplateArgs, S);
11966 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11967 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11968 ExplicitTemplateArgs);
11969 else
11970 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11971
11972 if (NewFn.isInvalid())
11973 return ExprError();
11974
11975 // This shouldn't cause an infinite loop because we're giving it
11976 // an expression with viable lookup results, which should never
11977 // end up here.
11978 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11979 MultiExprArg(Args.data(), Args.size()),
11980 RParenLoc);
11981 }
11982
11983 /// Constructs and populates an OverloadedCandidateSet from
11984 /// the given function.
11985 /// \returns true when an the ExprResult output parameter has been set.
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,MultiExprArg Args,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)11986 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11987 UnresolvedLookupExpr *ULE,
11988 MultiExprArg Args,
11989 SourceLocation RParenLoc,
11990 OverloadCandidateSet *CandidateSet,
11991 ExprResult *Result) {
11992 #ifndef NDEBUG
11993 if (ULE->requiresADL()) {
11994 // To do ADL, we must have found an unqualified name.
11995 assert(!ULE->getQualifier() && "qualified name with ADL");
11996
11997 // We don't perform ADL for implicit declarations of builtins.
11998 // Verify that this was correctly set up.
11999 FunctionDecl *F;
12000 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
12001 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12002 F->getBuiltinID() && F->isImplicit())
12003 llvm_unreachable("performing ADL for builtin");
12004
12005 // We don't perform ADL in C.
12006 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12007 }
12008 #endif
12009
12010 UnbridgedCastsSet UnbridgedCasts;
12011 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12012 *Result = ExprError();
12013 return true;
12014 }
12015
12016 // Add the functions denoted by the callee to the set of candidate
12017 // functions, including those from argument-dependent lookup.
12018 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12019
12020 if (getLangOpts().MSVCCompat &&
12021 CurContext->isDependentContext() && !isSFINAEContext() &&
12022 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12023
12024 OverloadCandidateSet::iterator Best;
12025 if (CandidateSet->empty() ||
12026 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12027 OR_No_Viable_Function) {
12028 // In Microsoft mode, if we are inside a template class member function
12029 // then create a type dependent CallExpr. The goal is to postpone name
12030 // lookup to instantiation time to be able to search into type dependent
12031 // base classes.
12032 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12033 VK_RValue, RParenLoc);
12034 CE->setTypeDependent(true);
12035 CE->setValueDependent(true);
12036 CE->setInstantiationDependent(true);
12037 *Result = CE;
12038 return true;
12039 }
12040 }
12041
12042 if (CandidateSet->empty())
12043 return false;
12044
12045 UnbridgedCasts.restore();
12046 return false;
12047 }
12048
12049 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12050 /// the completed call expression. If overload resolution fails, emits
12051 /// diagnostics and returns ExprError()
FinishOverloadedCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,OverloadCandidateSet * CandidateSet,OverloadCandidateSet::iterator * Best,OverloadingResult OverloadResult,bool AllowTypoCorrection)12052 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12053 UnresolvedLookupExpr *ULE,
12054 SourceLocation LParenLoc,
12055 MultiExprArg Args,
12056 SourceLocation RParenLoc,
12057 Expr *ExecConfig,
12058 OverloadCandidateSet *CandidateSet,
12059 OverloadCandidateSet::iterator *Best,
12060 OverloadingResult OverloadResult,
12061 bool AllowTypoCorrection) {
12062 if (CandidateSet->empty())
12063 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12064 RParenLoc, /*EmptyLookup=*/true,
12065 AllowTypoCorrection);
12066
12067 switch (OverloadResult) {
12068 case OR_Success: {
12069 FunctionDecl *FDecl = (*Best)->Function;
12070 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12071 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12072 return ExprError();
12073 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12074 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12075 ExecConfig, /*IsExecConfig=*/false,
12076 (*Best)->IsADLCandidate);
12077 }
12078
12079 case OR_No_Viable_Function: {
12080 // Try to recover by looking for viable functions which the user might
12081 // have meant to call.
12082 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12083 Args, RParenLoc,
12084 /*EmptyLookup=*/false,
12085 AllowTypoCorrection);
12086 if (!Recovery.isInvalid())
12087 return Recovery;
12088
12089 // If the user passes in a function that we can't take the address of, we
12090 // generally end up emitting really bad error messages. Here, we attempt to
12091 // emit better ones.
12092 for (const Expr *Arg : Args) {
12093 if (!Arg->getType()->isFunctionType())
12094 continue;
12095 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12096 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12097 if (FD &&
12098 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12099 Arg->getExprLoc()))
12100 return ExprError();
12101 }
12102 }
12103
12104 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12105 << ULE->getName() << Fn->getSourceRange();
12106 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12107 break;
12108 }
12109
12110 case OR_Ambiguous:
12111 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12112 << ULE->getName() << Fn->getSourceRange();
12113 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12114 break;
12115
12116 case OR_Deleted: {
12117 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12118 << (*Best)->Function->isDeleted() << ULE->getName()
12119 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12120 << Fn->getSourceRange();
12121 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12122
12123 // We emitted an error for the unavailable/deleted function call but keep
12124 // the call in the AST.
12125 FunctionDecl *FDecl = (*Best)->Function;
12126 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12127 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12128 ExecConfig, /*IsExecConfig=*/false,
12129 (*Best)->IsADLCandidate);
12130 }
12131 }
12132
12133 // Overload resolution failed.
12134 return ExprError();
12135 }
12136
markUnaddressableCandidatesUnviable(Sema & S,OverloadCandidateSet & CS)12137 static void markUnaddressableCandidatesUnviable(Sema &S,
12138 OverloadCandidateSet &CS) {
12139 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12140 if (I->Viable &&
12141 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12142 I->Viable = false;
12143 I->FailureKind = ovl_fail_addr_not_available;
12144 }
12145 }
12146 }
12147
12148 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12149 /// (which eventually refers to the declaration Func) and the call
12150 /// arguments Args/NumArgs, attempt to resolve the function call down
12151 /// to a specific function. If overload resolution succeeds, returns
12152 /// the call expression produced by overload resolution.
12153 /// Otherwise, emits diagnostics and returns ExprError.
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection,bool CalleesAddressIsTaken)12154 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12155 UnresolvedLookupExpr *ULE,
12156 SourceLocation LParenLoc,
12157 MultiExprArg Args,
12158 SourceLocation RParenLoc,
12159 Expr *ExecConfig,
12160 bool AllowTypoCorrection,
12161 bool CalleesAddressIsTaken) {
12162 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12163 OverloadCandidateSet::CSK_Normal);
12164 ExprResult result;
12165
12166 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12167 &result))
12168 return result;
12169
12170 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12171 // functions that aren't addressible are considered unviable.
12172 if (CalleesAddressIsTaken)
12173 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12174
12175 OverloadCandidateSet::iterator Best;
12176 OverloadingResult OverloadResult =
12177 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12178
12179 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12180 RParenLoc, ExecConfig, &CandidateSet,
12181 &Best, OverloadResult,
12182 AllowTypoCorrection);
12183 }
12184
IsOverloaded(const UnresolvedSetImpl & Functions)12185 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12186 return Functions.size() > 1 ||
12187 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12188 }
12189
12190 /// Create a unary operation that may resolve to an overloaded
12191 /// operator.
12192 ///
12193 /// \param OpLoc The location of the operator itself (e.g., '*').
12194 ///
12195 /// \param Opc The UnaryOperatorKind that describes this operator.
12196 ///
12197 /// \param Fns The set of non-member functions that will be
12198 /// considered by overload resolution. The caller needs to build this
12199 /// set based on the context using, e.g.,
12200 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12201 /// set should not contain any member functions; those will be added
12202 /// by CreateOverloadedUnaryOp().
12203 ///
12204 /// \param Input The input argument.
12205 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * Input,bool PerformADL)12206 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12207 const UnresolvedSetImpl &Fns,
12208 Expr *Input, bool PerformADL) {
12209 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12210 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12211 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12212 // TODO: provide better source location info.
12213 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12214
12215 if (checkPlaceholderForOverload(*this, Input))
12216 return ExprError();
12217
12218 Expr *Args[2] = { Input, nullptr };
12219 unsigned NumArgs = 1;
12220
12221 // For post-increment and post-decrement, add the implicit '0' as
12222 // the second argument, so that we know this is a post-increment or
12223 // post-decrement.
12224 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12225 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12226 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12227 SourceLocation());
12228 NumArgs = 2;
12229 }
12230
12231 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12232
12233 if (Input->isTypeDependent()) {
12234 if (Fns.empty())
12235 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12236 VK_RValue, OK_Ordinary, OpLoc, false);
12237
12238 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12239 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12240 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12241 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12242 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12243 Context.DependentTy, VK_RValue, OpLoc,
12244 FPOptions());
12245 }
12246
12247 // Build an empty overload set.
12248 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12249
12250 // Add the candidates from the given function set.
12251 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12252
12253 // Add operator candidates that are member functions.
12254 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12255
12256 // Add candidates from ADL.
12257 if (PerformADL) {
12258 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12259 /*ExplicitTemplateArgs*/nullptr,
12260 CandidateSet);
12261 }
12262
12263 // Add builtin operator candidates.
12264 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12265
12266 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12267
12268 // Perform overload resolution.
12269 OverloadCandidateSet::iterator Best;
12270 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12271 case OR_Success: {
12272 // We found a built-in operator or an overloaded operator.
12273 FunctionDecl *FnDecl = Best->Function;
12274
12275 if (FnDecl) {
12276 Expr *Base = nullptr;
12277 // We matched an overloaded operator. Build a call to that
12278 // operator.
12279
12280 // Convert the arguments.
12281 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12282 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12283
12284 ExprResult InputRes =
12285 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12286 Best->FoundDecl, Method);
12287 if (InputRes.isInvalid())
12288 return ExprError();
12289 Base = Input = InputRes.get();
12290 } else {
12291 // Convert the arguments.
12292 ExprResult InputInit
12293 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12294 Context,
12295 FnDecl->getParamDecl(0)),
12296 SourceLocation(),
12297 Input);
12298 if (InputInit.isInvalid())
12299 return ExprError();
12300 Input = InputInit.get();
12301 }
12302
12303 // Build the actual expression node.
12304 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12305 Base, HadMultipleCandidates,
12306 OpLoc);
12307 if (FnExpr.isInvalid())
12308 return ExprError();
12309
12310 // Determine the result type.
12311 QualType ResultTy = FnDecl->getReturnType();
12312 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12313 ResultTy = ResultTy.getNonLValueExprType(Context);
12314
12315 Args[0] = Input;
12316 CallExpr *TheCall = CXXOperatorCallExpr::Create(
12317 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12318 FPOptions(), Best->IsADLCandidate);
12319
12320 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12321 return ExprError();
12322
12323 if (CheckFunctionCall(FnDecl, TheCall,
12324 FnDecl->getType()->castAs<FunctionProtoType>()))
12325 return ExprError();
12326
12327 return MaybeBindToTemporary(TheCall);
12328 } else {
12329 // We matched a built-in operator. Convert the arguments, then
12330 // break out so that we will build the appropriate built-in
12331 // operator node.
12332 ExprResult InputRes = PerformImplicitConversion(
12333 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12334 CCK_ForBuiltinOverloadedOp);
12335 if (InputRes.isInvalid())
12336 return ExprError();
12337 Input = InputRes.get();
12338 break;
12339 }
12340 }
12341
12342 case OR_No_Viable_Function:
12343 // This is an erroneous use of an operator which can be overloaded by
12344 // a non-member function. Check for non-member operators which were
12345 // defined too late to be candidates.
12346 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12347 // FIXME: Recover by calling the found function.
12348 return ExprError();
12349
12350 // No viable function; fall through to handling this as a
12351 // built-in operator, which will produce an error message for us.
12352 break;
12353
12354 case OR_Ambiguous:
12355 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12356 << UnaryOperator::getOpcodeStr(Opc)
12357 << Input->getType()
12358 << Input->getSourceRange();
12359 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12360 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12361 return ExprError();
12362
12363 case OR_Deleted:
12364 Diag(OpLoc, diag::err_ovl_deleted_oper)
12365 << Best->Function->isDeleted()
12366 << UnaryOperator::getOpcodeStr(Opc)
12367 << getDeletedOrUnavailableSuffix(Best->Function)
12368 << Input->getSourceRange();
12369 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12370 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12371 return ExprError();
12372 }
12373
12374 // Either we found no viable overloaded operator or we matched a
12375 // built-in operator. In either case, fall through to trying to
12376 // build a built-in operation.
12377 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12378 }
12379
12380 /// Create a binary operation that may resolve to an overloaded
12381 /// operator.
12382 ///
12383 /// \param OpLoc The location of the operator itself (e.g., '+').
12384 ///
12385 /// \param Opc The BinaryOperatorKind that describes this operator.
12386 ///
12387 /// \param Fns The set of non-member functions that will be
12388 /// considered by overload resolution. The caller needs to build this
12389 /// set based on the context using, e.g.,
12390 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12391 /// set should not contain any member functions; those will be added
12392 /// by CreateOverloadedBinOp().
12393 ///
12394 /// \param LHS Left-hand argument.
12395 /// \param RHS Right-hand argument.
12396 ExprResult
CreateOverloadedBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,bool PerformADL)12397 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12398 BinaryOperatorKind Opc,
12399 const UnresolvedSetImpl &Fns,
12400 Expr *LHS, Expr *RHS, bool PerformADL) {
12401 Expr *Args[2] = { LHS, RHS };
12402 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12403
12404 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12405 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12406
12407 // If either side is type-dependent, create an appropriate dependent
12408 // expression.
12409 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12410 if (Fns.empty()) {
12411 // If there are no functions to store, just build a dependent
12412 // BinaryOperator or CompoundAssignment.
12413 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12414 return new (Context) BinaryOperator(
12415 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12416 OpLoc, FPFeatures);
12417
12418 return new (Context) CompoundAssignOperator(
12419 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12420 Context.DependentTy, Context.DependentTy, OpLoc,
12421 FPFeatures);
12422 }
12423
12424 // FIXME: save results of ADL from here?
12425 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12426 // TODO: provide better source location info in DNLoc component.
12427 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12428 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12429 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12430 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12431 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12432 Context.DependentTy, VK_RValue, OpLoc,
12433 FPFeatures);
12434 }
12435
12436 // Always do placeholder-like conversions on the RHS.
12437 if (checkPlaceholderForOverload(*this, Args[1]))
12438 return ExprError();
12439
12440 // Do placeholder-like conversion on the LHS; note that we should
12441 // not get here with a PseudoObject LHS.
12442 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12443 if (checkPlaceholderForOverload(*this, Args[0]))
12444 return ExprError();
12445
12446 // If this is the assignment operator, we only perform overload resolution
12447 // if the left-hand side is a class or enumeration type. This is actually
12448 // a hack. The standard requires that we do overload resolution between the
12449 // various built-in candidates, but as DR507 points out, this can lead to
12450 // problems. So we do it this way, which pretty much follows what GCC does.
12451 // Note that we go the traditional code path for compound assignment forms.
12452 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12453 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12454
12455 // If this is the .* operator, which is not overloadable, just
12456 // create a built-in binary operator.
12457 if (Opc == BO_PtrMemD)
12458 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12459
12460 // Build an empty overload set.
12461 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12462
12463 // Add the candidates from the given function set.
12464 AddFunctionCandidates(Fns, Args, CandidateSet);
12465
12466 // Add operator candidates that are member functions.
12467 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12468
12469 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12470 // performed for an assignment operator (nor for operator[] nor operator->,
12471 // which don't get here).
12472 if (Opc != BO_Assign && PerformADL)
12473 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12474 /*ExplicitTemplateArgs*/ nullptr,
12475 CandidateSet);
12476
12477 // Add builtin operator candidates.
12478 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12479
12480 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12481
12482 // Perform overload resolution.
12483 OverloadCandidateSet::iterator Best;
12484 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12485 case OR_Success: {
12486 // We found a built-in operator or an overloaded operator.
12487 FunctionDecl *FnDecl = Best->Function;
12488
12489 if (FnDecl) {
12490 Expr *Base = nullptr;
12491 // We matched an overloaded operator. Build a call to that
12492 // operator.
12493
12494 // Convert the arguments.
12495 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12496 // Best->Access is only meaningful for class members.
12497 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12498
12499 ExprResult Arg1 =
12500 PerformCopyInitialization(
12501 InitializedEntity::InitializeParameter(Context,
12502 FnDecl->getParamDecl(0)),
12503 SourceLocation(), Args[1]);
12504 if (Arg1.isInvalid())
12505 return ExprError();
12506
12507 ExprResult Arg0 =
12508 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12509 Best->FoundDecl, Method);
12510 if (Arg0.isInvalid())
12511 return ExprError();
12512 Base = Args[0] = Arg0.getAs<Expr>();
12513 Args[1] = RHS = Arg1.getAs<Expr>();
12514 } else {
12515 // Convert the arguments.
12516 ExprResult Arg0 = PerformCopyInitialization(
12517 InitializedEntity::InitializeParameter(Context,
12518 FnDecl->getParamDecl(0)),
12519 SourceLocation(), Args[0]);
12520 if (Arg0.isInvalid())
12521 return ExprError();
12522
12523 ExprResult Arg1 =
12524 PerformCopyInitialization(
12525 InitializedEntity::InitializeParameter(Context,
12526 FnDecl->getParamDecl(1)),
12527 SourceLocation(), Args[1]);
12528 if (Arg1.isInvalid())
12529 return ExprError();
12530 Args[0] = LHS = Arg0.getAs<Expr>();
12531 Args[1] = RHS = Arg1.getAs<Expr>();
12532 }
12533
12534 // Build the actual expression node.
12535 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12536 Best->FoundDecl, Base,
12537 HadMultipleCandidates, OpLoc);
12538 if (FnExpr.isInvalid())
12539 return ExprError();
12540
12541 // Determine the result type.
12542 QualType ResultTy = FnDecl->getReturnType();
12543 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12544 ResultTy = ResultTy.getNonLValueExprType(Context);
12545
12546 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12547 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12548 Best->IsADLCandidate);
12549
12550 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12551 FnDecl))
12552 return ExprError();
12553
12554 ArrayRef<const Expr *> ArgsArray(Args, 2);
12555 const Expr *ImplicitThis = nullptr;
12556 // Cut off the implicit 'this'.
12557 if (isa<CXXMethodDecl>(FnDecl)) {
12558 ImplicitThis = ArgsArray[0];
12559 ArgsArray = ArgsArray.slice(1);
12560 }
12561
12562 // Check for a self move.
12563 if (Op == OO_Equal)
12564 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12565
12566 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12567 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12568 VariadicDoesNotApply);
12569
12570 return MaybeBindToTemporary(TheCall);
12571 } else {
12572 // We matched a built-in operator. Convert the arguments, then
12573 // break out so that we will build the appropriate built-in
12574 // operator node.
12575 ExprResult ArgsRes0 = PerformImplicitConversion(
12576 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12577 AA_Passing, CCK_ForBuiltinOverloadedOp);
12578 if (ArgsRes0.isInvalid())
12579 return ExprError();
12580 Args[0] = ArgsRes0.get();
12581
12582 ExprResult ArgsRes1 = PerformImplicitConversion(
12583 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12584 AA_Passing, CCK_ForBuiltinOverloadedOp);
12585 if (ArgsRes1.isInvalid())
12586 return ExprError();
12587 Args[1] = ArgsRes1.get();
12588 break;
12589 }
12590 }
12591
12592 case OR_No_Viable_Function: {
12593 // C++ [over.match.oper]p9:
12594 // If the operator is the operator , [...] and there are no
12595 // viable functions, then the operator is assumed to be the
12596 // built-in operator and interpreted according to clause 5.
12597 if (Opc == BO_Comma)
12598 break;
12599
12600 // For class as left operand for assignment or compound assignment
12601 // operator do not fall through to handling in built-in, but report that
12602 // no overloaded assignment operator found
12603 ExprResult Result = ExprError();
12604 if (Args[0]->getType()->isRecordType() &&
12605 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12606 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12607 << BinaryOperator::getOpcodeStr(Opc)
12608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12609 if (Args[0]->getType()->isIncompleteType()) {
12610 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12611 << Args[0]->getType()
12612 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12613 }
12614 } else {
12615 // This is an erroneous use of an operator which can be overloaded by
12616 // a non-member function. Check for non-member operators which were
12617 // defined too late to be candidates.
12618 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12619 // FIXME: Recover by calling the found function.
12620 return ExprError();
12621
12622 // No viable function; try to create a built-in operation, which will
12623 // produce an error. Then, show the non-viable candidates.
12624 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12625 }
12626 assert(Result.isInvalid() &&
12627 "C++ binary operator overloading is missing candidates!");
12628 if (Result.isInvalid())
12629 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12630 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12631 return Result;
12632 }
12633
12634 case OR_Ambiguous:
12635 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12636 << BinaryOperator::getOpcodeStr(Opc)
12637 << Args[0]->getType() << Args[1]->getType()
12638 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12639 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12640 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12641 return ExprError();
12642
12643 case OR_Deleted:
12644 if (isImplicitlyDeleted(Best->Function)) {
12645 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12646 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12647 << Context.getRecordType(Method->getParent())
12648 << getSpecialMember(Method);
12649
12650 // The user probably meant to call this special member. Just
12651 // explain why it's deleted.
12652 NoteDeletedFunction(Method);
12653 return ExprError();
12654 } else {
12655 Diag(OpLoc, diag::err_ovl_deleted_oper)
12656 << Best->Function->isDeleted()
12657 << BinaryOperator::getOpcodeStr(Opc)
12658 << getDeletedOrUnavailableSuffix(Best->Function)
12659 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12660 }
12661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12662 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12663 return ExprError();
12664 }
12665
12666 // We matched a built-in operator; build it.
12667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12668 }
12669
12670 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)12671 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12672 SourceLocation RLoc,
12673 Expr *Base, Expr *Idx) {
12674 Expr *Args[2] = { Base, Idx };
12675 DeclarationName OpName =
12676 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12677
12678 // If either side is type-dependent, create an appropriate dependent
12679 // expression.
12680 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12681
12682 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12683 // CHECKME: no 'operator' keyword?
12684 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12685 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12686 UnresolvedLookupExpr *Fn
12687 = UnresolvedLookupExpr::Create(Context, NamingClass,
12688 NestedNameSpecifierLoc(), OpNameInfo,
12689 /*ADL*/ true, /*Overloaded*/ false,
12690 UnresolvedSetIterator(),
12691 UnresolvedSetIterator());
12692 // Can't add any actual overloads yet
12693
12694 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12695 Context.DependentTy, VK_RValue, RLoc,
12696 FPOptions());
12697 }
12698
12699 // Handle placeholders on both operands.
12700 if (checkPlaceholderForOverload(*this, Args[0]))
12701 return ExprError();
12702 if (checkPlaceholderForOverload(*this, Args[1]))
12703 return ExprError();
12704
12705 // Build an empty overload set.
12706 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12707
12708 // Subscript can only be overloaded as a member function.
12709
12710 // Add operator candidates that are member functions.
12711 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12712
12713 // Add builtin operator candidates.
12714 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12715
12716 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12717
12718 // Perform overload resolution.
12719 OverloadCandidateSet::iterator Best;
12720 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12721 case OR_Success: {
12722 // We found a built-in operator or an overloaded operator.
12723 FunctionDecl *FnDecl = Best->Function;
12724
12725 if (FnDecl) {
12726 // We matched an overloaded operator. Build a call to that
12727 // operator.
12728
12729 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12730
12731 // Convert the arguments.
12732 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12733 ExprResult Arg0 =
12734 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12735 Best->FoundDecl, Method);
12736 if (Arg0.isInvalid())
12737 return ExprError();
12738 Args[0] = Arg0.get();
12739
12740 // Convert the arguments.
12741 ExprResult InputInit
12742 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12743 Context,
12744 FnDecl->getParamDecl(0)),
12745 SourceLocation(),
12746 Args[1]);
12747 if (InputInit.isInvalid())
12748 return ExprError();
12749
12750 Args[1] = InputInit.getAs<Expr>();
12751
12752 // Build the actual expression node.
12753 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12754 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12755 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12756 Best->FoundDecl,
12757 Base,
12758 HadMultipleCandidates,
12759 OpLocInfo.getLoc(),
12760 OpLocInfo.getInfo());
12761 if (FnExpr.isInvalid())
12762 return ExprError();
12763
12764 // Determine the result type
12765 QualType ResultTy = FnDecl->getReturnType();
12766 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12767 ResultTy = ResultTy.getNonLValueExprType(Context);
12768
12769 CXXOperatorCallExpr *TheCall =
12770 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12771 Args, ResultTy, VK, RLoc, FPOptions());
12772
12773 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12774 return ExprError();
12775
12776 if (CheckFunctionCall(Method, TheCall,
12777 Method->getType()->castAs<FunctionProtoType>()))
12778 return ExprError();
12779
12780 return MaybeBindToTemporary(TheCall);
12781 } else {
12782 // We matched a built-in operator. Convert the arguments, then
12783 // break out so that we will build the appropriate built-in
12784 // operator node.
12785 ExprResult ArgsRes0 = PerformImplicitConversion(
12786 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12787 AA_Passing, CCK_ForBuiltinOverloadedOp);
12788 if (ArgsRes0.isInvalid())
12789 return ExprError();
12790 Args[0] = ArgsRes0.get();
12791
12792 ExprResult ArgsRes1 = PerformImplicitConversion(
12793 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12794 AA_Passing, CCK_ForBuiltinOverloadedOp);
12795 if (ArgsRes1.isInvalid())
12796 return ExprError();
12797 Args[1] = ArgsRes1.get();
12798
12799 break;
12800 }
12801 }
12802
12803 case OR_No_Viable_Function: {
12804 if (CandidateSet.empty())
12805 Diag(LLoc, diag::err_ovl_no_oper)
12806 << Args[0]->getType() << /*subscript*/ 0
12807 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12808 else
12809 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12810 << Args[0]->getType()
12811 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12812 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12813 "[]", LLoc);
12814 return ExprError();
12815 }
12816
12817 case OR_Ambiguous:
12818 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12819 << "[]"
12820 << Args[0]->getType() << Args[1]->getType()
12821 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12822 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12823 "[]", LLoc);
12824 return ExprError();
12825
12826 case OR_Deleted:
12827 Diag(LLoc, diag::err_ovl_deleted_oper)
12828 << Best->Function->isDeleted() << "[]"
12829 << getDeletedOrUnavailableSuffix(Best->Function)
12830 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12831 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12832 "[]", LLoc);
12833 return ExprError();
12834 }
12835
12836 // We matched a built-in operator; build it.
12837 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12838 }
12839
12840 /// BuildCallToMemberFunction - Build a call to a member
12841 /// function. MemExpr is the expression that refers to the member
12842 /// function (and includes the object parameter), Args/NumArgs are the
12843 /// arguments to the function call (not including the object
12844 /// parameter). The caller needs to validate that the member
12845 /// expression refers to a non-static member function or an overloaded
12846 /// member function.
12847 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)12848 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12849 SourceLocation LParenLoc,
12850 MultiExprArg Args,
12851 SourceLocation RParenLoc) {
12852 assert(MemExprE->getType() == Context.BoundMemberTy ||
12853 MemExprE->getType() == Context.OverloadTy);
12854
12855 // Dig out the member expression. This holds both the object
12856 // argument and the member function we're referring to.
12857 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12858
12859 // Determine whether this is a call to a pointer-to-member function.
12860 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12861 assert(op->getType() == Context.BoundMemberTy);
12862 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12863
12864 QualType fnType =
12865 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12866
12867 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12868 QualType resultType = proto->getCallResultType(Context);
12869 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12870
12871 // Check that the object type isn't more qualified than the
12872 // member function we're calling.
12873 Qualifiers funcQuals = proto->getTypeQuals();
12874
12875 QualType objectType = op->getLHS()->getType();
12876 if (op->getOpcode() == BO_PtrMemI)
12877 objectType = objectType->castAs<PointerType>()->getPointeeType();
12878 Qualifiers objectQuals = objectType.getQualifiers();
12879
12880 Qualifiers difference = objectQuals - funcQuals;
12881 difference.removeObjCGCAttr();
12882 difference.removeAddressSpace();
12883 if (difference) {
12884 std::string qualsString = difference.getAsString();
12885 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12886 << fnType.getUnqualifiedType()
12887 << qualsString
12888 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12889 }
12890
12891 CXXMemberCallExpr *call =
12892 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12893 valueKind, RParenLoc, proto->getNumParams());
12894
12895 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12896 call, nullptr))
12897 return ExprError();
12898
12899 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12900 return ExprError();
12901
12902 if (CheckOtherCall(call, proto))
12903 return ExprError();
12904
12905 return MaybeBindToTemporary(call);
12906 }
12907
12908 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12909 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
12910 RParenLoc);
12911
12912 UnbridgedCastsSet UnbridgedCasts;
12913 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12914 return ExprError();
12915
12916 MemberExpr *MemExpr;
12917 CXXMethodDecl *Method = nullptr;
12918 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12919 NestedNameSpecifier *Qualifier = nullptr;
12920 if (isa<MemberExpr>(NakedMemExpr)) {
12921 MemExpr = cast<MemberExpr>(NakedMemExpr);
12922 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12923 FoundDecl = MemExpr->getFoundDecl();
12924 Qualifier = MemExpr->getQualifier();
12925 UnbridgedCasts.restore();
12926 } else {
12927 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12928 Qualifier = UnresExpr->getQualifier();
12929
12930 QualType ObjectType = UnresExpr->getBaseType();
12931 Expr::Classification ObjectClassification
12932 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12933 : UnresExpr->getBase()->Classify(Context);
12934
12935 // Add overload candidates
12936 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12937 OverloadCandidateSet::CSK_Normal);
12938
12939 // FIXME: avoid copy.
12940 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12941 if (UnresExpr->hasExplicitTemplateArgs()) {
12942 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12943 TemplateArgs = &TemplateArgsBuffer;
12944 }
12945
12946 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12947 E = UnresExpr->decls_end(); I != E; ++I) {
12948
12949 NamedDecl *Func = *I;
12950 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12951 if (isa<UsingShadowDecl>(Func))
12952 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12953
12954
12955 // Microsoft supports direct constructor calls.
12956 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12957 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12958 Args, CandidateSet);
12959 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12960 // If explicit template arguments were provided, we can't call a
12961 // non-template member function.
12962 if (TemplateArgs)
12963 continue;
12964
12965 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12966 ObjectClassification, Args, CandidateSet,
12967 /*SuppressUserConversions=*/false);
12968 } else {
12969 AddMethodTemplateCandidate(
12970 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12971 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12972 /*SuppressUsedConversions=*/false);
12973 }
12974 }
12975
12976 DeclarationName DeclName = UnresExpr->getMemberName();
12977
12978 UnbridgedCasts.restore();
12979
12980 OverloadCandidateSet::iterator Best;
12981 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12982 Best)) {
12983 case OR_Success:
12984 Method = cast<CXXMethodDecl>(Best->Function);
12985 FoundDecl = Best->FoundDecl;
12986 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12987 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12988 return ExprError();
12989 // If FoundDecl is different from Method (such as if one is a template
12990 // and the other a specialization), make sure DiagnoseUseOfDecl is
12991 // called on both.
12992 // FIXME: This would be more comprehensively addressed by modifying
12993 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12994 // being used.
12995 if (Method != FoundDecl.getDecl() &&
12996 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12997 return ExprError();
12998 break;
12999
13000 case OR_No_Viable_Function:
13001 Diag(UnresExpr->getMemberLoc(),
13002 diag::err_ovl_no_viable_member_function_in_call)
13003 << DeclName << MemExprE->getSourceRange();
13004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13005 // FIXME: Leaking incoming expressions!
13006 return ExprError();
13007
13008 case OR_Ambiguous:
13009 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
13010 << DeclName << MemExprE->getSourceRange();
13011 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13012 // FIXME: Leaking incoming expressions!
13013 return ExprError();
13014
13015 case OR_Deleted:
13016 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
13017 << Best->Function->isDeleted()
13018 << DeclName
13019 << getDeletedOrUnavailableSuffix(Best->Function)
13020 << MemExprE->getSourceRange();
13021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13022 // FIXME: Leaking incoming expressions!
13023 return ExprError();
13024 }
13025
13026 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13027
13028 // If overload resolution picked a static member, build a
13029 // non-member call based on that function.
13030 if (Method->isStatic()) {
13031 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13032 RParenLoc);
13033 }
13034
13035 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13036 }
13037
13038 QualType ResultType = Method->getReturnType();
13039 ExprValueKind VK = Expr::getValueKindForType(ResultType);
13040 ResultType = ResultType.getNonLValueExprType(Context);
13041
13042 assert(Method && "Member call to something that isn't a method?");
13043 const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13044 CXXMemberCallExpr *TheCall =
13045 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13046 RParenLoc, Proto->getNumParams());
13047
13048 // Check for a valid return type.
13049 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13050 TheCall, Method))
13051 return ExprError();
13052
13053 // Convert the object argument (for a non-static member function call).
13054 // We only need to do this if there was actually an overload; otherwise
13055 // it was done at lookup.
13056 if (!Method->isStatic()) {
13057 ExprResult ObjectArg =
13058 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13059 FoundDecl, Method);
13060 if (ObjectArg.isInvalid())
13061 return ExprError();
13062 MemExpr->setBase(ObjectArg.get());
13063 }
13064
13065 // Convert the rest of the arguments
13066 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13067 RParenLoc))
13068 return ExprError();
13069
13070 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13071
13072 if (CheckFunctionCall(Method, TheCall, Proto))
13073 return ExprError();
13074
13075 // In the case the method to call was not selected by the overloading
13076 // resolution process, we still need to handle the enable_if attribute. Do
13077 // that here, so it will not hide previous -- and more relevant -- errors.
13078 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13079 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13080 Diag(MemE->getMemberLoc(),
13081 diag::err_ovl_no_viable_member_function_in_call)
13082 << Method << Method->getSourceRange();
13083 Diag(Method->getLocation(),
13084 diag::note_ovl_candidate_disabled_by_function_cond_attr)
13085 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13086 return ExprError();
13087 }
13088 }
13089
13090 if ((isa<CXXConstructorDecl>(CurContext) ||
13091 isa<CXXDestructorDecl>(CurContext)) &&
13092 TheCall->getMethodDecl()->isPure()) {
13093 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13094
13095 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13096 MemExpr->performsVirtualDispatch(getLangOpts())) {
13097 Diag(MemExpr->getBeginLoc(),
13098 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13099 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13100 << MD->getParent()->getDeclName();
13101
13102 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13103 if (getLangOpts().AppleKext)
13104 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13105 << MD->getParent()->getDeclName() << MD->getDeclName();
13106 }
13107 }
13108
13109 if (CXXDestructorDecl *DD =
13110 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13111 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13112 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13113 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13114 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13115 MemExpr->getMemberLoc());
13116 }
13117
13118 return MaybeBindToTemporary(TheCall);
13119 }
13120
13121 /// BuildCallToObjectOfClassType - Build a call to an object of class
13122 /// type (C++ [over.call.object]), which can end up invoking an
13123 /// overloaded function call operator (@c operator()) or performing a
13124 /// user-defined conversion on the object argument.
13125 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)13126 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13127 SourceLocation LParenLoc,
13128 MultiExprArg Args,
13129 SourceLocation RParenLoc) {
13130 if (checkPlaceholderForOverload(*this, Obj))
13131 return ExprError();
13132 ExprResult Object = Obj;
13133
13134 UnbridgedCastsSet UnbridgedCasts;
13135 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13136 return ExprError();
13137
13138 assert(Object.get()->getType()->isRecordType() &&
13139 "Requires object type argument");
13140 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13141
13142 // C++ [over.call.object]p1:
13143 // If the primary-expression E in the function call syntax
13144 // evaluates to a class object of type "cv T", then the set of
13145 // candidate functions includes at least the function call
13146 // operators of T. The function call operators of T are obtained by
13147 // ordinary lookup of the name operator() in the context of
13148 // (E).operator().
13149 OverloadCandidateSet CandidateSet(LParenLoc,
13150 OverloadCandidateSet::CSK_Operator);
13151 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13152
13153 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13154 diag::err_incomplete_object_call, Object.get()))
13155 return true;
13156
13157 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13158 LookupQualifiedName(R, Record->getDecl());
13159 R.suppressDiagnostics();
13160
13161 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13162 Oper != OperEnd; ++Oper) {
13163 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13164 Object.get()->Classify(Context), Args, CandidateSet,
13165 /*SuppressUserConversions=*/false);
13166 }
13167
13168 // C++ [over.call.object]p2:
13169 // In addition, for each (non-explicit in C++0x) conversion function
13170 // declared in T of the form
13171 //
13172 // operator conversion-type-id () cv-qualifier;
13173 //
13174 // where cv-qualifier is the same cv-qualification as, or a
13175 // greater cv-qualification than, cv, and where conversion-type-id
13176 // denotes the type "pointer to function of (P1,...,Pn) returning
13177 // R", or the type "reference to pointer to function of
13178 // (P1,...,Pn) returning R", or the type "reference to function
13179 // of (P1,...,Pn) returning R", a surrogate call function [...]
13180 // is also considered as a candidate function. Similarly,
13181 // surrogate call functions are added to the set of candidate
13182 // functions for each conversion function declared in an
13183 // accessible base class provided the function is not hidden
13184 // within T by another intervening declaration.
13185 const auto &Conversions =
13186 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13187 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13188 NamedDecl *D = *I;
13189 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13190 if (isa<UsingShadowDecl>(D))
13191 D = cast<UsingShadowDecl>(D)->getTargetDecl();
13192
13193 // Skip over templated conversion functions; they aren't
13194 // surrogates.
13195 if (isa<FunctionTemplateDecl>(D))
13196 continue;
13197
13198 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13199 if (!Conv->isExplicit()) {
13200 // Strip the reference type (if any) and then the pointer type (if
13201 // any) to get down to what might be a function type.
13202 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13203 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13204 ConvType = ConvPtrType->getPointeeType();
13205
13206 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13207 {
13208 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13209 Object.get(), Args, CandidateSet);
13210 }
13211 }
13212 }
13213
13214 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13215
13216 // Perform overload resolution.
13217 OverloadCandidateSet::iterator Best;
13218 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13219 Best)) {
13220 case OR_Success:
13221 // Overload resolution succeeded; we'll build the appropriate call
13222 // below.
13223 break;
13224
13225 case OR_No_Viable_Function:
13226 if (CandidateSet.empty())
13227 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13228 << Object.get()->getType() << /*call*/ 1
13229 << Object.get()->getSourceRange();
13230 else
13231 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13232 << Object.get()->getType() << Object.get()->getSourceRange();
13233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13234 break;
13235
13236 case OR_Ambiguous:
13237 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13238 << Object.get()->getType() << Object.get()->getSourceRange();
13239 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13240 break;
13241
13242 case OR_Deleted:
13243 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13244 << Best->Function->isDeleted() << Object.get()->getType()
13245 << getDeletedOrUnavailableSuffix(Best->Function)
13246 << Object.get()->getSourceRange();
13247 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13248 break;
13249 }
13250
13251 if (Best == CandidateSet.end())
13252 return true;
13253
13254 UnbridgedCasts.restore();
13255
13256 if (Best->Function == nullptr) {
13257 // Since there is no function declaration, this is one of the
13258 // surrogate candidates. Dig out the conversion function.
13259 CXXConversionDecl *Conv
13260 = cast<CXXConversionDecl>(
13261 Best->Conversions[0].UserDefined.ConversionFunction);
13262
13263 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13264 Best->FoundDecl);
13265 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13266 return ExprError();
13267 assert(Conv == Best->FoundDecl.getDecl() &&
13268 "Found Decl & conversion-to-functionptr should be same, right?!");
13269 // We selected one of the surrogate functions that converts the
13270 // object parameter to a function pointer. Perform the conversion
13271 // on the object argument, then let ActOnCallExpr finish the job.
13272
13273 // Create an implicit member expr to refer to the conversion operator.
13274 // and then call it.
13275 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13276 Conv, HadMultipleCandidates);
13277 if (Call.isInvalid())
13278 return ExprError();
13279 // Record usage of conversion in an implicit cast.
13280 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13281 CK_UserDefinedConversion, Call.get(),
13282 nullptr, VK_RValue);
13283
13284 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13285 }
13286
13287 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13288
13289 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13290 // that calls this method, using Object for the implicit object
13291 // parameter and passing along the remaining arguments.
13292 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13293
13294 // An error diagnostic has already been printed when parsing the declaration.
13295 if (Method->isInvalidDecl())
13296 return ExprError();
13297
13298 const FunctionProtoType *Proto =
13299 Method->getType()->getAs<FunctionProtoType>();
13300
13301 unsigned NumParams = Proto->getNumParams();
13302
13303 DeclarationNameInfo OpLocInfo(
13304 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13305 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13306 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13307 Obj, HadMultipleCandidates,
13308 OpLocInfo.getLoc(),
13309 OpLocInfo.getInfo());
13310 if (NewFn.isInvalid())
13311 return true;
13312
13313 // The number of argument slots to allocate in the call. If we have default
13314 // arguments we need to allocate space for them as well. We additionally
13315 // need one more slot for the object parameter.
13316 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13317
13318 // Build the full argument list for the method call (the implicit object
13319 // parameter is placed at the beginning of the list).
13320 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13321
13322 bool IsError = false;
13323
13324 // Initialize the implicit object parameter.
13325 ExprResult ObjRes =
13326 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13327 Best->FoundDecl, Method);
13328 if (ObjRes.isInvalid())
13329 IsError = true;
13330 else
13331 Object = ObjRes;
13332 MethodArgs[0] = Object.get();
13333
13334 // Check the argument types.
13335 for (unsigned i = 0; i != NumParams; i++) {
13336 Expr *Arg;
13337 if (i < Args.size()) {
13338 Arg = Args[i];
13339
13340 // Pass the argument.
13341
13342 ExprResult InputInit
13343 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13344 Context,
13345 Method->getParamDecl(i)),
13346 SourceLocation(), Arg);
13347
13348 IsError |= InputInit.isInvalid();
13349 Arg = InputInit.getAs<Expr>();
13350 } else {
13351 ExprResult DefArg
13352 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13353 if (DefArg.isInvalid()) {
13354 IsError = true;
13355 break;
13356 }
13357
13358 Arg = DefArg.getAs<Expr>();
13359 }
13360
13361 MethodArgs[i + 1] = Arg;
13362 }
13363
13364 // If this is a variadic call, handle args passed through "...".
13365 if (Proto->isVariadic()) {
13366 // Promote the arguments (C99 6.5.2.2p7).
13367 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13368 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13369 nullptr);
13370 IsError |= Arg.isInvalid();
13371 MethodArgs[i + 1] = Arg.get();
13372 }
13373 }
13374
13375 if (IsError)
13376 return true;
13377
13378 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13379
13380 // Once we've built TheCall, all of the expressions are properly owned.
13381 QualType ResultTy = Method->getReturnType();
13382 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13383 ResultTy = ResultTy.getNonLValueExprType(Context);
13384
13385 CXXOperatorCallExpr *TheCall =
13386 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13387 ResultTy, VK, RParenLoc, FPOptions());
13388
13389 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13390 return true;
13391
13392 if (CheckFunctionCall(Method, TheCall, Proto))
13393 return true;
13394
13395 return MaybeBindToTemporary(TheCall);
13396 }
13397
13398 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13399 /// (if one exists), where @c Base is an expression of class type and
13400 /// @c Member is the name of the member we're trying to find.
13401 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)13402 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13403 bool *NoArrowOperatorFound) {
13404 assert(Base->getType()->isRecordType() &&
13405 "left-hand side must have class type");
13406
13407 if (checkPlaceholderForOverload(*this, Base))
13408 return ExprError();
13409
13410 SourceLocation Loc = Base->getExprLoc();
13411
13412 // C++ [over.ref]p1:
13413 //
13414 // [...] An expression x->m is interpreted as (x.operator->())->m
13415 // for a class object x of type T if T::operator->() exists and if
13416 // the operator is selected as the best match function by the
13417 // overload resolution mechanism (13.3).
13418 DeclarationName OpName =
13419 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13420 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13421 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13422
13423 if (RequireCompleteType(Loc, Base->getType(),
13424 diag::err_typecheck_incomplete_tag, Base))
13425 return ExprError();
13426
13427 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13428 LookupQualifiedName(R, BaseRecord->getDecl());
13429 R.suppressDiagnostics();
13430
13431 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13432 Oper != OperEnd; ++Oper) {
13433 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13434 None, CandidateSet, /*SuppressUserConversions=*/false);
13435 }
13436
13437 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13438
13439 // Perform overload resolution.
13440 OverloadCandidateSet::iterator Best;
13441 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13442 case OR_Success:
13443 // Overload resolution succeeded; we'll build the call below.
13444 break;
13445
13446 case OR_No_Viable_Function:
13447 if (CandidateSet.empty()) {
13448 QualType BaseType = Base->getType();
13449 if (NoArrowOperatorFound) {
13450 // Report this specific error to the caller instead of emitting a
13451 // diagnostic, as requested.
13452 *NoArrowOperatorFound = true;
13453 return ExprError();
13454 }
13455 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13456 << BaseType << Base->getSourceRange();
13457 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13458 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13459 << FixItHint::CreateReplacement(OpLoc, ".");
13460 }
13461 } else
13462 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13463 << "operator->" << Base->getSourceRange();
13464 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13465 return ExprError();
13466
13467 case OR_Ambiguous:
13468 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13469 << "->" << Base->getType() << Base->getSourceRange();
13470 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13471 return ExprError();
13472
13473 case OR_Deleted:
13474 Diag(OpLoc, diag::err_ovl_deleted_oper)
13475 << Best->Function->isDeleted()
13476 << "->"
13477 << getDeletedOrUnavailableSuffix(Best->Function)
13478 << Base->getSourceRange();
13479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13480 return ExprError();
13481 }
13482
13483 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13484
13485 // Convert the object parameter.
13486 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13487 ExprResult BaseResult =
13488 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13489 Best->FoundDecl, Method);
13490 if (BaseResult.isInvalid())
13491 return ExprError();
13492 Base = BaseResult.get();
13493
13494 // Build the operator call.
13495 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13496 Base, HadMultipleCandidates, OpLoc);
13497 if (FnExpr.isInvalid())
13498 return ExprError();
13499
13500 QualType ResultTy = Method->getReturnType();
13501 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13502 ResultTy = ResultTy.getNonLValueExprType(Context);
13503 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13504 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13505
13506 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13507 return ExprError();
13508
13509 if (CheckFunctionCall(Method, TheCall,
13510 Method->getType()->castAs<FunctionProtoType>()))
13511 return ExprError();
13512
13513 return MaybeBindToTemporary(TheCall);
13514 }
13515
13516 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13517 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)13518 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13519 DeclarationNameInfo &SuffixInfo,
13520 ArrayRef<Expr*> Args,
13521 SourceLocation LitEndLoc,
13522 TemplateArgumentListInfo *TemplateArgs) {
13523 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13524
13525 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13526 OverloadCandidateSet::CSK_Normal);
13527 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13528 /*SuppressUserConversions=*/true);
13529
13530 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13531
13532 // Perform overload resolution. This will usually be trivial, but might need
13533 // to perform substitutions for a literal operator template.
13534 OverloadCandidateSet::iterator Best;
13535 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13536 case OR_Success:
13537 case OR_Deleted:
13538 break;
13539
13540 case OR_No_Viable_Function:
13541 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13542 << R.getLookupName();
13543 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13544 return ExprError();
13545
13546 case OR_Ambiguous:
13547 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13548 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13549 return ExprError();
13550 }
13551
13552 FunctionDecl *FD = Best->Function;
13553 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13554 nullptr, HadMultipleCandidates,
13555 SuffixInfo.getLoc(),
13556 SuffixInfo.getInfo());
13557 if (Fn.isInvalid())
13558 return true;
13559
13560 // Check the argument types. This should almost always be a no-op, except
13561 // that array-to-pointer decay is applied to string literals.
13562 Expr *ConvArgs[2];
13563 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13564 ExprResult InputInit = PerformCopyInitialization(
13565 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13566 SourceLocation(), Args[ArgIdx]);
13567 if (InputInit.isInvalid())
13568 return true;
13569 ConvArgs[ArgIdx] = InputInit.get();
13570 }
13571
13572 QualType ResultTy = FD->getReturnType();
13573 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13574 ResultTy = ResultTy.getNonLValueExprType(Context);
13575
13576 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13577 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13578 VK, LitEndLoc, UDSuffixLoc);
13579
13580 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13581 return ExprError();
13582
13583 if (CheckFunctionCall(FD, UDL, nullptr))
13584 return ExprError();
13585
13586 return MaybeBindToTemporary(UDL);
13587 }
13588
13589 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13590 /// given LookupResult is non-empty, it is assumed to describe a member which
13591 /// will be invoked. Otherwise, the function will be found via argument
13592 /// dependent lookup.
13593 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13594 /// otherwise CallExpr is set to ExprError() and some non-success value
13595 /// is returned.
13596 Sema::ForRangeStatus
BuildForRangeBeginEndCall(SourceLocation Loc,SourceLocation RangeLoc,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)13597 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13598 SourceLocation RangeLoc,
13599 const DeclarationNameInfo &NameInfo,
13600 LookupResult &MemberLookup,
13601 OverloadCandidateSet *CandidateSet,
13602 Expr *Range, ExprResult *CallExpr) {
13603 Scope *S = nullptr;
13604
13605 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13606 if (!MemberLookup.empty()) {
13607 ExprResult MemberRef =
13608 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13609 /*IsPtr=*/false, CXXScopeSpec(),
13610 /*TemplateKWLoc=*/SourceLocation(),
13611 /*FirstQualifierInScope=*/nullptr,
13612 MemberLookup,
13613 /*TemplateArgs=*/nullptr, S);
13614 if (MemberRef.isInvalid()) {
13615 *CallExpr = ExprError();
13616 return FRS_DiagnosticIssued;
13617 }
13618 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13619 if (CallExpr->isInvalid()) {
13620 *CallExpr = ExprError();
13621 return FRS_DiagnosticIssued;
13622 }
13623 } else {
13624 UnresolvedSet<0> FoundNames;
13625 UnresolvedLookupExpr *Fn =
13626 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13627 NestedNameSpecifierLoc(), NameInfo,
13628 /*NeedsADL=*/true, /*Overloaded=*/false,
13629 FoundNames.begin(), FoundNames.end());
13630
13631 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13632 CandidateSet, CallExpr);
13633 if (CandidateSet->empty() || CandidateSetError) {
13634 *CallExpr = ExprError();
13635 return FRS_NoViableFunction;
13636 }
13637 OverloadCandidateSet::iterator Best;
13638 OverloadingResult OverloadResult =
13639 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13640
13641 if (OverloadResult == OR_No_Viable_Function) {
13642 *CallExpr = ExprError();
13643 return FRS_NoViableFunction;
13644 }
13645 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13646 Loc, nullptr, CandidateSet, &Best,
13647 OverloadResult,
13648 /*AllowTypoCorrection=*/false);
13649 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13650 *CallExpr = ExprError();
13651 return FRS_DiagnosticIssued;
13652 }
13653 }
13654 return FRS_Success;
13655 }
13656
13657
13658 /// FixOverloadedFunctionReference - E is an expression that refers to
13659 /// a C++ overloaded function (possibly with some parentheses and
13660 /// perhaps a '&' around it). We have resolved the overloaded function
13661 /// to the function declaration Fn, so patch up the expression E to
13662 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)13663 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13664 FunctionDecl *Fn) {
13665 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13666 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13667 Found, Fn);
13668 if (SubExpr == PE->getSubExpr())
13669 return PE;
13670
13671 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13672 }
13673
13674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13675 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13676 Found, Fn);
13677 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13678 SubExpr->getType()) &&
13679 "Implicit cast type cannot be determined from overload");
13680 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13681 if (SubExpr == ICE->getSubExpr())
13682 return ICE;
13683
13684 return ImplicitCastExpr::Create(Context, ICE->getType(),
13685 ICE->getCastKind(),
13686 SubExpr, nullptr,
13687 ICE->getValueKind());
13688 }
13689
13690 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13691 if (!GSE->isResultDependent()) {
13692 Expr *SubExpr =
13693 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13694 if (SubExpr == GSE->getResultExpr())
13695 return GSE;
13696
13697 // Replace the resulting type information before rebuilding the generic
13698 // selection expression.
13699 ArrayRef<Expr *> A = GSE->getAssocExprs();
13700 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13701 unsigned ResultIdx = GSE->getResultIndex();
13702 AssocExprs[ResultIdx] = SubExpr;
13703
13704 return new (Context) GenericSelectionExpr(
13705 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13706 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13707 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13708 ResultIdx);
13709 }
13710 // Rather than fall through to the unreachable, return the original generic
13711 // selection expression.
13712 return GSE;
13713 }
13714
13715 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13716 assert(UnOp->getOpcode() == UO_AddrOf &&
13717 "Can only take the address of an overloaded function");
13718 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13719 if (Method->isStatic()) {
13720 // Do nothing: static member functions aren't any different
13721 // from non-member functions.
13722 } else {
13723 // Fix the subexpression, which really has to be an
13724 // UnresolvedLookupExpr holding an overloaded member function
13725 // or template.
13726 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13727 Found, Fn);
13728 if (SubExpr == UnOp->getSubExpr())
13729 return UnOp;
13730
13731 assert(isa<DeclRefExpr>(SubExpr)
13732 && "fixed to something other than a decl ref");
13733 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13734 && "fixed to a member ref with no nested name qualifier");
13735
13736 // We have taken the address of a pointer to member
13737 // function. Perform the computation here so that we get the
13738 // appropriate pointer to member type.
13739 QualType ClassType
13740 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13741 QualType MemPtrType
13742 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13743 // Under the MS ABI, lock down the inheritance model now.
13744 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13745 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13746
13747 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13748 VK_RValue, OK_Ordinary,
13749 UnOp->getOperatorLoc(), false);
13750 }
13751 }
13752 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13753 Found, Fn);
13754 if (SubExpr == UnOp->getSubExpr())
13755 return UnOp;
13756
13757 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13758 Context.getPointerType(SubExpr->getType()),
13759 VK_RValue, OK_Ordinary,
13760 UnOp->getOperatorLoc(), false);
13761 }
13762
13763 // C++ [except.spec]p17:
13764 // An exception-specification is considered to be needed when:
13765 // - in an expression the function is the unique lookup result or the
13766 // selected member of a set of overloaded functions
13767 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13768 ResolveExceptionSpec(E->getExprLoc(), FPT);
13769
13770 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13771 // FIXME: avoid copy.
13772 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13773 if (ULE->hasExplicitTemplateArgs()) {
13774 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13775 TemplateArgs = &TemplateArgsBuffer;
13776 }
13777
13778 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13779 ULE->getQualifierLoc(),
13780 ULE->getTemplateKeywordLoc(),
13781 Fn,
13782 /*enclosing*/ false, // FIXME?
13783 ULE->getNameLoc(),
13784 Fn->getType(),
13785 VK_LValue,
13786 Found.getDecl(),
13787 TemplateArgs);
13788 MarkDeclRefReferenced(DRE);
13789 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13790 return DRE;
13791 }
13792
13793 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13794 // FIXME: avoid copy.
13795 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13796 if (MemExpr->hasExplicitTemplateArgs()) {
13797 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13798 TemplateArgs = &TemplateArgsBuffer;
13799 }
13800
13801 Expr *Base;
13802
13803 // If we're filling in a static method where we used to have an
13804 // implicit member access, rewrite to a simple decl ref.
13805 if (MemExpr->isImplicitAccess()) {
13806 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13807 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13808 MemExpr->getQualifierLoc(),
13809 MemExpr->getTemplateKeywordLoc(),
13810 Fn,
13811 /*enclosing*/ false,
13812 MemExpr->getMemberLoc(),
13813 Fn->getType(),
13814 VK_LValue,
13815 Found.getDecl(),
13816 TemplateArgs);
13817 MarkDeclRefReferenced(DRE);
13818 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13819 return DRE;
13820 } else {
13821 SourceLocation Loc = MemExpr->getMemberLoc();
13822 if (MemExpr->getQualifier())
13823 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13824 CheckCXXThisCapture(Loc);
13825 Base = new (Context) CXXThisExpr(Loc,
13826 MemExpr->getBaseType(),
13827 /*isImplicit=*/true);
13828 }
13829 } else
13830 Base = MemExpr->getBase();
13831
13832 ExprValueKind valueKind;
13833 QualType type;
13834 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13835 valueKind = VK_LValue;
13836 type = Fn->getType();
13837 } else {
13838 valueKind = VK_RValue;
13839 type = Context.BoundMemberTy;
13840 }
13841
13842 MemberExpr *ME = MemberExpr::Create(
13843 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13844 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13845 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13846 OK_Ordinary);
13847 ME->setHadMultipleCandidates(true);
13848 MarkMemberReferenced(ME);
13849 return ME;
13850 }
13851
13852 llvm_unreachable("Invalid reference to overloaded function");
13853 }
13854
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)13855 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13856 DeclAccessPair Found,
13857 FunctionDecl *Fn) {
13858 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13859 }
13860