Bug Summary

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

Annotated Source Code

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
39using namespace clang;
40using namespace sema;
41
42static 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.
49static ExprResult
50CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 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) DeclRefExpr(Fn, false, Fn->getType(),
67 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
70
71 S.MarkDeclRefReferenced(DRE);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
74}
75
76static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle,
80 bool AllowObjCWritebackConversion);
81
82static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
87static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
91 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
93
94
95static ImplicitConversionSequence::CompareKind
96CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
106CompareDerivedToBaseConversions(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.
112ImplicitConversionRank 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_Conversion,
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.
150static 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.
185void 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.
204ImplicitConversionRank 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).
219bool 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()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
228 getFromType()->isNullPtrType() ||
229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
239bool
240StandardConversionSequence::
241isPointerConversionToVoidPointer(ASTContext& Context) const {
242 QualType FromType = getFromType();
243 QualType ToType = getToType(1);
244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
267 case CK_BooleanToSignedIntegral:
268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
291NarrowingKind
292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue,
295 QualType &ConstantType) const {
296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 296, __PRETTY_FUNCTION__))
;
297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
309 switch (Second) {
310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 FloatingIntegralConversion:
328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333
334 // If it's value-dependent, we can't tell whether it's narrowing.
335 if (Initializer->isValueDependent())
336 return NK_Dependent_Narrowing;
337
338 if (Initializer &&
339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
352 ConstantType = Initializer->getType();
353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 378, __PRETTY_FUNCTION__))
;
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
389 return NK_Constant_Narrowing;
390 }
391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
402 case ICK_Integral_Conversion:
403 IntegralConversion: {
404 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 404, __PRETTY_FUNCTION__))
;
405 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 405, __PRETTY_FUNCTION__))
;
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
431 Narrowing = true;
432 } else {
433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
462/// dump - Print this standard conversion sequence to standard
463/// error. Useful for debugging overloading issues.
464LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
465 raw_ostream &OS = llvm::errs();
466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
468 OS << GetImplicitConversionName(First);
469 PrintedSomething = true;
470 }
471
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
474 OS << " -> ";
475 }
476 OS << GetImplicitConversionName(Second);
477
478 if (CopyConstructor) {
479 OS << " (by copy constructor)";
480 } else if (DirectBinding) {
481 OS << " (direct reference binding)";
482 } else if (ReferenceBinding) {
483 OS << " (reference binding)";
484 }
485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
490 OS << " -> ";
491 }
492 OS << GetImplicitConversionName(Third);
493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
497 OS << "No conversions required";
498 }
499}
500
501/// dump - Print this user-defined conversion sequence to standard
502/// error. Useful for debugging overloading issues.
503void UserDefinedConversionSequence::dump() const {
504 raw_ostream &OS = llvm::errs();
505 if (Before.First || Before.Second || Before.Third) {
506 Before.dump();
507 OS << " -> ";
508 }
509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
513 if (After.First || After.Second || After.Third) {
514 OS << " -> ";
515 After.dump();
516 }
517}
518
519/// dump - Print this implicit conversion sequence to standard
520/// error. Useful for debugging overloading issues.
521void ImplicitConversionSequence::dump() const {
522 raw_ostream &OS = llvm::errs();
523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
525 switch (ConversionKind) {
526 case StandardConversion:
527 OS << "Standard conversion: ";
528 Standard.dump();
529 break;
530 case UserDefinedConversion:
531 OS << "User-defined conversion: ";
532 UserDefined.dump();
533 break;
534 case EllipsisConversion:
535 OS << "Ellipsis conversion";
536 break;
537 case AmbiguousConversion:
538 OS << "Ambiguous conversion";
539 break;
540 case BadConversion:
541 OS << "Bad conversion";
542 break;
543 }
544
545 OS << "\n";
546}
547
548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
563namespace {
564 // Structure used by DeductionFailureInfo to store
565 // template argument information.
566 struct DFIArguments {
567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
570 // Structure used by DeductionFailureInfo to store
571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
581}
582
583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
589 DeductionFailureInfo Result;
590 Result.Result = static_cast<unsigned>(TDK);
591 Result.HasDiagnostic = false;
592 switch (TDK) {
593 case Sema::TDK_Invalid:
594 case Sema::TDK_InstantiationDepth:
595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
597 case Sema::TDK_MiscellaneousDeductionFailure:
598 case Sema::TDK_CUDATargetMismatch:
599 Result.Data = nullptr;
600 break;
601
602 case Sema::TDK_Incomplete:
603 case Sema::TDK_InvalidExplicitArguments:
604 Result.Data = Info.Param.getOpaqueValue();
605 break;
606
607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
628 case Sema::TDK_Inconsistent:
629 case Sema::TDK_Underqualified: {
630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
638
639 case Sema::TDK_SubstitutionFailure:
640 Result.Data = Info.take();
641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
647 break;
648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 651)
;
652 }
653
654 return Result;
655}
656
657void DeductionFailureInfo::Destroy() {
658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
660 case Sema::TDK_Invalid:
661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
665 case Sema::TDK_InvalidExplicitArguments:
666 case Sema::TDK_CUDATargetMismatch:
667 case Sema::TDK_NonDependentConversionFailure:
668 break;
669
670 case Sema::TDK_Inconsistent:
671 case Sema::TDK_Underqualified:
672 case Sema::TDK_DeducedMismatch:
673 case Sema::TDK_DeducedMismatchNested:
674 case Sema::TDK_NonDeducedMismatch:
675 // FIXME: Destroy the data?
676 Data = nullptr;
677 break;
678
679 case Sema::TDK_SubstitutionFailure:
680 // FIXME: Destroy the template argument list?
681 Data = nullptr;
682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
686 break;
687
688 // Unhandled
689 case Sema::TDK_MiscellaneousDeductionFailure:
690 break;
691 }
692}
693
694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697 return nullptr;
698}
699
700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_SubstitutionFailure:
708 case Sema::TDK_DeducedMismatch:
709 case Sema::TDK_DeducedMismatchNested:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_CUDATargetMismatch:
712 case Sema::TDK_NonDependentConversionFailure:
713 return TemplateParameter();
714
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 return TemplateParameter::getFromOpaqueValue(Data);
718
719 case Sema::TDK_Inconsistent:
720 case Sema::TDK_Underqualified:
721 return static_cast<DFIParamWithArguments*>(Data)->Param;
722
723 // Unhandled
724 case Sema::TDK_MiscellaneousDeductionFailure:
725 break;
726 }
727
728 return TemplateParameter();
729}
730
731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
743 case Sema::TDK_CUDATargetMismatch:
744 case Sema::TDK_NonDependentConversionFailure:
745 return nullptr;
746
747 case Sema::TDK_DeducedMismatch:
748 case Sema::TDK_DeducedMismatchNested:
749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
753
754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
757 }
758
759 return nullptr;
760}
761
762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
765 case Sema::TDK_Invalid:
766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
770 case Sema::TDK_InvalidExplicitArguments:
771 case Sema::TDK_SubstitutionFailure:
772 case Sema::TDK_CUDATargetMismatch:
773 case Sema::TDK_NonDependentConversionFailure:
774 return nullptr;
775
776 case Sema::TDK_Inconsistent:
777 case Sema::TDK_Underqualified:
778 case Sema::TDK_DeducedMismatch:
779 case Sema::TDK_DeducedMismatchNested:
780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
782
783 // Unhandled
784 case Sema::TDK_MiscellaneousDeductionFailure:
785 break;
786 }
787
788 return nullptr;
789}
790
791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
794 case Sema::TDK_Invalid:
795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
799 case Sema::TDK_InvalidExplicitArguments:
800 case Sema::TDK_SubstitutionFailure:
801 case Sema::TDK_CUDATargetMismatch:
802 case Sema::TDK_NonDependentConversionFailure:
803 return nullptr;
804
805 case Sema::TDK_Inconsistent:
806 case Sema::TDK_Underqualified:
807 case Sema::TDK_DeducedMismatch:
808 case Sema::TDK_DeducedMismatchNested:
809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
811
812 // Unhandled
813 case Sema::TDK_MiscellaneousDeductionFailure:
814 break;
815 }
816
817 return nullptr;
818}
819
820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
826 default:
827 return llvm::None;
828 }
829}
830
831void OverloadCandidateSet::destroyCandidates() {
832 for (iterator i = begin(), e = end(); i != e; ++i) {
833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
838}
839
840void OverloadCandidateSet::clear() {
841 destroyCandidates();
842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
844 Candidates.clear();
845 Functions.clear();
846}
847
848namespace {
849 class UnbridgedCastsSet {
850 struct Entry {
851 Expr **Addr;
852 Expr *Saved;
853 };
854 SmallVector<Entry, 2> Entries;
855
856 public:
857 void save(Sema &S, Expr *&E) {
858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 858, __PRETTY_FUNCTION__))
;
859 Entry entry = { &E, E };
860 Entries.push_back(entry);
861 E = S.stripARCUnbridgedCast(E);
862 }
863
864 void restore() {
865 for (SmallVectorImpl<Entry>::iterator
866 i = Entries.begin(), e = Entries.end(); i != e; ++i)
867 *i->Addr = i->Saved;
868 }
869 };
870}
871
872/// checkPlaceholderForOverload - Do any interesting placeholder-like
873/// preprocessing on the given expression.
874///
875/// \param unbridgedCasts a collection to which to add unbridged casts;
876/// without this, they will be immediately diagnosed as errors
877///
878/// Return true on unrecoverable error.
879static bool
880checkPlaceholderForOverload(Sema &S, Expr *&E,
881 UnbridgedCastsSet *unbridgedCasts = nullptr) {
882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
883 // We can't handle overloaded expressions here because overload
884 // resolution might reasonably tweak them.
885 if (placeholder->getKind() == BuiltinType::Overload) return false;
886
887 // If the context potentially accepts unbridged ARC casts, strip
888 // the unbridged cast and add it to the collection for later restoration.
889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890 unbridgedCasts) {
891 unbridgedCasts->save(S, E);
892 return false;
893 }
894
895 // Go ahead and check everything else.
896 ExprResult result = S.CheckPlaceholderExpr(E);
897 if (result.isInvalid())
898 return true;
899
900 E = result.get();
901 return false;
902 }
903
904 // Nothing to do.
905 return false;
906}
907
908/// checkArgPlaceholdersForOverload - Check a set of call operands for
909/// placeholders.
910static bool checkArgPlaceholdersForOverload(Sema &S,
911 MultiExprArg Args,
912 UnbridgedCastsSet &unbridged) {
913 for (unsigned i = 0, e = Args.size(); i != e; ++i)
914 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
915 return true;
916
917 return false;
918}
919
920// IsOverload - Determine whether the given New declaration is an
921// overload of the declarations in Old. This routine returns false if
922// New and Old cannot be overloaded, e.g., if New has the same
923// signature as some function in Old (C++ 1.3.10) or if the Old
924// declarations aren't functions (or function templates) at all. When
925// it does return false, MatchedDecl will point to the decl that New
926// cannot be overloaded with. This decl may be a UsingShadowDecl on
927// top of the underlying declaration.
928//
929// Example: Given the following input:
930//
931// void f(int, float); // #1
932// void f(int, int); // #2
933// int f(int, int); // #3
934//
935// When we process #1, there is no previous declaration of "f",
936// so IsOverload will not be used.
937//
938// When we process #2, Old contains only the FunctionDecl for #1. By
939// comparing the parameter types, we see that #1 and #2 are overloaded
940// (since they have different signatures), so this routine returns
941// false; MatchedDecl is unchanged.
942//
943// When we process #3, Old is an overload set containing #1 and #2. We
944// compare the signatures of #3 to #1 (they're overloaded, so we do
945// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
946// identical (return types of functions are not part of the
947// signature), IsOverload returns false and MatchedDecl will be set to
948// point to the FunctionDecl for #2.
949//
950// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
951// into a class by a using declaration. The rules for whether to hide
952// shadow declarations ignore some properties which otherwise figure
953// into a function template's signature.
954Sema::OverloadKind
955Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
958 I != E; ++I) {
959 NamedDecl *OldD = *I;
960
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
964
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
968
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970 }
971
972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975 continue;
976
977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
985
986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990 continue;
991 }
992
993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
995 continue;
996
997 Match = *I;
998 return Ovl_Match;
999 }
1000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1003, __PRETTY_FUNCTION__))
;
1004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
1006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
1010 //
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 Match = *I;
1015 return Ovl_NonFunction;
1016 }
1017 } else {
1018 // (C++ 13p1):
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
1021 Match = *I;
1022 return Ovl_NonFunction;
1023 }
1024 }
1025
1026 return Ovl_Overload;
1027}
1028
1029bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1032 if (New->isMain())
1033 return false;
1034
1035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1037 return false;
1038
1039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
1045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1046 return true;
1047
1048 // Is the function New an overload of the function Old?
1049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
1051
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1055
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060 return false;
1061
1062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
1069 (OldType->getNumParams() != NewType->getNumParams() ||
1070 OldType->isVariadic() != NewType->isVariadic() ||
1071 !FunctionParamTypesAreEqual(OldType, NewType)))
1072 return true;
1073
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1079 // signature.
1080 //
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
1083 //
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
1086 if (!UseMemberUsingDeclRules && NewTemplate &&
1087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
1090 OldType->getReturnType() != NewType->getReturnType()))
1091 return true;
1092
1093 // If the function is a class member, its signature includes the
1094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095 //
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
1101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103 if (OldMethod && NewMethod &&
1104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106 if (!UseMemberUsingDeclRules &&
1107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
1115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1118 }
1119 return true;
1120 }
1121
1122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
1126 unsigned OldQuals = OldMethod->getTypeQualifiers();
1127 unsigned NewQuals = NewMethod->getTypeQualifiers();
1128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129 !isa<CXXConstructorDecl>(NewMethod))
1130 NewQuals |= Qualifiers::Const;
1131
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
1136 return true;
1137 }
1138
1139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1145 return true;
1146
1147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1155 return true;
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
1159 if (NewID != OldID)
1160 return true;
1161 }
1162
1163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1167 return false;
1168
1169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
1171 if (NewTarget == CFT_InvalidTarget)
1172 return false;
1173
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1174, __PRETTY_FUNCTION__))
;
1175
1176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
1178 return NewTarget != OldTarget;
1179 }
1180
1181 // The signatures match; this is not an overload.
1182 return false;
1183}
1184
1185/// \brief Checks availability of the function depending on the current
1186/// function context. Inside an unavailable function, unavailability is ignored.
1187///
1188/// \returns true if \arg FD is unavailable and current context is inside
1189/// an available function, false otherwise.
1190bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191 if (!FD->isUnavailable())
1192 return false;
1193
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1196 do {
1197 if (C->isUnavailable())
1198 return false;
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200 return true;
1201}
1202
1203/// \brief Tries a user-defined conversion from From to ToType.
1204///
1205/// Produces an implicit conversion sequence for when a standard conversion
1206/// is not an option. See TryImplicitConversion for more information.
1207static ImplicitConversionSequence
1208TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
1213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
1215 ImplicitConversionSequence ICS;
1216
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1219 // we can perform.
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221 return ICS;
1222 }
1223
1224 // Attempt user-defined conversion.
1225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
1227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1230 case OR_Success:
1231 case OR_Deleted:
1232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 QualType FromCanon
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 QualType ToCanon
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
1247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
1251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
1257 ICS.Standard.FoundCopyConstructor = Found;
1258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1260 }
1261 }
1262 break;
1263
1264 case OR_Ambiguous:
1265 ICS.setAmbiguous();
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1270 if (Cand->Viable)
1271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1272 break;
1273
1274 // Fall through.
1275 case OR_No_Viable_Function:
1276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1277 break;
1278 }
1279
1280 return ICS;
1281}
1282
1283/// TryImplicitConversion - Attempt to perform an implicit conversion
1284/// from the given expression (Expr) to the given type (ToType). This
1285/// function returns an implicit conversion sequence that can be used
1286/// to perform the initialization. Given
1287///
1288/// void f(float f);
1289/// void g(int i) { f(i); }
1290///
1291/// this routine would produce an implicit conversion sequence to
1292/// describe the initialization of f from i, which will be a standard
1293/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295//
1296/// Note that this routine only determines how the conversion can be
1297/// performed; it does not actually perform the conversion. As such,
1298/// it will not produce any diagnostics if no conversion is available,
1299/// but will instead return an implicit conversion sequence of kind
1300/// "BadConversion".
1301///
1302/// If @p SuppressUserConversions, then user-defined conversions are
1303/// not permitted.
1304/// If @p AllowExplicit, then explicit user-defined conversions are
1305/// permitted.
1306///
1307/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308/// writeback conversion, which allows __autoreleasing id* parameters to
1309/// be initialized with __strong id* or __weak id* arguments.
1310static ImplicitConversionSequence
1311TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
1313 bool AllowExplicit,
1314 bool InOverloadResolution,
1315 bool CStyle,
1316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
1318 ImplicitConversionSequence ICS;
1319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1321 ICS.setStandard();
1322 return ICS;
1323 }
1324
1325 if (!S.getLangOpts().CPlusPlus) {
1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327 return ICS;
1328 }
1329
1330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341 ICS.setStandard();
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
1345
1346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
1350 ICS.Standard.CopyConstructor = nullptr;
1351
1352 // Determine whether this is considered a derived-to-base conversion.
1353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354 ICS.Standard.Second = ICK_Derived_To_Base;
1355
1356 return ICS;
1357 }
1358
1359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
1361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
1363}
1364
1365ImplicitConversionSequence
1366Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1368 bool AllowExplicit,
1369 bool InOverloadResolution,
1370 bool CStyle,
1371 bool AllowObjCWritebackConversion) {
1372 return ::TryImplicitConversion(*this, From, ToType,
1373 SuppressUserConversions, AllowExplicit,
1374 InOverloadResolution, CStyle,
1375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
1377}
1378
1379/// PerformImplicitConversion - Perform an implicit conversion of the
1380/// expression From to the type ToType. Returns the
1381/// converted expression. Flavor is the kind of conversion we're
1382/// performing, used in the error message. If @p AllowExplicit,
1383/// explicit user-defined conversions are permitted.
1384ExprResult
1385Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386 AssignmentAction Action, bool AllowExplicit) {
1387 ImplicitConversionSequence ICS;
1388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1389}
1390
1391ExprResult
1392Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393 AssignmentAction Action, bool AllowExplicit,
1394 ImplicitConversionSequence& ICS) {
1395 if (checkPlaceholderForOverload(*this, From))
1396 return ExprError();
1397
1398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
1400 = getLangOpts().ObjCAutoRefCount &&
1401 (Action == AA_Passing || Action == AA_Sending);
1402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
1405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1407 AllowExplicit,
1408 /*InOverloadResolution=*/false,
1409 /*CStyle=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
1412 return PerformImplicitConversion(From, ToType, ICS, Action);
1413}
1414
1415/// \brief Determine whether the conversion from FromType to ToType is a valid
1416/// conversion that strips "noexcept" or "noreturn" off the nested function
1417/// type.
1418bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419 QualType &ResultTy) {
1420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1421 return false;
1422
1423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424 // or F(t noexcept) -> F(t)
1425 // where F adds one of the following at most once:
1426 // - a pointer
1427 // - a member pointer
1428 // - a block pointer
1429 // Changes here need matching changes in FindCompositePointerType.
1430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
1442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1446 return false;
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
1449 } else {
1450 return false;
1451 }
1452
1453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456 return false;
1457 }
1458
1459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461
1462 const auto *ToFn = cast<FunctionType>(CanTo);
1463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464
1465 bool Changed = false;
1466
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470 Changed = true;
1471 }
1472
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
1478 Context.getFunctionType(FromFPT->getReturnType(),
1479 FromFPT->getParamTypes(),
1480 FromFPT->getExtProtoInfo().withExceptionSpec(
1481 FunctionProtoType::ExceptionSpecInfo()))
1482 .getTypePtr());
1483 Changed = true;
1484 }
1485 }
1486
1487 if (!Changed)
1488 return false;
1489
1490 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1490, __PRETTY_FUNCTION__))
;
1491 if (QualType(FromFn, 0) != CanTo) return false;
1492
1493 ResultTy = ToType;
1494 return true;
1495}
1496
1497/// \brief Determine whether the conversion from FromType to ToType is a valid
1498/// vector conversion.
1499///
1500/// \param ICK Will be set to the vector conversion kind, if this is a vector
1501/// conversion.
1502static bool IsVectorConversion(Sema &S, QualType FromType,
1503 QualType ToType, ImplicitConversionKind &ICK) {
1504 // We need at least one of these types to be a vector type to have a vector
1505 // conversion.
1506 if (!ToType->isVectorType() && !FromType->isVectorType())
1507 return false;
1508
1509 // Identical types require no conversions.
1510 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1511 return false;
1512
1513 // There are no conversions between extended vector types, only identity.
1514 if (ToType->isExtVectorType()) {
1515 // There are no conversions between extended vector types other than the
1516 // identity conversion.
1517 if (FromType->isExtVectorType())
1518 return false;
1519
1520 // Vector splat from any arithmetic type to a vector.
1521 if (FromType->isArithmeticType()) {
1522 ICK = ICK_Vector_Splat;
1523 return true;
1524 }
1525 }
1526
1527 // We can perform the conversion between vector types in the following cases:
1528 // 1)vector types are equivalent AltiVec and GCC vector types
1529 // 2)lax vector conversions are permitted and the vector types are of the
1530 // same size
1531 if (ToType->isVectorType() && FromType->isVectorType()) {
1532 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1533 S.isLaxVectorConversion(FromType, ToType)) {
1534 ICK = ICK_Vector_Conversion;
1535 return true;
1536 }
1537 }
1538
1539 return false;
1540}
1541
1542static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1543 bool InOverloadResolution,
1544 StandardConversionSequence &SCS,
1545 bool CStyle);
1546
1547/// IsStandardConversion - Determines whether there is a standard
1548/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1549/// expression From to the type ToType. Standard conversion sequences
1550/// only consider non-class types; for conversions that involve class
1551/// types, use TryImplicitConversion. If a conversion exists, SCS will
1552/// contain the standard conversion sequence required to perform this
1553/// conversion and this routine will return true. Otherwise, this
1554/// routine will return false and the value of SCS is unspecified.
1555static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1556 bool InOverloadResolution,
1557 StandardConversionSequence &SCS,
1558 bool CStyle,
1559 bool AllowObjCWritebackConversion) {
1560 QualType FromType = From->getType();
1561
1562 // Standard conversions (C++ [conv])
1563 SCS.setAsIdentityConversion();
1564 SCS.IncompatibleObjC = false;
1565 SCS.setFromType(FromType);
1566 SCS.CopyConstructor = nullptr;
1567
1568 // There are no standard conversions for class types in C++, so
1569 // abort early. When overloading in C, however, we do permit them.
1570 if (S.getLangOpts().CPlusPlus &&
1571 (FromType->isRecordType() || ToType->isRecordType()))
1572 return false;
1573
1574 // The first conversion can be an lvalue-to-rvalue conversion,
1575 // array-to-pointer conversion, or function-to-pointer conversion
1576 // (C++ 4p1).
1577
1578 if (FromType == S.Context.OverloadTy) {
1579 DeclAccessPair AccessPair;
1580 if (FunctionDecl *Fn
1581 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1582 AccessPair)) {
1583 // We were able to resolve the address of the overloaded function,
1584 // so we can convert to the type of that function.
1585 FromType = Fn->getType();
1586 SCS.setFromType(FromType);
1587
1588 // we can sometimes resolve &foo<int> regardless of ToType, so check
1589 // if the type matches (identity) or we are converting to bool
1590 if (!S.Context.hasSameUnqualifiedType(
1591 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1592 QualType resultTy;
1593 // if the function type matches except for [[noreturn]], it's ok
1594 if (!S.IsFunctionConversion(FromType,
1595 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1596 // otherwise, only a boolean conversion is standard
1597 if (!ToType->isBooleanType())
1598 return false;
1599 }
1600
1601 // Check if the "from" expression is taking the address of an overloaded
1602 // function and recompute the FromType accordingly. Take advantage of the
1603 // fact that non-static member functions *must* have such an address-of
1604 // expression.
1605 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1606 if (Method && !Method->isStatic()) {
1607 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1608, __PRETTY_FUNCTION__))
1608 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1608, __PRETTY_FUNCTION__))
;
1609 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1611, __PRETTY_FUNCTION__))
1610 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1611, __PRETTY_FUNCTION__))
1611 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1611, __PRETTY_FUNCTION__))
;
1612 const Type *ClassType
1613 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1614 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1615 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1616 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1618, __PRETTY_FUNCTION__))
1617 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1618, __PRETTY_FUNCTION__))
1618 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1618, __PRETTY_FUNCTION__))
;
1619 FromType = S.Context.getPointerType(FromType);
1620 }
1621
1622 // Check that we've computed the proper type after overload resolution.
1623 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1624 // be calling it from within an NDEBUG block.
1625 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1627, __PRETTY_FUNCTION__))
1626 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1627, __PRETTY_FUNCTION__))
1627 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 1627, __PRETTY_FUNCTION__))
;
1628 } else {
1629 return false;
1630 }
1631 }
1632 // Lvalue-to-rvalue conversion (C++11 4.1):
1633 // A glvalue (3.10) of a non-function, non-array type T can
1634 // be converted to a prvalue.
1635 bool argIsLValue = From->isGLValue();
1636 if (argIsLValue &&
1637 !FromType->isFunctionType() && !FromType->isArrayType() &&
1638 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1639 SCS.First = ICK_Lvalue_To_Rvalue;
1640
1641 // C11 6.3.2.1p2:
1642 // ... if the lvalue has atomic type, the value has the non-atomic version
1643 // of the type of the lvalue ...
1644 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1645 FromType = Atomic->getValueType();
1646
1647 // If T is a non-class type, the type of the rvalue is the
1648 // cv-unqualified version of T. Otherwise, the type of the rvalue
1649 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1650 // just strip the qualifiers because they don't matter.
1651 FromType = FromType.getUnqualifiedType();
1652 } else if (FromType->isArrayType()) {
1653 // Array-to-pointer conversion (C++ 4.2)
1654 SCS.First = ICK_Array_To_Pointer;
1655
1656 // An lvalue or rvalue of type "array of N T" or "array of unknown
1657 // bound of T" can be converted to an rvalue of type "pointer to
1658 // T" (C++ 4.2p1).
1659 FromType = S.Context.getArrayDecayedType(FromType);
1660
1661 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1662 // This conversion is deprecated in C++03 (D.4)
1663 SCS.DeprecatedStringLiteralToCharPtr = true;
1664
1665 // For the purpose of ranking in overload resolution
1666 // (13.3.3.1.1), this conversion is considered an
1667 // array-to-pointer conversion followed by a qualification
1668 // conversion (4.4). (C++ 4.2p2)
1669 SCS.Second = ICK_Identity;
1670 SCS.Third = ICK_Qualification;
1671 SCS.QualificationIncludesObjCLifetime = false;
1672 SCS.setAllToTypes(FromType);
1673 return true;
1674 }
1675 } else if (FromType->isFunctionType() && argIsLValue) {
1676 // Function-to-pointer conversion (C++ 4.3).
1677 SCS.First = ICK_Function_To_Pointer;
1678
1679 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1680 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1681 if (!S.checkAddressOfFunctionIsAvailable(FD))
1682 return false;
1683
1684 // An lvalue of function type T can be converted to an rvalue of
1685 // type "pointer to T." The result is a pointer to the
1686 // function. (C++ 4.3p1).
1687 FromType = S.Context.getPointerType(FromType);
1688 } else {
1689 // We don't require any conversions for the first step.
1690 SCS.First = ICK_Identity;
1691 }
1692 SCS.setToType(0, FromType);
1693
1694 // The second conversion can be an integral promotion, floating
1695 // point promotion, integral conversion, floating point conversion,
1696 // floating-integral conversion, pointer conversion,
1697 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1698 // For overloading in C, this can also be a "compatible-type"
1699 // conversion.
1700 bool IncompatibleObjC = false;
1701 ImplicitConversionKind SecondICK = ICK_Identity;
1702 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1703 // The unqualified versions of the types are the same: there's no
1704 // conversion to do.
1705 SCS.Second = ICK_Identity;
1706 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1707 // Integral promotion (C++ 4.5).
1708 SCS.Second = ICK_Integral_Promotion;
1709 FromType = ToType.getUnqualifiedType();
1710 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1711 // Floating point promotion (C++ 4.6).
1712 SCS.Second = ICK_Floating_Promotion;
1713 FromType = ToType.getUnqualifiedType();
1714 } else if (S.IsComplexPromotion(FromType, ToType)) {
1715 // Complex promotion (Clang extension)
1716 SCS.Second = ICK_Complex_Promotion;
1717 FromType = ToType.getUnqualifiedType();
1718 } else if (ToType->isBooleanType() &&
1719 (FromType->isArithmeticType() ||
1720 FromType->isAnyPointerType() ||
1721 FromType->isBlockPointerType() ||
1722 FromType->isMemberPointerType() ||
1723 FromType->isNullPtrType())) {
1724 // Boolean conversions (C++ 4.12).
1725 SCS.Second = ICK_Boolean_Conversion;
1726 FromType = S.Context.BoolTy;
1727 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1728 ToType->isIntegralType(S.Context)) {
1729 // Integral conversions (C++ 4.7).
1730 SCS.Second = ICK_Integral_Conversion;
1731 FromType = ToType.getUnqualifiedType();
1732 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1733 // Complex conversions (C99 6.3.1.6)
1734 SCS.Second = ICK_Complex_Conversion;
1735 FromType = ToType.getUnqualifiedType();
1736 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1737 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1738 // Complex-real conversions (C99 6.3.1.7)
1739 SCS.Second = ICK_Complex_Real;
1740 FromType = ToType.getUnqualifiedType();
1741 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1742 // FIXME: disable conversions between long double and __float128 if
1743 // their representation is different until there is back end support
1744 // We of course allow this conversion if long double is really double.
1745 if (&S.Context.getFloatTypeSemantics(FromType) !=
1746 &S.Context.getFloatTypeSemantics(ToType)) {
1747 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1748 ToType == S.Context.LongDoubleTy) ||
1749 (FromType == S.Context.LongDoubleTy &&
1750 ToType == S.Context.Float128Ty));
1751 if (Float128AndLongDouble &&
1752 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1753 &llvm::APFloat::IEEEdouble()))
1754 return false;
1755 }
1756 // Floating point conversions (C++ 4.8).
1757 SCS.Second = ICK_Floating_Conversion;
1758 FromType = ToType.getUnqualifiedType();
1759 } else if ((FromType->isRealFloatingType() &&
1760 ToType->isIntegralType(S.Context)) ||
1761 (FromType->isIntegralOrUnscopedEnumerationType() &&
1762 ToType->isRealFloatingType())) {
1763 // Floating-integral conversions (C++ 4.9).
1764 SCS.Second = ICK_Floating_Integral;
1765 FromType = ToType.getUnqualifiedType();
1766 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1767 SCS.Second = ICK_Block_Pointer_Conversion;
1768 } else if (AllowObjCWritebackConversion &&
1769 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1770 SCS.Second = ICK_Writeback_Conversion;
1771 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1772 FromType, IncompatibleObjC)) {
1773 // Pointer conversions (C++ 4.10).
1774 SCS.Second = ICK_Pointer_Conversion;
1775 SCS.IncompatibleObjC = IncompatibleObjC;
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1778 InOverloadResolution, FromType)) {
1779 // Pointer to member conversions (4.11).
1780 SCS.Second = ICK_Pointer_Member;
1781 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1782 SCS.Second = SecondICK;
1783 FromType = ToType.getUnqualifiedType();
1784 } else if (!S.getLangOpts().CPlusPlus &&
1785 S.Context.typesAreCompatible(ToType, FromType)) {
1786 // Compatible conversions (Clang extension for C function overloading)
1787 SCS.Second = ICK_Compatible_Conversion;
1788 FromType = ToType.getUnqualifiedType();
1789 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1790 InOverloadResolution,
1791 SCS, CStyle)) {
1792 SCS.Second = ICK_TransparentUnionConversion;
1793 FromType = ToType;
1794 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1795 CStyle)) {
1796 // tryAtomicConversion has updated the standard conversion sequence
1797 // appropriately.
1798 return true;
1799 } else if (ToType->isEventT() &&
1800 From->isIntegerConstantExpr(S.getASTContext()) &&
1801 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1802 SCS.Second = ICK_Zero_Event_Conversion;
1803 FromType = ToType;
1804 } else if (ToType->isQueueT() &&
1805 From->isIntegerConstantExpr(S.getASTContext()) &&
1806 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1807 SCS.Second = ICK_Zero_Queue_Conversion;
1808 FromType = ToType;
1809 } else {
1810 // No second conversion required.
1811 SCS.Second = ICK_Identity;
1812 }
1813 SCS.setToType(1, FromType);
1814
1815 // The third conversion can be a function pointer conversion or a
1816 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1817 bool ObjCLifetimeConversion;
1818 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1819 // Function pointer conversions (removing 'noexcept') including removal of
1820 // 'noreturn' (Clang extension).
1821 SCS.Third = ICK_Function_Conversion;
1822 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1823 ObjCLifetimeConversion)) {
1824 SCS.Third = ICK_Qualification;
1825 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1826 FromType = ToType;
1827 } else {
1828 // No conversion required
1829 SCS.Third = ICK_Identity;
1830 }
1831
1832 // C++ [over.best.ics]p6:
1833 // [...] Any difference in top-level cv-qualification is
1834 // subsumed by the initialization itself and does not constitute
1835 // a conversion. [...]
1836 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1837 QualType CanonTo = S.Context.getCanonicalType(ToType);
1838 if (CanonFrom.getLocalUnqualifiedType()
1839 == CanonTo.getLocalUnqualifiedType() &&
1840 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1841 FromType = ToType;
1842 CanonFrom = CanonTo;
1843 }
1844
1845 SCS.setToType(2, FromType);
1846
1847 if (CanonFrom == CanonTo)
1848 return true;
1849
1850 // If we have not converted the argument type to the parameter type,
1851 // this is a bad conversion sequence, unless we're resolving an overload in C.
1852 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1853 return false;
1854
1855 ExprResult ER = ExprResult{From};
1856 Sema::AssignConvertType Conv =
1857 S.CheckSingleAssignmentConstraints(ToType, ER,
1858 /*Diagnose=*/false,
1859 /*DiagnoseCFAudited=*/false,
1860 /*ConvertRHS=*/false);
1861 ImplicitConversionKind SecondConv;
1862 switch (Conv) {
1863 case Sema::Compatible:
1864 SecondConv = ICK_C_Only_Conversion;
1865 break;
1866 // For our purposes, discarding qualifiers is just as bad as using an
1867 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1868 // qualifiers, as well.
1869 case Sema::CompatiblePointerDiscardsQualifiers:
1870 case Sema::IncompatiblePointer:
1871 case Sema::IncompatiblePointerSign:
1872 SecondConv = ICK_Incompatible_Pointer_Conversion;
1873 break;
1874 default:
1875 return false;
1876 }
1877
1878 // First can only be an lvalue conversion, so we pretend that this was the
1879 // second conversion. First should already be valid from earlier in the
1880 // function.
1881 SCS.Second = SecondConv;
1882 SCS.setToType(1, ToType);
1883
1884 // Third is Identity, because Second should rank us worse than any other
1885 // conversion. This could also be ICK_Qualification, but it's simpler to just
1886 // lump everything in with the second conversion, and we don't gain anything
1887 // from making this ICK_Qualification.
1888 SCS.Third = ICK_Identity;
1889 SCS.setToType(2, ToType);
1890 return true;
1891}
1892
1893static bool
1894IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1895 QualType &ToType,
1896 bool InOverloadResolution,
1897 StandardConversionSequence &SCS,
1898 bool CStyle) {
1899
1900 const RecordType *UT = ToType->getAsUnionType();
1901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1902 return false;
1903 // The field to initialize within the transparent union.
1904 RecordDecl *UD = UT->getDecl();
1905 // It's compatible if the expression matches any of the fields.
1906 for (const auto *it : UD->fields()) {
1907 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1908 CStyle, /*ObjCWritebackConversion=*/false)) {
1909 ToType = it->getType();
1910 return true;
1911 }
1912 }
1913 return false;
1914}
1915
1916/// IsIntegralPromotion - Determines whether the conversion from the
1917/// expression From (whose potentially-adjusted type is FromType) to
1918/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1919/// sets PromotedType to the promoted type.
1920bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1921 const BuiltinType *To = ToType->getAs<BuiltinType>();
1922 // All integers are built-in.
1923 if (!To) {
1924 return false;
1925 }
1926
1927 // An rvalue of type char, signed char, unsigned char, short int, or
1928 // unsigned short int can be converted to an rvalue of type int if
1929 // int can represent all the values of the source type; otherwise,
1930 // the source rvalue can be converted to an rvalue of type unsigned
1931 // int (C++ 4.5p1).
1932 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1933 !FromType->isEnumeralType()) {
1934 if (// We can promote any signed, promotable integer type to an int
1935 (FromType->isSignedIntegerType() ||
1936 // We can promote any unsigned integer type whose size is
1937 // less than int to an int.
1938 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1939 return To->getKind() == BuiltinType::Int;
1940 }
1941
1942 return To->getKind() == BuiltinType::UInt;
1943 }
1944
1945 // C++11 [conv.prom]p3:
1946 // A prvalue of an unscoped enumeration type whose underlying type is not
1947 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1948 // following types that can represent all the values of the enumeration
1949 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1950 // unsigned int, long int, unsigned long int, long long int, or unsigned
1951 // long long int. If none of the types in that list can represent all the
1952 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1953 // type can be converted to an rvalue a prvalue of the extended integer type
1954 // with lowest integer conversion rank (4.13) greater than the rank of long
1955 // long in which all the values of the enumeration can be represented. If
1956 // there are two such extended types, the signed one is chosen.
1957 // C++11 [conv.prom]p4:
1958 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1959 // can be converted to a prvalue of its underlying type. Moreover, if
1960 // integral promotion can be applied to its underlying type, a prvalue of an
1961 // unscoped enumeration type whose underlying type is fixed can also be
1962 // converted to a prvalue of the promoted underlying type.
1963 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1964 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1965 // provided for a scoped enumeration.
1966 if (FromEnumType->getDecl()->isScoped())
1967 return false;
1968
1969 // We can perform an integral promotion to the underlying type of the enum,
1970 // even if that's not the promoted type. Note that the check for promoting
1971 // the underlying type is based on the type alone, and does not consider
1972 // the bitfield-ness of the actual source expression.
1973 if (FromEnumType->getDecl()->isFixed()) {
1974 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1975 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1976 IsIntegralPromotion(nullptr, Underlying, ToType);
1977 }
1978
1979 // We have already pre-calculated the promotion type, so this is trivial.
1980 if (ToType->isIntegerType() &&
1981 isCompleteType(From->getLocStart(), FromType))
1982 return Context.hasSameUnqualifiedType(
1983 ToType, FromEnumType->getDecl()->getPromotionType());
1984 }
1985
1986 // C++0x [conv.prom]p2:
1987 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1988 // to an rvalue a prvalue of the first of the following types that can
1989 // represent all the values of its underlying type: int, unsigned int,
1990 // long int, unsigned long int, long long int, or unsigned long long int.
1991 // If none of the types in that list can represent all the values of its
1992 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1993 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1994 // type.
1995 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1996 ToType->isIntegerType()) {
1997 // Determine whether the type we're converting from is signed or
1998 // unsigned.
1999 bool FromIsSigned = FromType->isSignedIntegerType();
2000 uint64_t FromSize = Context.getTypeSize(FromType);
2001
2002 // The types we'll try to promote to, in the appropriate
2003 // order. Try each of these types.
2004 QualType PromoteTypes[6] = {
2005 Context.IntTy, Context.UnsignedIntTy,
2006 Context.LongTy, Context.UnsignedLongTy ,
2007 Context.LongLongTy, Context.UnsignedLongLongTy
2008 };
2009 for (int Idx = 0; Idx < 6; ++Idx) {
2010 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2011 if (FromSize < ToSize ||
2012 (FromSize == ToSize &&
2013 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2014 // We found the type that we can promote to. If this is the
2015 // type we wanted, we have a promotion. Otherwise, no
2016 // promotion.
2017 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2018 }
2019 }
2020 }
2021
2022 // An rvalue for an integral bit-field (9.6) can be converted to an
2023 // rvalue of type int if int can represent all the values of the
2024 // bit-field; otherwise, it can be converted to unsigned int if
2025 // unsigned int can represent all the values of the bit-field. If
2026 // the bit-field is larger yet, no integral promotion applies to
2027 // it. If the bit-field has an enumerated type, it is treated as any
2028 // other value of that type for promotion purposes (C++ 4.5p3).
2029 // FIXME: We should delay checking of bit-fields until we actually perform the
2030 // conversion.
2031 if (From) {
2032 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2033 llvm::APSInt BitWidth;
2034 if (FromType->isIntegralType(Context) &&
2035 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2036 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2037 ToSize = Context.getTypeSize(ToType);
2038
2039 // Are we promoting to an int from a bitfield that fits in an int?
2040 if (BitWidth < ToSize ||
2041 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2042 return To->getKind() == BuiltinType::Int;
2043 }
2044
2045 // Are we promoting to an unsigned int from an unsigned bitfield
2046 // that fits into an unsigned int?
2047 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2048 return To->getKind() == BuiltinType::UInt;
2049 }
2050
2051 return false;
2052 }
2053 }
2054 }
2055
2056 // An rvalue of type bool can be converted to an rvalue of type int,
2057 // with false becoming zero and true becoming one (C++ 4.5p4).
2058 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2059 return true;
2060 }
2061
2062 return false;
2063}
2064
2065/// IsFloatingPointPromotion - Determines whether the conversion from
2066/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2067/// returns true and sets PromotedType to the promoted type.
2068bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2069 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2070 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2071 /// An rvalue of type float can be converted to an rvalue of type
2072 /// double. (C++ 4.6p1).
2073 if (FromBuiltin->getKind() == BuiltinType::Float &&
2074 ToBuiltin->getKind() == BuiltinType::Double)
2075 return true;
2076
2077 // C99 6.3.1.5p1:
2078 // When a float is promoted to double or long double, or a
2079 // double is promoted to long double [...].
2080 if (!getLangOpts().CPlusPlus &&
2081 (FromBuiltin->getKind() == BuiltinType::Float ||
2082 FromBuiltin->getKind() == BuiltinType::Double) &&
2083 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2084 ToBuiltin->getKind() == BuiltinType::Float128))
2085 return true;
2086
2087 // Half can be promoted to float.
2088 if (!getLangOpts().NativeHalfType &&
2089 FromBuiltin->getKind() == BuiltinType::Half &&
2090 ToBuiltin->getKind() == BuiltinType::Float)
2091 return true;
2092 }
2093
2094 return false;
2095}
2096
2097/// \brief Determine if a conversion is a complex promotion.
2098///
2099/// A complex promotion is defined as a complex -> complex conversion
2100/// where the conversion between the underlying real types is a
2101/// floating-point or integral promotion.
2102bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2103 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2104 if (!FromComplex)
2105 return false;
2106
2107 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2108 if (!ToComplex)
2109 return false;
2110
2111 return IsFloatingPointPromotion(FromComplex->getElementType(),
2112 ToComplex->getElementType()) ||
2113 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2114 ToComplex->getElementType());
2115}
2116
2117/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2118/// the pointer type FromPtr to a pointer to type ToPointee, with the
2119/// same type qualifiers as FromPtr has on its pointee type. ToType,
2120/// if non-empty, will be a pointer to ToType that may or may not have
2121/// the right set of qualifiers on its pointee.
2122///
2123static QualType
2124BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2125 QualType ToPointee, QualType ToType,
2126 ASTContext &Context,
2127 bool StripObjCLifetime = false) {
2128 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2130, __PRETTY_FUNCTION__))
2129 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2130, __PRETTY_FUNCTION__))
2130 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2130, __PRETTY_FUNCTION__))
;
2131
2132 /// Conversions to 'id' subsume cv-qualifier conversions.
2133 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2134 return ToType.getUnqualifiedType();
2135
2136 QualType CanonFromPointee
2137 = Context.getCanonicalType(FromPtr->getPointeeType());
2138 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2139 Qualifiers Quals = CanonFromPointee.getQualifiers();
2140
2141 if (StripObjCLifetime)
2142 Quals.removeObjCLifetime();
2143
2144 // Exact qualifier match -> return the pointer type we're converting to.
2145 if (CanonToPointee.getLocalQualifiers() == Quals) {
2146 // ToType is exactly what we need. Return it.
2147 if (!ToType.isNull())
2148 return ToType.getUnqualifiedType();
2149
2150 // Build a pointer to ToPointee. It has the right qualifiers
2151 // already.
2152 if (isa<ObjCObjectPointerType>(ToType))
2153 return Context.getObjCObjectPointerType(ToPointee);
2154 return Context.getPointerType(ToPointee);
2155 }
2156
2157 // Just build a canonical type that has the right qualifiers.
2158 QualType QualifiedCanonToPointee
2159 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2160
2161 if (isa<ObjCObjectPointerType>(ToType))
2162 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2163 return Context.getPointerType(QualifiedCanonToPointee);
2164}
2165
2166static bool isNullPointerConstantForConversion(Expr *Expr,
2167 bool InOverloadResolution,
2168 ASTContext &Context) {
2169 // Handle value-dependent integral null pointer constants correctly.
2170 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2171 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2172 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2173 return !InOverloadResolution;
2174
2175 return Expr->isNullPointerConstant(Context,
2176 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2177 : Expr::NPC_ValueDependentIsNull);
2178}
2179
2180/// IsPointerConversion - Determines whether the conversion of the
2181/// expression From, which has the (possibly adjusted) type FromType,
2182/// can be converted to the type ToType via a pointer conversion (C++
2183/// 4.10). If so, returns true and places the converted type (that
2184/// might differ from ToType in its cv-qualifiers at some level) into
2185/// ConvertedType.
2186///
2187/// This routine also supports conversions to and from block pointers
2188/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2189/// pointers to interfaces. FIXME: Once we've determined the
2190/// appropriate overloading rules for Objective-C, we may want to
2191/// split the Objective-C checks into a different routine; however,
2192/// GCC seems to consider all of these conversions to be pointer
2193/// conversions, so for now they live here. IncompatibleObjC will be
2194/// set if the conversion is an allowed Objective-C conversion that
2195/// should result in a warning.
2196bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2197 bool InOverloadResolution,
2198 QualType& ConvertedType,
2199 bool &IncompatibleObjC) {
2200 IncompatibleObjC = false;
2201 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2202 IncompatibleObjC))
2203 return true;
2204
2205 // Conversion from a null pointer constant to any Objective-C pointer type.
2206 if (ToType->isObjCObjectPointerType() &&
2207 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2208 ConvertedType = ToType;
2209 return true;
2210 }
2211
2212 // Blocks: Block pointers can be converted to void*.
2213 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2214 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2215 ConvertedType = ToType;
2216 return true;
2217 }
2218 // Blocks: A null pointer constant can be converted to a block
2219 // pointer type.
2220 if (ToType->isBlockPointerType() &&
2221 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2222 ConvertedType = ToType;
2223 return true;
2224 }
2225
2226 // If the left-hand-side is nullptr_t, the right side can be a null
2227 // pointer constant.
2228 if (ToType->isNullPtrType() &&
2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2230 ConvertedType = ToType;
2231 return true;
2232 }
2233
2234 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2235 if (!ToTypePtr)
2236 return false;
2237
2238 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2239 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2240 ConvertedType = ToType;
2241 return true;
2242 }
2243
2244 // Beyond this point, both types need to be pointers
2245 // , including objective-c pointers.
2246 QualType ToPointeeType = ToTypePtr->getPointeeType();
2247 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2248 !getLangOpts().ObjCAutoRefCount) {
2249 ConvertedType = BuildSimilarlyQualifiedPointerType(
2250 FromType->getAs<ObjCObjectPointerType>(),
2251 ToPointeeType,
2252 ToType, Context);
2253 return true;
2254 }
2255 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2256 if (!FromTypePtr)
2257 return false;
2258
2259 QualType FromPointeeType = FromTypePtr->getPointeeType();
2260
2261 // If the unqualified pointee types are the same, this can't be a
2262 // pointer conversion, so don't do all of the work below.
2263 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2264 return false;
2265
2266 // An rvalue of type "pointer to cv T," where T is an object type,
2267 // can be converted to an rvalue of type "pointer to cv void" (C++
2268 // 4.10p2).
2269 if (FromPointeeType->isIncompleteOrObjectType() &&
2270 ToPointeeType->isVoidType()) {
2271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2272 ToPointeeType,
2273 ToType, Context,
2274 /*StripObjCLifetime=*/true);
2275 return true;
2276 }
2277
2278 // MSVC allows implicit function to void* type conversion.
2279 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2280 ToPointeeType->isVoidType()) {
2281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2282 ToPointeeType,
2283 ToType, Context);
2284 return true;
2285 }
2286
2287 // When we're overloading in C, we allow a special kind of pointer
2288 // conversion for compatible-but-not-identical pointee types.
2289 if (!getLangOpts().CPlusPlus &&
2290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2292 ToPointeeType,
2293 ToType, Context);
2294 return true;
2295 }
2296
2297 // C++ [conv.ptr]p3:
2298 //
2299 // An rvalue of type "pointer to cv D," where D is a class type,
2300 // can be converted to an rvalue of type "pointer to cv B," where
2301 // B is a base class (clause 10) of D. If B is an inaccessible
2302 // (clause 11) or ambiguous (10.2) base class of D, a program that
2303 // necessitates this conversion is ill-formed. The result of the
2304 // conversion is a pointer to the base class sub-object of the
2305 // derived class object. The null pointer value is converted to
2306 // the null pointer value of the destination type.
2307 //
2308 // Note that we do not check for ambiguity or inaccessibility
2309 // here. That is handled by CheckPointerConversion.
2310 if (getLangOpts().CPlusPlus &&
2311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2313 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2315 ToPointeeType,
2316 ToType, Context);
2317 return true;
2318 }
2319
2320 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2321 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2323 ToPointeeType,
2324 ToType, Context);
2325 return true;
2326 }
2327
2328 return false;
2329}
2330
2331/// \brief Adopt the given qualifiers for the given type.
2332static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2333 Qualifiers TQs = T.getQualifiers();
2334
2335 // Check whether qualifiers already match.
2336 if (TQs == Qs)
2337 return T;
2338
2339 if (Qs.compatiblyIncludes(TQs))
2340 return Context.getQualifiedType(T, Qs);
2341
2342 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2343}
2344
2345/// isObjCPointerConversion - Determines whether this is an
2346/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2347/// with the same arguments and return values.
2348bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2349 QualType& ConvertedType,
2350 bool &IncompatibleObjC) {
2351 if (!getLangOpts().ObjC1)
2352 return false;
2353
2354 // The set of qualifiers on the type we're converting from.
2355 Qualifiers FromQualifiers = FromType.getQualifiers();
2356
2357 // First, we handle all conversions on ObjC object pointer types.
2358 const ObjCObjectPointerType* ToObjCPtr =
2359 ToType->getAs<ObjCObjectPointerType>();
2360 const ObjCObjectPointerType *FromObjCPtr =
2361 FromType->getAs<ObjCObjectPointerType>();
2362
2363 if (ToObjCPtr && FromObjCPtr) {
2364 // If the pointee types are the same (ignoring qualifications),
2365 // then this is not a pointer conversion.
2366 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2367 FromObjCPtr->getPointeeType()))
2368 return false;
2369
2370 // Conversion between Objective-C pointers.
2371 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2372 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2373 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2374 if (getLangOpts().CPlusPlus && LHS && RHS &&
2375 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2376 FromObjCPtr->getPointeeType()))
2377 return false;
2378 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2379 ToObjCPtr->getPointeeType(),
2380 ToType, Context);
2381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2382 return true;
2383 }
2384
2385 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2386 // Okay: this is some kind of implicit downcast of Objective-C
2387 // interfaces, which is permitted. However, we're going to
2388 // complain about it.
2389 IncompatibleObjC = true;
2390 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2391 ToObjCPtr->getPointeeType(),
2392 ToType, Context);
2393 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2394 return true;
2395 }
2396 }
2397 // Beyond this point, both types need to be C pointers or block pointers.
2398 QualType ToPointeeType;
2399 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2400 ToPointeeType = ToCPtr->getPointeeType();
2401 else if (const BlockPointerType *ToBlockPtr =
2402 ToType->getAs<BlockPointerType>()) {
2403 // Objective C++: We're able to convert from a pointer to any object
2404 // to a block pointer type.
2405 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2407 return true;
2408 }
2409 ToPointeeType = ToBlockPtr->getPointeeType();
2410 }
2411 else if (FromType->getAs<BlockPointerType>() &&
2412 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2413 // Objective C++: We're able to convert from a block pointer type to a
2414 // pointer to any object.
2415 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2416 return true;
2417 }
2418 else
2419 return false;
2420
2421 QualType FromPointeeType;
2422 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2423 FromPointeeType = FromCPtr->getPointeeType();
2424 else if (const BlockPointerType *FromBlockPtr =
2425 FromType->getAs<BlockPointerType>())
2426 FromPointeeType = FromBlockPtr->getPointeeType();
2427 else
2428 return false;
2429
2430 // If we have pointers to pointers, recursively check whether this
2431 // is an Objective-C conversion.
2432 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2433 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2434 IncompatibleObjC)) {
2435 // We always complain about this conversion.
2436 IncompatibleObjC = true;
2437 ConvertedType = Context.getPointerType(ConvertedType);
2438 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2439 return true;
2440 }
2441 // Allow conversion of pointee being objective-c pointer to another one;
2442 // as in I* to id.
2443 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2444 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2446 IncompatibleObjC)) {
2447
2448 ConvertedType = Context.getPointerType(ConvertedType);
2449 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2450 return true;
2451 }
2452
2453 // If we have pointers to functions or blocks, check whether the only
2454 // differences in the argument and result types are in Objective-C
2455 // pointer conversions. If so, we permit the conversion (but
2456 // complain about it).
2457 const FunctionProtoType *FromFunctionType
2458 = FromPointeeType->getAs<FunctionProtoType>();
2459 const FunctionProtoType *ToFunctionType
2460 = ToPointeeType->getAs<FunctionProtoType>();
2461 if (FromFunctionType && ToFunctionType) {
2462 // If the function types are exactly the same, this isn't an
2463 // Objective-C pointer conversion.
2464 if (Context.getCanonicalType(FromPointeeType)
2465 == Context.getCanonicalType(ToPointeeType))
2466 return false;
2467
2468 // Perform the quick checks that will tell us whether these
2469 // function types are obviously different.
2470 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2471 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2472 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2473 return false;
2474
2475 bool HasObjCConversion = false;
2476 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2477 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2478 // Okay, the types match exactly. Nothing to do.
2479 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2480 ToFunctionType->getReturnType(),
2481 ConvertedType, IncompatibleObjC)) {
2482 // Okay, we have an Objective-C pointer conversion.
2483 HasObjCConversion = true;
2484 } else {
2485 // Function types are too different. Abort.
2486 return false;
2487 }
2488
2489 // Check argument types.
2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2491 ArgIdx != NumArgs; ++ArgIdx) {
2492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2494 if (Context.getCanonicalType(FromArgType)
2495 == Context.getCanonicalType(ToArgType)) {
2496 // Okay, the types match exactly. Nothing to do.
2497 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2501 } else {
2502 // Argument types are too different. Abort.
2503 return false;
2504 }
2505 }
2506
2507 if (HasObjCConversion) {
2508 // We had an Objective-C conversion. Allow this pointer
2509 // conversion, but complain about it.
2510 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2511 IncompatibleObjC = true;
2512 return true;
2513 }
2514 }
2515
2516 return false;
2517}
2518
2519/// \brief Determine whether this is an Objective-C writeback conversion,
2520/// used for parameter passing when performing automatic reference counting.
2521///
2522/// \param FromType The type we're converting form.
2523///
2524/// \param ToType The type we're converting to.
2525///
2526/// \param ConvertedType The type that will be produced after applying
2527/// this conversion.
2528bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2529 QualType &ConvertedType) {
2530 if (!getLangOpts().ObjCAutoRefCount ||
2531 Context.hasSameUnqualifiedType(FromType, ToType))
2532 return false;
2533
2534 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2535 QualType ToPointee;
2536 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2537 ToPointee = ToPointer->getPointeeType();
2538 else
2539 return false;
2540
2541 Qualifiers ToQuals = ToPointee.getQualifiers();
2542 if (!ToPointee->isObjCLifetimeType() ||
2543 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2544 !ToQuals.withoutObjCLifetime().empty())
2545 return false;
2546
2547 // Argument must be a pointer to __strong to __weak.
2548 QualType FromPointee;
2549 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2550 FromPointee = FromPointer->getPointeeType();
2551 else
2552 return false;
2553
2554 Qualifiers FromQuals = FromPointee.getQualifiers();
2555 if (!FromPointee->isObjCLifetimeType() ||
2556 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2557 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2558 return false;
2559
2560 // Make sure that we have compatible qualifiers.
2561 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2562 if (!ToQuals.compatiblyIncludes(FromQuals))
2563 return false;
2564
2565 // Remove qualifiers from the pointee type we're converting from; they
2566 // aren't used in the compatibility check belong, and we'll be adding back
2567 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2568 FromPointee = FromPointee.getUnqualifiedType();
2569
2570 // The unqualified form of the pointee types must be compatible.
2571 ToPointee = ToPointee.getUnqualifiedType();
2572 bool IncompatibleObjC;
2573 if (Context.typesAreCompatible(FromPointee, ToPointee))
2574 FromPointee = ToPointee;
2575 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2576 IncompatibleObjC))
2577 return false;
2578
2579 /// \brief Construct the type we're converting to, which is a pointer to
2580 /// __autoreleasing pointee.
2581 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2582 ConvertedType = Context.getPointerType(FromPointee);
2583 return true;
2584}
2585
2586bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2587 QualType& ConvertedType) {
2588 QualType ToPointeeType;
2589 if (const BlockPointerType *ToBlockPtr =
2590 ToType->getAs<BlockPointerType>())
2591 ToPointeeType = ToBlockPtr->getPointeeType();
2592 else
2593 return false;
2594
2595 QualType FromPointeeType;
2596 if (const BlockPointerType *FromBlockPtr =
2597 FromType->getAs<BlockPointerType>())
2598 FromPointeeType = FromBlockPtr->getPointeeType();
2599 else
2600 return false;
2601 // We have pointer to blocks, check whether the only
2602 // differences in the argument and result types are in Objective-C
2603 // pointer conversions. If so, we permit the conversion.
2604
2605 const FunctionProtoType *FromFunctionType
2606 = FromPointeeType->getAs<FunctionProtoType>();
2607 const FunctionProtoType *ToFunctionType
2608 = ToPointeeType->getAs<FunctionProtoType>();
2609
2610 if (!FromFunctionType || !ToFunctionType)
2611 return false;
2612
2613 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2614 return true;
2615
2616 // Perform the quick checks that will tell us whether these
2617 // function types are obviously different.
2618 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2619 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2620 return false;
2621
2622 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2623 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2624 if (FromEInfo != ToEInfo)
2625 return false;
2626
2627 bool IncompatibleObjC = false;
2628 if (Context.hasSameType(FromFunctionType->getReturnType(),
2629 ToFunctionType->getReturnType())) {
2630 // Okay, the types match exactly. Nothing to do.
2631 } else {
2632 QualType RHS = FromFunctionType->getReturnType();
2633 QualType LHS = ToFunctionType->getReturnType();
2634 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2635 !RHS.hasQualifiers() && LHS.hasQualifiers())
2636 LHS = LHS.getUnqualifiedType();
2637
2638 if (Context.hasSameType(RHS,LHS)) {
2639 // OK exact match.
2640 } else if (isObjCPointerConversion(RHS, LHS,
2641 ConvertedType, IncompatibleObjC)) {
2642 if (IncompatibleObjC)
2643 return false;
2644 // Okay, we have an Objective-C pointer conversion.
2645 }
2646 else
2647 return false;
2648 }
2649
2650 // Check argument types.
2651 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2652 ArgIdx != NumArgs; ++ArgIdx) {
2653 IncompatibleObjC = false;
2654 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2655 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2656 if (Context.hasSameType(FromArgType, ToArgType)) {
2657 // Okay, the types match exactly. Nothing to do.
2658 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2659 ConvertedType, IncompatibleObjC)) {
2660 if (IncompatibleObjC)
2661 return false;
2662 // Okay, we have an Objective-C pointer conversion.
2663 } else
2664 // Argument types are too different. Abort.
2665 return false;
2666 }
2667 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2668 ToFunctionType))
2669 return false;
2670
2671 ConvertedType = ToType;
2672 return true;
2673}
2674
2675enum {
2676 ft_default,
2677 ft_different_class,
2678 ft_parameter_arity,
2679 ft_parameter_mismatch,
2680 ft_return_type,
2681 ft_qualifer_mismatch,
2682 ft_noexcept
2683};
2684
2685/// Attempts to get the FunctionProtoType from a Type. Handles
2686/// MemberFunctionPointers properly.
2687static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2688 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2689 return FPT;
2690
2691 if (auto *MPT = FromType->getAs<MemberPointerType>())
2692 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2693
2694 return nullptr;
2695}
2696
2697/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2698/// function types. Catches different number of parameter, mismatch in
2699/// parameter types, and different return types.
2700void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2701 QualType FromType, QualType ToType) {
2702 // If either type is not valid, include no extra info.
2703 if (FromType.isNull() || ToType.isNull()) {
2704 PDiag << ft_default;
2705 return;
2706 }
2707
2708 // Get the function type from the pointers.
2709 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2710 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2711 *ToMember = ToType->getAs<MemberPointerType>();
2712 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2713 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2714 << QualType(FromMember->getClass(), 0);
2715 return;
2716 }
2717 FromType = FromMember->getPointeeType();
2718 ToType = ToMember->getPointeeType();
2719 }
2720
2721 if (FromType->isPointerType())
2722 FromType = FromType->getPointeeType();
2723 if (ToType->isPointerType())
2724 ToType = ToType->getPointeeType();
2725
2726 // Remove references.
2727 FromType = FromType.getNonReferenceType();
2728 ToType = ToType.getNonReferenceType();
2729
2730 // Don't print extra info for non-specialized template functions.
2731 if (FromType->isInstantiationDependentType() &&
2732 !FromType->getAs<TemplateSpecializationType>()) {
2733 PDiag << ft_default;
2734 return;
2735 }
2736
2737 // No extra info for same types.
2738 if (Context.hasSameType(FromType, ToType)) {
2739 PDiag << ft_default;
2740 return;
2741 }
2742
2743 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2744 *ToFunction = tryGetFunctionProtoType(ToType);
2745
2746 // Both types need to be function types.
2747 if (!FromFunction || !ToFunction) {
2748 PDiag << ft_default;
2749 return;
2750 }
2751
2752 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2753 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2754 << FromFunction->getNumParams();
2755 return;
2756 }
2757
2758 // Handle different parameter types.
2759 unsigned ArgPos;
2760 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2761 PDiag << ft_parameter_mismatch << ArgPos + 1
2762 << ToFunction->getParamType(ArgPos)
2763 << FromFunction->getParamType(ArgPos);
2764 return;
2765 }
2766
2767 // Handle different return type.
2768 if (!Context.hasSameType(FromFunction->getReturnType(),
2769 ToFunction->getReturnType())) {
2770 PDiag << ft_return_type << ToFunction->getReturnType()
2771 << FromFunction->getReturnType();
2772 return;
2773 }
2774
2775 unsigned FromQuals = FromFunction->getTypeQuals(),
2776 ToQuals = ToFunction->getTypeQuals();
2777 if (FromQuals != ToQuals) {
2778 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2779 return;
2780 }
2781
2782 // Handle exception specification differences on canonical type (in C++17
2783 // onwards).
2784 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2785 ->isNothrow(Context) !=
2786 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2787 ->isNothrow(Context)) {
2788 PDiag << ft_noexcept;
2789 return;
2790 }
2791
2792 // Unable to find a difference, so add no extra info.
2793 PDiag << ft_default;
2794}
2795
2796/// FunctionParamTypesAreEqual - This routine checks two function proto types
2797/// for equality of their argument types. Caller has already checked that
2798/// they have same number of arguments. If the parameters are different,
2799/// ArgPos will have the parameter index of the first different parameter.
2800bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2801 const FunctionProtoType *NewType,
2802 unsigned *ArgPos) {
2803 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2804 N = NewType->param_type_begin(),
2805 E = OldType->param_type_end();
2806 O && (O != E); ++O, ++N) {
2807 if (!Context.hasSameType(O->getUnqualifiedType(),
2808 N->getUnqualifiedType())) {
2809 if (ArgPos)
2810 *ArgPos = O - OldType->param_type_begin();
2811 return false;
2812 }
2813 }
2814 return true;
2815}
2816
2817/// CheckPointerConversion - Check the pointer conversion from the
2818/// expression From to the type ToType. This routine checks for
2819/// ambiguous or inaccessible derived-to-base pointer
2820/// conversions for which IsPointerConversion has already returned
2821/// true. It returns true and produces a diagnostic if there was an
2822/// error, or returns false otherwise.
2823bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2824 CastKind &Kind,
2825 CXXCastPath& BasePath,
2826 bool IgnoreBaseAccess,
2827 bool Diagnose) {
2828 QualType FromType = From->getType();
2829 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2830
2831 Kind = CK_BitCast;
2832
2833 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2834 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2835 Expr::NPCK_ZeroExpression) {
2836 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2837 DiagRuntimeBehavior(From->getExprLoc(), From,
2838 PDiag(diag::warn_impcast_bool_to_null_pointer)
2839 << ToType << From->getSourceRange());
2840 else if (!isUnevaluatedContext())
2841 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2842 << ToType << From->getSourceRange();
2843 }
2844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2845 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2846 QualType FromPointeeType = FromPtrType->getPointeeType(),
2847 ToPointeeType = ToPtrType->getPointeeType();
2848
2849 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2850 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2851 // We must have a derived-to-base conversion. Check an
2852 // ambiguous or inaccessible conversion.
2853 unsigned InaccessibleID = 0;
2854 unsigned AmbigiousID = 0;
2855 if (Diagnose) {
2856 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2857 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2858 }
2859 if (CheckDerivedToBaseConversion(
2860 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2861 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2862 &BasePath, IgnoreBaseAccess))
2863 return true;
2864
2865 // The conversion was successful.
2866 Kind = CK_DerivedToBase;
2867 }
2868
2869 if (Diagnose && !IsCStyleOrFunctionalCast &&
2870 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2871 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2872, __PRETTY_FUNCTION__))
2872 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2872, __PRETTY_FUNCTION__))
;
2873 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2874 << From->getSourceRange();
2875 }
2876 }
2877 } else if (const ObjCObjectPointerType *ToPtrType =
2878 ToType->getAs<ObjCObjectPointerType>()) {
2879 if (const ObjCObjectPointerType *FromPtrType =
2880 FromType->getAs<ObjCObjectPointerType>()) {
2881 // Objective-C++ conversions are always okay.
2882 // FIXME: We should have a different class of conversions for the
2883 // Objective-C++ implicit conversions.
2884 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2885 return false;
2886 } else if (FromType->isBlockPointerType()) {
2887 Kind = CK_BlockPointerToObjCPointerCast;
2888 } else {
2889 Kind = CK_CPointerToObjCPointerCast;
2890 }
2891 } else if (ToType->isBlockPointerType()) {
2892 if (!FromType->isBlockPointerType())
2893 Kind = CK_AnyPointerToBlockPointerCast;
2894 }
2895
2896 // We shouldn't fall into this case unless it's valid for other
2897 // reasons.
2898 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2899 Kind = CK_NullToPointer;
2900
2901 return false;
2902}
2903
2904/// IsMemberPointerConversion - Determines whether the conversion of the
2905/// expression From, which has the (possibly adjusted) type FromType, can be
2906/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2907/// If so, returns true and places the converted type (that might differ from
2908/// ToType in its cv-qualifiers at some level) into ConvertedType.
2909bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2910 QualType ToType,
2911 bool InOverloadResolution,
2912 QualType &ConvertedType) {
2913 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2914 if (!ToTypePtr)
2915 return false;
2916
2917 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2918 if (From->isNullPointerConstant(Context,
2919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2920 : Expr::NPC_ValueDependentIsNull)) {
2921 ConvertedType = ToType;
2922 return true;
2923 }
2924
2925 // Otherwise, both types have to be member pointers.
2926 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2927 if (!FromTypePtr)
2928 return false;
2929
2930 // A pointer to member of B can be converted to a pointer to member of D,
2931 // where D is derived from B (C++ 4.11p2).
2932 QualType FromClass(FromTypePtr->getClass(), 0);
2933 QualType ToClass(ToTypePtr->getClass(), 0);
2934
2935 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2936 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2937 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2938 ToClass.getTypePtr());
2939 return true;
2940 }
2941
2942 return false;
2943}
2944
2945/// CheckMemberPointerConversion - Check the member pointer conversion from the
2946/// expression From to the type ToType. This routine checks for ambiguous or
2947/// virtual or inaccessible base-to-derived member pointer conversions
2948/// for which IsMemberPointerConversion has already returned true. It returns
2949/// true and produces a diagnostic if there was an error, or returns false
2950/// otherwise.
2951bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2952 CastKind &Kind,
2953 CXXCastPath &BasePath,
2954 bool IgnoreBaseAccess) {
2955 QualType FromType = From->getType();
2956 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2957 if (!FromPtrType) {
2958 // This must be a null pointer to member pointer conversion
2959 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2961, __PRETTY_FUNCTION__))
2960 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2961, __PRETTY_FUNCTION__))
2961 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2961, __PRETTY_FUNCTION__))
;
2962 Kind = CK_NullToMemberPointer;
2963 return false;
2964 }
2965
2966 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2967 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2968, __PRETTY_FUNCTION__))
2968 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2968, __PRETTY_FUNCTION__))
;
2969
2970 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2971 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2972
2973 // FIXME: What about dependent types?
2974 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2974, __PRETTY_FUNCTION__))
;
2975 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2975, __PRETTY_FUNCTION__))
;
2976
2977 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2978 /*DetectVirtual=*/true);
2979 bool DerivationOkay =
2980 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2981 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2982, __PRETTY_FUNCTION__))
2982 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 2982, __PRETTY_FUNCTION__))
;
2983 (void)DerivationOkay;
2984
2985 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2986 getUnqualifiedType())) {
2987 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2988 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2989 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2990 return true;
2991 }
2992
2993 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2994 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2995 << FromClass << ToClass << QualType(VBase, 0)
2996 << From->getSourceRange();
2997 return true;
2998 }
2999
3000 if (!IgnoreBaseAccess)
3001 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3002 Paths.front(),
3003 diag::err_downcast_from_inaccessible_base);
3004
3005 // Must be a base to derived member conversion.
3006 BuildBasePathArray(Paths, BasePath);
3007 Kind = CK_BaseToDerivedMemberPointer;
3008 return false;
3009}
3010
3011/// Determine whether the lifetime conversion between the two given
3012/// qualifiers sets is nontrivial.
3013static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3014 Qualifiers ToQuals) {
3015 // Converting anything to const __unsafe_unretained is trivial.
3016 if (ToQuals.hasConst() &&
3017 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3018 return false;
3019
3020 return true;
3021}
3022
3023/// IsQualificationConversion - Determines whether the conversion from
3024/// an rvalue of type FromType to ToType is a qualification conversion
3025/// (C++ 4.4).
3026///
3027/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3028/// when the qualification conversion involves a change in the Objective-C
3029/// object lifetime.
3030bool
3031Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3032 bool CStyle, bool &ObjCLifetimeConversion) {
3033 FromType = Context.getCanonicalType(FromType);
3034 ToType = Context.getCanonicalType(ToType);
3035 ObjCLifetimeConversion = false;
3036
3037 // If FromType and ToType are the same type, this is not a
3038 // qualification conversion.
3039 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3040 return false;
3041
3042 // (C++ 4.4p4):
3043 // A conversion can add cv-qualifiers at levels other than the first
3044 // in multi-level pointers, subject to the following rules: [...]
3045 bool PreviousToQualsIncludeConst = true;
3046 bool UnwrappedAnyPointer = false;
3047 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3048 // Within each iteration of the loop, we check the qualifiers to
3049 // determine if this still looks like a qualification
3050 // conversion. Then, if all is well, we unwrap one more level of
3051 // pointers or pointers-to-members and do it all again
3052 // until there are no more pointers or pointers-to-members left to
3053 // unwrap.
3054 UnwrappedAnyPointer = true;
3055
3056 Qualifiers FromQuals = FromType.getQualifiers();
3057 Qualifiers ToQuals = ToType.getQualifiers();
3058
3059 // Ignore __unaligned qualifier if this type is void.
3060 if (ToType.getUnqualifiedType()->isVoidType())
3061 FromQuals.removeUnaligned();
3062
3063 // Objective-C ARC:
3064 // Check Objective-C lifetime conversions.
3065 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3066 UnwrappedAnyPointer) {
3067 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3068 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3069 ObjCLifetimeConversion = true;
3070 FromQuals.removeObjCLifetime();
3071 ToQuals.removeObjCLifetime();
3072 } else {
3073 // Qualification conversions cannot cast between different
3074 // Objective-C lifetime qualifiers.
3075 return false;
3076 }
3077 }
3078
3079 // Allow addition/removal of GC attributes but not changing GC attributes.
3080 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3081 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3082 FromQuals.removeObjCGCAttr();
3083 ToQuals.removeObjCGCAttr();
3084 }
3085
3086 // -- for every j > 0, if const is in cv 1,j then const is in cv
3087 // 2,j, and similarly for volatile.
3088 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3089 return false;
3090
3091 // -- if the cv 1,j and cv 2,j are different, then const is in
3092 // every cv for 0 < k < j.
3093 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3094 && !PreviousToQualsIncludeConst)
3095 return false;
3096
3097 // Keep track of whether all prior cv-qualifiers in the "to" type
3098 // include const.
3099 PreviousToQualsIncludeConst
3100 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3101 }
3102
3103 // We are left with FromType and ToType being the pointee types
3104 // after unwrapping the original FromType and ToType the same number
3105 // of types. If we unwrapped any pointers, and if FromType and
3106 // ToType have the same unqualified type (since we checked
3107 // qualifiers above), then this is a qualification conversion.
3108 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3109}
3110
3111/// \brief - Determine whether this is a conversion from a scalar type to an
3112/// atomic type.
3113///
3114/// If successful, updates \c SCS's second and third steps in the conversion
3115/// sequence to finish the conversion.
3116static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3117 bool InOverloadResolution,
3118 StandardConversionSequence &SCS,
3119 bool CStyle) {
3120 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3121 if (!ToAtomic)
3122 return false;
3123
3124 StandardConversionSequence InnerSCS;
3125 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3126 InOverloadResolution, InnerSCS,
3127 CStyle, /*AllowObjCWritebackConversion=*/false))
3128 return false;
3129
3130 SCS.Second = InnerSCS.Second;
3131 SCS.setToType(1, InnerSCS.getToType(1));
3132 SCS.Third = InnerSCS.Third;
3133 SCS.QualificationIncludesObjCLifetime
3134 = InnerSCS.QualificationIncludesObjCLifetime;
3135 SCS.setToType(2, InnerSCS.getToType(2));
3136 return true;
3137}
3138
3139static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3140 CXXConstructorDecl *Constructor,
3141 QualType Type) {
3142 const FunctionProtoType *CtorType =
3143 Constructor->getType()->getAs<FunctionProtoType>();
3144 if (CtorType->getNumParams() > 0) {
3145 QualType FirstArg = CtorType->getParamType(0);
3146 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3147 return true;
3148 }
3149 return false;
3150}
3151
3152static OverloadingResult
3153IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3154 CXXRecordDecl *To,
3155 UserDefinedConversionSequence &User,
3156 OverloadCandidateSet &CandidateSet,
3157 bool AllowExplicit) {
3158 for (auto *D : S.LookupConstructors(To)) {
3159 auto Info = getConstructorInfo(D);
3160 if (!Info)
3161 continue;
3162
3163 bool Usable = !Info.Constructor->isInvalidDecl() &&
3164 S.isInitListConstructor(Info.Constructor) &&
3165 (AllowExplicit || !Info.Constructor->isExplicit());
3166 if (Usable) {
3167 // If the first argument is (a reference to) the target type,
3168 // suppress conversions.
3169 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3170 S.Context, Info.Constructor, ToType);
3171 if (Info.ConstructorTmpl)
3172 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3173 /*ExplicitArgs*/ nullptr, From,
3174 CandidateSet, SuppressUserConversions);
3175 else
3176 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3177 CandidateSet, SuppressUserConversions);
3178 }
3179 }
3180
3181 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3182
3183 OverloadCandidateSet::iterator Best;
3184 switch (auto Result =
3185 CandidateSet.BestViableFunction(S, From->getLocStart(),
3186 Best, true)) {
3187 case OR_Deleted:
3188 case OR_Success: {
3189 // Record the standard conversion we used and the conversion function.
3190 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3191 QualType ThisType = Constructor->getThisType(S.Context);
3192 // Initializer lists don't have conversions as such.
3193 User.Before.setAsIdentityConversion();
3194 User.HadMultipleCandidates = HadMultipleCandidates;
3195 User.ConversionFunction = Constructor;
3196 User.FoundConversionFunction = Best->FoundDecl;
3197 User.After.setAsIdentityConversion();
3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3199 User.After.setAllToTypes(ToType);
3200 return Result;
3201 }
3202
3203 case OR_No_Viable_Function:
3204 return OR_No_Viable_Function;
3205 case OR_Ambiguous:
3206 return OR_Ambiguous;
3207 }
3208
3209 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 3209)
;
3210}
3211
3212/// Determines whether there is a user-defined conversion sequence
3213/// (C++ [over.ics.user]) that converts expression From to the type
3214/// ToType. If such a conversion exists, User will contain the
3215/// user-defined conversion sequence that performs such a conversion
3216/// and this routine will return true. Otherwise, this routine returns
3217/// false and User is unspecified.
3218///
3219/// \param AllowExplicit true if the conversion should consider C++0x
3220/// "explicit" conversion functions as well as non-explicit conversion
3221/// functions (C++0x [class.conv.fct]p2).
3222///
3223/// \param AllowObjCConversionOnExplicit true if the conversion should
3224/// allow an extra Objective-C pointer conversion on uses of explicit
3225/// constructors. Requires \c AllowExplicit to also be set.
3226static OverloadingResult
3227IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3228 UserDefinedConversionSequence &User,
3229 OverloadCandidateSet &CandidateSet,
3230 bool AllowExplicit,
3231 bool AllowObjCConversionOnExplicit) {
3232 assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 3232, __PRETTY_FUNCTION__))
;
3233
3234 // Whether we will only visit constructors.
3235 bool ConstructorsOnly = false;
3236
3237 // If the type we are conversion to is a class type, enumerate its
3238 // constructors.
3239 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3240 // C++ [over.match.ctor]p1:
3241 // When objects of class type are direct-initialized (8.5), or
3242 // copy-initialized from an expression of the same or a
3243 // derived class type (8.5), overload resolution selects the
3244 // constructor. [...] For copy-initialization, the candidate
3245 // functions are all the converting constructors (12.3.1) of
3246 // that class. The argument list is the expression-list within
3247 // the parentheses of the initializer.
3248 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3249 (From->getType()->getAs<RecordType>() &&
3250 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3251 ConstructorsOnly = true;
3252
3253 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3254 // We're not going to find any constructors.
3255 } else if (CXXRecordDecl *ToRecordDecl
3256 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3257
3258 Expr **Args = &From;
3259 unsigned NumArgs = 1;
3260 bool ListInitializing = false;
3261 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3262 // But first, see if there is an init-list-constructor that will work.
3263 OverloadingResult Result = IsInitializerListConstructorConversion(
3264 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3265 if (Result != OR_No_Viable_Function)
3266 return Result;
3267 // Never mind.
3268 CandidateSet.clear();
3269
3270 // If we're list-initializing, we pass the individual elements as
3271 // arguments, not the entire list.
3272 Args = InitList->getInits();
3273 NumArgs = InitList->getNumInits();
3274 ListInitializing = true;
3275 }
3276
3277 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3278 auto Info = getConstructorInfo(D);
3279 if (!Info)
3280 continue;
3281
3282 bool Usable = !Info.Constructor->isInvalidDecl();
3283 if (ListInitializing)
3284 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3285 else
3286 Usable = Usable &&
3287 Info.Constructor->isConvertingConstructor(AllowExplicit);
3288 if (Usable) {
3289 bool SuppressUserConversions = !ConstructorsOnly;
3290 if (SuppressUserConversions && ListInitializing) {
3291 SuppressUserConversions = false;
3292 if (NumArgs == 1) {
3293 // If the first argument is (a reference to) the target type,
3294 // suppress conversions.
3295 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3296 S.Context, Info.Constructor, ToType);
3297 }
3298 }
3299 if (Info.ConstructorTmpl)
3300 S.AddTemplateOverloadCandidate(
3301 Info.ConstructorTmpl, Info.FoundDecl,
3302 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3303 CandidateSet, SuppressUserConversions);
3304 else
3305 // Allow one user-defined conversion when user specifies a
3306 // From->ToType conversion via an static cast (c-style, etc).
3307 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3308 llvm::makeArrayRef(Args, NumArgs),
3309 CandidateSet, SuppressUserConversions);
3310 }
3311 }
3312 }
3313 }
3314
3315 // Enumerate conversion functions, if we're allowed to.
3316 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3317 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3318 // No conversion functions from incomplete types.
3319 } else if (const RecordType *FromRecordType
3320 = From->getType()->getAs<RecordType>()) {
3321 if (CXXRecordDecl *FromRecordDecl
3322 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3323 // Add all of the conversion functions as candidates.
3324 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3325 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3326 DeclAccessPair FoundDecl = I.getPair();
3327 NamedDecl *D = FoundDecl.getDecl();
3328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3329 if (isa<UsingShadowDecl>(D))
3330 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3331
3332 CXXConversionDecl *Conv;
3333 FunctionTemplateDecl *ConvTemplate;
3334 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3335 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3336 else
3337 Conv = cast<CXXConversionDecl>(D);
3338
3339 if (AllowExplicit || !Conv->isExplicit()) {
3340 if (ConvTemplate)
3341 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3342 ActingContext, From, ToType,
3343 CandidateSet,
3344 AllowObjCConversionOnExplicit);
3345 else
3346 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3347 From, ToType, CandidateSet,
3348 AllowObjCConversionOnExplicit);
3349 }
3350 }
3351 }
3352 }
3353
3354 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3355
3356 OverloadCandidateSet::iterator Best;
3357 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3358 Best, true)) {
3359 case OR_Success:
3360 case OR_Deleted:
3361 // Record the standard conversion we used and the conversion function.
3362 if (CXXConstructorDecl *Constructor
3363 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3364 // C++ [over.ics.user]p1:
3365 // If the user-defined conversion is specified by a
3366 // constructor (12.3.1), the initial standard conversion
3367 // sequence converts the source type to the type required by
3368 // the argument of the constructor.
3369 //
3370 QualType ThisType = Constructor->getThisType(S.Context);
3371 if (isa<InitListExpr>(From)) {
3372 // Initializer lists don't have conversions as such.
3373 User.Before.setAsIdentityConversion();
3374 } else {
3375 if (Best->Conversions[0].isEllipsis())
3376 User.EllipsisConversion = true;
3377 else {
3378 User.Before = Best->Conversions[0].Standard;
3379 User.EllipsisConversion = false;
3380 }
3381 }
3382 User.HadMultipleCandidates = HadMultipleCandidates;
3383 User.ConversionFunction = Constructor;
3384 User.FoundConversionFunction = Best->FoundDecl;
3385 User.After.setAsIdentityConversion();
3386 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3387 User.After.setAllToTypes(ToType);
3388 return Result;
3389 }
3390 if (CXXConversionDecl *Conversion
3391 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3392 // C++ [over.ics.user]p1:
3393 //
3394 // [...] If the user-defined conversion is specified by a
3395 // conversion function (12.3.2), the initial standard
3396 // conversion sequence converts the source type to the
3397 // implicit object parameter of the conversion function.
3398 User.Before = Best->Conversions[0].Standard;
3399 User.HadMultipleCandidates = HadMultipleCandidates;
3400 User.ConversionFunction = Conversion;
3401 User.FoundConversionFunction = Best->FoundDecl;
3402 User.EllipsisConversion = false;
3403
3404 // C++ [over.ics.user]p2:
3405 // The second standard conversion sequence converts the
3406 // result of the user-defined conversion to the target type
3407 // for the sequence. Since an implicit conversion sequence
3408 // is an initialization, the special rules for
3409 // initialization by user-defined conversion apply when
3410 // selecting the best user-defined conversion for a
3411 // user-defined conversion sequence (see 13.3.3 and
3412 // 13.3.3.1).
3413 User.After = Best->FinalConversion;
3414 return Result;
3415 }
3416 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 3416)
;
3417
3418 case OR_No_Viable_Function:
3419 return OR_No_Viable_Function;
3420
3421 case OR_Ambiguous:
3422 return OR_Ambiguous;
3423 }
3424
3425 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 3425)
;
3426}
3427
3428bool
3429Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3430 ImplicitConversionSequence ICS;
3431 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3432 OverloadCandidateSet::CSK_Normal);
3433 OverloadingResult OvResult =
3434 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3435 CandidateSet, false, false);
3436 if (OvResult == OR_Ambiguous)
3437 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3438 << From->getType() << ToType << From->getSourceRange();
3439 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3440 if (!RequireCompleteType(From->getLocStart(), ToType,
3441 diag::err_typecheck_nonviable_condition_incomplete,
3442 From->getType(), From->getSourceRange()))
3443 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3444 << false << From->getType() << From->getSourceRange() << ToType;
3445 } else
3446 return false;
3447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3448 return true;
3449}
3450
3451/// \brief Compare the user-defined conversion functions or constructors
3452/// of two user-defined conversion sequences to determine whether any ordering
3453/// is possible.
3454static ImplicitConversionSequence::CompareKind
3455compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3456 FunctionDecl *Function2) {
3457 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3458 return ImplicitConversionSequence::Indistinguishable;
3459
3460 // Objective-C++:
3461 // If both conversion functions are implicitly-declared conversions from
3462 // a lambda closure type to a function pointer and a block pointer,
3463 // respectively, always prefer the conversion to a function pointer,
3464 // because the function pointer is more lightweight and is more likely
3465 // to keep code working.
3466 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3467 if (!Conv1)
3468 return ImplicitConversionSequence::Indistinguishable;
3469
3470 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3471 if (!Conv2)
3472 return ImplicitConversionSequence::Indistinguishable;
3473
3474 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3475 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3476 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3477 if (Block1 != Block2)
3478 return Block1 ? ImplicitConversionSequence::Worse
3479 : ImplicitConversionSequence::Better;
3480 }
3481
3482 return ImplicitConversionSequence::Indistinguishable;
3483}
3484
3485static bool hasDeprecatedStringLiteralToCharPtrConversion(
3486 const ImplicitConversionSequence &ICS) {
3487 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3488 (ICS.isUserDefined() &&
3489 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3490}
3491
3492/// CompareImplicitConversionSequences - Compare two implicit
3493/// conversion sequences to determine whether one is better than the
3494/// other or if they are indistinguishable (C++ 13.3.3.2).
3495static ImplicitConversionSequence::CompareKind
3496CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3497 const ImplicitConversionSequence& ICS1,
3498 const ImplicitConversionSequence& ICS2)
3499{
3500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3501 // conversion sequences (as defined in 13.3.3.1)
3502 // -- a standard conversion sequence (13.3.3.1.1) is a better
3503 // conversion sequence than a user-defined conversion sequence or
3504 // an ellipsis conversion sequence, and
3505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3506 // conversion sequence than an ellipsis conversion sequence
3507 // (13.3.3.1.3).
3508 //
3509 // C++0x [over.best.ics]p10:
3510 // For the purpose of ranking implicit conversion sequences as
3511 // described in 13.3.3.2, the ambiguous conversion sequence is
3512 // treated as a user-defined sequence that is indistinguishable
3513 // from any other user-defined conversion sequence.
3514
3515 // String literal to 'char *' conversion has been deprecated in C++03. It has
3516 // been removed from C++11. We still accept this conversion, if it happens at
3517 // the best viable function. Otherwise, this conversion is considered worse
3518 // than ellipsis conversion. Consider this as an extension; this is not in the
3519 // standard. For example:
3520 //
3521 // int &f(...); // #1
3522 // void f(char*); // #2
3523 // void g() { int &r = f("foo"); }
3524 //
3525 // In C++03, we pick #2 as the best viable function.
3526 // In C++11, we pick #1 as the best viable function, because ellipsis
3527 // conversion is better than string-literal to char* conversion (since there
3528 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3529 // convert arguments, #2 would be the best viable function in C++11.
3530 // If the best viable function has this conversion, a warning will be issued
3531 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3532
3533 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3535 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3536 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3537 ? ImplicitConversionSequence::Worse
3538 : ImplicitConversionSequence::Better;
3539
3540 if (ICS1.getKindRank() < ICS2.getKindRank())
3541 return ImplicitConversionSequence::Better;
3542 if (ICS2.getKindRank() < ICS1.getKindRank())
3543 return ImplicitConversionSequence::Worse;
3544
3545 // The following checks require both conversion sequences to be of
3546 // the same kind.
3547 if (ICS1.getKind() != ICS2.getKind())
3548 return ImplicitConversionSequence::Indistinguishable;
3549
3550 ImplicitConversionSequence::CompareKind Result =
3551 ImplicitConversionSequence::Indistinguishable;
3552
3553 // Two implicit conversion sequences of the same form are
3554 // indistinguishable conversion sequences unless one of the
3555 // following rules apply: (C++ 13.3.3.2p3):
3556
3557 // List-initialization sequence L1 is a better conversion sequence than
3558 // list-initialization sequence L2 if:
3559 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3560 // if not that,
3561 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3562 // and N1 is smaller than N2.,
3563 // even if one of the other rules in this paragraph would otherwise apply.
3564 if (!ICS1.isBad()) {
3565 if (ICS1.isStdInitializerListElement() &&
3566 !ICS2.isStdInitializerListElement())
3567 return ImplicitConversionSequence::Better;
3568 if (!ICS1.isStdInitializerListElement() &&
3569 ICS2.isStdInitializerListElement())
3570 return ImplicitConversionSequence::Worse;
3571 }
3572
3573 if (ICS1.isStandard())
3574 // Standard conversion sequence S1 is a better conversion sequence than
3575 // standard conversion sequence S2 if [...]
3576 Result = CompareStandardConversionSequences(S, Loc,
3577 ICS1.Standard, ICS2.Standard);
3578 else if (ICS1.isUserDefined()) {
3579 // User-defined conversion sequence U1 is a better conversion
3580 // sequence than another user-defined conversion sequence U2 if
3581 // they contain the same user-defined conversion function or
3582 // constructor and if the second standard conversion sequence of
3583 // U1 is better than the second standard conversion sequence of
3584 // U2 (C++ 13.3.3.2p3).
3585 if (ICS1.UserDefined.ConversionFunction ==
3586 ICS2.UserDefined.ConversionFunction)
3587 Result = CompareStandardConversionSequences(S, Loc,
3588 ICS1.UserDefined.After,
3589 ICS2.UserDefined.After);
3590 else
3591 Result = compareConversionFunctions(S,
3592 ICS1.UserDefined.ConversionFunction,
3593 ICS2.UserDefined.ConversionFunction);
3594 }
3595
3596 return Result;
3597}
3598
3599static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3600 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3601 Qualifiers Quals;
3602 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3603 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3604 }
3605
3606 return Context.hasSameUnqualifiedType(T1, T2);
3607}
3608
3609// Per 13.3.3.2p3, compare the given standard conversion sequences to
3610// determine if one is a proper subset of the other.
3611static ImplicitConversionSequence::CompareKind
3612compareStandardConversionSubsets(ASTContext &Context,
3613 const StandardConversionSequence& SCS1,
3614 const StandardConversionSequence& SCS2) {
3615 ImplicitConversionSequence::CompareKind Result
3616 = ImplicitConversionSequence::Indistinguishable;
3617
3618 // the identity conversion sequence is considered to be a subsequence of
3619 // any non-identity conversion sequence
3620 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3621 return ImplicitConversionSequence::Better;
3622 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3623 return ImplicitConversionSequence::Worse;
3624
3625 if (SCS1.Second != SCS2.Second) {
3626 if (SCS1.Second == ICK_Identity)
3627 Result = ImplicitConversionSequence::Better;
3628 else if (SCS2.Second == ICK_Identity)
3629 Result = ImplicitConversionSequence::Worse;
3630 else
3631 return ImplicitConversionSequence::Indistinguishable;
3632 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3633 return ImplicitConversionSequence::Indistinguishable;
3634
3635 if (SCS1.Third == SCS2.Third) {
3636 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3637 : ImplicitConversionSequence::Indistinguishable;
3638 }
3639
3640 if (SCS1.Third == ICK_Identity)
3641 return Result == ImplicitConversionSequence::Worse
3642 ? ImplicitConversionSequence::Indistinguishable
3643 : ImplicitConversionSequence::Better;
3644
3645 if (SCS2.Third == ICK_Identity)
3646 return Result == ImplicitConversionSequence::Better
3647 ? ImplicitConversionSequence::Indistinguishable
3648 : ImplicitConversionSequence::Worse;
3649
3650 return ImplicitConversionSequence::Indistinguishable;
3651}
3652
3653/// \brief Determine whether one of the given reference bindings is better
3654/// than the other based on what kind of bindings they are.
3655static bool
3656isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3657 const StandardConversionSequence &SCS2) {
3658 // C++0x [over.ics.rank]p3b4:
3659 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3660 // implicit object parameter of a non-static member function declared
3661 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3662 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3663 // lvalue reference to a function lvalue and S2 binds an rvalue
3664 // reference*.
3665 //
3666 // FIXME: Rvalue references. We're going rogue with the above edits,
3667 // because the semantics in the current C++0x working paper (N3225 at the
3668 // time of this writing) break the standard definition of std::forward
3669 // and std::reference_wrapper when dealing with references to functions.
3670 // Proposed wording changes submitted to CWG for consideration.
3671 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3672 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3673 return false;
3674
3675 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3676 SCS2.IsLvalueReference) ||
3677 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3678 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3679}
3680
3681/// CompareStandardConversionSequences - Compare two standard
3682/// conversion sequences to determine whether one is better than the
3683/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3684static ImplicitConversionSequence::CompareKind
3685CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3686 const StandardConversionSequence& SCS1,
3687 const StandardConversionSequence& SCS2)
3688{
3689 // Standard conversion sequence S1 is a better conversion sequence
3690 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3691
3692 // -- S1 is a proper subsequence of S2 (comparing the conversion
3693 // sequences in the canonical form defined by 13.3.3.1.1,
3694 // excluding any Lvalue Transformation; the identity conversion
3695 // sequence is considered to be a subsequence of any
3696 // non-identity conversion sequence) or, if not that,
3697 if (ImplicitConversionSequence::CompareKind CK
3698 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3699 return CK;
3700
3701 // -- the rank of S1 is better than the rank of S2 (by the rules
3702 // defined below), or, if not that,
3703 ImplicitConversionRank Rank1 = SCS1.getRank();
3704 ImplicitConversionRank Rank2 = SCS2.getRank();
3705 if (Rank1 < Rank2)
3706 return ImplicitConversionSequence::Better;
3707 else if (Rank2 < Rank1)
3708 return ImplicitConversionSequence::Worse;
3709
3710 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3711 // are indistinguishable unless one of the following rules
3712 // applies:
3713
3714 // A conversion that is not a conversion of a pointer, or
3715 // pointer to member, to bool is better than another conversion
3716 // that is such a conversion.
3717 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3718 return SCS2.isPointerConversionToBool()
3719 ? ImplicitConversionSequence::Better
3720 : ImplicitConversionSequence::Worse;
3721
3722 // C++ [over.ics.rank]p4b2:
3723 //
3724 // If class B is derived directly or indirectly from class A,
3725 // conversion of B* to A* is better than conversion of B* to
3726 // void*, and conversion of A* to void* is better than conversion
3727 // of B* to void*.
3728 bool SCS1ConvertsToVoid
3729 = SCS1.isPointerConversionToVoidPointer(S.Context);
3730 bool SCS2ConvertsToVoid
3731 = SCS2.isPointerConversionToVoidPointer(S.Context);
3732 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3733 // Exactly one of the conversion sequences is a conversion to
3734 // a void pointer; it's the worse conversion.
3735 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3736 : ImplicitConversionSequence::Worse;
3737 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3738 // Neither conversion sequence converts to a void pointer; compare
3739 // their derived-to-base conversions.
3740 if (ImplicitConversionSequence::CompareKind DerivedCK
3741 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3742 return DerivedCK;
3743 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3744 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3745 // Both conversion sequences are conversions to void
3746 // pointers. Compare the source types to determine if there's an
3747 // inheritance relationship in their sources.
3748 QualType FromType1 = SCS1.getFromType();
3749 QualType FromType2 = SCS2.getFromType();
3750
3751 // Adjust the types we're converting from via the array-to-pointer
3752 // conversion, if we need to.
3753 if (SCS1.First == ICK_Array_To_Pointer)
3754 FromType1 = S.Context.getArrayDecayedType(FromType1);
3755 if (SCS2.First == ICK_Array_To_Pointer)
3756 FromType2 = S.Context.getArrayDecayedType(FromType2);
3757
3758 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3759 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3760
3761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3762 return ImplicitConversionSequence::Better;
3763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3764 return ImplicitConversionSequence::Worse;
3765
3766 // Objective-C++: If one interface is more specific than the
3767 // other, it is the better one.
3768 const ObjCObjectPointerType* FromObjCPtr1
3769 = FromType1->getAs<ObjCObjectPointerType>();
3770 const ObjCObjectPointerType* FromObjCPtr2
3771 = FromType2->getAs<ObjCObjectPointerType>();
3772 if (FromObjCPtr1 && FromObjCPtr2) {
3773 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3774 FromObjCPtr2);
3775 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3776 FromObjCPtr1);
3777 if (AssignLeft != AssignRight) {
3778 return AssignLeft? ImplicitConversionSequence::Better
3779 : ImplicitConversionSequence::Worse;
3780 }
3781 }
3782 }
3783
3784 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3785 // bullet 3).
3786 if (ImplicitConversionSequence::CompareKind QualCK
3787 = CompareQualificationConversions(S, SCS1, SCS2))
3788 return QualCK;
3789
3790 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3791 // Check for a better reference binding based on the kind of bindings.
3792 if (isBetterReferenceBindingKind(SCS1, SCS2))
3793 return ImplicitConversionSequence::Better;
3794 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3795 return ImplicitConversionSequence::Worse;
3796
3797 // C++ [over.ics.rank]p3b4:
3798 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3799 // which the references refer are the same type except for
3800 // top-level cv-qualifiers, and the type to which the reference
3801 // initialized by S2 refers is more cv-qualified than the type
3802 // to which the reference initialized by S1 refers.
3803 QualType T1 = SCS1.getToType(2);
3804 QualType T2 = SCS2.getToType(2);
3805 T1 = S.Context.getCanonicalType(T1);
3806 T2 = S.Context.getCanonicalType(T2);
3807 Qualifiers T1Quals, T2Quals;
3808 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3809 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3810 if (UnqualT1 == UnqualT2) {
3811 // Objective-C++ ARC: If the references refer to objects with different
3812 // lifetimes, prefer bindings that don't change lifetime.
3813 if (SCS1.ObjCLifetimeConversionBinding !=
3814 SCS2.ObjCLifetimeConversionBinding) {
3815 return SCS1.ObjCLifetimeConversionBinding
3816 ? ImplicitConversionSequence::Worse
3817 : ImplicitConversionSequence::Better;
3818 }
3819
3820 // If the type is an array type, promote the element qualifiers to the
3821 // type for comparison.
3822 if (isa<ArrayType>(T1) && T1Quals)
3823 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3824 if (isa<ArrayType>(T2) && T2Quals)
3825 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3826 if (T2.isMoreQualifiedThan(T1))
3827 return ImplicitConversionSequence::Better;
3828 else if (T1.isMoreQualifiedThan(T2))
3829 return ImplicitConversionSequence::Worse;
3830 }
3831 }
3832
3833 // In Microsoft mode, prefer an integral conversion to a
3834 // floating-to-integral conversion if the integral conversion
3835 // is between types of the same size.
3836 // For example:
3837 // void f(float);
3838 // void f(int);
3839 // int main {
3840 // long a;
3841 // f(a);
3842 // }
3843 // Here, MSVC will call f(int) instead of generating a compile error
3844 // as clang will do in standard mode.
3845 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3846 SCS2.Second == ICK_Floating_Integral &&
3847 S.Context.getTypeSize(SCS1.getFromType()) ==
3848 S.Context.getTypeSize(SCS1.getToType(2)))
3849 return ImplicitConversionSequence::Better;
3850
3851 return ImplicitConversionSequence::Indistinguishable;
3852}
3853
3854/// CompareQualificationConversions - Compares two standard conversion
3855/// sequences to determine whether they can be ranked based on their
3856/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3857static ImplicitConversionSequence::CompareKind
3858CompareQualificationConversions(Sema &S,
3859 const StandardConversionSequence& SCS1,
3860 const StandardConversionSequence& SCS2) {
3861 // C++ 13.3.3.2p3:
3862 // -- S1 and S2 differ only in their qualification conversion and
3863 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3864 // cv-qualification signature of type T1 is a proper subset of
3865 // the cv-qualification signature of type T2, and S1 is not the
3866 // deprecated string literal array-to-pointer conversion (4.2).
3867 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3868 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3869 return ImplicitConversionSequence::Indistinguishable;
3870
3871 // FIXME: the example in the standard doesn't use a qualification
3872 // conversion (!)
3873 QualType T1 = SCS1.getToType(2);
3874 QualType T2 = SCS2.getToType(2);
3875 T1 = S.Context.getCanonicalType(T1);
3876 T2 = S.Context.getCanonicalType(T2);
3877 Qualifiers T1Quals, T2Quals;
3878 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3879 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3880
3881 // If the types are the same, we won't learn anything by unwrapped
3882 // them.
3883 if (UnqualT1 == UnqualT2)
3884 return ImplicitConversionSequence::Indistinguishable;
3885
3886 // If the type is an array type, promote the element qualifiers to the type
3887 // for comparison.
3888 if (isa<ArrayType>(T1) && T1Quals)
3889 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3890 if (isa<ArrayType>(T2) && T2Quals)
3891 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3892
3893 ImplicitConversionSequence::CompareKind Result
3894 = ImplicitConversionSequence::Indistinguishable;
3895
3896 // Objective-C++ ARC:
3897 // Prefer qualification conversions not involving a change in lifetime
3898 // to qualification conversions that do not change lifetime.
3899 if (SCS1.QualificationIncludesObjCLifetime !=
3900 SCS2.QualificationIncludesObjCLifetime) {
3901 Result = SCS1.QualificationIncludesObjCLifetime
3902 ? ImplicitConversionSequence::Worse
3903 : ImplicitConversionSequence::Better;
3904 }
3905
3906 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3907 // Within each iteration of the loop, we check the qualifiers to
3908 // determine if this still looks like a qualification
3909 // conversion. Then, if all is well, we unwrap one more level of
3910 // pointers or pointers-to-members and do it all again
3911 // until there are no more pointers or pointers-to-members left
3912 // to unwrap. This essentially mimics what
3913 // IsQualificationConversion does, but here we're checking for a
3914 // strict subset of qualifiers.
3915 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3916 // The qualifiers are the same, so this doesn't tell us anything
3917 // about how the sequences rank.
3918 ;
3919 else if (T2.isMoreQualifiedThan(T1)) {
3920 // T1 has fewer qualifiers, so it could be the better sequence.
3921 if (Result == ImplicitConversionSequence::Worse)
3922 // Neither has qualifiers that are a subset of the other's
3923 // qualifiers.
3924 return ImplicitConversionSequence::Indistinguishable;
3925
3926 Result = ImplicitConversionSequence::Better;
3927 } else if (T1.isMoreQualifiedThan(T2)) {
3928 // T2 has fewer qualifiers, so it could be the better sequence.
3929 if (Result == ImplicitConversionSequence::Better)
3930 // Neither has qualifiers that are a subset of the other's
3931 // qualifiers.
3932 return ImplicitConversionSequence::Indistinguishable;
3933
3934 Result = ImplicitConversionSequence::Worse;
3935 } else {
3936 // Qualifiers are disjoint.
3937 return ImplicitConversionSequence::Indistinguishable;
3938 }
3939
3940 // If the types after this point are equivalent, we're done.
3941 if (S.Context.hasSameUnqualifiedType(T1, T2))
3942 break;
3943 }
3944
3945 // Check that the winning standard conversion sequence isn't using
3946 // the deprecated string literal array to pointer conversion.
3947 switch (Result) {
3948 case ImplicitConversionSequence::Better:
3949 if (SCS1.DeprecatedStringLiteralToCharPtr)
3950 Result = ImplicitConversionSequence::Indistinguishable;
3951 break;
3952
3953 case ImplicitConversionSequence::Indistinguishable:
3954 break;
3955
3956 case ImplicitConversionSequence::Worse:
3957 if (SCS2.DeprecatedStringLiteralToCharPtr)
3958 Result = ImplicitConversionSequence::Indistinguishable;
3959 break;
3960 }
3961
3962 return Result;
3963}
3964
3965/// CompareDerivedToBaseConversions - Compares two standard conversion
3966/// sequences to determine whether they can be ranked based on their
3967/// various kinds of derived-to-base conversions (C++
3968/// [over.ics.rank]p4b3). As part of these checks, we also look at
3969/// conversions between Objective-C interface types.
3970static ImplicitConversionSequence::CompareKind
3971CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3972 const StandardConversionSequence& SCS1,
3973 const StandardConversionSequence& SCS2) {
3974 QualType FromType1 = SCS1.getFromType();
3975 QualType ToType1 = SCS1.getToType(1);
3976 QualType FromType2 = SCS2.getFromType();
3977 QualType ToType2 = SCS2.getToType(1);
3978
3979 // Adjust the types we're converting from via the array-to-pointer
3980 // conversion, if we need to.
3981 if (SCS1.First == ICK_Array_To_Pointer)
3982 FromType1 = S.Context.getArrayDecayedType(FromType1);
3983 if (SCS2.First == ICK_Array_To_Pointer)
3984 FromType2 = S.Context.getArrayDecayedType(FromType2);
3985
3986 // Canonicalize all of the types.
3987 FromType1 = S.Context.getCanonicalType(FromType1);
3988 ToType1 = S.Context.getCanonicalType(ToType1);
3989 FromType2 = S.Context.getCanonicalType(FromType2);
3990 ToType2 = S.Context.getCanonicalType(ToType2);
3991
3992 // C++ [over.ics.rank]p4b3:
3993 //
3994 // If class B is derived directly or indirectly from class A and
3995 // class C is derived directly or indirectly from B,
3996 //
3997 // Compare based on pointer conversions.
3998 if (SCS1.Second == ICK_Pointer_Conversion &&
3999 SCS2.Second == ICK_Pointer_Conversion &&
4000 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4001 FromType1->isPointerType() && FromType2->isPointerType() &&
4002 ToType1->isPointerType() && ToType2->isPointerType()) {
4003 QualType FromPointee1
4004 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4005 QualType ToPointee1
4006 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4007 QualType FromPointee2
4008 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4009 QualType ToPointee2
4010 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4011
4012 // -- conversion of C* to B* is better than conversion of C* to A*,
4013 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4014 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4015 return ImplicitConversionSequence::Better;
4016 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4017 return ImplicitConversionSequence::Worse;
4018 }
4019
4020 // -- conversion of B* to A* is better than conversion of C* to A*,
4021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4022 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4023 return ImplicitConversionSequence::Better;
4024 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4025 return ImplicitConversionSequence::Worse;
4026 }
4027 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4028 SCS2.Second == ICK_Pointer_Conversion) {
4029 const ObjCObjectPointerType *FromPtr1
4030 = FromType1->getAs<ObjCObjectPointerType>();
4031 const ObjCObjectPointerType *FromPtr2
4032 = FromType2->getAs<ObjCObjectPointerType>();
4033 const ObjCObjectPointerType *ToPtr1
4034 = ToType1->getAs<ObjCObjectPointerType>();
4035 const ObjCObjectPointerType *ToPtr2
4036 = ToType2->getAs<ObjCObjectPointerType>();
4037
4038 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4039 // Apply the same conversion ranking rules for Objective-C pointer types
4040 // that we do for C++ pointers to class types. However, we employ the
4041 // Objective-C pseudo-subtyping relationship used for assignment of
4042 // Objective-C pointer types.
4043 bool FromAssignLeft
4044 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4045 bool FromAssignRight
4046 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4047 bool ToAssignLeft
4048 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4049 bool ToAssignRight
4050 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4051
4052 // A conversion to an a non-id object pointer type or qualified 'id'
4053 // type is better than a conversion to 'id'.
4054 if (ToPtr1->isObjCIdType() &&
4055 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4056 return ImplicitConversionSequence::Worse;
4057 if (ToPtr2->isObjCIdType() &&
4058 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4059 return ImplicitConversionSequence::Better;
4060
4061 // A conversion to a non-id object pointer type is better than a
4062 // conversion to a qualified 'id' type
4063 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4064 return ImplicitConversionSequence::Worse;
4065 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4066 return ImplicitConversionSequence::Better;
4067
4068 // A conversion to an a non-Class object pointer type or qualified 'Class'
4069 // type is better than a conversion to 'Class'.
4070 if (ToPtr1->isObjCClassType() &&
4071 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4072 return ImplicitConversionSequence::Worse;
4073 if (ToPtr2->isObjCClassType() &&
4074 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4075 return ImplicitConversionSequence::Better;
4076
4077 // A conversion to a non-Class object pointer type is better than a
4078 // conversion to a qualified 'Class' type.
4079 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4082 return ImplicitConversionSequence::Better;
4083
4084 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4085 if (S.Context.hasSameType(FromType1, FromType2) &&
4086 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4087 (ToAssignLeft != ToAssignRight))
4088 return ToAssignLeft? ImplicitConversionSequence::Worse
4089 : ImplicitConversionSequence::Better;
4090
4091 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4092 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4093 (FromAssignLeft != FromAssignRight))
4094 return FromAssignLeft? ImplicitConversionSequence::Better
4095 : ImplicitConversionSequence::Worse;
4096 }
4097 }
4098
4099 // Ranking of member-pointer types.
4100 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4101 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4102 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4103 const MemberPointerType * FromMemPointer1 =
4104 FromType1->getAs<MemberPointerType>();
4105 const MemberPointerType * ToMemPointer1 =
4106 ToType1->getAs<MemberPointerType>();
4107 const MemberPointerType * FromMemPointer2 =
4108 FromType2->getAs<MemberPointerType>();
4109 const MemberPointerType * ToMemPointer2 =
4110 ToType2->getAs<MemberPointerType>();
4111 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4112 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4113 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4114 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4115 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4116 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4117 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4118 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4119 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4122 return ImplicitConversionSequence::Worse;
4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4124 return ImplicitConversionSequence::Better;
4125 }
4126 // conversion of B::* to C::* is better than conversion of A::* to C::*
4127 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4128 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4129 return ImplicitConversionSequence::Better;
4130 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4131 return ImplicitConversionSequence::Worse;
4132 }
4133 }
4134
4135 if (SCS1.Second == ICK_Derived_To_Base) {
4136 // -- conversion of C to B is better than conversion of C to A,
4137 // -- binding of an expression of type C to a reference of type
4138 // B& is better than binding an expression of type C to a
4139 // reference of type A&,
4140 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4141 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4142 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4143 return ImplicitConversionSequence::Better;
4144 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4145 return ImplicitConversionSequence::Worse;
4146 }
4147
4148 // -- conversion of B to A is better than conversion of C to A.
4149 // -- binding of an expression of type B to a reference of type
4150 // A& is better than binding an expression of type C to a
4151 // reference of type A&,
4152 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4153 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4154 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4155 return ImplicitConversionSequence::Better;
4156 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4157 return ImplicitConversionSequence::Worse;
4158 }
4159 }
4160
4161 return ImplicitConversionSequence::Indistinguishable;
4162}
4163
4164/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4165/// C++ class.
4166static bool isTypeValid(QualType T) {
4167 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4168 return !Record->isInvalidDecl();
4169
4170 return true;
4171}
4172
4173/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4174/// determine whether they are reference-related,
4175/// reference-compatible, reference-compatible with added
4176/// qualification, or incompatible, for use in C++ initialization by
4177/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4178/// type, and the first type (T1) is the pointee type of the reference
4179/// type being initialized.
4180Sema::ReferenceCompareResult
4181Sema::CompareReferenceRelationship(SourceLocation Loc,
4182 QualType OrigT1, QualType OrigT2,
4183 bool &DerivedToBase,
4184 bool &ObjCConversion,
4185 bool &ObjCLifetimeConversion) {
4186 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4187, __PRETTY_FUNCTION__))
4187 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4187, __PRETTY_FUNCTION__))
;
4188 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4188, __PRETTY_FUNCTION__))
;
4189
4190 QualType T1 = Context.getCanonicalType(OrigT1);
4191 QualType T2 = Context.getCanonicalType(OrigT2);
4192 Qualifiers T1Quals, T2Quals;
4193 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4194 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4195
4196 // C++ [dcl.init.ref]p4:
4197 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4198 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4199 // T1 is a base class of T2.
4200 DerivedToBase = false;
4201 ObjCConversion = false;
4202 ObjCLifetimeConversion = false;
4203 QualType ConvertedT2;
4204 if (UnqualT1 == UnqualT2) {
4205 // Nothing to do.
4206 } else if (isCompleteType(Loc, OrigT2) &&
4207 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4208 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4209 DerivedToBase = true;
4210 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4211 UnqualT2->isObjCObjectOrInterfaceType() &&
4212 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4213 ObjCConversion = true;
4214 else if (UnqualT2->isFunctionType() &&
4215 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4216 // C++1z [dcl.init.ref]p4:
4217 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4218 // function" and T1 is "function"
4219 //
4220 // We extend this to also apply to 'noreturn', so allow any function
4221 // conversion between function types.
4222 return Ref_Compatible;
4223 else
4224 return Ref_Incompatible;
4225
4226 // At this point, we know that T1 and T2 are reference-related (at
4227 // least).
4228
4229 // If the type is an array type, promote the element qualifiers to the type
4230 // for comparison.
4231 if (isa<ArrayType>(T1) && T1Quals)
4232 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4233 if (isa<ArrayType>(T2) && T2Quals)
4234 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4235
4236 // C++ [dcl.init.ref]p4:
4237 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4238 // reference-related to T2 and cv1 is the same cv-qualification
4239 // as, or greater cv-qualification than, cv2. For purposes of
4240 // overload resolution, cases for which cv1 is greater
4241 // cv-qualification than cv2 are identified as
4242 // reference-compatible with added qualification (see 13.3.3.2).
4243 //
4244 // Note that we also require equivalence of Objective-C GC and address-space
4245 // qualifiers when performing these computations, so that e.g., an int in
4246 // address space 1 is not reference-compatible with an int in address
4247 // space 2.
4248 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4249 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4250 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4251 ObjCLifetimeConversion = true;
4252
4253 T1Quals.removeObjCLifetime();
4254 T2Quals.removeObjCLifetime();
4255 }
4256
4257 // MS compiler ignores __unaligned qualifier for references; do the same.
4258 T1Quals.removeUnaligned();
4259 T2Quals.removeUnaligned();
4260
4261 if (T1Quals.compatiblyIncludes(T2Quals))
4262 return Ref_Compatible;
4263 else
4264 return Ref_Related;
4265}
4266
4267/// \brief Look for a user-defined conversion to a value reference-compatible
4268/// with DeclType. Return true if something definite is found.
4269static bool
4270FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4271 QualType DeclType, SourceLocation DeclLoc,
4272 Expr *Init, QualType T2, bool AllowRvalues,
4273 bool AllowExplicit) {
4274 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4274, __PRETTY_FUNCTION__))
;
4275 CXXRecordDecl *T2RecordDecl
4276 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4277
4278 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4279 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4281 NamedDecl *D = *I;
4282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4283 if (isa<UsingShadowDecl>(D))
4284 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4285
4286 FunctionTemplateDecl *ConvTemplate
4287 = dyn_cast<FunctionTemplateDecl>(D);
4288 CXXConversionDecl *Conv;
4289 if (ConvTemplate)
4290 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4291 else
4292 Conv = cast<CXXConversionDecl>(D);
4293
4294 // If this is an explicit conversion, and we're not allowed to consider
4295 // explicit conversions, skip it.
4296 if (!AllowExplicit && Conv->isExplicit())
4297 continue;
4298
4299 if (AllowRvalues) {
4300 bool DerivedToBase = false;
4301 bool ObjCConversion = false;
4302 bool ObjCLifetimeConversion = false;
4303
4304 // If we are initializing an rvalue reference, don't permit conversion
4305 // functions that return lvalues.
4306 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4307 const ReferenceType *RefType
4308 = Conv->getConversionType()->getAs<LValueReferenceType>();
4309 if (RefType && !RefType->getPointeeType()->isFunctionType())
4310 continue;
4311 }
4312
4313 if (!ConvTemplate &&
4314 S.CompareReferenceRelationship(
4315 DeclLoc,
4316 Conv->getConversionType().getNonReferenceType()
4317 .getUnqualifiedType(),
4318 DeclType.getNonReferenceType().getUnqualifiedType(),
4319 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4320 Sema::Ref_Incompatible)
4321 continue;
4322 } else {
4323 // If the conversion function doesn't return a reference type,
4324 // it can't be considered for this conversion. An rvalue reference
4325 // is only acceptable if its referencee is a function type.
4326
4327 const ReferenceType *RefType =
4328 Conv->getConversionType()->getAs<ReferenceType>();
4329 if (!RefType ||
4330 (!RefType->isLValueReferenceType() &&
4331 !RefType->getPointeeType()->isFunctionType()))
4332 continue;
4333 }
4334
4335 if (ConvTemplate)
4336 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4337 Init, DeclType, CandidateSet,
4338 /*AllowObjCConversionOnExplicit=*/false);
4339 else
4340 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4341 DeclType, CandidateSet,
4342 /*AllowObjCConversionOnExplicit=*/false);
4343 }
4344
4345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346
4347 OverloadCandidateSet::iterator Best;
4348 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4349 case OR_Success:
4350 // C++ [over.ics.ref]p1:
4351 //
4352 // [...] If the parameter binds directly to the result of
4353 // applying a conversion function to the argument
4354 // expression, the implicit conversion sequence is a
4355 // user-defined conversion sequence (13.3.3.1.2), with the
4356 // second standard conversion sequence either an identity
4357 // conversion or, if the conversion function returns an
4358 // entity of a type that is a derived class of the parameter
4359 // type, a derived-to-base Conversion.
4360 if (!Best->FinalConversion.DirectBinding)
4361 return false;
4362
4363 ICS.setUserDefined();
4364 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4365 ICS.UserDefined.After = Best->FinalConversion;
4366 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4367 ICS.UserDefined.ConversionFunction = Best->Function;
4368 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4369 ICS.UserDefined.EllipsisConversion = false;
4370 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4372, __PRETTY_FUNCTION__))
4371 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4372, __PRETTY_FUNCTION__))
4372 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4372, __PRETTY_FUNCTION__))
;
4373 return true;
4374
4375 case OR_Ambiguous:
4376 ICS.setAmbiguous();
4377 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4378 Cand != CandidateSet.end(); ++Cand)
4379 if (Cand->Viable)
4380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4381 return true;
4382
4383 case OR_No_Viable_Function:
4384 case OR_Deleted:
4385 // There was no suitable conversion, or we found a deleted
4386 // conversion; continue with other checks.
4387 return false;
4388 }
4389
4390 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4390)
;
4391}
4392
4393/// \brief Compute an implicit conversion sequence for reference
4394/// initialization.
4395static ImplicitConversionSequence
4396TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4397 SourceLocation DeclLoc,
4398 bool SuppressUserConversions,
4399 bool AllowExplicit) {
4400 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4400, __PRETTY_FUNCTION__))
;
4401
4402 // Most paths end in a failed conversion.
4403 ImplicitConversionSequence ICS;
4404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4405
4406 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4407 QualType T2 = Init->getType();
4408
4409 // If the initializer is the address of an overloaded function, try
4410 // to resolve the overloaded function. If all goes well, T2 is the
4411 // type of the resulting function.
4412 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4413 DeclAccessPair Found;
4414 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4415 false, Found))
4416 T2 = Fn->getType();
4417 }
4418
4419 // Compute some basic properties of the types and the initializer.
4420 bool isRValRef = DeclType->isRValueReferenceType();
4421 bool DerivedToBase = false;
4422 bool ObjCConversion = false;
4423 bool ObjCLifetimeConversion = false;
4424 Expr::Classification InitCategory = Init->Classify(S.Context);
4425 Sema::ReferenceCompareResult RefRelationship
4426 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4427 ObjCConversion, ObjCLifetimeConversion);
4428
4429
4430 // C++0x [dcl.init.ref]p5:
4431 // A reference to type "cv1 T1" is initialized by an expression
4432 // of type "cv2 T2" as follows:
4433
4434 // -- If reference is an lvalue reference and the initializer expression
4435 if (!isRValRef) {
4436 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4437 // reference-compatible with "cv2 T2," or
4438 //
4439 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4440 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4441 // C++ [over.ics.ref]p1:
4442 // When a parameter of reference type binds directly (8.5.3)
4443 // to an argument expression, the implicit conversion sequence
4444 // is the identity conversion, unless the argument expression
4445 // has a type that is a derived class of the parameter type,
4446 // in which case the implicit conversion sequence is a
4447 // derived-to-base Conversion (13.3.3.1).
4448 ICS.setStandard();
4449 ICS.Standard.First = ICK_Identity;
4450 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4451 : ObjCConversion? ICK_Compatible_Conversion
4452 : ICK_Identity;
4453 ICS.Standard.Third = ICK_Identity;
4454 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4455 ICS.Standard.setToType(0, T2);
4456 ICS.Standard.setToType(1, T1);
4457 ICS.Standard.setToType(2, T1);
4458 ICS.Standard.ReferenceBinding = true;
4459 ICS.Standard.DirectBinding = true;
4460 ICS.Standard.IsLvalueReference = !isRValRef;
4461 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4462 ICS.Standard.BindsToRvalue = false;
4463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4464 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4465 ICS.Standard.CopyConstructor = nullptr;
4466 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4467
4468 // Nothing more to do: the inaccessibility/ambiguity check for
4469 // derived-to-base conversions is suppressed when we're
4470 // computing the implicit conversion sequence (C++
4471 // [over.best.ics]p2).
4472 return ICS;
4473 }
4474
4475 // -- has a class type (i.e., T2 is a class type), where T1 is
4476 // not reference-related to T2, and can be implicitly
4477 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4478 // is reference-compatible with "cv3 T3" 92) (this
4479 // conversion is selected by enumerating the applicable
4480 // conversion functions (13.3.1.6) and choosing the best
4481 // one through overload resolution (13.3)),
4482 if (!SuppressUserConversions && T2->isRecordType() &&
4483 S.isCompleteType(DeclLoc, T2) &&
4484 RefRelationship == Sema::Ref_Incompatible) {
4485 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4486 Init, T2, /*AllowRvalues=*/false,
4487 AllowExplicit))
4488 return ICS;
4489 }
4490 }
4491
4492 // -- Otherwise, the reference shall be an lvalue reference to a
4493 // non-volatile const type (i.e., cv1 shall be const), or the reference
4494 // shall be an rvalue reference.
4495 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4496 return ICS;
4497
4498 // -- If the initializer expression
4499 //
4500 // -- is an xvalue, class prvalue, array prvalue or function
4501 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4502 if (RefRelationship == Sema::Ref_Compatible &&
4503 (InitCategory.isXValue() ||
4504 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4505 (InitCategory.isLValue() && T2->isFunctionType()))) {
4506 ICS.setStandard();
4507 ICS.Standard.First = ICK_Identity;
4508 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4509 : ObjCConversion? ICK_Compatible_Conversion
4510 : ICK_Identity;
4511 ICS.Standard.Third = ICK_Identity;
4512 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4513 ICS.Standard.setToType(0, T2);
4514 ICS.Standard.setToType(1, T1);
4515 ICS.Standard.setToType(2, T1);
4516 ICS.Standard.ReferenceBinding = true;
4517 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4518 // binding unless we're binding to a class prvalue.
4519 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4520 // allow the use of rvalue references in C++98/03 for the benefit of
4521 // standard library implementors; therefore, we need the xvalue check here.
4522 ICS.Standard.DirectBinding =
4523 S.getLangOpts().CPlusPlus11 ||
4524 !(InitCategory.isPRValue() || T2->isRecordType());
4525 ICS.Standard.IsLvalueReference = !isRValRef;
4526 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4527 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4528 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4529 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4530 ICS.Standard.CopyConstructor = nullptr;
4531 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4532 return ICS;
4533 }
4534
4535 // -- has a class type (i.e., T2 is a class type), where T1 is not
4536 // reference-related to T2, and can be implicitly converted to
4537 // an xvalue, class prvalue, or function lvalue of type
4538 // "cv3 T3", where "cv1 T1" is reference-compatible with
4539 // "cv3 T3",
4540 //
4541 // then the reference is bound to the value of the initializer
4542 // expression in the first case and to the result of the conversion
4543 // in the second case (or, in either case, to an appropriate base
4544 // class subobject).
4545 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4546 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4547 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4548 Init, T2, /*AllowRvalues=*/true,
4549 AllowExplicit)) {
4550 // In the second case, if the reference is an rvalue reference
4551 // and the second standard conversion sequence of the
4552 // user-defined conversion sequence includes an lvalue-to-rvalue
4553 // conversion, the program is ill-formed.
4554 if (ICS.isUserDefined() && isRValRef &&
4555 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4556 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4557
4558 return ICS;
4559 }
4560
4561 // A temporary of function type cannot be created; don't even try.
4562 if (T1->isFunctionType())
4563 return ICS;
4564
4565 // -- Otherwise, a temporary of type "cv1 T1" is created and
4566 // initialized from the initializer expression using the
4567 // rules for a non-reference copy initialization (8.5). The
4568 // reference is then bound to the temporary. If T1 is
4569 // reference-related to T2, cv1 must be the same
4570 // cv-qualification as, or greater cv-qualification than,
4571 // cv2; otherwise, the program is ill-formed.
4572 if (RefRelationship == Sema::Ref_Related) {
4573 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4574 // we would be reference-compatible or reference-compatible with
4575 // added qualification. But that wasn't the case, so the reference
4576 // initialization fails.
4577 //
4578 // Note that we only want to check address spaces and cvr-qualifiers here.
4579 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4580 Qualifiers T1Quals = T1.getQualifiers();
4581 Qualifiers T2Quals = T2.getQualifiers();
4582 T1Quals.removeObjCGCAttr();
4583 T1Quals.removeObjCLifetime();
4584 T2Quals.removeObjCGCAttr();
4585 T2Quals.removeObjCLifetime();
4586 // MS compiler ignores __unaligned qualifier for references; do the same.
4587 T1Quals.removeUnaligned();
4588 T2Quals.removeUnaligned();
4589 if (!T1Quals.compatiblyIncludes(T2Quals))
4590 return ICS;
4591 }
4592
4593 // If at least one of the types is a class type, the types are not
4594 // related, and we aren't allowed any user conversions, the
4595 // reference binding fails. This case is important for breaking
4596 // recursion, since TryImplicitConversion below will attempt to
4597 // create a temporary through the use of a copy constructor.
4598 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4599 (T1->isRecordType() || T2->isRecordType()))
4600 return ICS;
4601
4602 // If T1 is reference-related to T2 and the reference is an rvalue
4603 // reference, the initializer expression shall not be an lvalue.
4604 if (RefRelationship >= Sema::Ref_Related &&
4605 isRValRef && Init->Classify(S.Context).isLValue())
4606 return ICS;
4607
4608 // C++ [over.ics.ref]p2:
4609 // When a parameter of reference type is not bound directly to
4610 // an argument expression, the conversion sequence is the one
4611 // required to convert the argument expression to the
4612 // underlying type of the reference according to
4613 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4614 // to copy-initializing a temporary of the underlying type with
4615 // the argument expression. Any difference in top-level
4616 // cv-qualification is subsumed by the initialization itself
4617 // and does not constitute a conversion.
4618 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4619 /*AllowExplicit=*/false,
4620 /*InOverloadResolution=*/false,
4621 /*CStyle=*/false,
4622 /*AllowObjCWritebackConversion=*/false,
4623 /*AllowObjCConversionOnExplicit=*/false);
4624
4625 // Of course, that's still a reference binding.
4626 if (ICS.isStandard()) {
4627 ICS.Standard.ReferenceBinding = true;
4628 ICS.Standard.IsLvalueReference = !isRValRef;
4629 ICS.Standard.BindsToFunctionLvalue = false;
4630 ICS.Standard.BindsToRvalue = true;
4631 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4632 ICS.Standard.ObjCLifetimeConversionBinding = false;
4633 } else if (ICS.isUserDefined()) {
4634 const ReferenceType *LValRefType =
4635 ICS.UserDefined.ConversionFunction->getReturnType()
4636 ->getAs<LValueReferenceType>();
4637
4638 // C++ [over.ics.ref]p3:
4639 // Except for an implicit object parameter, for which see 13.3.1, a
4640 // standard conversion sequence cannot be formed if it requires [...]
4641 // binding an rvalue reference to an lvalue other than a function
4642 // lvalue.
4643 // Note that the function case is not possible here.
4644 if (DeclType->isRValueReferenceType() && LValRefType) {
4645 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4646 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4647 // reference to an rvalue!
4648 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4649 return ICS;
4650 }
4651
4652 ICS.UserDefined.After.ReferenceBinding = true;
4653 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4654 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4655 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4656 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4657 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4658 }
4659
4660 return ICS;
4661}
4662
4663static ImplicitConversionSequence
4664TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4665 bool SuppressUserConversions,
4666 bool InOverloadResolution,
4667 bool AllowObjCWritebackConversion,
4668 bool AllowExplicit = false);
4669
4670/// TryListConversion - Try to copy-initialize a value of type ToType from the
4671/// initializer list From.
4672static ImplicitConversionSequence
4673TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4674 bool SuppressUserConversions,
4675 bool InOverloadResolution,
4676 bool AllowObjCWritebackConversion) {
4677 // C++11 [over.ics.list]p1:
4678 // When an argument is an initializer list, it is not an expression and
4679 // special rules apply for converting it to a parameter type.
4680
4681 ImplicitConversionSequence Result;
4682 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4683
4684 // We need a complete type for what follows. Incomplete types can never be
4685 // initialized from init lists.
4686 if (!S.isCompleteType(From->getLocStart(), ToType))
4687 return Result;
4688
4689 // Per DR1467:
4690 // If the parameter type is a class X and the initializer list has a single
4691 // element of type cv U, where U is X or a class derived from X, the
4692 // implicit conversion sequence is the one required to convert the element
4693 // to the parameter type.
4694 //
4695 // Otherwise, if the parameter type is a character array [... ]
4696 // and the initializer list has a single element that is an
4697 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4698 // implicit conversion sequence is the identity conversion.
4699 if (From->getNumInits() == 1) {
4700 if (ToType->isRecordType()) {
4701 QualType InitType = From->getInit(0)->getType();
4702 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4703 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4704 return TryCopyInitialization(S, From->getInit(0), ToType,
4705 SuppressUserConversions,
4706 InOverloadResolution,
4707 AllowObjCWritebackConversion);
4708 }
4709 // FIXME: Check the other conditions here: array of character type,
4710 // initializer is a string literal.
4711 if (ToType->isArrayType()) {
4712 InitializedEntity Entity =
4713 InitializedEntity::InitializeParameter(S.Context, ToType,
4714 /*Consumed=*/false);
4715 if (S.CanPerformCopyInitialization(Entity, From)) {
4716 Result.setStandard();
4717 Result.Standard.setAsIdentityConversion();
4718 Result.Standard.setFromType(ToType);
4719 Result.Standard.setAllToTypes(ToType);
4720 return Result;
4721 }
4722 }
4723 }
4724
4725 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4726 // C++11 [over.ics.list]p2:
4727 // If the parameter type is std::initializer_list<X> or "array of X" and
4728 // all the elements can be implicitly converted to X, the implicit
4729 // conversion sequence is the worst conversion necessary to convert an
4730 // element of the list to X.
4731 //
4732 // C++14 [over.ics.list]p3:
4733 // Otherwise, if the parameter type is "array of N X", if the initializer
4734 // list has exactly N elements or if it has fewer than N elements and X is
4735 // default-constructible, and if all the elements of the initializer list
4736 // can be implicitly converted to X, the implicit conversion sequence is
4737 // the worst conversion necessary to convert an element of the list to X.
4738 //
4739 // FIXME: We're missing a lot of these checks.
4740 bool toStdInitializerList = false;
4741 QualType X;
4742 if (ToType->isArrayType())
4743 X = S.Context.getAsArrayType(ToType)->getElementType();
4744 else
4745 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4746 if (!X.isNull()) {
4747 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4748 Expr *Init = From->getInit(i);
4749 ImplicitConversionSequence ICS =
4750 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4751 InOverloadResolution,
4752 AllowObjCWritebackConversion);
4753 // If a single element isn't convertible, fail.
4754 if (ICS.isBad()) {
4755 Result = ICS;
4756 break;
4757 }
4758 // Otherwise, look for the worst conversion.
4759 if (Result.isBad() ||
4760 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4761 Result) ==
4762 ImplicitConversionSequence::Worse)
4763 Result = ICS;
4764 }
4765
4766 // For an empty list, we won't have computed any conversion sequence.
4767 // Introduce the identity conversion sequence.
4768 if (From->getNumInits() == 0) {
4769 Result.setStandard();
4770 Result.Standard.setAsIdentityConversion();
4771 Result.Standard.setFromType(ToType);
4772 Result.Standard.setAllToTypes(ToType);
4773 }
4774
4775 Result.setStdInitializerListElement(toStdInitializerList);
4776 return Result;
4777 }
4778
4779 // C++14 [over.ics.list]p4:
4780 // C++11 [over.ics.list]p3:
4781 // Otherwise, if the parameter is a non-aggregate class X and overload
4782 // resolution chooses a single best constructor [...] the implicit
4783 // conversion sequence is a user-defined conversion sequence. If multiple
4784 // constructors are viable but none is better than the others, the
4785 // implicit conversion sequence is a user-defined conversion sequence.
4786 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4787 // This function can deal with initializer lists.
4788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4789 /*AllowExplicit=*/false,
4790 InOverloadResolution, /*CStyle=*/false,
4791 AllowObjCWritebackConversion,
4792 /*AllowObjCConversionOnExplicit=*/false);
4793 }
4794
4795 // C++14 [over.ics.list]p5:
4796 // C++11 [over.ics.list]p4:
4797 // Otherwise, if the parameter has an aggregate type which can be
4798 // initialized from the initializer list [...] the implicit conversion
4799 // sequence is a user-defined conversion sequence.
4800 if (ToType->isAggregateType()) {
4801 // Type is an aggregate, argument is an init list. At this point it comes
4802 // down to checking whether the initialization works.
4803 // FIXME: Find out whether this parameter is consumed or not.
4804 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4805 // need to call into the initialization code here; overload resolution
4806 // should not be doing that.
4807 InitializedEntity Entity =
4808 InitializedEntity::InitializeParameter(S.Context, ToType,
4809 /*Consumed=*/false);
4810 if (S.CanPerformCopyInitialization(Entity, From)) {
4811 Result.setUserDefined();
4812 Result.UserDefined.Before.setAsIdentityConversion();
4813 // Initializer lists don't have a type.
4814 Result.UserDefined.Before.setFromType(QualType());
4815 Result.UserDefined.Before.setAllToTypes(QualType());
4816
4817 Result.UserDefined.After.setAsIdentityConversion();
4818 Result.UserDefined.After.setFromType(ToType);
4819 Result.UserDefined.After.setAllToTypes(ToType);
4820 Result.UserDefined.ConversionFunction = nullptr;
4821 }
4822 return Result;
4823 }
4824
4825 // C++14 [over.ics.list]p6:
4826 // C++11 [over.ics.list]p5:
4827 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4828 if (ToType->isReferenceType()) {
4829 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4830 // mention initializer lists in any way. So we go by what list-
4831 // initialization would do and try to extrapolate from that.
4832
4833 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4834
4835 // If the initializer list has a single element that is reference-related
4836 // to the parameter type, we initialize the reference from that.
4837 if (From->getNumInits() == 1) {
4838 Expr *Init = From->getInit(0);
4839
4840 QualType T2 = Init->getType();
4841
4842 // If the initializer is the address of an overloaded function, try
4843 // to resolve the overloaded function. If all goes well, T2 is the
4844 // type of the resulting function.
4845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4846 DeclAccessPair Found;
4847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4848 Init, ToType, false, Found))
4849 T2 = Fn->getType();
4850 }
4851
4852 // Compute some basic properties of the types and the initializer.
4853 bool dummy1 = false;
4854 bool dummy2 = false;
4855 bool dummy3 = false;
4856 Sema::ReferenceCompareResult RefRelationship
4857 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4858 dummy2, dummy3);
4859
4860 if (RefRelationship >= Sema::Ref_Related) {
4861 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4862 SuppressUserConversions,
4863 /*AllowExplicit=*/false);
4864 }
4865 }
4866
4867 // Otherwise, we bind the reference to a temporary created from the
4868 // initializer list.
4869 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4870 InOverloadResolution,
4871 AllowObjCWritebackConversion);
4872 if (Result.isFailure())
4873 return Result;
4874 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4875, __PRETTY_FUNCTION__))
4875 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4875, __PRETTY_FUNCTION__))
;
4876
4877 // Can we even bind to a temporary?
4878 if (ToType->isRValueReferenceType() ||
4879 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4880 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4881 Result.UserDefined.After;
4882 SCS.ReferenceBinding = true;
4883 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4884 SCS.BindsToRvalue = true;
4885 SCS.BindsToFunctionLvalue = false;
4886 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4887 SCS.ObjCLifetimeConversionBinding = false;
4888 } else
4889 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4890 From, ToType);
4891 return Result;
4892 }
4893
4894 // C++14 [over.ics.list]p7:
4895 // C++11 [over.ics.list]p6:
4896 // Otherwise, if the parameter type is not a class:
4897 if (!ToType->isRecordType()) {
4898 // - if the initializer list has one element that is not itself an
4899 // initializer list, the implicit conversion sequence is the one
4900 // required to convert the element to the parameter type.
4901 unsigned NumInits = From->getNumInits();
4902 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4903 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4904 SuppressUserConversions,
4905 InOverloadResolution,
4906 AllowObjCWritebackConversion);
4907 // - if the initializer list has no elements, the implicit conversion
4908 // sequence is the identity conversion.
4909 else if (NumInits == 0) {
4910 Result.setStandard();
4911 Result.Standard.setAsIdentityConversion();
4912 Result.Standard.setFromType(ToType);
4913 Result.Standard.setAllToTypes(ToType);
4914 }
4915 return Result;
4916 }
4917
4918 // C++14 [over.ics.list]p8:
4919 // C++11 [over.ics.list]p7:
4920 // In all cases other than those enumerated above, no conversion is possible
4921 return Result;
4922}
4923
4924/// TryCopyInitialization - Try to copy-initialize a value of type
4925/// ToType from the expression From. Return the implicit conversion
4926/// sequence required to pass this argument, which may be a bad
4927/// conversion sequence (meaning that the argument cannot be passed to
4928/// a parameter of this type). If @p SuppressUserConversions, then we
4929/// do not permit any user-defined conversion sequences.
4930static ImplicitConversionSequence
4931TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4932 bool SuppressUserConversions,
4933 bool InOverloadResolution,
4934 bool AllowObjCWritebackConversion,
4935 bool AllowExplicit) {
4936 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4937 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4938 InOverloadResolution,AllowObjCWritebackConversion);
4939
4940 if (ToType->isReferenceType())
4941 return TryReferenceInit(S, From, ToType,
4942 /*FIXME:*/From->getLocStart(),
4943 SuppressUserConversions,
4944 AllowExplicit);
4945
4946 return TryImplicitConversion(S, From, ToType,
4947 SuppressUserConversions,
4948 /*AllowExplicit=*/false,
4949 InOverloadResolution,
4950 /*CStyle=*/false,
4951 AllowObjCWritebackConversion,
4952 /*AllowObjCConversionOnExplicit=*/false);
4953}
4954
4955static bool TryCopyInitialization(const CanQualType FromQTy,
4956 const CanQualType ToQTy,
4957 Sema &S,
4958 SourceLocation Loc,
4959 ExprValueKind FromVK) {
4960 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4961 ImplicitConversionSequence ICS =
4962 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4963
4964 return !ICS.isBad();
4965}
4966
4967/// TryObjectArgumentInitialization - Try to initialize the object
4968/// parameter of the given member function (@c Method) from the
4969/// expression @p From.
4970static ImplicitConversionSequence
4971TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4972 Expr::Classification FromClassification,
4973 CXXMethodDecl *Method,
4974 CXXRecordDecl *ActingContext) {
4975 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4976 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4977 // const volatile object.
4978 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4979 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4980 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4981
4982 // Set up the conversion sequence as a "bad" conversion, to allow us
4983 // to exit early.
4984 ImplicitConversionSequence ICS;
4985
4986 // We need to have an object of class type.
4987 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4988 FromType = PT->getPointeeType();
4989
4990 // When we had a pointer, it's implicitly dereferenced, so we
4991 // better have an lvalue.
4992 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4992, __PRETTY_FUNCTION__))
;
4993 }
4994
4995 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 4995, __PRETTY_FUNCTION__))
;
4996
4997 // C++0x [over.match.funcs]p4:
4998 // For non-static member functions, the type of the implicit object
4999 // parameter is
5000 //
5001 // - "lvalue reference to cv X" for functions declared without a
5002 // ref-qualifier or with the & ref-qualifier
5003 // - "rvalue reference to cv X" for functions declared with the &&
5004 // ref-qualifier
5005 //
5006 // where X is the class of which the function is a member and cv is the
5007 // cv-qualification on the member function declaration.
5008 //
5009 // However, when finding an implicit conversion sequence for the argument, we
5010 // are not allowed to perform user-defined conversions
5011 // (C++ [over.match.funcs]p5). We perform a simplified version of
5012 // reference binding here, that allows class rvalues to bind to
5013 // non-constant references.
5014
5015 // First check the qualifiers.
5016 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5017 if (ImplicitParamType.getCVRQualifiers()
5018 != FromTypeCanon.getLocalCVRQualifiers() &&
5019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5020 ICS.setBad(BadConversionSequence::bad_qualifiers,
5021 FromType, ImplicitParamType);
5022 return ICS;
5023 }
5024
5025 // Check that we have either the same type or a derived type. It
5026 // affects the conversion rank.
5027 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5028 ImplicitConversionKind SecondKind;
5029 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5030 SecondKind = ICK_Identity;
5031 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5032 SecondKind = ICK_Derived_To_Base;
5033 else {
5034 ICS.setBad(BadConversionSequence::unrelated_class,
5035 FromType, ImplicitParamType);
5036 return ICS;
5037 }
5038
5039 // Check the ref-qualifier.
5040 switch (Method->getRefQualifier()) {
5041 case RQ_None:
5042 // Do nothing; we don't care about lvalueness or rvalueness.
5043 break;
5044
5045 case RQ_LValue:
5046 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5047 // non-const lvalue reference cannot bind to an rvalue
5048 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5049 ImplicitParamType);
5050 return ICS;
5051 }
5052 break;
5053
5054 case RQ_RValue:
5055 if (!FromClassification.isRValue()) {
5056 // rvalue reference cannot bind to an lvalue
5057 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5058 ImplicitParamType);
5059 return ICS;
5060 }
5061 break;
5062 }
5063
5064 // Success. Mark this as a reference binding.
5065 ICS.setStandard();
5066 ICS.Standard.setAsIdentityConversion();
5067 ICS.Standard.Second = SecondKind;
5068 ICS.Standard.setFromType(FromType);
5069 ICS.Standard.setAllToTypes(ImplicitParamType);
5070 ICS.Standard.ReferenceBinding = true;
5071 ICS.Standard.DirectBinding = true;
5072 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5073 ICS.Standard.BindsToFunctionLvalue = false;
5074 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5075 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5076 = (Method->getRefQualifier() == RQ_None);
5077 return ICS;
5078}
5079
5080/// PerformObjectArgumentInitialization - Perform initialization of
5081/// the implicit object parameter for the given Method with the given
5082/// expression.
5083ExprResult
5084Sema::PerformObjectArgumentInitialization(Expr *From,
5085 NestedNameSpecifier *Qualifier,
5086 NamedDecl *FoundDecl,
5087 CXXMethodDecl *Method) {
5088 QualType FromRecordType, DestType;
5089 QualType ImplicitParamRecordType =
5090 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5091
5092 Expr::Classification FromClassification;
5093 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5094 FromRecordType = PT->getPointeeType();
5095 DestType = Method->getThisType(Context);
5096 FromClassification = Expr::Classification::makeSimpleLValue();
5097 } else {
5098 FromRecordType = From->getType();
5099 DestType = ImplicitParamRecordType;
5100 FromClassification = From->Classify(Context);
5101 }
5102
5103 // Note that we always use the true parent context when performing
5104 // the actual argument initialization.
5105 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5106 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5107 Method->getParent());
5108 if (ICS.isBad()) {
5109 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5110 Qualifiers FromQs = FromRecordType.getQualifiers();
5111 Qualifiers ToQs = DestType.getQualifiers();
5112 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5113 if (CVR) {
5114 Diag(From->getLocStart(),
5115 diag::err_member_function_call_bad_cvr)
5116 << Method->getDeclName() << FromRecordType << (CVR - 1)
5117 << From->getSourceRange();
5118 Diag(Method->getLocation(), diag::note_previous_decl)
5119 << Method->getDeclName();
5120 return ExprError();
5121 }
5122 }
5123
5124 return Diag(From->getLocStart(),
5125 diag::err_implicit_object_parameter_init)
5126 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5127 }
5128
5129 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5130 ExprResult FromRes =
5131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5132 if (FromRes.isInvalid())
5133 return ExprError();
5134 From = FromRes.get();
5135 }
5136
5137 if (!Context.hasSameType(From->getType(), DestType))
5138 From = ImpCastExprToType(From, DestType, CK_NoOp,
5139 From->getValueKind()).get();
5140 return From;
5141}
5142
5143/// TryContextuallyConvertToBool - Attempt to contextually convert the
5144/// expression From to bool (C++0x [conv]p3).
5145static ImplicitConversionSequence
5146TryContextuallyConvertToBool(Sema &S, Expr *From) {
5147 return TryImplicitConversion(S, From, S.Context.BoolTy,
5148 /*SuppressUserConversions=*/false,
5149 /*AllowExplicit=*/true,
5150 /*InOverloadResolution=*/false,
5151 /*CStyle=*/false,
5152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/false);
5154}
5155
5156/// PerformContextuallyConvertToBool - Perform a contextual conversion
5157/// of the expression From to bool (C++0x [conv]p3).
5158ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5159 if (checkPlaceholderForOverload(*this, From))
5160 return ExprError();
5161
5162 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5163 if (!ICS.isBad())
5164 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5165
5166 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5167 return Diag(From->getLocStart(),
5168 diag::err_typecheck_bool_condition)
5169 << From->getType() << From->getSourceRange();
5170 return ExprError();
5171}
5172
5173/// Check that the specified conversion is permitted in a converted constant
5174/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5175/// is acceptable.
5176static bool CheckConvertedConstantConversions(Sema &S,
5177 StandardConversionSequence &SCS) {
5178 // Since we know that the target type is an integral or unscoped enumeration
5179 // type, most conversion kinds are impossible. All possible First and Third
5180 // conversions are fine.
5181 switch (SCS.Second) {
5182 case ICK_Identity:
5183 case ICK_Function_Conversion:
5184 case ICK_Integral_Promotion:
5185 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5186 case ICK_Zero_Queue_Conversion:
5187 return true;
5188
5189 case ICK_Boolean_Conversion:
5190 // Conversion from an integral or unscoped enumeration type to bool is
5191 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5192 // conversion, so we allow it in a converted constant expression.
5193 //
5194 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5195 // a lot of popular code. We should at least add a warning for this
5196 // (non-conforming) extension.
5197 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5198 SCS.getToType(2)->isBooleanType();
5199
5200 case ICK_Pointer_Conversion:
5201 case ICK_Pointer_Member:
5202 // C++1z: null pointer conversions and null member pointer conversions are
5203 // only permitted if the source type is std::nullptr_t.
5204 return SCS.getFromType()->isNullPtrType();
5205
5206 case ICK_Floating_Promotion:
5207 case ICK_Complex_Promotion:
5208 case ICK_Floating_Conversion:
5209 case ICK_Complex_Conversion:
5210 case ICK_Floating_Integral:
5211 case ICK_Compatible_Conversion:
5212 case ICK_Derived_To_Base:
5213 case ICK_Vector_Conversion:
5214 case ICK_Vector_Splat:
5215 case ICK_Complex_Real:
5216 case ICK_Block_Pointer_Conversion:
5217 case ICK_TransparentUnionConversion:
5218 case ICK_Writeback_Conversion:
5219 case ICK_Zero_Event_Conversion:
5220 case ICK_C_Only_Conversion:
5221 case ICK_Incompatible_Pointer_Conversion:
5222 return false;
5223
5224 case ICK_Lvalue_To_Rvalue:
5225 case ICK_Array_To_Pointer:
5226 case ICK_Function_To_Pointer:
5227 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5227)
;
5228
5229 case ICK_Qualification:
5230 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5230)
;
5231
5232 case ICK_Num_Conversion_Kinds:
5233 break;
5234 }
5235
5236 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5236)
;
5237}
5238
5239/// CheckConvertedConstantExpression - Check that the expression From is a
5240/// converted constant expression of type T, perform the conversion and produce
5241/// the converted expression, per C++11 [expr.const]p3.
5242static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5243 QualType T, APValue &Value,
5244 Sema::CCEKind CCE,
5245 bool RequireInt) {
5246 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5247, __PRETTY_FUNCTION__))
5247 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5247, __PRETTY_FUNCTION__))
;
5248
5249 if (checkPlaceholderForOverload(S, From))
5250 return ExprError();
5251
5252 // C++1z [expr.const]p3:
5253 // A converted constant expression of type T is an expression,
5254 // implicitly converted to type T, where the converted
5255 // expression is a constant expression and the implicit conversion
5256 // sequence contains only [... list of conversions ...].
5257 // C++1z [stmt.if]p2:
5258 // If the if statement is of the form if constexpr, the value of the
5259 // condition shall be a contextually converted constant expression of type
5260 // bool.
5261 ImplicitConversionSequence ICS =
5262 CCE == Sema::CCEK_ConstexprIf
5263 ? TryContextuallyConvertToBool(S, From)
5264 : TryCopyInitialization(S, From, T,
5265 /*SuppressUserConversions=*/false,
5266 /*InOverloadResolution=*/false,
5267 /*AllowObjcWritebackConversion=*/false,
5268 /*AllowExplicit=*/false);
5269 StandardConversionSequence *SCS = nullptr;
5270 switch (ICS.getKind()) {
5271 case ImplicitConversionSequence::StandardConversion:
5272 SCS = &ICS.Standard;
5273 break;
5274 case ImplicitConversionSequence::UserDefinedConversion:
5275 // We are converting to a non-class type, so the Before sequence
5276 // must be trivial.
5277 SCS = &ICS.UserDefined.After;
5278 break;
5279 case ImplicitConversionSequence::AmbiguousConversion:
5280 case ImplicitConversionSequence::BadConversion:
5281 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5282 return S.Diag(From->getLocStart(),
5283 diag::err_typecheck_converted_constant_expression)
5284 << From->getType() << From->getSourceRange() << T;
5285 return ExprError();
5286
5287 case ImplicitConversionSequence::EllipsisConversion:
5288 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5288)
;
5289 }
5290
5291 // Check that we would only use permitted conversions.
5292 if (!CheckConvertedConstantConversions(S, *SCS)) {
5293 return S.Diag(From->getLocStart(),
5294 diag::err_typecheck_converted_constant_expression_disallowed)
5295 << From->getType() << From->getSourceRange() << T;
5296 }
5297 // [...] and where the reference binding (if any) binds directly.
5298 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5299 return S.Diag(From->getLocStart(),
5300 diag::err_typecheck_converted_constant_expression_indirect)
5301 << From->getType() << From->getSourceRange() << T;
5302 }
5303
5304 ExprResult Result =
5305 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5306 if (Result.isInvalid())
5307 return Result;
5308
5309 // Check for a narrowing implicit conversion.
5310 APValue PreNarrowingValue;
5311 QualType PreNarrowingType;
5312 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5313 PreNarrowingType)) {
5314 case NK_Dependent_Narrowing:
5315 // Implicit conversion to a narrower type, but the expression is
5316 // value-dependent so we can't tell whether it's actually narrowing.
5317 case NK_Variable_Narrowing:
5318 // Implicit conversion to a narrower type, and the value is not a constant
5319 // expression. We'll diagnose this in a moment.
5320 case NK_Not_Narrowing:
5321 break;
5322
5323 case NK_Constant_Narrowing:
5324 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5325 << CCE << /*Constant*/1
5326 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5327 break;
5328
5329 case NK_Type_Narrowing:
5330 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5331 << CCE << /*Constant*/0 << From->getType() << T;
5332 break;
5333 }
5334
5335 if (Result.get()->isValueDependent()) {
5336 Value = APValue();
5337 return Result;
5338 }
5339
5340 // Check the expression is a constant expression.
5341 SmallVector<PartialDiagnosticAt, 8> Notes;
5342 Expr::EvalResult Eval;
5343 Eval.Diag = &Notes;
5344
5345 if ((T->isReferenceType()
5346 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5347 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5348 (RequireInt && !Eval.Val.isInt())) {
5349 // The expression can't be folded, so we can't keep it at this position in
5350 // the AST.
5351 Result = ExprError();
5352 } else {
5353 Value = Eval.Val;
5354
5355 if (Notes.empty()) {
5356 // It's a constant expression.
5357 return Result;
5358 }
5359 }
5360
5361 // It's not a constant expression. Produce an appropriate diagnostic.
5362 if (Notes.size() == 1 &&
5363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5364 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5365 else {
5366 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5367 << CCE << From->getSourceRange();
5368 for (unsigned I = 0; I < Notes.size(); ++I)
5369 S.Diag(Notes[I].first, Notes[I].second);
5370 }
5371 return ExprError();
5372}
5373
5374ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5375 APValue &Value, CCEKind CCE) {
5376 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5377}
5378
5379ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5380 llvm::APSInt &Value,
5381 CCEKind CCE) {
5382 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5382, __PRETTY_FUNCTION__))
;
5383
5384 APValue V;
5385 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5386 if (!R.isInvalid() && !R.get()->isValueDependent())
5387 Value = V.getInt();
5388 return R;
5389}
5390
5391
5392/// dropPointerConversions - If the given standard conversion sequence
5393/// involves any pointer conversions, remove them. This may change
5394/// the result type of the conversion sequence.
5395static void dropPointerConversion(StandardConversionSequence &SCS) {
5396 if (SCS.Second == ICK_Pointer_Conversion) {
5397 SCS.Second = ICK_Identity;
5398 SCS.Third = ICK_Identity;
5399 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5400 }
5401}
5402
5403/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5404/// convert the expression From to an Objective-C pointer type.
5405static ImplicitConversionSequence
5406TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5407 // Do an implicit conversion to 'id'.
5408 QualType Ty = S.Context.getObjCIdType();
5409 ImplicitConversionSequence ICS
5410 = TryImplicitConversion(S, From, Ty,
5411 // FIXME: Are these flags correct?
5412 /*SuppressUserConversions=*/false,
5413 /*AllowExplicit=*/true,
5414 /*InOverloadResolution=*/false,
5415 /*CStyle=*/false,
5416 /*AllowObjCWritebackConversion=*/false,
5417 /*AllowObjCConversionOnExplicit=*/true);
5418
5419 // Strip off any final conversions to 'id'.
5420 switch (ICS.getKind()) {
5421 case ImplicitConversionSequence::BadConversion:
5422 case ImplicitConversionSequence::AmbiguousConversion:
5423 case ImplicitConversionSequence::EllipsisConversion:
5424 break;
5425
5426 case ImplicitConversionSequence::UserDefinedConversion:
5427 dropPointerConversion(ICS.UserDefined.After);
5428 break;
5429
5430 case ImplicitConversionSequence::StandardConversion:
5431 dropPointerConversion(ICS.Standard);
5432 break;
5433 }
5434
5435 return ICS;
5436}
5437
5438/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5439/// conversion of the expression From to an Objective-C pointer type.
5440/// Returns a valid but null ExprResult if no conversion sequence exists.
5441ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5442 if (checkPlaceholderForOverload(*this, From))
5443 return ExprError();
5444
5445 QualType Ty = Context.getObjCIdType();
5446 ImplicitConversionSequence ICS =
5447 TryContextuallyConvertToObjCPointer(*this, From);
5448 if (!ICS.isBad())
5449 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5450 return ExprResult();
5451}
5452
5453/// Determine whether the provided type is an integral type, or an enumeration
5454/// type of a permitted flavor.
5455bool Sema::ICEConvertDiagnoser::match(QualType T) {
5456 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5457 : T->isIntegralOrUnscopedEnumerationType();
5458}
5459
5460static ExprResult
5461diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5462 Sema::ContextualImplicitConverter &Converter,
5463 QualType T, UnresolvedSetImpl &ViableConversions) {
5464
5465 if (Converter.Suppress)
5466 return ExprError();
5467
5468 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5470 CXXConversionDecl *Conv =
5471 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5472 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5473 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5474 }
5475 return From;
5476}
5477
5478static bool
5479diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5480 Sema::ContextualImplicitConverter &Converter,
5481 QualType T, bool HadMultipleCandidates,
5482 UnresolvedSetImpl &ExplicitConversions) {
5483 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5484 DeclAccessPair Found = ExplicitConversions[0];
5485 CXXConversionDecl *Conversion =
5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5487
5488 // The user probably meant to invoke the given explicit
5489 // conversion; use it.
5490 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5491 std::string TypeStr;
5492 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5493
5494 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5495 << FixItHint::CreateInsertion(From->getLocStart(),
5496 "static_cast<" + TypeStr + ">(")
5497 << FixItHint::CreateInsertion(
5498 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5499 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5500
5501 // If we aren't in a SFINAE context, build a call to the
5502 // explicit conversion function.
5503 if (SemaRef.isSFINAEContext())
5504 return true;
5505
5506 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5507 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5508 HadMultipleCandidates);
5509 if (Result.isInvalid())
5510 return true;
5511 // Record usage of conversion in an implicit cast.
5512 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5513 CK_UserDefinedConversion, Result.get(),
5514 nullptr, Result.get()->getValueKind());
5515 }
5516 return false;
5517}
5518
5519static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5520 Sema::ContextualImplicitConverter &Converter,
5521 QualType T, bool HadMultipleCandidates,
5522 DeclAccessPair &Found) {
5523 CXXConversionDecl *Conversion =
5524 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5525 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5526
5527 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5528 if (!Converter.SuppressConversion) {
5529 if (SemaRef.isSFINAEContext())
5530 return true;
5531
5532 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5533 << From->getSourceRange();
5534 }
5535
5536 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5537 HadMultipleCandidates);
5538 if (Result.isInvalid())
5539 return true;
5540 // Record usage of conversion in an implicit cast.
5541 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5542 CK_UserDefinedConversion, Result.get(),
5543 nullptr, Result.get()->getValueKind());
5544 return false;
5545}
5546
5547static ExprResult finishContextualImplicitConversion(
5548 Sema &SemaRef, SourceLocation Loc, Expr *From,
5549 Sema::ContextualImplicitConverter &Converter) {
5550 if (!Converter.match(From->getType()) && !Converter.Suppress)
5551 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5552 << From->getSourceRange();
5553
5554 return SemaRef.DefaultLvalueConversion(From);
5555}
5556
5557static void
5558collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5559 UnresolvedSetImpl &ViableConversions,
5560 OverloadCandidateSet &CandidateSet) {
5561 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5562 DeclAccessPair FoundDecl = ViableConversions[I];
5563 NamedDecl *D = FoundDecl.getDecl();
5564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5565 if (isa<UsingShadowDecl>(D))
5566 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5567
5568 CXXConversionDecl *Conv;
5569 FunctionTemplateDecl *ConvTemplate;
5570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5571 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5572 else
5573 Conv = cast<CXXConversionDecl>(D);
5574
5575 if (ConvTemplate)
5576 SemaRef.AddTemplateConversionCandidate(
5577 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5578 /*AllowObjCConversionOnExplicit=*/false);
5579 else
5580 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5581 ToType, CandidateSet,
5582 /*AllowObjCConversionOnExplicit=*/false);
5583 }
5584}
5585
5586/// \brief Attempt to convert the given expression to a type which is accepted
5587/// by the given converter.
5588///
5589/// This routine will attempt to convert an expression of class type to a
5590/// type accepted by the specified converter. In C++11 and before, the class
5591/// must have a single non-explicit conversion function converting to a matching
5592/// type. In C++1y, there can be multiple such conversion functions, but only
5593/// one target type.
5594///
5595/// \param Loc The source location of the construct that requires the
5596/// conversion.
5597///
5598/// \param From The expression we're converting from.
5599///
5600/// \param Converter Used to control and diagnose the conversion process.
5601///
5602/// \returns The expression, converted to an integral or enumeration type if
5603/// successful.
5604ExprResult Sema::PerformContextualImplicitConversion(
5605 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5606 // We can't perform any more checking for type-dependent expressions.
5607 if (From->isTypeDependent())
5608 return From;
5609
5610 // Process placeholders immediately.
5611 if (From->hasPlaceholderType()) {
5612 ExprResult result = CheckPlaceholderExpr(From);
5613 if (result.isInvalid())
5614 return result;
5615 From = result.get();
5616 }
5617
5618 // If the expression already has a matching type, we're golden.
5619 QualType T = From->getType();
5620 if (Converter.match(T))
5621 return DefaultLvalueConversion(From);
5622
5623 // FIXME: Check for missing '()' if T is a function type?
5624
5625 // We can only perform contextual implicit conversions on objects of class
5626 // type.
5627 const RecordType *RecordTy = T->getAs<RecordType>();
5628 if (!RecordTy || !getLangOpts().CPlusPlus) {
5629 if (!Converter.Suppress)
5630 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5631 return From;
5632 }
5633
5634 // We must have a complete class type.
5635 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5636 ContextualImplicitConverter &Converter;
5637 Expr *From;
5638
5639 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5640 : Converter(Converter), From(From) {}
5641
5642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5643 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5644 }
5645 } IncompleteDiagnoser(Converter, From);
5646
5647 if (Converter.Suppress ? !isCompleteType(Loc, T)
5648 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5649 return From;
5650
5651 // Look for a conversion to an integral or enumeration type.
5652 UnresolvedSet<4>
5653 ViableConversions; // These are *potentially* viable in C++1y.
5654 UnresolvedSet<4> ExplicitConversions;
5655 const auto &Conversions =
5656 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5657
5658 bool HadMultipleCandidates =
5659 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5660
5661 // To check that there is only one target type, in C++1y:
5662 QualType ToType;
5663 bool HasUniqueTargetType = true;
5664
5665 // Collect explicit or viable (potentially in C++1y) conversions.
5666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5667 NamedDecl *D = (*I)->getUnderlyingDecl();
5668 CXXConversionDecl *Conversion;
5669 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5670 if (ConvTemplate) {
5671 if (getLangOpts().CPlusPlus14)
5672 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5673 else
5674 continue; // C++11 does not consider conversion operator templates(?).
5675 } else
5676 Conversion = cast<CXXConversionDecl>(D);
5677
5678 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5680, __PRETTY_FUNCTION__))
5679 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5680, __PRETTY_FUNCTION__))
5680 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5680, __PRETTY_FUNCTION__))
;
5681
5682 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5683 if (Converter.match(CurToType) || ConvTemplate) {
5684
5685 if (Conversion->isExplicit()) {
5686 // FIXME: For C++1y, do we need this restriction?
5687 // cf. diagnoseNoViableConversion()
5688 if (!ConvTemplate)
5689 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5690 } else {
5691 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5692 if (ToType.isNull())
5693 ToType = CurToType.getUnqualifiedType();
5694 else if (HasUniqueTargetType &&
5695 (CurToType.getUnqualifiedType() != ToType))
5696 HasUniqueTargetType = false;
5697 }
5698 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5699 }
5700 }
5701 }
5702
5703 if (getLangOpts().CPlusPlus14) {
5704 // C++1y [conv]p6:
5705 // ... An expression e of class type E appearing in such a context
5706 // is said to be contextually implicitly converted to a specified
5707 // type T and is well-formed if and only if e can be implicitly
5708 // converted to a type T that is determined as follows: E is searched
5709 // for conversion functions whose return type is cv T or reference to
5710 // cv T such that T is allowed by the context. There shall be
5711 // exactly one such T.
5712
5713 // If no unique T is found:
5714 if (ToType.isNull()) {
5715 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5716 HadMultipleCandidates,
5717 ExplicitConversions))
5718 return ExprError();
5719 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5720 }
5721
5722 // If more than one unique Ts are found:
5723 if (!HasUniqueTargetType)
5724 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5725 ViableConversions);
5726
5727 // If one unique T is found:
5728 // First, build a candidate set from the previously recorded
5729 // potentially viable conversions.
5730 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5731 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5732 CandidateSet);
5733
5734 // Then, perform overload resolution over the candidate set.
5735 OverloadCandidateSet::iterator Best;
5736 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5737 case OR_Success: {
5738 // Apply this conversion.
5739 DeclAccessPair Found =
5740 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5741 if (recordConversion(*this, Loc, From, Converter, T,
5742 HadMultipleCandidates, Found))
5743 return ExprError();
5744 break;
5745 }
5746 case OR_Ambiguous:
5747 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5748 ViableConversions);
5749 case OR_No_Viable_Function:
5750 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5751 HadMultipleCandidates,
5752 ExplicitConversions))
5753 return ExprError();
5754 // fall through 'OR_Deleted' case.
5755 case OR_Deleted:
5756 // We'll complain below about a non-integral condition type.
5757 break;
5758 }
5759 } else {
5760 switch (ViableConversions.size()) {
5761 case 0: {
5762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5763 HadMultipleCandidates,
5764 ExplicitConversions))
5765 return ExprError();
5766
5767 // We'll complain below about a non-integral condition type.
5768 break;
5769 }
5770 case 1: {
5771 // Apply this conversion.
5772 DeclAccessPair Found = ViableConversions[0];
5773 if (recordConversion(*this, Loc, From, Converter, T,
5774 HadMultipleCandidates, Found))
5775 return ExprError();
5776 break;
5777 }
5778 default:
5779 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5780 ViableConversions);
5781 }
5782 }
5783
5784 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5785}
5786
5787/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5788/// an acceptable non-member overloaded operator for a call whose
5789/// arguments have types T1 (and, if non-empty, T2). This routine
5790/// implements the check in C++ [over.match.oper]p3b2 concerning
5791/// enumeration types.
5792static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5793 FunctionDecl *Fn,
5794 ArrayRef<Expr *> Args) {
5795 QualType T1 = Args[0]->getType();
5796 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5797
5798 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5799 return true;
5800
5801 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5802 return true;
5803
5804 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5805 if (Proto->getNumParams() < 1)
5806 return false;
5807
5808 if (T1->isEnumeralType()) {
5809 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5810 if (Context.hasSameUnqualifiedType(T1, ArgType))
5811 return true;
5812 }
5813
5814 if (Proto->getNumParams() < 2)
5815 return false;
5816
5817 if (!T2.isNull() && T2->isEnumeralType()) {
5818 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5819 if (Context.hasSameUnqualifiedType(T2, ArgType))
5820 return true;
5821 }
5822
5823 return false;
5824}
5825
5826/// AddOverloadCandidate - Adds the given function to the set of
5827/// candidate functions, using the given function call arguments. If
5828/// @p SuppressUserConversions, then don't allow user-defined
5829/// conversions via constructors or conversion operators.
5830///
5831/// \param PartialOverloading true if we are performing "partial" overloading
5832/// based on an incomplete set of function arguments. This feature is used by
5833/// code completion.
5834void
5835Sema::AddOverloadCandidate(FunctionDecl *Function,
5836 DeclAccessPair FoundDecl,
5837 ArrayRef<Expr *> Args,
5838 OverloadCandidateSet &CandidateSet,
5839 bool SuppressUserConversions,
5840 bool PartialOverloading,
5841 bool AllowExplicit,
5842 ConversionSequenceList EarlyConversions) {
5843 const FunctionProtoType *Proto
5844 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5845 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5845, __PRETTY_FUNCTION__))
;
5846 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5847, __PRETTY_FUNCTION__))
5847 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 5847, __PRETTY_FUNCTION__))
;
5848
5849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5850 if (!isa<CXXConstructorDecl>(Method)) {
5851 // If we get here, it's because we're calling a member function
5852 // that is named without a member access expression (e.g.,
5853 // "this->f") that was either written explicitly or created
5854 // implicitly. This can happen with a qualified call to a member
5855 // function, e.g., X::f(). We use an empty type for the implied
5856 // object argument (C++ [over.call.func]p3), and the acting context
5857 // is irrelevant.
5858 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5859 Expr::Classification::makeSimpleLValue(), Args,
5860 CandidateSet, SuppressUserConversions,
5861 PartialOverloading, EarlyConversions);
5862 return;
5863 }
5864 // We treat a constructor like a non-member function, since its object
5865 // argument doesn't participate in overload resolution.
5866 }
5867
5868 if (!CandidateSet.isNewCandidate(Function))
5869 return;
5870
5871 // C++ [over.match.oper]p3:
5872 // if no operand has a class type, only those non-member functions in the
5873 // lookup set that have a first parameter of type T1 or "reference to
5874 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5875 // is a right operand) a second parameter of type T2 or "reference to
5876 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5877 // candidate functions.
5878 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5879 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5880 return;
5881
5882 // C++11 [class.copy]p11: [DR1402]
5883 // A defaulted move constructor that is defined as deleted is ignored by
5884 // overload resolution.
5885 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5886 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5887 Constructor->isMoveConstructor())
5888 return;
5889
5890 // Overload resolution is always an unevaluated context.
5891 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5892
5893 // Add this candidate
5894 OverloadCandidate &Candidate =
5895 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5896 Candidate.FoundDecl = FoundDecl;
5897 Candidate.Function = Function;
5898 Candidate.Viable = true;
5899 Candidate.IsSurrogate = false;
5900 Candidate.IgnoreObjectArgument = false;
5901 Candidate.ExplicitCallArguments = Args.size();
5902
5903 if (Constructor) {
5904 // C++ [class.copy]p3:
5905 // A member function template is never instantiated to perform the copy
5906 // of a class object to an object of its class type.
5907 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5908 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5909 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5910 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5911 ClassType))) {
5912 Candidate.Viable = false;
5913 Candidate.FailureKind = ovl_fail_illegal_constructor;
5914 return;
5915 }
5916
5917 // C++ [over.match.funcs]p8: (proposed DR resolution)
5918 // A constructor inherited from class type C that has a first parameter
5919 // of type "reference to P" (including such a constructor instantiated
5920 // from a template) is excluded from the set of candidate functions when
5921 // constructing an object of type cv D if the argument list has exactly
5922 // one argument and D is reference-related to P and P is reference-related
5923 // to C.
5924 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5925 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5926 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5927 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5928 QualType C = Context.getRecordType(Constructor->getParent());
5929 QualType D = Context.getRecordType(Shadow->getParent());
5930 SourceLocation Loc = Args.front()->getExprLoc();
5931 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5932 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5933 Candidate.Viable = false;
5934 Candidate.FailureKind = ovl_fail_inhctor_slice;
5935 return;
5936 }
5937 }
5938 }
5939
5940 unsigned NumParams = Proto->getNumParams();
5941
5942 // (C++ 13.3.2p2): A candidate function having fewer than m
5943 // parameters is viable only if it has an ellipsis in its parameter
5944 // list (8.3.5).
5945 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5946 !Proto->isVariadic()) {
5947 Candidate.Viable = false;
5948 Candidate.FailureKind = ovl_fail_too_many_arguments;
5949 return;
5950 }
5951
5952 // (C++ 13.3.2p2): A candidate function having more than m parameters
5953 // is viable only if the (m+1)st parameter has a default argument
5954 // (8.3.6). For the purposes of overload resolution, the
5955 // parameter list is truncated on the right, so that there are
5956 // exactly m parameters.
5957 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5958 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5959 // Not enough arguments.
5960 Candidate.Viable = false;
5961 Candidate.FailureKind = ovl_fail_too_few_arguments;
5962 return;
5963 }
5964
5965 // (CUDA B.1): Check for invalid calls between targets.
5966 if (getLangOpts().CUDA)
5967 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5968 // Skip the check for callers that are implicit members, because in this
5969 // case we may not yet know what the member's target is; the target is
5970 // inferred for the member automatically, based on the bases and fields of
5971 // the class.
5972 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5973 Candidate.Viable = false;
5974 Candidate.FailureKind = ovl_fail_bad_target;
5975 return;
5976 }
5977
5978 // Determine the implicit conversion sequences for each of the
5979 // arguments.
5980 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5981 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5982 // We already formed a conversion sequence for this parameter during
5983 // template argument deduction.
5984 } else if (ArgIdx < NumParams) {
5985 // (C++ 13.3.2p3): for F to be a viable function, there shall
5986 // exist for each argument an implicit conversion sequence
5987 // (13.3.3.1) that converts that argument to the corresponding
5988 // parameter of F.
5989 QualType ParamType = Proto->getParamType(ArgIdx);
5990 Candidate.Conversions[ArgIdx]
5991 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5992 SuppressUserConversions,
5993 /*InOverloadResolution=*/true,
5994 /*AllowObjCWritebackConversion=*/
5995 getLangOpts().ObjCAutoRefCount,
5996 AllowExplicit);
5997 if (Candidate.Conversions[ArgIdx].isBad()) {
5998 Candidate.Viable = false;
5999 Candidate.FailureKind = ovl_fail_bad_conversion;
6000 return;
6001 }
6002 } else {
6003 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6004 // argument for which there is no corresponding parameter is
6005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6006 Candidate.Conversions[ArgIdx].setEllipsis();
6007 }
6008 }
6009
6010 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6011 Candidate.Viable = false;
6012 Candidate.FailureKind = ovl_fail_enable_if;
6013 Candidate.DeductionFailure.Data = FailedAttr;
6014 return;
6015 }
6016
6017 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6018 Candidate.Viable = false;
6019 Candidate.FailureKind = ovl_fail_ext_disabled;
6020 return;
6021 }
6022}
6023
6024ObjCMethodDecl *
6025Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6026 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6027 if (Methods.size() <= 1)
6028 return nullptr;
6029
6030 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6031 bool Match = true;
6032 ObjCMethodDecl *Method = Methods[b];
6033 unsigned NumNamedArgs = Sel.getNumArgs();
6034 // Method might have more arguments than selector indicates. This is due
6035 // to addition of c-style arguments in method.
6036 if (Method->param_size() > NumNamedArgs)
6037 NumNamedArgs = Method->param_size();
6038 if (Args.size() < NumNamedArgs)
6039 continue;
6040
6041 for (unsigned i = 0; i < NumNamedArgs; i++) {
6042 // We can't do any type-checking on a type-dependent argument.
6043 if (Args[i]->isTypeDependent()) {
6044 Match = false;
6045 break;
6046 }
6047
6048 ParmVarDecl *param = Method->parameters()[i];
6049 Expr *argExpr = Args[i];
6050 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6050, __PRETTY_FUNCTION__))
;
6051
6052 // Strip the unbridged-cast placeholder expression off unless it's
6053 // a consumed argument.
6054 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6055 !param->hasAttr<CFConsumedAttr>())
6056 argExpr = stripARCUnbridgedCast(argExpr);
6057
6058 // If the parameter is __unknown_anytype, move on to the next method.
6059 if (param->getType() == Context.UnknownAnyTy) {
6060 Match = false;
6061 break;
6062 }
6063
6064 ImplicitConversionSequence ConversionState
6065 = TryCopyInitialization(*this, argExpr, param->getType(),
6066 /*SuppressUserConversions*/false,
6067 /*InOverloadResolution=*/true,
6068 /*AllowObjCWritebackConversion=*/
6069 getLangOpts().ObjCAutoRefCount,
6070 /*AllowExplicit*/false);
6071 // This function looks for a reasonably-exact match, so we consider
6072 // incompatible pointer conversions to be a failure here.
6073 if (ConversionState.isBad() ||
6074 (ConversionState.isStandard() &&
6075 ConversionState.Standard.Second ==
6076 ICK_Incompatible_Pointer_Conversion)) {
6077 Match = false;
6078 break;
6079 }
6080 }
6081 // Promote additional arguments to variadic methods.
6082 if (Match && Method->isVariadic()) {
6083 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6084 if (Args[i]->isTypeDependent()) {
6085 Match = false;
6086 break;
6087 }
6088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6089 nullptr);
6090 if (Arg.isInvalid()) {
6091 Match = false;
6092 break;
6093 }
6094 }
6095 } else {
6096 // Check for extra arguments to non-variadic methods.
6097 if (Args.size() != NumNamedArgs)
6098 Match = false;
6099 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6100 // Special case when selectors have no argument. In this case, select
6101 // one with the most general result type of 'id'.
6102 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6103 QualType ReturnT = Methods[b]->getReturnType();
6104 if (ReturnT->isObjCIdType())
6105 return Methods[b];
6106 }
6107 }
6108 }
6109
6110 if (Match)
6111 return Method;
6112 }
6113 return nullptr;
6114}
6115
6116// specific_attr_iterator iterates over enable_if attributes in reverse, and
6117// enable_if is order-sensitive. As a result, we need to reverse things
6118// sometimes. Size of 4 elements is arbitrary.
6119static SmallVector<EnableIfAttr *, 4>
6120getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6121 SmallVector<EnableIfAttr *, 4> Result;
6122 if (!Function->hasAttrs())
6123 return Result;
6124
6125 const auto &FuncAttrs = Function->getAttrs();
6126 for (Attr *Attr : FuncAttrs)
6127 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6128 Result.push_back(EnableIf);
6129
6130 std::reverse(Result.begin(), Result.end());
6131 return Result;
6132}
6133
6134static bool
6135convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6136 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6137 bool MissingImplicitThis, Expr *&ConvertedThis,
6138 SmallVectorImpl<Expr *> &ConvertedArgs) {
6139 if (ThisArg) {
6140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6141 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6142, __PRETTY_FUNCTION__))
6142 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6142, __PRETTY_FUNCTION__))
;
6143 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6143, __PRETTY_FUNCTION__))
;
6144 ExprResult R = S.PerformObjectArgumentInitialization(
6145 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6146 if (R.isInvalid())
6147 return false;
6148 ConvertedThis = R.get();
6149 } else {
6150 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6151 (void)MD;
6152 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6154, __PRETTY_FUNCTION__))
6153 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6154, __PRETTY_FUNCTION__))
6154 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6154, __PRETTY_FUNCTION__))
;
6155 }
6156 ConvertedThis = nullptr;
6157 }
6158
6159 // Ignore any variadic arguments. Converting them is pointless, since the
6160 // user can't refer to them in the function condition.
6161 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6162
6163 // Convert the arguments.
6164 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6165 ExprResult R;
6166 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6167 S.Context, Function->getParamDecl(I)),
6168 SourceLocation(), Args[I]);
6169
6170 if (R.isInvalid())
6171 return false;
6172
6173 ConvertedArgs.push_back(R.get());
6174 }
6175
6176 if (Trap.hasErrorOccurred())
6177 return false;
6178
6179 // Push default arguments if needed.
6180 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6181 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6182 ParmVarDecl *P = Function->getParamDecl(i);
6183 ExprResult R = S.PerformCopyInitialization(
6184 InitializedEntity::InitializeParameter(S.Context,
6185 Function->getParamDecl(i)),
6186 SourceLocation(),
6187 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6188 : P->getDefaultArg());
6189 if (R.isInvalid())
6190 return false;
6191 ConvertedArgs.push_back(R.get());
6192 }
6193
6194 if (Trap.hasErrorOccurred())
6195 return false;
6196 }
6197 return true;
6198}
6199
6200EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6201 bool MissingImplicitThis) {
6202 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6203 getOrderedEnableIfAttrs(Function);
6204 if (EnableIfAttrs.empty())
6205 return nullptr;
6206
6207 SFINAETrap Trap(*this);
6208 SmallVector<Expr *, 16> ConvertedArgs;
6209 // FIXME: We should look into making enable_if late-parsed.
6210 Expr *DiscardedThis;
6211 if (!convertArgsForAvailabilityChecks(
6212 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6213 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6214 return EnableIfAttrs[0];
6215
6216 for (auto *EIA : EnableIfAttrs) {
6217 APValue Result;
6218 // FIXME: This doesn't consider value-dependent cases, because doing so is
6219 // very difficult. Ideally, we should handle them more gracefully.
6220 if (!EIA->getCond()->EvaluateWithSubstitution(
6221 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6222 return EIA;
6223
6224 if (!Result.isInt() || !Result.getInt().getBoolValue())
6225 return EIA;
6226 }
6227 return nullptr;
6228}
6229
6230template <typename CheckFn>
6231static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD,
6232 bool ArgDependent, SourceLocation Loc,
6233 CheckFn &&IsSuccessful) {
6234 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6235 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) {
6236 if (ArgDependent == DIA->getArgDependent())
6237 Attrs.push_back(DIA);
6238 }
6239
6240 // Common case: No diagnose_if attributes, so we can quit early.
6241 if (Attrs.empty())
6242 return false;
6243
6244 auto WarningBegin = std::stable_partition(
6245 Attrs.begin(), Attrs.end(),
6246 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6247
6248 // Note that diagnose_if attributes are late-parsed, so they appear in the
6249 // correct order (unlike enable_if attributes).
6250 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6251 IsSuccessful);
6252 if (ErrAttr != WarningBegin) {
6253 const DiagnoseIfAttr *DIA = *ErrAttr;
6254 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6256 << DIA->getParent() << DIA->getCond()->getSourceRange();
6257 return true;
6258 }
6259
6260 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6261 if (IsSuccessful(DIA)) {
6262 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6263 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6264 << DIA->getParent() << DIA->getCond()->getSourceRange();
6265 }
6266
6267 return false;
6268}
6269
6270bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6271 const Expr *ThisArg,
6272 ArrayRef<const Expr *> Args,
6273 SourceLocation Loc) {
6274 return diagnoseDiagnoseIfAttrsWith(
6275 *this, Function, /*ArgDependent=*/true, Loc,
6276 [&](const DiagnoseIfAttr *DIA) {
6277 APValue Result;
6278 // It's sane to use the same Args for any redecl of this function, since
6279 // EvaluateWithSubstitution only cares about the position of each
6280 // argument in the arg list, not the ParmVarDecl* it maps to.
6281 if (!DIA->getCond()->EvaluateWithSubstitution(
6282 Result, Context, DIA->getParent(), Args, ThisArg))
6283 return false;
6284 return Result.isInt() && Result.getInt().getBoolValue();
6285 });
6286}
6287
6288bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
6289 SourceLocation Loc) {
6290 return diagnoseDiagnoseIfAttrsWith(
6291 *this, Function, /*ArgDependent=*/false, Loc,
6292 [&](const DiagnoseIfAttr *DIA) {
6293 bool Result;
6294 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6295 Result;
6296 });
6297}
6298
6299/// \brief Add all of the function declarations in the given function set to
6300/// the overload candidate set.
6301void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6302 ArrayRef<Expr *> Args,
6303 OverloadCandidateSet& CandidateSet,
6304 TemplateArgumentListInfo *ExplicitTemplateArgs,
6305 bool SuppressUserConversions,
6306 bool PartialOverloading) {
6307 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6308 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6310 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6311 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6312 cast<CXXMethodDecl>(FD)->getParent(),
6313 Args[0]->getType(), Args[0]->Classify(Context),
6314 Args.slice(1), CandidateSet, SuppressUserConversions,
6315 PartialOverloading);
6316 else
6317 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6318 SuppressUserConversions, PartialOverloading);
6319 } else {
6320 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6321 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6322 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6323 AddMethodTemplateCandidate(
6324 FunTmpl, F.getPair(),
6325 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6326 ExplicitTemplateArgs, Args[0]->getType(),
6327 Args[0]->Classify(Context), Args.slice(1), CandidateSet,
6328 SuppressUserConversions, PartialOverloading);
6329 else
6330 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6331 ExplicitTemplateArgs, Args,
6332 CandidateSet, SuppressUserConversions,
6333 PartialOverloading);
6334 }
6335 }
6336}
6337
6338/// AddMethodCandidate - Adds a named decl (which is some kind of
6339/// method) as a method candidate to the given overload set.
6340void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6341 QualType ObjectType,
6342 Expr::Classification ObjectClassification,
6343 ArrayRef<Expr *> Args,
6344 OverloadCandidateSet& CandidateSet,
6345 bool SuppressUserConversions) {
6346 NamedDecl *Decl = FoundDecl.getDecl();
6347 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6348
6349 if (isa<UsingShadowDecl>(Decl))
6350 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6351
6352 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6353 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6354, __PRETTY_FUNCTION__))
6354 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6354, __PRETTY_FUNCTION__))
;
6355 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6356 /*ExplicitArgs*/ nullptr, ObjectType,
6357 ObjectClassification, Args, CandidateSet,
6358 SuppressUserConversions);
6359 } else {
6360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6361 ObjectType, ObjectClassification, Args, CandidateSet,
6362 SuppressUserConversions);
6363 }
6364}
6365
6366/// AddMethodCandidate - Adds the given C++ member function to the set
6367/// of candidate functions, using the given function call arguments
6368/// and the object argument (@c Object). For example, in a call
6369/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6370/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6371/// allow user-defined conversions via constructors or conversion
6372/// operators.
6373void
6374Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6375 CXXRecordDecl *ActingContext, QualType ObjectType,
6376 Expr::Classification ObjectClassification,
6377 ArrayRef<Expr *> Args,
6378 OverloadCandidateSet &CandidateSet,
6379 bool SuppressUserConversions,
6380 bool PartialOverloading,
6381 ConversionSequenceList EarlyConversions) {
6382 const FunctionProtoType *Proto
6383 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6384 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6384, __PRETTY_FUNCTION__))
;
6385 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6386, __PRETTY_FUNCTION__))
6386 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6386, __PRETTY_FUNCTION__))
;
6387
6388 if (!CandidateSet.isNewCandidate(Method))
6389 return;
6390
6391 // C++11 [class.copy]p23: [DR1402]
6392 // A defaulted move assignment operator that is defined as deleted is
6393 // ignored by overload resolution.
6394 if (Method->isDefaulted() && Method->isDeleted() &&
6395 Method->isMoveAssignmentOperator())
6396 return;
6397
6398 // Overload resolution is always an unevaluated context.
6399 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6400
6401 // Add this candidate
6402 OverloadCandidate &Candidate =
6403 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6404 Candidate.FoundDecl = FoundDecl;
6405 Candidate.Function = Method;
6406 Candidate.IsSurrogate = false;
6407 Candidate.IgnoreObjectArgument = false;
6408 Candidate.ExplicitCallArguments = Args.size();
6409
6410 unsigned NumParams = Proto->getNumParams();
6411
6412 // (C++ 13.3.2p2): A candidate function having fewer than m
6413 // parameters is viable only if it has an ellipsis in its parameter
6414 // list (8.3.5).
6415 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6416 !Proto->isVariadic()) {
6417 Candidate.Viable = false;
6418 Candidate.FailureKind = ovl_fail_too_many_arguments;
6419 return;
6420 }
6421
6422 // (C++ 13.3.2p2): A candidate function having more than m parameters
6423 // is viable only if the (m+1)st parameter has a default argument
6424 // (8.3.6). For the purposes of overload resolution, the
6425 // parameter list is truncated on the right, so that there are
6426 // exactly m parameters.
6427 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6428 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6429 // Not enough arguments.
6430 Candidate.Viable = false;
6431 Candidate.FailureKind = ovl_fail_too_few_arguments;
6432 return;
6433 }
6434
6435 Candidate.Viable = true;
6436
6437 if (Method->isStatic() || ObjectType.isNull())
6438 // The implicit object argument is ignored.
6439 Candidate.IgnoreObjectArgument = true;
6440 else {
6441 // Determine the implicit conversion sequence for the object
6442 // parameter.
6443 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6444 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6445 Method, ActingContext);
6446 if (Candidate.Conversions[0].isBad()) {
6447 Candidate.Viable = false;
6448 Candidate.FailureKind = ovl_fail_bad_conversion;
6449 return;
6450 }
6451 }
6452
6453 // (CUDA B.1): Check for invalid calls between targets.
6454 if (getLangOpts().CUDA)
6455 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6456 if (!IsAllowedCUDACall(Caller, Method)) {
6457 Candidate.Viable = false;
6458 Candidate.FailureKind = ovl_fail_bad_target;
6459 return;
6460 }
6461
6462 // Determine the implicit conversion sequences for each of the
6463 // arguments.
6464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6465 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6466 // We already formed a conversion sequence for this parameter during
6467 // template argument deduction.
6468 } else if (ArgIdx < NumParams) {
6469 // (C++ 13.3.2p3): for F to be a viable function, there shall
6470 // exist for each argument an implicit conversion sequence
6471 // (13.3.3.1) that converts that argument to the corresponding
6472 // parameter of F.
6473 QualType ParamType = Proto->getParamType(ArgIdx);
6474 Candidate.Conversions[ArgIdx + 1]
6475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6476 SuppressUserConversions,
6477 /*InOverloadResolution=*/true,
6478 /*AllowObjCWritebackConversion=*/
6479 getLangOpts().ObjCAutoRefCount);
6480 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6481 Candidate.Viable = false;
6482 Candidate.FailureKind = ovl_fail_bad_conversion;
6483 return;
6484 }
6485 } else {
6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6487 // argument for which there is no corresponding parameter is
6488 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6489 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6490 }
6491 }
6492
6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6494 Candidate.Viable = false;
6495 Candidate.FailureKind = ovl_fail_enable_if;
6496 Candidate.DeductionFailure.Data = FailedAttr;
6497 return;
6498 }
6499}
6500
6501/// \brief Add a C++ member function template as a candidate to the candidate
6502/// set, using template argument deduction to produce an appropriate member
6503/// function template specialization.
6504void
6505Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6506 DeclAccessPair FoundDecl,
6507 CXXRecordDecl *ActingContext,
6508 TemplateArgumentListInfo *ExplicitTemplateArgs,
6509 QualType ObjectType,
6510 Expr::Classification ObjectClassification,
6511 ArrayRef<Expr *> Args,
6512 OverloadCandidateSet& CandidateSet,
6513 bool SuppressUserConversions,
6514 bool PartialOverloading) {
6515 if (!CandidateSet.isNewCandidate(MethodTmpl))
6516 return;
6517
6518 // C++ [over.match.funcs]p7:
6519 // In each case where a candidate is a function template, candidate
6520 // function template specializations are generated using template argument
6521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6522 // candidate functions in the usual way.113) A given name can refer to one
6523 // or more function templates and also to a set of overloaded non-template
6524 // functions. In such a case, the candidate functions generated from each
6525 // function template are combined with the set of non-template candidate
6526 // functions.
6527 TemplateDeductionInfo Info(CandidateSet.getLocation());
6528 FunctionDecl *Specialization = nullptr;
6529 ConversionSequenceList Conversions;
6530 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6531 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6532 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6533 return CheckNonDependentConversions(
6534 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6535 SuppressUserConversions, ActingContext, ObjectType,
6536 ObjectClassification);
6537 })) {
6538 OverloadCandidate &Candidate =
6539 CandidateSet.addCandidate(Conversions.size(), Conversions);
6540 Candidate.FoundDecl = FoundDecl;
6541 Candidate.Function = MethodTmpl->getTemplatedDecl();
6542 Candidate.Viable = false;
6543 Candidate.IsSurrogate = false;
6544 Candidate.IgnoreObjectArgument =
6545 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6546 ObjectType.isNull();
6547 Candidate.ExplicitCallArguments = Args.size();
6548 if (Result == TDK_NonDependentConversionFailure)
6549 Candidate.FailureKind = ovl_fail_bad_conversion;
6550 else {
6551 Candidate.FailureKind = ovl_fail_bad_deduction;
6552 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6553 Info);
6554 }
6555 return;
6556 }
6557
6558 // Add the function template specialization produced by template argument
6559 // deduction as a candidate.
6560 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6560, __PRETTY_FUNCTION__))
;
6561 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6562, __PRETTY_FUNCTION__))
6562 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6562, __PRETTY_FUNCTION__))
;
6563 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6564 ActingContext, ObjectType, ObjectClassification, Args,
6565 CandidateSet, SuppressUserConversions, PartialOverloading,
6566 Conversions);
6567}
6568
6569/// \brief Add a C++ function template specialization as a candidate
6570/// in the candidate set, using template argument deduction to produce
6571/// an appropriate function template specialization.
6572void
6573Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6574 DeclAccessPair FoundDecl,
6575 TemplateArgumentListInfo *ExplicitTemplateArgs,
6576 ArrayRef<Expr *> Args,
6577 OverloadCandidateSet& CandidateSet,
6578 bool SuppressUserConversions,
6579 bool PartialOverloading) {
6580 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6581 return;
6582
6583 // C++ [over.match.funcs]p7:
6584 // In each case where a candidate is a function template, candidate
6585 // function template specializations are generated using template argument
6586 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6587 // candidate functions in the usual way.113) A given name can refer to one
6588 // or more function templates and also to a set of overloaded non-template
6589 // functions. In such a case, the candidate functions generated from each
6590 // function template are combined with the set of non-template candidate
6591 // functions.
6592 TemplateDeductionInfo Info(CandidateSet.getLocation());
6593 FunctionDecl *Specialization = nullptr;
6594 ConversionSequenceList Conversions;
6595 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6596 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6597 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6598 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6599 Args, CandidateSet, Conversions,
6600 SuppressUserConversions);
6601 })) {
6602 OverloadCandidate &Candidate =
6603 CandidateSet.addCandidate(Conversions.size(), Conversions);
6604 Candidate.FoundDecl = FoundDecl;
6605 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6606 Candidate.Viable = false;
6607 Candidate.IsSurrogate = false;
6608 // Ignore the object argument if there is one, since we don't have an object
6609 // type.
6610 Candidate.IgnoreObjectArgument =
6611 isa<CXXMethodDecl>(Candidate.Function) &&
6612 !isa<CXXConstructorDecl>(Candidate.Function);
6613 Candidate.ExplicitCallArguments = Args.size();
6614 if (Result == TDK_NonDependentConversionFailure)
6615 Candidate.FailureKind = ovl_fail_bad_conversion;
6616 else {
6617 Candidate.FailureKind = ovl_fail_bad_deduction;
6618 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6619 Info);
6620 }
6621 return;
6622 }
6623
6624 // Add the function template specialization produced by template argument
6625 // deduction as a candidate.
6626 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6626, __PRETTY_FUNCTION__))
;
6627 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6628 SuppressUserConversions, PartialOverloading,
6629 /*AllowExplicit*/false, Conversions);
6630}
6631
6632/// Check that implicit conversion sequences can be formed for each argument
6633/// whose corresponding parameter has a non-dependent type, per DR1391's
6634/// [temp.deduct.call]p10.
6635bool Sema::CheckNonDependentConversions(
6636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6638 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6639 CXXRecordDecl *ActingContext, QualType ObjectType,
6640 Expr::Classification ObjectClassification) {
6641 // FIXME: The cases in which we allow explicit conversions for constructor
6642 // arguments never consider calling a constructor template. It's not clear
6643 // that is correct.
6644 const bool AllowExplicit = false;
6645
6646 auto *FD = FunctionTemplate->getTemplatedDecl();
6647 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6648 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6649 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6650
6651 Conversions =
6652 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6653
6654 // Overload resolution is always an unevaluated context.
6655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6656
6657 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6658 // require that, but this check should never result in a hard error, and
6659 // overload resolution is permitted to sidestep instantiations.
6660 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6661 !ObjectType.isNull()) {
6662 Conversions[0] = TryObjectArgumentInitialization(
6663 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6664 Method, ActingContext);
6665 if (Conversions[0].isBad())
6666 return true;
6667 }
6668
6669 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6670 ++I) {
6671 QualType ParamType = ParamTypes[I];
6672 if (!ParamType->isDependentType()) {
6673 Conversions[ThisConversions + I]
6674 = TryCopyInitialization(*this, Args[I], ParamType,
6675 SuppressUserConversions,
6676 /*InOverloadResolution=*/true,
6677 /*AllowObjCWritebackConversion=*/
6678 getLangOpts().ObjCAutoRefCount,
6679 AllowExplicit);
6680 if (Conversions[ThisConversions + I].isBad())
6681 return true;
6682 }
6683 }
6684
6685 return false;
6686}
6687
6688/// Determine whether this is an allowable conversion from the result
6689/// of an explicit conversion operator to the expected type, per C++
6690/// [over.match.conv]p1 and [over.match.ref]p1.
6691///
6692/// \param ConvType The return type of the conversion function.
6693///
6694/// \param ToType The type we are converting to.
6695///
6696/// \param AllowObjCPointerConversion Allow a conversion from one
6697/// Objective-C pointer to another.
6698///
6699/// \returns true if the conversion is allowable, false otherwise.
6700static bool isAllowableExplicitConversion(Sema &S,
6701 QualType ConvType, QualType ToType,
6702 bool AllowObjCPointerConversion) {
6703 QualType ToNonRefType = ToType.getNonReferenceType();
6704
6705 // Easy case: the types are the same.
6706 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6707 return true;
6708
6709 // Allow qualification conversions.
6710 bool ObjCLifetimeConversion;
6711 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6712 ObjCLifetimeConversion))
6713 return true;
6714
6715 // If we're not allowed to consider Objective-C pointer conversions,
6716 // we're done.
6717 if (!AllowObjCPointerConversion)
6718 return false;
6719
6720 // Is this an Objective-C pointer conversion?
6721 bool IncompatibleObjC = false;
6722 QualType ConvertedType;
6723 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6724 IncompatibleObjC);
6725}
6726
6727/// AddConversionCandidate - Add a C++ conversion function as a
6728/// candidate in the candidate set (C++ [over.match.conv],
6729/// C++ [over.match.copy]). From is the expression we're converting from,
6730/// and ToType is the type that we're eventually trying to convert to
6731/// (which may or may not be the same type as the type that the
6732/// conversion function produces).
6733void
6734Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6735 DeclAccessPair FoundDecl,
6736 CXXRecordDecl *ActingContext,
6737 Expr *From, QualType ToType,
6738 OverloadCandidateSet& CandidateSet,
6739 bool AllowObjCConversionOnExplicit) {
6740 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6741, __PRETTY_FUNCTION__))
6741 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6741, __PRETTY_FUNCTION__))
;
6742 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6743 if (!CandidateSet.isNewCandidate(Conversion))
6744 return;
6745
6746 // If the conversion function has an undeduced return type, trigger its
6747 // deduction now.
6748 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6749 if (DeduceReturnType(Conversion, From->getExprLoc()))
6750 return;
6751 ConvType = Conversion->getConversionType().getNonReferenceType();
6752 }
6753
6754 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6755 // operator is only a candidate if its return type is the target type or
6756 // can be converted to the target type with a qualification conversion.
6757 if (Conversion->isExplicit() &&
6758 !isAllowableExplicitConversion(*this, ConvType, ToType,
6759 AllowObjCConversionOnExplicit))
6760 return;
6761
6762 // Overload resolution is always an unevaluated context.
6763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6764
6765 // Add this candidate
6766 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6767 Candidate.FoundDecl = FoundDecl;
6768 Candidate.Function = Conversion;
6769 Candidate.IsSurrogate = false;
6770 Candidate.IgnoreObjectArgument = false;
6771 Candidate.FinalConversion.setAsIdentityConversion();
6772 Candidate.FinalConversion.setFromType(ConvType);
6773 Candidate.FinalConversion.setAllToTypes(ToType);
6774 Candidate.Viable = true;
6775 Candidate.ExplicitCallArguments = 1;
6776
6777 // C++ [over.match.funcs]p4:
6778 // For conversion functions, the function is considered to be a member of
6779 // the class of the implicit implied object argument for the purpose of
6780 // defining the type of the implicit object parameter.
6781 //
6782 // Determine the implicit conversion sequence for the implicit
6783 // object parameter.
6784 QualType ImplicitParamType = From->getType();
6785 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6786 ImplicitParamType = FromPtrType->getPointeeType();
6787 CXXRecordDecl *ConversionContext
6788 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6789
6790 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6791 *this, CandidateSet.getLocation(), From->getType(),
6792 From->Classify(Context), Conversion, ConversionContext);
6793
6794 if (Candidate.Conversions[0].isBad()) {
6795 Candidate.Viable = false;
6796 Candidate.FailureKind = ovl_fail_bad_conversion;
6797 return;
6798 }
6799
6800 // We won't go through a user-defined type conversion function to convert a
6801 // derived to base as such conversions are given Conversion Rank. They only
6802 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6803 QualType FromCanon
6804 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6805 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6806 if (FromCanon == ToCanon ||
6807 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6808 Candidate.Viable = false;
6809 Candidate.FailureKind = ovl_fail_trivial_conversion;
6810 return;
6811 }
6812
6813 // To determine what the conversion from the result of calling the
6814 // conversion function to the type we're eventually trying to
6815 // convert to (ToType), we need to synthesize a call to the
6816 // conversion function and attempt copy initialization from it. This
6817 // makes sure that we get the right semantics with respect to
6818 // lvalues/rvalues and the type. Fortunately, we can allocate this
6819 // call on the stack and we don't need its arguments to be
6820 // well-formed.
6821 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6822 VK_LValue, From->getLocStart());
6823 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6824 Context.getPointerType(Conversion->getType()),
6825 CK_FunctionToPointerDecay,
6826 &ConversionRef, VK_RValue);
6827
6828 QualType ConversionType = Conversion->getConversionType();
6829 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6830 Candidate.Viable = false;
6831 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6832 return;
6833 }
6834
6835 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6836
6837 // Note that it is safe to allocate CallExpr on the stack here because
6838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6839 // allocator).
6840 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6841 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6842 From->getLocStart());
6843 ImplicitConversionSequence ICS =
6844 TryCopyInitialization(*this, &Call, ToType,
6845 /*SuppressUserConversions=*/true,
6846 /*InOverloadResolution=*/false,
6847 /*AllowObjCWritebackConversion=*/false);
6848
6849 switch (ICS.getKind()) {
6850 case ImplicitConversionSequence::StandardConversion:
6851 Candidate.FinalConversion = ICS.Standard;
6852
6853 // C++ [over.ics.user]p3:
6854 // If the user-defined conversion is specified by a specialization of a
6855 // conversion function template, the second standard conversion sequence
6856 // shall have exact match rank.
6857 if (Conversion->getPrimaryTemplate() &&
6858 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6859 Candidate.Viable = false;
6860 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6861 return;
6862 }
6863
6864 // C++0x [dcl.init.ref]p5:
6865 // In the second case, if the reference is an rvalue reference and
6866 // the second standard conversion sequence of the user-defined
6867 // conversion sequence includes an lvalue-to-rvalue conversion, the
6868 // program is ill-formed.
6869 if (ToType->isRValueReferenceType() &&
6870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6871 Candidate.Viable = false;
6872 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6873 return;
6874 }
6875 break;
6876
6877 case ImplicitConversionSequence::BadConversion:
6878 Candidate.Viable = false;
6879 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6880 return;
6881
6882 default:
6883 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6884)
6884 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6884)
;
6885 }
6886
6887 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6888 Candidate.Viable = false;
6889 Candidate.FailureKind = ovl_fail_enable_if;
6890 Candidate.DeductionFailure.Data = FailedAttr;
6891 return;
6892 }
6893}
6894
6895/// \brief Adds a conversion function template specialization
6896/// candidate to the overload set, using template argument deduction
6897/// to deduce the template arguments of the conversion function
6898/// template from the type that we are converting to (C++
6899/// [temp.deduct.conv]).
6900void
6901Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6902 DeclAccessPair FoundDecl,
6903 CXXRecordDecl *ActingDC,
6904 Expr *From, QualType ToType,
6905 OverloadCandidateSet &CandidateSet,
6906 bool AllowObjCConversionOnExplicit) {
6907 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6908, __PRETTY_FUNCTION__))
6908 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6908, __PRETTY_FUNCTION__))
;
6909
6910 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6911 return;
6912
6913 TemplateDeductionInfo Info(CandidateSet.getLocation());
6914 CXXConversionDecl *Specialization = nullptr;
6915 if (TemplateDeductionResult Result
6916 = DeduceTemplateArguments(FunctionTemplate, ToType,
6917 Specialization, Info)) {
6918 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6919 Candidate.FoundDecl = FoundDecl;
6920 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6921 Candidate.Viable = false;
6922 Candidate.FailureKind = ovl_fail_bad_deduction;
6923 Candidate.IsSurrogate = false;
6924 Candidate.IgnoreObjectArgument = false;
6925 Candidate.ExplicitCallArguments = 1;
6926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6927 Info);
6928 return;
6929 }
6930
6931 // Add the conversion function template specialization produced by
6932 // template argument deduction as a candidate.
6933 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
;
6934 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6935 CandidateSet, AllowObjCConversionOnExplicit);
6936}
6937
6938/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6939/// converts the given @c Object to a function pointer via the
6940/// conversion function @c Conversion, and then attempts to call it
6941/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6942/// the type of function that we'll eventually be calling.
6943void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6944 DeclAccessPair FoundDecl,
6945 CXXRecordDecl *ActingContext,
6946 const FunctionProtoType *Proto,
6947 Expr *Object,
6948 ArrayRef<Expr *> Args,
6949 OverloadCandidateSet& CandidateSet) {
6950 if (!CandidateSet.isNewCandidate(Conversion))
6951 return;
6952
6953 // Overload resolution is always an unevaluated context.
6954 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6955
6956 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6957 Candidate.FoundDecl = FoundDecl;
6958 Candidate.Function = nullptr;
6959 Candidate.Surrogate = Conversion;
6960 Candidate.Viable = true;
6961 Candidate.IsSurrogate = true;
6962 Candidate.IgnoreObjectArgument = false;
6963 Candidate.ExplicitCallArguments = Args.size();
6964
6965 // Determine the implicit conversion sequence for the implicit
6966 // object parameter.
6967 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6968 *this, CandidateSet.getLocation(), Object->getType(),
6969 Object->Classify(Context), Conversion, ActingContext);
6970 if (ObjectInit.isBad()) {
6971 Candidate.Viable = false;
6972 Candidate.FailureKind = ovl_fail_bad_conversion;
6973 Candidate.Conversions[0] = ObjectInit;
6974 return;
6975 }
6976
6977 // The first conversion is actually a user-defined conversion whose
6978 // first conversion is ObjectInit's standard conversion (which is
6979 // effectively a reference binding). Record it as such.
6980 Candidate.Conversions[0].setUserDefined();
6981 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6982 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6983 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6984 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6985 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6986 Candidate.Conversions[0].UserDefined.After
6987 = Candidate.Conversions[0].UserDefined.Before;
6988 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6989
6990 // Find the
6991 unsigned NumParams = Proto->getNumParams();
6992
6993 // (C++ 13.3.2p2): A candidate function having fewer than m
6994 // parameters is viable only if it has an ellipsis in its parameter
6995 // list (8.3.5).
6996 if (Args.size() > NumParams && !Proto->isVariadic()) {
6997 Candidate.Viable = false;
6998 Candidate.FailureKind = ovl_fail_too_many_arguments;
6999 return;
7000 }
7001
7002 // Function types don't have any default arguments, so just check if
7003 // we have enough arguments.
7004 if (Args.size() < NumParams) {
7005 // Not enough arguments.
7006 Candidate.Viable = false;
7007 Candidate.FailureKind = ovl_fail_too_few_arguments;
7008 return;
7009 }
7010
7011 // Determine the implicit conversion sequences for each of the
7012 // arguments.
7013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7014 if (ArgIdx < NumParams) {
7015 // (C++ 13.3.2p3): for F to be a viable function, there shall
7016 // exist for each argument an implicit conversion sequence
7017 // (13.3.3.1) that converts that argument to the corresponding
7018 // parameter of F.
7019 QualType ParamType = Proto->getParamType(ArgIdx);
7020 Candidate.Conversions[ArgIdx + 1]
7021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7022 /*SuppressUserConversions=*/false,
7023 /*InOverloadResolution=*/false,
7024 /*AllowObjCWritebackConversion=*/
7025 getLangOpts().ObjCAutoRefCount);
7026 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7027 Candidate.Viable = false;
7028 Candidate.FailureKind = ovl_fail_bad_conversion;
7029 return;
7030 }
7031 } else {
7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7033 // argument for which there is no corresponding parameter is
7034 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7035 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7036 }
7037 }
7038
7039 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7040 Candidate.Viable = false;
7041 Candidate.FailureKind = ovl_fail_enable_if;
7042 Candidate.DeductionFailure.Data = FailedAttr;
7043 return;
7044 }
7045}
7046
7047/// \brief Add overload candidates for overloaded operators that are
7048/// member functions.
7049///
7050/// Add the overloaded operator candidates that are member functions
7051/// for the operator Op that was used in an operator expression such
7052/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7053/// CandidateSet will store the added overload candidates. (C++
7054/// [over.match.oper]).
7055void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7056 SourceLocation OpLoc,
7057 ArrayRef<Expr *> Args,
7058 OverloadCandidateSet& CandidateSet,
7059 SourceRange OpRange) {
7060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7061
7062 // C++ [over.match.oper]p3:
7063 // For a unary operator @ with an operand of a type whose
7064 // cv-unqualified version is T1, and for a binary operator @ with
7065 // a left operand of a type whose cv-unqualified version is T1 and
7066 // a right operand of a type whose cv-unqualified version is T2,
7067 // three sets of candidate functions, designated member
7068 // candidates, non-member candidates and built-in candidates, are
7069 // constructed as follows:
7070 QualType T1 = Args[0]->getType();
7071
7072 // -- If T1 is a complete class type or a class currently being
7073 // defined, the set of member candidates is the result of the
7074 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7075 // the set of member candidates is empty.
7076 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7077 // Complete the type if it can be completed.
7078 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7079 return;
7080 // If the type is neither complete nor being defined, bail out now.
7081 if (!T1Rec->getDecl()->getDefinition())
7082 return;
7083
7084 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7085 LookupQualifiedName(Operators, T1Rec->getDecl());
7086 Operators.suppressDiagnostics();
7087
7088 for (LookupResult::iterator Oper = Operators.begin(),
7089 OperEnd = Operators.end();
7090 Oper != OperEnd;
7091 ++Oper)
7092 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7093 Args[0]->Classify(Context), Args.slice(1),
7094 CandidateSet, /*SuppressUserConversions=*/false);
7095 }
7096}
7097
7098/// AddBuiltinCandidate - Add a candidate for a built-in
7099/// operator. ResultTy and ParamTys are the result and parameter types
7100/// of the built-in candidate, respectively. Args and NumArgs are the
7101/// arguments being passed to the candidate. IsAssignmentOperator
7102/// should be true when this built-in candidate is an assignment
7103/// operator. NumContextualBoolArguments is the number of arguments
7104/// (at the beginning of the argument list) that will be contextually
7105/// converted to bool.
7106void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7107 ArrayRef<Expr *> Args,
7108 OverloadCandidateSet& CandidateSet,
7109 bool IsAssignmentOperator,
7110 unsigned NumContextualBoolArguments) {
7111 // Overload resolution is always an unevaluated context.
7112 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7113
7114 // Add this candidate
7115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7116 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7117 Candidate.Function = nullptr;
7118 Candidate.IsSurrogate = false;
7119 Candidate.IgnoreObjectArgument = false;
7120 Candidate.BuiltinTypes.ResultTy = ResultTy;
7121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7122 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7123
7124 // Determine the implicit conversion sequences for each of the
7125 // arguments.
7126 Candidate.Viable = true;
7127 Candidate.ExplicitCallArguments = Args.size();
7128 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7129 // C++ [over.match.oper]p4:
7130 // For the built-in assignment operators, conversions of the
7131 // left operand are restricted as follows:
7132 // -- no temporaries are introduced to hold the left operand, and
7133 // -- no user-defined conversions are applied to the left
7134 // operand to achieve a type match with the left-most
7135 // parameter of a built-in candidate.
7136 //
7137 // We block these conversions by turning off user-defined
7138 // conversions, since that is the only way that initialization of
7139 // a reference to a non-class type can occur from something that
7140 // is not of the same type.
7141 if (ArgIdx < NumContextualBoolArguments) {
7142 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7143, __PRETTY_FUNCTION__))
7143 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7143, __PRETTY_FUNCTION__))
;
7144 Candidate.Conversions[ArgIdx]
7145 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7146 } else {
7147 Candidate.Conversions[ArgIdx]
7148 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7149 ArgIdx == 0 && IsAssignmentOperator,
7150 /*InOverloadResolution=*/false,
7151 /*AllowObjCWritebackConversion=*/
7152 getLangOpts().ObjCAutoRefCount);
7153 }
7154 if (Candidate.Conversions[ArgIdx].isBad()) {
7155 Candidate.Viable = false;
7156 Candidate.FailureKind = ovl_fail_bad_conversion;
7157 break;
7158 }
7159 }
7160}
7161
7162namespace {
7163
7164/// BuiltinCandidateTypeSet - A set of types that will be used for the
7165/// candidate operator functions for built-in operators (C++
7166/// [over.built]). The types are separated into pointer types and
7167/// enumeration types.
7168class BuiltinCandidateTypeSet {
7169 /// TypeSet - A set of types.
7170 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7171 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7172
7173 /// PointerTypes - The set of pointer types that will be used in the
7174 /// built-in candidates.
7175 TypeSet PointerTypes;
7176
7177 /// MemberPointerTypes - The set of member pointer types that will be
7178 /// used in the built-in candidates.
7179 TypeSet MemberPointerTypes;
7180
7181 /// EnumerationTypes - The set of enumeration types that will be
7182 /// used in the built-in candidates.
7183 TypeSet EnumerationTypes;
7184
7185 /// \brief The set of vector types that will be used in the built-in
7186 /// candidates.
7187 TypeSet VectorTypes;
7188
7189 /// \brief A flag indicating non-record types are viable candidates
7190 bool HasNonRecordTypes;
7191
7192 /// \brief A flag indicating whether either arithmetic or enumeration types
7193 /// were present in the candidate set.
7194 bool HasArithmeticOrEnumeralTypes;
7195
7196 /// \brief A flag indicating whether the nullptr type was present in the
7197 /// candidate set.
7198 bool HasNullPtrType;
7199
7200 /// Sema - The semantic analysis instance where we are building the
7201 /// candidate type set.
7202 Sema &SemaRef;
7203
7204 /// Context - The AST context in which we will build the type sets.
7205 ASTContext &Context;
7206
7207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7208 const Qualifiers &VisibleQuals);
7209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7210
7211public:
7212 /// iterator - Iterates through the types that are part of the set.
7213 typedef TypeSet::iterator iterator;
7214
7215 BuiltinCandidateTypeSet(Sema &SemaRef)
7216 : HasNonRecordTypes(false),
7217 HasArithmeticOrEnumeralTypes(false),
7218 HasNullPtrType(false),
7219 SemaRef(SemaRef),
7220 Context(SemaRef.Context) { }
7221
7222 void AddTypesConvertedFrom(QualType Ty,
7223 SourceLocation Loc,
7224 bool AllowUserConversions,
7225 bool AllowExplicitConversions,
7226 const Qualifiers &VisibleTypeConversionsQuals);
7227
7228 /// pointer_begin - First pointer type found;
7229 iterator pointer_begin() { return PointerTypes.begin(); }
7230
7231 /// pointer_end - Past the last pointer type found;
7232 iterator pointer_end() { return PointerTypes.end(); }
7233
7234 /// member_pointer_begin - First member pointer type found;
7235 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7236
7237 /// member_pointer_end - Past the last member pointer type found;
7238 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7239
7240 /// enumeration_begin - First enumeration type found;
7241 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7242
7243 /// enumeration_end - Past the last enumeration type found;
7244 iterator enumeration_end() { return EnumerationTypes.end(); }
7245
7246 iterator vector_begin() { return VectorTypes.begin(); }
7247 iterator vector_end() { return VectorTypes.end(); }
7248
7249 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7250 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7251 bool hasNullPtrType() const { return HasNullPtrType; }
7252};
7253
7254} // end anonymous namespace
7255
7256/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7257/// the set of pointer types along with any more-qualified variants of
7258/// that type. For example, if @p Ty is "int const *", this routine
7259/// will add "int const *", "int const volatile *", "int const
7260/// restrict *", and "int const volatile restrict *" to the set of
7261/// pointer types. Returns true if the add of @p Ty itself succeeded,
7262/// false otherwise.
7263///
7264/// FIXME: what to do about extended qualifiers?
7265bool
7266BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7267 const Qualifiers &VisibleQuals) {
7268
7269 // Insert this type.
7270 if (!PointerTypes.insert(Ty))
7271 return false;
7272
7273 QualType PointeeTy;
7274 const PointerType *PointerTy = Ty->getAs<PointerType>();
7275 bool buildObjCPtr = false;
7276 if (!PointerTy) {
7277 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7278 PointeeTy = PTy->getPointeeType();
7279 buildObjCPtr = true;
7280 } else {
7281 PointeeTy = PointerTy->getPointeeType();
7282 }
7283
7284 // Don't add qualified variants of arrays. For one, they're not allowed
7285 // (the qualifier would sink to the element type), and for another, the
7286 // only overload situation where it matters is subscript or pointer +- int,
7287 // and those shouldn't have qualifier variants anyway.
7288 if (PointeeTy->isArrayType())
7289 return true;
7290
7291 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7292 bool hasVolatile = VisibleQuals.hasVolatile();
7293 bool hasRestrict = VisibleQuals.hasRestrict();
7294
7295 // Iterate through all strict supersets of BaseCVR.
7296 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7297 if ((CVR | BaseCVR) != CVR) continue;
7298 // Skip over volatile if no volatile found anywhere in the types.
7299 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7300
7301 // Skip over restrict if no restrict found anywhere in the types, or if
7302 // the type cannot be restrict-qualified.
7303 if ((CVR & Qualifiers::Restrict) &&
7304 (!hasRestrict ||
7305 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7306 continue;
7307
7308 // Build qualified pointee type.
7309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7310
7311 // Build qualified pointer type.
7312 QualType QPointerTy;
7313 if (!buildObjCPtr)
7314 QPointerTy = Context.getPointerType(QPointeeTy);
7315 else
7316 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7317
7318 // Insert qualified pointer type.
7319 PointerTypes.insert(QPointerTy);
7320 }
7321
7322 return true;
7323}
7324
7325/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7326/// to the set of pointer types along with any more-qualified variants of
7327/// that type. For example, if @p Ty is "int const *", this routine
7328/// will add "int const *", "int const volatile *", "int const
7329/// restrict *", and "int const volatile restrict *" to the set of
7330/// pointer types. Returns true if the add of @p Ty itself succeeded,
7331/// false otherwise.
7332///
7333/// FIXME: what to do about extended qualifiers?
7334bool
7335BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7336 QualType Ty) {
7337 // Insert this type.
7338 if (!MemberPointerTypes.insert(Ty))
7339 return false;
7340
7341 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7342 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7342, __PRETTY_FUNCTION__))
;
7343
7344 QualType PointeeTy = PointerTy->getPointeeType();
7345 // Don't add qualified variants of arrays. For one, they're not allowed
7346 // (the qualifier would sink to the element type), and for another, the
7347 // only overload situation where it matters is subscript or pointer +- int,
7348 // and those shouldn't have qualifier variants anyway.
7349 if (PointeeTy->isArrayType())
7350 return true;
7351 const Type *ClassTy = PointerTy->getClass();
7352
7353 // Iterate through all strict supersets of the pointee type's CVR
7354 // qualifiers.
7355 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7356 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7357 if ((CVR | BaseCVR) != CVR) continue;
7358
7359 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7360 MemberPointerTypes.insert(
7361 Context.getMemberPointerType(QPointeeTy, ClassTy));
7362 }
7363
7364 return true;
7365}
7366
7367/// AddTypesConvertedFrom - Add each of the types to which the type @p
7368/// Ty can be implicit converted to the given set of @p Types. We're
7369/// primarily interested in pointer types and enumeration types. We also
7370/// take member pointer types, for the conditional operator.
7371/// AllowUserConversions is true if we should look at the conversion
7372/// functions of a class type, and AllowExplicitConversions if we
7373/// should also include the explicit conversion functions of a class
7374/// type.
7375void
7376BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7377 SourceLocation Loc,
7378 bool AllowUserConversions,
7379 bool AllowExplicitConversions,
7380 const Qualifiers &VisibleQuals) {
7381 // Only deal with canonical types.
7382 Ty = Context.getCanonicalType(Ty);
7383
7384 // Look through reference types; they aren't part of the type of an
7385 // expression for the purposes of conversions.
7386 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7387 Ty = RefTy->getPointeeType();
7388
7389 // If we're dealing with an array type, decay to the pointer.
7390 if (Ty->isArrayType())
7391 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7392
7393 // Otherwise, we don't care about qualifiers on the type.
7394 Ty = Ty.getLocalUnqualifiedType();
7395
7396 // Flag if we ever add a non-record type.
7397 const RecordType *TyRec = Ty->getAs<RecordType>();
7398 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7399
7400 // Flag if we encounter an arithmetic type.
7401 HasArithmeticOrEnumeralTypes =
7402 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7403
7404 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7405 PointerTypes.insert(Ty);
7406 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7407 // Insert our type, and its more-qualified variants, into the set
7408 // of types.
7409 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7410 return;
7411 } else if (Ty->isMemberPointerType()) {
7412 // Member pointers are far easier, since the pointee can't be converted.
7413 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7414 return;
7415 } else if (Ty->isEnumeralType()) {
7416 HasArithmeticOrEnumeralTypes = true;
7417 EnumerationTypes.insert(Ty);
7418 } else if (Ty->isVectorType()) {
7419 // We treat vector types as arithmetic types in many contexts as an
7420 // extension.
7421 HasArithmeticOrEnumeralTypes = true;
7422 VectorTypes.insert(Ty);
7423 } else if (Ty->isNullPtrType()) {
7424 HasNullPtrType = true;
7425 } else if (AllowUserConversions && TyRec) {
7426 // No conversion functions in incomplete types.
7427 if (!SemaRef.isCompleteType(Loc, Ty))
7428 return;
7429
7430 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7431 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7432 if (isa<UsingShadowDecl>(D))
7433 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7434
7435 // Skip conversion function templates; they don't tell us anything
7436 // about which builtin types we can convert to.
7437 if (isa<FunctionTemplateDecl>(D))
7438 continue;
7439
7440 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7441 if (AllowExplicitConversions || !Conv->isExplicit()) {
7442 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7443 VisibleQuals);
7444 }
7445 }
7446 }
7447}
7448
7449/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7450/// the volatile- and non-volatile-qualified assignment operators for the
7451/// given type to the candidate set.
7452static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7453 QualType T,
7454 ArrayRef<Expr *> Args,
7455 OverloadCandidateSet &CandidateSet) {
7456 QualType ParamTypes[2];
7457
7458 // T& operator=(T&, T)
7459 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7460 ParamTypes[1] = T;
7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7462 /*IsAssignmentOperator=*/true);
7463
7464 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7465 // volatile T& operator=(volatile T&, T)
7466 ParamTypes[0]
7467 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7468 ParamTypes[1] = T;
7469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7470 /*IsAssignmentOperator=*/true);
7471 }
7472}
7473
7474/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7475/// if any, found in visible type conversion functions found in ArgExpr's type.
7476static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7477 Qualifiers VRQuals;
7478 const RecordType *TyRec;
7479 if (const MemberPointerType *RHSMPType =
7480 ArgExpr->getType()->getAs<MemberPointerType>())
7481 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7482 else
7483 TyRec = ArgExpr->getType()->getAs<RecordType>();
7484 if (!TyRec) {
7485 // Just to be safe, assume the worst case.
7486 VRQuals.addVolatile();
7487 VRQuals.addRestrict();
7488 return VRQuals;
7489 }
7490
7491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7492 if (!ClassDecl->hasDefinition())
7493 return VRQuals;
7494
7495 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7496 if (isa<UsingShadowDecl>(D))
7497 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7498 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7499 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7500 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7501 CanTy = ResTypeRef->getPointeeType();
7502 // Need to go down the pointer/mempointer chain and add qualifiers
7503 // as see them.
7504 bool done = false;
7505 while (!done) {
7506 if (CanTy.isRestrictQualified())
7507 VRQuals.addRestrict();
7508 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7509 CanTy = ResTypePtr->getPointeeType();
7510 else if (const MemberPointerType *ResTypeMPtr =
7511 CanTy->getAs<MemberPointerType>())
7512 CanTy = ResTypeMPtr->getPointeeType();
7513 else
7514 done = true;
7515 if (CanTy.isVolatileQualified())
7516 VRQuals.addVolatile();
7517 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7518 return VRQuals;
7519 }
7520 }
7521 }
7522 return VRQuals;
7523}
7524
7525namespace {
7526
7527/// \brief Helper class to manage the addition of builtin operator overload
7528/// candidates. It provides shared state and utility methods used throughout
7529/// the process, as well as a helper method to add each group of builtin
7530/// operator overloads from the standard to a candidate set.
7531class BuiltinOperatorOverloadBuilder {
7532 // Common instance state available to all overload candidate addition methods.
7533 Sema &S;
7534 ArrayRef<Expr *> Args;
7535 Qualifiers VisibleTypeConversionsQuals;
7536 bool HasArithmeticOrEnumeralCandidateType;
7537 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7538 OverloadCandidateSet &CandidateSet;
7539
7540 // Define some constants used to index and iterate over the arithemetic types
7541 // provided via the getArithmeticType() method below.
7542 // The "promoted arithmetic types" are the arithmetic
7543 // types are that preserved by promotion (C++ [over.built]p2).
7544 static const unsigned FirstIntegralType = 4;
7545 static const unsigned LastIntegralType = 21;
7546 static const unsigned FirstPromotedIntegralType = 4,
7547 LastPromotedIntegralType = 12;
7548 static const unsigned FirstPromotedArithmeticType = 0,
7549 LastPromotedArithmeticType = 12;
7550 static const unsigned NumArithmeticTypes = 21;
7551
7552 /// \brief Get the canonical type for a given arithmetic type index.
7553 CanQualType getArithmeticType(unsigned index) {
7554 assert(index < NumArithmeticTypes)((index < NumArithmeticTypes) ? static_cast<void> (0
) : __assert_fail ("index < NumArithmeticTypes", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7554, __PRETTY_FUNCTION__))
;
7555 static CanQualType ASTContext::* const
7556 ArithmeticTypes[NumArithmeticTypes] = {
7557 // Start of promoted types.
7558 &ASTContext::FloatTy,
7559 &ASTContext::DoubleTy,
7560 &ASTContext::LongDoubleTy,
7561 &ASTContext::Float128Ty,
7562
7563 // Start of integral types.
7564 &ASTContext::IntTy,
7565 &ASTContext::LongTy,
7566 &ASTContext::LongLongTy,
7567 &ASTContext::Int128Ty,
7568 &ASTContext::UnsignedIntTy,
7569 &ASTContext::UnsignedLongTy,
7570 &ASTContext::UnsignedLongLongTy,
7571 &ASTContext::UnsignedInt128Ty,
7572 // End of promoted types.
7573
7574 &ASTContext::BoolTy,
7575 &ASTContext::CharTy,
7576 &ASTContext::WCharTy,
7577 &ASTContext::Char16Ty,
7578 &ASTContext::Char32Ty,
7579 &ASTContext::SignedCharTy,
7580 &ASTContext::ShortTy,
7581 &ASTContext::UnsignedCharTy,
7582 &ASTContext::UnsignedShortTy,
7583 // End of integral types.
7584 // FIXME: What about complex? What about half?
7585 };
7586 return S.Context.*ArithmeticTypes[index];
7587 }
7588
7589 /// \brief Gets the canonical type resulting from the usual arithemetic
7590 /// converions for the given arithmetic types.
7591 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7592 // Accelerator table for performing the usual arithmetic conversions.
7593 // The rules are basically:
7594 // - if either is floating-point, use the wider floating-point
7595 // - if same signedness, use the higher rank
7596 // - if same size, use unsigned of the higher rank
7597 // - use the larger type
7598 // These rules, together with the axiom that higher ranks are
7599 // never smaller, are sufficient to precompute all of these results
7600 // *except* when dealing with signed types of higher rank.
7601 // (we could precompute SLL x UI for all known platforms, but it's
7602 // better not to make any assumptions).
7603 // We assume that int128 has a higher rank than long long on all platforms.
7604 enum PromotedType : int8_t {
7605 Dep=-1,
7606 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7607 };
7608 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7609 [LastPromotedArithmeticType] = {
7610/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7611/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7612/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7613/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7614/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7615/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7616/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7617/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7618/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7619/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7620/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7621 };
7622
7623 assert(L < LastPromotedArithmeticType)((L < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("L < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7623, __PRETTY_FUNCTION__))
;
7624 assert(R < LastPromotedArithmeticType)((R < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("R < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7624, __PRETTY_FUNCTION__))
;
7625 int Idx = ConversionsTable[L][R];
7626
7627 // Fast path: the table gives us a concrete answer.
7628 if (Idx != Dep) return getArithmeticType(Idx);
7629
7630 // Slow path: we need to compare widths.
7631 // An invariant is that the signed type has higher rank.
7632 CanQualType LT = getArithmeticType(L),
7633 RT = getArithmeticType(R);
7634 unsigned LW = S.Context.getIntWidth(LT),
7635 RW = S.Context.getIntWidth(RT);
7636
7637 // If they're different widths, use the signed type.
7638 if (LW > RW) return LT;
7639 else if (LW < RW) return RT;
7640
7641 // Otherwise, use the unsigned type of the signed type's rank.
7642 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7643 assert(L == SLL || R == SLL)((L == SLL || R == SLL) ? static_cast<void> (0) : __assert_fail
("L == SLL || R == SLL", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7643, __PRETTY_FUNCTION__))
;
7644 return S.Context.UnsignedLongLongTy;
7645 }
7646
7647 /// \brief Helper method to factor out the common pattern of adding overloads
7648 /// for '++' and '--' builtin operators.
7649 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7650 bool HasVolatile,
7651 bool HasRestrict) {
7652 QualType ParamTypes[2] = {
7653 S.Context.getLValueReferenceType(CandidateTy),
7654 S.Context.IntTy
7655 };
7656
7657 // Non-volatile version.
7658 if (Args.size() == 1)
7659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7660 else
7661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7662
7663 // Use a heuristic to reduce number of builtin candidates in the set:
7664 // add volatile version only if there are conversions to a volatile type.
7665 if (HasVolatile) {
7666 ParamTypes[0] =
7667 S.Context.getLValueReferenceType(
7668 S.Context.getVolatileType(CandidateTy));
7669 if (Args.size() == 1)
7670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7671 else
7672 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7673 }
7674
7675 // Add restrict version only if there are conversions to a restrict type
7676 // and our candidate type is a non-restrict-qualified pointer.
7677 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7678 !CandidateTy.isRestrictQualified()) {
7679 ParamTypes[0]
7680 = S.Context.getLValueReferenceType(
7681 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7682 if (Args.size() == 1)
7683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7684 else
7685 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7686
7687 if (HasVolatile) {
7688 ParamTypes[0]
7689 = S.Context.getLValueReferenceType(
7690 S.Context.getCVRQualifiedType(CandidateTy,
7691 (Qualifiers::Volatile |
7692 Qualifiers::Restrict)));
7693 if (Args.size() == 1)
7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7695 else
7696 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7697 }
7698 }
7699
7700 }
7701
7702public:
7703 BuiltinOperatorOverloadBuilder(
7704 Sema &S, ArrayRef<Expr *> Args,
7705 Qualifiers VisibleTypeConversionsQuals,
7706 bool HasArithmeticOrEnumeralCandidateType,
7707 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7708 OverloadCandidateSet &CandidateSet)
7709 : S(S), Args(Args),
7710 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7711 HasArithmeticOrEnumeralCandidateType(
7712 HasArithmeticOrEnumeralCandidateType),
7713 CandidateTypes(CandidateTypes),
7714 CandidateSet(CandidateSet) {
7715 // Validate some of our static helper constants in debug builds.
7716 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&((getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy
&& "Invalid first promoted integral type") ? static_cast
<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && \"Invalid first promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7717, __PRETTY_FUNCTION__))
7717 "Invalid first promoted integral type")((getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy
&& "Invalid first promoted integral type") ? static_cast
<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && \"Invalid first promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7717, __PRETTY_FUNCTION__))
;
7718 assert(getArithmeticType(LastPromotedIntegralType - 1)((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7720, __PRETTY_FUNCTION__))
7719 == S.Context.UnsignedInt128Ty &&((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7720, __PRETTY_FUNCTION__))
7720 "Invalid last promoted integral type")((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7720, __PRETTY_FUNCTION__))
;
7721 assert(getArithmeticType(FirstPromotedArithmeticType)((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7723, __PRETTY_FUNCTION__))
7722 == S.Context.FloatTy &&((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7723, __PRETTY_FUNCTION__))
7723 "Invalid first promoted arithmetic type")((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/tools/clang/lib/Sema/SemaOverload.cpp"
, 7723, __PRETTY_FUNCTION__))
;
7724 assert(getArithmeticType(LastPromotedArithmeticType - 1)((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.Unsigned