Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Location:line 9188, column 50
Description: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/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36#include <cstdlib>
37
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
46/// A convenience routine for creating a decayed reference to a function.
47static ExprResult
48CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
50 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
53 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
61 return ExprError();
62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
63 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
66
67 S.MarkDeclRefReferenced(DRE);
68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
70}
71
72static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
74 StandardConversionSequence &SCS,
75 bool CStyle,
76 bool AllowObjCWritebackConversion);
77
78static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
83static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
87 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
89
90
91static ImplicitConversionSequence::CompareKind
92CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
93 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
102CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
108ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Promotion,
118 ICR_Promotion,
119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
139 };
140 return Rank[(int)Kind];
141}
142
143/// GetImplicitConversionName - Return the name of this kind of
144/// implicit conversion.
145static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
151 "Noreturn adjustment",
152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
155 "Complex promotion",
156 "Integral conversion",
157 "Floating conversion",
158 "Complex conversion",
159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
162 "Boolean conversion",
163 "Compatible-types conversion",
164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
167 "Complex-real conversion",
168 "Block Pointer conversion",
169 "Transparent Union Conversion",
170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
173 };
174 return Name[Kind];
175}
176
177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
183 DeprecatedStringLiteralToCharPtr = false;
184 QualificationIncludesObjCLifetime = false;
185 ReferenceBinding = false;
186 DirectBinding = false;
187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
191 ObjCLifetimeConversionBinding = false;
192 CopyConstructor = nullptr;
193}
194
195/// getRank - Retrieve the rank of this standard conversion sequence
196/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197/// implicit conversions.
198ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207}
208
209/// isPointerConversionToBool - Determines whether this conversion is
210/// a conversion of a pointer or pointer-to-member to bool. This is
211/// used as part of the ranking of standard conversion sequences
212/// (C++ 13.3.3.2p4).
213bool StandardConversionSequence::isPointerConversionToBool() const {
214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
218 if (getToType(1)->isBooleanType() &&
219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
222 getFromType()->isNullPtrType() ||
223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227}
228
229/// isPointerConversionToVoidPointer - Determines whether this
230/// conversion is a conversion of a pointer to a void pointer. This is
231/// used as part of the ranking of standard conversion sequences (C++
232/// 13.3.3.2p4).
233bool
234StandardConversionSequence::
235isPointerConversionToVoidPointer(ASTContext& Context) const {
236 QualType FromType = getFromType();
237 QualType ToType = getToType(1);
238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250}
251
252/// Skip any implicit casts which could be either part of a narrowing conversion
253/// or after one in an implicit conversion.
254static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
261 case CK_BooleanToSignedIntegral:
262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274}
275
276/// Check if this standard conversion sequence represents a narrowing
277/// conversion, according to C++11 [dcl.init.list]p7.
278///
279/// \param Ctx The AST context.
280/// \param Converted The result of applying this standard conversion sequence.
281/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282/// value of the expression prior to the narrowing conversion.
283/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284/// type of the expression prior to the narrowing conversion.
285NarrowingKind
286StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
288 APValue &ConstantValue,
289 QualType &ConstantType) const {
290 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 290, __PRETTY_FUNCTION__))
;
291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
296
297 // A conversion to an enumeration type is narrowing if the conversion to
298 // the underlying type is narrowing. This only arises for expressions of
299 // the form 'Enum{init}'.
300 if (auto *ET = ToType->getAs<EnumType>())
301 ToType = ET->getDecl()->getIntegerType();
302
303 switch (Second) {
304 // 'bool' is an integral type; dispatch to the right place to handle it.
305 case ICK_Boolean_Conversion:
306 if (FromType->isRealFloatingType())
307 goto FloatingIntegralConversion;
308 if (FromType->isIntegralOrUnscopedEnumerationType())
309 goto IntegralConversion;
310 // Boolean conversions can be from pointers and pointers to members
311 // [conv.bool], and those aren't considered narrowing conversions.
312 return NK_Not_Narrowing;
313
314 // -- from a floating-point type to an integer type, or
315 //
316 // -- from an integer type or unscoped enumeration type to a floating-point
317 // type, except where the source is a constant expression and the actual
318 // value after conversion will fit into the target type and will produce
319 // the original value when converted back to the original type, or
320 case ICK_Floating_Integral:
321 FloatingIntegralConversion:
322 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
323 return NK_Type_Narrowing;
324 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
325 llvm::APSInt IntConstantValue;
326 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
327 if (Initializer &&
328 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
329 // Convert the integer to the floating type.
330 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
331 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
332 llvm::APFloat::rmNearestTiesToEven);
333 // And back.
334 llvm::APSInt ConvertedValue = IntConstantValue;
335 bool ignored;
336 Result.convertToInteger(ConvertedValue,
337 llvm::APFloat::rmTowardZero, &ignored);
338 // If the resulting value is different, this was a narrowing conversion.
339 if (IntConstantValue != ConvertedValue) {
340 ConstantValue = APValue(IntConstantValue);
341 ConstantType = Initializer->getType();
342 return NK_Constant_Narrowing;
343 }
344 } else {
345 // Variables are always narrowings.
346 return NK_Variable_Narrowing;
347 }
348 }
349 return NK_Not_Narrowing;
350
351 // -- from long double to double or float, or from double to float, except
352 // where the source is a constant expression and the actual value after
353 // conversion is within the range of values that can be represented (even
354 // if it cannot be represented exactly), or
355 case ICK_Floating_Conversion:
356 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
357 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
358 // FromType is larger than ToType.
359 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
360 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
361 // Constant!
362 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 362, __PRETTY_FUNCTION__))
;
363 llvm::APFloat FloatVal = ConstantValue.getFloat();
364 // Convert the source value into the target type.
365 bool ignored;
366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
367 Ctx.getFloatTypeSemantics(ToType),
368 llvm::APFloat::rmNearestTiesToEven, &ignored);
369 // If there was no overflow, the source value is within the range of
370 // values that can be represented.
371 if (ConvertStatus & llvm::APFloat::opOverflow) {
372 ConstantType = Initializer->getType();
373 return NK_Constant_Narrowing;
374 }
375 } else {
376 return NK_Variable_Narrowing;
377 }
378 }
379 return NK_Not_Narrowing;
380
381 // -- from an integer type or unscoped enumeration type to an integer type
382 // that cannot represent all the values of the original type, except where
383 // the source is a constant expression and the actual value after
384 // conversion will fit into the target type and will produce the original
385 // value when converted back to the original type.
386 case ICK_Integral_Conversion:
387 IntegralConversion: {
388 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 388, __PRETTY_FUNCTION__))
;
389 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 389, __PRETTY_FUNCTION__))
;
390 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
391 const unsigned FromWidth = Ctx.getIntWidth(FromType);
392 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
393 const unsigned ToWidth = Ctx.getIntWidth(ToType);
394
395 if (FromWidth > ToWidth ||
396 (FromWidth == ToWidth && FromSigned != ToSigned) ||
397 (FromSigned && !ToSigned)) {
398 // Not all values of FromType can be represented in ToType.
399 llvm::APSInt InitializerValue;
400 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
401 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
402 // Such conversions on variables are always narrowing.
403 return NK_Variable_Narrowing;
404 }
405 bool Narrowing = false;
406 if (FromWidth < ToWidth) {
407 // Negative -> unsigned is narrowing. Otherwise, more bits is never
408 // narrowing.
409 if (InitializerValue.isSigned() && InitializerValue.isNegative())
410 Narrowing = true;
411 } else {
412 // Add a bit to the InitializerValue so we don't have to worry about
413 // signed vs. unsigned comparisons.
414 InitializerValue = InitializerValue.extend(
415 InitializerValue.getBitWidth() + 1);
416 // Convert the initializer to and from the target width and signed-ness.
417 llvm::APSInt ConvertedValue = InitializerValue;
418 ConvertedValue = ConvertedValue.trunc(ToWidth);
419 ConvertedValue.setIsSigned(ToSigned);
420 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
421 ConvertedValue.setIsSigned(InitializerValue.isSigned());
422 // If the result is different, this was a narrowing conversion.
423 if (ConvertedValue != InitializerValue)
424 Narrowing = true;
425 }
426 if (Narrowing) {
427 ConstantType = Initializer->getType();
428 ConstantValue = APValue(InitializerValue);
429 return NK_Constant_Narrowing;
430 }
431 }
432 return NK_Not_Narrowing;
433 }
434
435 default:
436 // Other kinds of conversions are not narrowings.
437 return NK_Not_Narrowing;
438 }
439}
440
441/// dump - Print this standard conversion sequence to standard
442/// error. Useful for debugging overloading issues.
443LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
444 raw_ostream &OS = llvm::errs();
445 bool PrintedSomething = false;
446 if (First != ICK_Identity) {
447 OS << GetImplicitConversionName(First);
448 PrintedSomething = true;
449 }
450
451 if (Second != ICK_Identity) {
452 if (PrintedSomething) {
453 OS << " -> ";
454 }
455 OS << GetImplicitConversionName(Second);
456
457 if (CopyConstructor) {
458 OS << " (by copy constructor)";
459 } else if (DirectBinding) {
460 OS << " (direct reference binding)";
461 } else if (ReferenceBinding) {
462 OS << " (reference binding)";
463 }
464 PrintedSomething = true;
465 }
466
467 if (Third != ICK_Identity) {
468 if (PrintedSomething) {
469 OS << " -> ";
470 }
471 OS << GetImplicitConversionName(Third);
472 PrintedSomething = true;
473 }
474
475 if (!PrintedSomething) {
476 OS << "No conversions required";
477 }
478}
479
480/// dump - Print this user-defined conversion sequence to standard
481/// error. Useful for debugging overloading issues.
482void UserDefinedConversionSequence::dump() const {
483 raw_ostream &OS = llvm::errs();
484 if (Before.First || Before.Second || Before.Third) {
485 Before.dump();
486 OS << " -> ";
487 }
488 if (ConversionFunction)
489 OS << '\'' << *ConversionFunction << '\'';
490 else
491 OS << "aggregate initialization";
492 if (After.First || After.Second || After.Third) {
493 OS << " -> ";
494 After.dump();
495 }
496}
497
498/// dump - Print this implicit conversion sequence to standard
499/// error. Useful for debugging overloading issues.
500void ImplicitConversionSequence::dump() const {
501 raw_ostream &OS = llvm::errs();
502 if (isStdInitializerListElement())
503 OS << "Worst std::initializer_list element conversion: ";
504 switch (ConversionKind) {
505 case StandardConversion:
506 OS << "Standard conversion: ";
507 Standard.dump();
508 break;
509 case UserDefinedConversion:
510 OS << "User-defined conversion: ";
511 UserDefined.dump();
512 break;
513 case EllipsisConversion:
514 OS << "Ellipsis conversion";
515 break;
516 case AmbiguousConversion:
517 OS << "Ambiguous conversion";
518 break;
519 case BadConversion:
520 OS << "Bad conversion";
521 break;
522 }
523
524 OS << "\n";
525}
526
527void AmbiguousConversionSequence::construct() {
528 new (&conversions()) ConversionSet();
529}
530
531void AmbiguousConversionSequence::destruct() {
532 conversions().~ConversionSet();
533}
534
535void
536AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
537 FromTypePtr = O.FromTypePtr;
538 ToTypePtr = O.ToTypePtr;
539 new (&conversions()) ConversionSet(O.conversions());
540}
541
542namespace {
543 // Structure used by DeductionFailureInfo to store
544 // template argument information.
545 struct DFIArguments {
546 TemplateArgument FirstArg;
547 TemplateArgument SecondArg;
548 };
549 // Structure used by DeductionFailureInfo to store
550 // template parameter and template argument information.
551 struct DFIParamWithArguments : DFIArguments {
552 TemplateParameter Param;
553 };
554 // Structure used by DeductionFailureInfo to store template argument
555 // information and the index of the problematic call argument.
556 struct DFIDeducedMismatchArgs : DFIArguments {
557 TemplateArgumentList *TemplateArgs;
558 unsigned CallArgIndex;
559 };
560}
561
562/// \brief Convert from Sema's representation of template deduction information
563/// to the form used in overload-candidate information.
564DeductionFailureInfo
565clang::MakeDeductionFailureInfo(ASTContext &Context,
566 Sema::TemplateDeductionResult TDK,
567 TemplateDeductionInfo &Info) {
568 DeductionFailureInfo Result;
569 Result.Result = static_cast<unsigned>(TDK);
570 Result.HasDiagnostic = false;
571 switch (TDK) {
572 case Sema::TDK_Success:
573 case Sema::TDK_Invalid:
574 case Sema::TDK_InstantiationDepth:
575 case Sema::TDK_TooManyArguments:
576 case Sema::TDK_TooFewArguments:
577 case Sema::TDK_MiscellaneousDeductionFailure:
578 Result.Data = nullptr;
579 break;
580
581 case Sema::TDK_Incomplete:
582 case Sema::TDK_InvalidExplicitArguments:
583 Result.Data = Info.Param.getOpaqueValue();
584 break;
585
586 case Sema::TDK_DeducedMismatch: {
587 // FIXME: Should allocate from normal heap so that we can free this later.
588 auto *Saved = new (Context) DFIDeducedMismatchArgs;
589 Saved->FirstArg = Info.FirstArg;
590 Saved->SecondArg = Info.SecondArg;
591 Saved->TemplateArgs = Info.take();
592 Saved->CallArgIndex = Info.CallArgIndex;
593 Result.Data = Saved;
594 break;
595 }
596
597 case Sema::TDK_NonDeducedMismatch: {
598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIArguments *Saved = new (Context) DFIArguments;
600 Saved->FirstArg = Info.FirstArg;
601 Saved->SecondArg = Info.SecondArg;
602 Result.Data = Saved;
603 break;
604 }
605
606 case Sema::TDK_Inconsistent:
607 case Sema::TDK_Underqualified: {
608 // FIXME: Should allocate from normal heap so that we can free this later.
609 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
610 Saved->Param = Info.Param;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Result.Data = Saved;
614 break;
615 }
616
617 case Sema::TDK_SubstitutionFailure:
618 Result.Data = Info.take();
619 if (Info.hasSFINAEDiagnostic()) {
620 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
621 SourceLocation(), PartialDiagnostic::NullDiagnostic());
622 Info.takeSFINAEDiagnostic(*Diag);
623 Result.HasDiagnostic = true;
624 }
625 break;
626
627 case Sema::TDK_FailedOverloadResolution:
628 Result.Data = Info.Expression;
629 break;
630 }
631
632 return Result;
633}
634
635void DeductionFailureInfo::Destroy() {
636 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
637 case Sema::TDK_Success:
638 case Sema::TDK_Invalid:
639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_Incomplete:
641 case Sema::TDK_TooManyArguments:
642 case Sema::TDK_TooFewArguments:
643 case Sema::TDK_InvalidExplicitArguments:
644 case Sema::TDK_FailedOverloadResolution:
645 break;
646
647 case Sema::TDK_Inconsistent:
648 case Sema::TDK_Underqualified:
649 case Sema::TDK_DeducedMismatch:
650 case Sema::TDK_NonDeducedMismatch:
651 // FIXME: Destroy the data?
652 Data = nullptr;
653 break;
654
655 case Sema::TDK_SubstitutionFailure:
656 // FIXME: Destroy the template argument list?
657 Data = nullptr;
658 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
659 Diag->~PartialDiagnosticAt();
660 HasDiagnostic = false;
661 }
662 break;
663
664 // Unhandled
665 case Sema::TDK_MiscellaneousDeductionFailure:
666 break;
667 }
668}
669
670PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
671 if (HasDiagnostic)
672 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
673 return nullptr;
674}
675
676TemplateParameter DeductionFailureInfo::getTemplateParameter() {
677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678 case Sema::TDK_Success:
679 case Sema::TDK_Invalid:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_TooManyArguments:
682 case Sema::TDK_TooFewArguments:
683 case Sema::TDK_SubstitutionFailure:
684 case Sema::TDK_DeducedMismatch:
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 return TemplateParameter();
688
689 case Sema::TDK_Incomplete:
690 case Sema::TDK_InvalidExplicitArguments:
691 return TemplateParameter::getFromOpaqueValue(Data);
692
693 case Sema::TDK_Inconsistent:
694 case Sema::TDK_Underqualified:
695 return static_cast<DFIParamWithArguments*>(Data)->Param;
696
697 // Unhandled
698 case Sema::TDK_MiscellaneousDeductionFailure:
699 break;
700 }
701
702 return TemplateParameter();
703}
704
705TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
707 case Sema::TDK_Success:
708 case Sema::TDK_Invalid:
709 case Sema::TDK_InstantiationDepth:
710 case Sema::TDK_TooManyArguments:
711 case Sema::TDK_TooFewArguments:
712 case Sema::TDK_Incomplete:
713 case Sema::TDK_InvalidExplicitArguments:
714 case Sema::TDK_Inconsistent:
715 case Sema::TDK_Underqualified:
716 case Sema::TDK_NonDeducedMismatch:
717 case Sema::TDK_FailedOverloadResolution:
718 return nullptr;
719
720 case Sema::TDK_DeducedMismatch:
721 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
722
723 case Sema::TDK_SubstitutionFailure:
724 return static_cast<TemplateArgumentList*>(Data);
725
726 // Unhandled
727 case Sema::TDK_MiscellaneousDeductionFailure:
728 break;
729 }
730
731 return nullptr;
732}
733
734const TemplateArgument *DeductionFailureInfo::getFirstArg() {
735 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736 case Sema::TDK_Success:
737 case Sema::TDK_Invalid:
738 case Sema::TDK_InstantiationDepth:
739 case Sema::TDK_Incomplete:
740 case Sema::TDK_TooManyArguments:
741 case Sema::TDK_TooFewArguments:
742 case Sema::TDK_InvalidExplicitArguments:
743 case Sema::TDK_SubstitutionFailure:
744 case Sema::TDK_FailedOverloadResolution:
745 return nullptr;
746
747 case Sema::TDK_Inconsistent:
748 case Sema::TDK_Underqualified:
749 case Sema::TDK_DeducedMismatch:
750 case Sema::TDK_NonDeducedMismatch:
751 return &static_cast<DFIArguments*>(Data)->FirstArg;
752
753 // Unhandled
754 case Sema::TDK_MiscellaneousDeductionFailure:
755 break;
756 }
757
758 return nullptr;
759}
760
761const TemplateArgument *DeductionFailureInfo::getSecondArg() {
762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763 case Sema::TDK_Success:
764 case Sema::TDK_Invalid:
765 case Sema::TDK_InstantiationDepth:
766 case Sema::TDK_Incomplete:
767 case Sema::TDK_TooManyArguments:
768 case Sema::TDK_TooFewArguments:
769 case Sema::TDK_InvalidExplicitArguments:
770 case Sema::TDK_SubstitutionFailure:
771 case Sema::TDK_FailedOverloadResolution:
772 return nullptr;
773
774 case Sema::TDK_Inconsistent:
775 case Sema::TDK_Underqualified:
776 case Sema::TDK_DeducedMismatch:
777 case Sema::TDK_NonDeducedMismatch:
778 return &static_cast<DFIArguments*>(Data)->SecondArg;
779
780 // Unhandled
781 case Sema::TDK_MiscellaneousDeductionFailure:
782 break;
783 }
784
785 return nullptr;
786}
787
788Expr *DeductionFailureInfo::getExpr() {
789 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790 Sema::TDK_FailedOverloadResolution)
791 return static_cast<Expr*>(Data);
792
793 return nullptr;
794}
795
796llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
797 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
798 Sema::TDK_DeducedMismatch)
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
800
801 return llvm::None;
802}
803
804void OverloadCandidateSet::destroyCandidates() {
805 for (iterator i = begin(), e = end(); i != e; ++i) {
806 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
807 i->Conversions[ii].~ImplicitConversionSequence();
808 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
809 i->DeductionFailure.Destroy();
810 }
811}
812
813void OverloadCandidateSet::clear() {
814 destroyCandidates();
815 NumInlineSequences = 0;
816 Candidates.clear();
817 Functions.clear();
818}
819
820namespace {
821 class UnbridgedCastsSet {
822 struct Entry {
823 Expr **Addr;
824 Expr *Saved;
825 };
826 SmallVector<Entry, 2> Entries;
827
828 public:
829 void save(Sema &S, Expr *&E) {
830 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 830, __PRETTY_FUNCTION__))
;
831 Entry entry = { &E, E };
832 Entries.push_back(entry);
833 E = S.stripARCUnbridgedCast(E);
834 }
835
836 void restore() {
837 for (SmallVectorImpl<Entry>::iterator
838 i = Entries.begin(), e = Entries.end(); i != e; ++i)
839 *i->Addr = i->Saved;
840 }
841 };
842}
843
844/// checkPlaceholderForOverload - Do any interesting placeholder-like
845/// preprocessing on the given expression.
846///
847/// \param unbridgedCasts a collection to which to add unbridged casts;
848/// without this, they will be immediately diagnosed as errors
849///
850/// Return true on unrecoverable error.
851static bool
852checkPlaceholderForOverload(Sema &S, Expr *&E,
853 UnbridgedCastsSet *unbridgedCasts = nullptr) {
854 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
855 // We can't handle overloaded expressions here because overload
856 // resolution might reasonably tweak them.
857 if (placeholder->getKind() == BuiltinType::Overload) return false;
858
859 // If the context potentially accepts unbridged ARC casts, strip
860 // the unbridged cast and add it to the collection for later restoration.
861 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
862 unbridgedCasts) {
863 unbridgedCasts->save(S, E);
864 return false;
865 }
866
867 // Go ahead and check everything else.
868 ExprResult result = S.CheckPlaceholderExpr(E);
869 if (result.isInvalid())
870 return true;
871
872 E = result.get();
873 return false;
874 }
875
876 // Nothing to do.
877 return false;
878}
879
880/// checkArgPlaceholdersForOverload - Check a set of call operands for
881/// placeholders.
882static bool checkArgPlaceholdersForOverload(Sema &S,
883 MultiExprArg Args,
884 UnbridgedCastsSet &unbridged) {
885 for (unsigned i = 0, e = Args.size(); i != e; ++i)
886 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
887 return true;
888
889 return false;
890}
891
892// IsOverload - Determine whether the given New declaration is an
893// overload of the declarations in Old. This routine returns false if
894// New and Old cannot be overloaded, e.g., if New has the same
895// signature as some function in Old (C++ 1.3.10) or if the Old
896// declarations aren't functions (or function templates) at all. When
897// it does return false, MatchedDecl will point to the decl that New
898// cannot be overloaded with. This decl may be a UsingShadowDecl on
899// top of the underlying declaration.
900//
901// Example: Given the following input:
902//
903// void f(int, float); // #1
904// void f(int, int); // #2
905// int f(int, int); // #3
906//
907// When we process #1, there is no previous declaration of "f",
908// so IsOverload will not be used.
909//
910// When we process #2, Old contains only the FunctionDecl for #1. By
911// comparing the parameter types, we see that #1 and #2 are overloaded
912// (since they have different signatures), so this routine returns
913// false; MatchedDecl is unchanged.
914//
915// When we process #3, Old is an overload set containing #1 and #2. We
916// compare the signatures of #3 to #1 (they're overloaded, so we do
917// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
918// identical (return types of functions are not part of the
919// signature), IsOverload returns false and MatchedDecl will be set to
920// point to the FunctionDecl for #2.
921//
922// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
923// into a class by a using declaration. The rules for whether to hide
924// shadow declarations ignore some properties which otherwise figure
925// into a function template's signature.
926Sema::OverloadKind
927Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
928 NamedDecl *&Match, bool NewIsUsingDecl) {
929 for (LookupResult::iterator I = Old.begin(), E = Old.end();
930 I != E; ++I) {
931 NamedDecl *OldD = *I;
932
933 bool OldIsUsingDecl = false;
934 if (isa<UsingShadowDecl>(OldD)) {
935 OldIsUsingDecl = true;
936
937 // We can always introduce two using declarations into the same
938 // context, even if they have identical signatures.
939 if (NewIsUsingDecl) continue;
940
941 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
942 }
943
944 // A using-declaration does not conflict with another declaration
945 // if one of them is hidden.
946 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
947 continue;
948
949 // If either declaration was introduced by a using declaration,
950 // we'll need to use slightly different rules for matching.
951 // Essentially, these rules are the normal rules, except that
952 // function templates hide function templates with different
953 // return types or template parameter lists.
954 bool UseMemberUsingDeclRules =
955 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
956 !New->getFriendObjectKind();
957
958 if (FunctionDecl *OldF = OldD->getAsFunction()) {
959 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
960 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
961 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
962 continue;
963 }
964
965 if (!isa<FunctionTemplateDecl>(OldD) &&
966 !shouldLinkPossiblyHiddenDecl(*I, New))
967 continue;
968
969 Match = *I;
970 return Ovl_Match;
971 }
972 } else if (isa<UsingDecl>(OldD)) {
973 // We can overload with these, which can show up when doing
974 // redeclaration checks for UsingDecls.
975 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 975, __PRETTY_FUNCTION__))
;
976 } else if (isa<TagDecl>(OldD)) {
977 // We can always overload with tags by hiding them.
978 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
979 // Optimistically assume that an unresolved using decl will
980 // overload; if it doesn't, we'll have to diagnose during
981 // template instantiation.
982 } else {
983 // (C++ 13p1):
984 // Only function declarations can be overloaded; object and type
985 // declarations cannot be overloaded.
986 Match = *I;
987 return Ovl_NonFunction;
988 }
989 }
990
991 return Ovl_Overload;
992}
993
994bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
995 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
996 // C++ [basic.start.main]p2: This function shall not be overloaded.
997 if (New->isMain())
998 return false;
999
1000 // MSVCRT user defined entry points cannot be overloaded.
1001 if (New->isMSVCRTEntryPoint())
1002 return false;
1003
1004 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1005 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1006
1007 // C++ [temp.fct]p2:
1008 // A function template can be overloaded with other function templates
1009 // and with normal (non-template) functions.
1010 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1011 return true;
1012
1013 // Is the function New an overload of the function Old?
1014 QualType OldQType = Context.getCanonicalType(Old->getType());
1015 QualType NewQType = Context.getCanonicalType(New->getType());
1016
1017 // Compare the signatures (C++ 1.3.10) of the two functions to
1018 // determine whether they are overloads. If we find any mismatch
1019 // in the signature, they are overloads.
1020
1021 // If either of these functions is a K&R-style function (no
1022 // prototype), then we consider them to have matching signatures.
1023 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1024 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1025 return false;
1026
1027 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1028 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1029
1030 // The signature of a function includes the types of its
1031 // parameters (C++ 1.3.10), which includes the presence or absence
1032 // of the ellipsis; see C++ DR 357).
1033 if (OldQType != NewQType &&
1034 (OldType->getNumParams() != NewType->getNumParams() ||
1035 OldType->isVariadic() != NewType->isVariadic() ||
1036 !FunctionParamTypesAreEqual(OldType, NewType)))
1037 return true;
1038
1039 // C++ [temp.over.link]p4:
1040 // The signature of a function template consists of its function
1041 // signature, its return type and its template parameter list. The names
1042 // of the template parameters are significant only for establishing the
1043 // relationship between the template parameters and the rest of the
1044 // signature.
1045 //
1046 // We check the return type and template parameter lists for function
1047 // templates first; the remaining checks follow.
1048 //
1049 // However, we don't consider either of these when deciding whether
1050 // a member introduced by a shadow declaration is hidden.
1051 if (!UseMemberUsingDeclRules && NewTemplate &&
1052 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1053 OldTemplate->getTemplateParameters(),
1054 false, TPL_TemplateMatch) ||
1055 OldType->getReturnType() != NewType->getReturnType()))
1056 return true;
1057
1058 // If the function is a class member, its signature includes the
1059 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1060 //
1061 // As part of this, also check whether one of the member functions
1062 // is static, in which case they are not overloads (C++
1063 // 13.1p2). While not part of the definition of the signature,
1064 // this check is important to determine whether these functions
1065 // can be overloaded.
1066 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1068 if (OldMethod && NewMethod &&
1069 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1070 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1071 if (!UseMemberUsingDeclRules &&
1072 (OldMethod->getRefQualifier() == RQ_None ||
1073 NewMethod->getRefQualifier() == RQ_None)) {
1074 // C++0x [over.load]p2:
1075 // - Member function declarations with the same name and the same
1076 // parameter-type-list as well as member function template
1077 // declarations with the same name, the same parameter-type-list, and
1078 // the same template parameter lists cannot be overloaded if any of
1079 // them, but not all, have a ref-qualifier (8.3.5).
1080 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1081 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1082 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1083 }
1084 return true;
1085 }
1086
1087 // We may not have applied the implicit const for a constexpr member
1088 // function yet (because we haven't yet resolved whether this is a static
1089 // or non-static member function). Add it now, on the assumption that this
1090 // is a redeclaration of OldMethod.
1091 unsigned OldQuals = OldMethod->getTypeQualifiers();
1092 unsigned NewQuals = NewMethod->getTypeQualifiers();
1093 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1094 !isa<CXXConstructorDecl>(NewMethod))
1095 NewQuals |= Qualifiers::Const;
1096
1097 // We do not allow overloading based off of '__restrict'.
1098 OldQuals &= ~Qualifiers::Restrict;
1099 NewQuals &= ~Qualifiers::Restrict;
1100 if (OldQuals != NewQuals)
1101 return true;
1102 }
1103
1104 // Though pass_object_size is placed on parameters and takes an argument, we
1105 // consider it to be a function-level modifier for the sake of function
1106 // identity. Either the function has one or more parameters with
1107 // pass_object_size or it doesn't.
1108 if (functionHasPassObjectSizeParams(New) !=
1109 functionHasPassObjectSizeParams(Old))
1110 return true;
1111
1112 // enable_if attributes are an order-sensitive part of the signature.
1113 for (specific_attr_iterator<EnableIfAttr>
1114 NewI = New->specific_attr_begin<EnableIfAttr>(),
1115 NewE = New->specific_attr_end<EnableIfAttr>(),
1116 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1117 OldE = Old->specific_attr_end<EnableIfAttr>();
1118 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1119 if (NewI == NewE || OldI == OldE)
1120 return true;
1121 llvm::FoldingSetNodeID NewID, OldID;
1122 NewI->getCond()->Profile(NewID, Context, true);
1123 OldI->getCond()->Profile(OldID, Context, true);
1124 if (NewID != OldID)
1125 return true;
1126 }
1127
1128 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1129 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1130 OldTarget = IdentifyCUDATarget(Old);
1131 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1132 return false;
1133
1134 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1134, __PRETTY_FUNCTION__))
;
1135
1136 // Don't allow mixing of HD with other kinds. This guarantees that
1137 // we have only one viable function with this signature on any
1138 // side of CUDA compilation .
1139 // __global__ functions can't be overloaded based on attribute
1140 // difference because, like HD, they also exist on both sides.
1141 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1142 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1143 return false;
1144
1145 // Allow overloading of functions with same signature, but
1146 // different CUDA target attributes.
1147 return NewTarget != OldTarget;
1148 }
1149
1150 // The signatures match; this is not an overload.
1151 return false;
1152}
1153
1154/// \brief Checks availability of the function depending on the current
1155/// function context. Inside an unavailable function, unavailability is ignored.
1156///
1157/// \returns true if \arg FD is unavailable and current context is inside
1158/// an available function, false otherwise.
1159bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1160 if (!FD->isUnavailable())
1161 return false;
1162
1163 // Walk up the context of the caller.
1164 Decl *C = cast<Decl>(CurContext);
1165 do {
1166 if (C->isUnavailable())
1167 return false;
1168 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1169 return true;
1170}
1171
1172/// \brief Tries a user-defined conversion from From to ToType.
1173///
1174/// Produces an implicit conversion sequence for when a standard conversion
1175/// is not an option. See TryImplicitConversion for more information.
1176static ImplicitConversionSequence
1177TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
1179 bool AllowExplicit,
1180 bool InOverloadResolution,
1181 bool CStyle,
1182 bool AllowObjCWritebackConversion,
1183 bool AllowObjCConversionOnExplicit) {
1184 ImplicitConversionSequence ICS;
1185
1186 if (SuppressUserConversions) {
1187 // We're not in the case above, so there is no conversion that
1188 // we can perform.
1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190 return ICS;
1191 }
1192
1193 // Attempt user-defined conversion.
1194 OverloadCandidateSet Conversions(From->getExprLoc(),
1195 OverloadCandidateSet::CSK_Normal);
1196 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1197 Conversions, AllowExplicit,
1198 AllowObjCConversionOnExplicit)) {
1199 case OR_Success:
1200 case OR_Deleted:
1201 ICS.setUserDefined();
1202 ICS.UserDefined.Before.setAsIdentityConversion();
1203 // C++ [over.ics.user]p4:
1204 // A conversion of an expression of class type to the same class
1205 // type is given Exact Match rank, and a conversion of an
1206 // expression of class type to a base class of that type is
1207 // given Conversion rank, in spite of the fact that a copy
1208 // constructor (i.e., a user-defined conversion function) is
1209 // called for those cases.
1210 if (CXXConstructorDecl *Constructor
1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1212 QualType FromCanon
1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1214 QualType ToCanon
1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1216 if (Constructor->isCopyConstructor() &&
1217 (FromCanon == ToCanon ||
1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1219 // Turn this into a "standard" conversion sequence, so that it
1220 // gets ranked with standard conversion sequences.
1221 ICS.setStandard();
1222 ICS.Standard.setAsIdentityConversion();
1223 ICS.Standard.setFromType(From->getType());
1224 ICS.Standard.setAllToTypes(ToType);
1225 ICS.Standard.CopyConstructor = Constructor;
1226 if (ToCanon != FromCanon)
1227 ICS.Standard.Second = ICK_Derived_To_Base;
1228 }
1229 }
1230 break;
1231
1232 case OR_Ambiguous:
1233 ICS.setAmbiguous();
1234 ICS.Ambiguous.setFromType(From->getType());
1235 ICS.Ambiguous.setToType(ToType);
1236 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1237 Cand != Conversions.end(); ++Cand)
1238 if (Cand->Viable)
1239 ICS.Ambiguous.addConversion(Cand->Function);
1240 break;
1241
1242 // Fall through.
1243 case OR_No_Viable_Function:
1244 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1245 break;
1246 }
1247
1248 return ICS;
1249}
1250
1251/// TryImplicitConversion - Attempt to perform an implicit conversion
1252/// from the given expression (Expr) to the given type (ToType). This
1253/// function returns an implicit conversion sequence that can be used
1254/// to perform the initialization. Given
1255///
1256/// void f(float f);
1257/// void g(int i) { f(i); }
1258///
1259/// this routine would produce an implicit conversion sequence to
1260/// describe the initialization of f from i, which will be a standard
1261/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1262/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1263//
1264/// Note that this routine only determines how the conversion can be
1265/// performed; it does not actually perform the conversion. As such,
1266/// it will not produce any diagnostics if no conversion is available,
1267/// but will instead return an implicit conversion sequence of kind
1268/// "BadConversion".
1269///
1270/// If @p SuppressUserConversions, then user-defined conversions are
1271/// not permitted.
1272/// If @p AllowExplicit, then explicit user-defined conversions are
1273/// permitted.
1274///
1275/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1276/// writeback conversion, which allows __autoreleasing id* parameters to
1277/// be initialized with __strong id* or __weak id* arguments.
1278static ImplicitConversionSequence
1279TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1280 bool SuppressUserConversions,
1281 bool AllowExplicit,
1282 bool InOverloadResolution,
1283 bool CStyle,
1284 bool AllowObjCWritebackConversion,
1285 bool AllowObjCConversionOnExplicit) {
1286 ImplicitConversionSequence ICS;
1287 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1288 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1289 ICS.setStandard();
1290 return ICS;
1291 }
1292
1293 if (!S.getLangOpts().CPlusPlus) {
1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1295 return ICS;
1296 }
1297
1298 // C++ [over.ics.user]p4:
1299 // A conversion of an expression of class type to the same class
1300 // type is given Exact Match rank, and a conversion of an
1301 // expression of class type to a base class of that type is
1302 // given Conversion rank, in spite of the fact that a copy/move
1303 // constructor (i.e., a user-defined conversion function) is
1304 // called for those cases.
1305 QualType FromType = From->getType();
1306 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1307 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1308 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1309 ICS.setStandard();
1310 ICS.Standard.setAsIdentityConversion();
1311 ICS.Standard.setFromType(FromType);
1312 ICS.Standard.setAllToTypes(ToType);
1313
1314 // We don't actually check at this point whether there is a valid
1315 // copy/move constructor, since overloading just assumes that it
1316 // exists. When we actually perform initialization, we'll find the
1317 // appropriate constructor to copy the returned object, if needed.
1318 ICS.Standard.CopyConstructor = nullptr;
1319
1320 // Determine whether this is considered a derived-to-base conversion.
1321 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1322 ICS.Standard.Second = ICK_Derived_To_Base;
1323
1324 return ICS;
1325 }
1326
1327 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1328 AllowExplicit, InOverloadResolution, CStyle,
1329 AllowObjCWritebackConversion,
1330 AllowObjCConversionOnExplicit);
1331}
1332
1333ImplicitConversionSequence
1334Sema::TryImplicitConversion(Expr *From, QualType ToType,
1335 bool SuppressUserConversions,
1336 bool AllowExplicit,
1337 bool InOverloadResolution,
1338 bool CStyle,
1339 bool AllowObjCWritebackConversion) {
1340 return ::TryImplicitConversion(*this, From, ToType,
1341 SuppressUserConversions, AllowExplicit,
1342 InOverloadResolution, CStyle,
1343 AllowObjCWritebackConversion,
1344 /*AllowObjCConversionOnExplicit=*/false);
1345}
1346
1347/// PerformImplicitConversion - Perform an implicit conversion of the
1348/// expression From to the type ToType. Returns the
1349/// converted expression. Flavor is the kind of conversion we're
1350/// performing, used in the error message. If @p AllowExplicit,
1351/// explicit user-defined conversions are permitted.
1352ExprResult
1353Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1354 AssignmentAction Action, bool AllowExplicit) {
1355 ImplicitConversionSequence ICS;
1356 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1357}
1358
1359ExprResult
1360Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1361 AssignmentAction Action, bool AllowExplicit,
1362 ImplicitConversionSequence& ICS) {
1363 if (checkPlaceholderForOverload(*this, From))
1364 return ExprError();
1365
1366 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1367 bool AllowObjCWritebackConversion
1368 = getLangOpts().ObjCAutoRefCount &&
1369 (Action == AA_Passing || Action == AA_Sending);
1370 if (getLangOpts().ObjC1)
1371 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1372 ToType, From->getType(), From);
1373 ICS = ::TryImplicitConversion(*this, From, ToType,
1374 /*SuppressUserConversions=*/false,
1375 AllowExplicit,
1376 /*InOverloadResolution=*/false,
1377 /*CStyle=*/false,
1378 AllowObjCWritebackConversion,
1379 /*AllowObjCConversionOnExplicit=*/false);
1380 return PerformImplicitConversion(From, ToType, ICS, Action);
1381}
1382
1383/// \brief Determine whether the conversion from FromType to ToType is a valid
1384/// conversion that strips "noreturn" off the nested function type.
1385bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1386 QualType &ResultTy) {
1387 if (Context.hasSameUnqualifiedType(FromType, ToType))
1388 return false;
1389
1390 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1391 // where F adds one of the following at most once:
1392 // - a pointer
1393 // - a member pointer
1394 // - a block pointer
1395 CanQualType CanTo = Context.getCanonicalType(ToType);
1396 CanQualType CanFrom = Context.getCanonicalType(FromType);
1397 Type::TypeClass TyClass = CanTo->getTypeClass();
1398 if (TyClass != CanFrom->getTypeClass()) return false;
1399 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1400 if (TyClass == Type::Pointer) {
1401 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1402 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1403 } else if (TyClass == Type::BlockPointer) {
1404 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1405 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1406 } else if (TyClass == Type::MemberPointer) {
1407 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1408 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1409 } else {
1410 return false;
1411 }
1412
1413 TyClass = CanTo->getTypeClass();
1414 if (TyClass != CanFrom->getTypeClass()) return false;
1415 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1416 return false;
1417 }
1418
1419 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1420 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1421 if (!EInfo.getNoReturn()) return false;
1422
1423 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1424 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1424, __PRETTY_FUNCTION__))
;
1425 if (QualType(FromFn, 0) != CanTo) return false;
1426
1427 ResultTy = ToType;
1428 return true;
1429}
1430
1431/// \brief Determine whether the conversion from FromType to ToType is a valid
1432/// vector conversion.
1433///
1434/// \param ICK Will be set to the vector conversion kind, if this is a vector
1435/// conversion.
1436static bool IsVectorConversion(Sema &S, QualType FromType,
1437 QualType ToType, ImplicitConversionKind &ICK) {
1438 // We need at least one of these types to be a vector type to have a vector
1439 // conversion.
1440 if (!ToType->isVectorType() && !FromType->isVectorType())
1441 return false;
1442
1443 // Identical types require no conversions.
1444 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1445 return false;
1446
1447 // There are no conversions between extended vector types, only identity.
1448 if (ToType->isExtVectorType()) {
1449 // There are no conversions between extended vector types other than the
1450 // identity conversion.
1451 if (FromType->isExtVectorType())
1452 return false;
1453
1454 // Vector splat from any arithmetic type to a vector.
1455 if (FromType->isArithmeticType()) {
1456 ICK = ICK_Vector_Splat;
1457 return true;
1458 }
1459 }
1460
1461 // We can perform the conversion between vector types in the following cases:
1462 // 1)vector types are equivalent AltiVec and GCC vector types
1463 // 2)lax vector conversions are permitted and the vector types are of the
1464 // same size
1465 if (ToType->isVectorType() && FromType->isVectorType()) {
1466 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1467 S.isLaxVectorConversion(FromType, ToType)) {
1468 ICK = ICK_Vector_Conversion;
1469 return true;
1470 }
1471 }
1472
1473 return false;
1474}
1475
1476static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1477 bool InOverloadResolution,
1478 StandardConversionSequence &SCS,
1479 bool CStyle);
1480
1481/// IsStandardConversion - Determines whether there is a standard
1482/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1483/// expression From to the type ToType. Standard conversion sequences
1484/// only consider non-class types; for conversions that involve class
1485/// types, use TryImplicitConversion. If a conversion exists, SCS will
1486/// contain the standard conversion sequence required to perform this
1487/// conversion and this routine will return true. Otherwise, this
1488/// routine will return false and the value of SCS is unspecified.
1489static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1490 bool InOverloadResolution,
1491 StandardConversionSequence &SCS,
1492 bool CStyle,
1493 bool AllowObjCWritebackConversion) {
1494 QualType FromType = From->getType();
1495
1496 // Standard conversions (C++ [conv])
1497 SCS.setAsIdentityConversion();
1498 SCS.IncompatibleObjC = false;
1499 SCS.setFromType(FromType);
1500 SCS.CopyConstructor = nullptr;
1501
1502 // There are no standard conversions for class types in C++, so
1503 // abort early. When overloading in C, however, we do permit them.
1504 if (S.getLangOpts().CPlusPlus &&
1505 (FromType->isRecordType() || ToType->isRecordType()))
1506 return false;
1507
1508 // The first conversion can be an lvalue-to-rvalue conversion,
1509 // array-to-pointer conversion, or function-to-pointer conversion
1510 // (C++ 4p1).
1511
1512 if (FromType == S.Context.OverloadTy) {
1513 DeclAccessPair AccessPair;
1514 if (FunctionDecl *Fn
1515 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1516 AccessPair)) {
1517 // We were able to resolve the address of the overloaded function,
1518 // so we can convert to the type of that function.
1519 FromType = Fn->getType();
1520 SCS.setFromType(FromType);
1521
1522 // we can sometimes resolve &foo<int> regardless of ToType, so check
1523 // if the type matches (identity) or we are converting to bool
1524 if (!S.Context.hasSameUnqualifiedType(
1525 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1526 QualType resultTy;
1527 // if the function type matches except for [[noreturn]], it's ok
1528 if (!S.IsNoReturnConversion(FromType,
1529 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1530 // otherwise, only a boolean conversion is standard
1531 if (!ToType->isBooleanType())
1532 return false;
1533 }
1534
1535 // Check if the "from" expression is taking the address of an overloaded
1536 // function and recompute the FromType accordingly. Take advantage of the
1537 // fact that non-static member functions *must* have such an address-of
1538 // expression.
1539 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1540 if (Method && !Method->isStatic()) {
1541 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1542, __PRETTY_FUNCTION__))
1542 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1542, __PRETTY_FUNCTION__))
;
1543 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1545, __PRETTY_FUNCTION__))
1544 == 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1545, __PRETTY_FUNCTION__))
1545 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1545, __PRETTY_FUNCTION__))
;
1546 const Type *ClassType
1547 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1548 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1549 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1550 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1552, __PRETTY_FUNCTION__))
1551 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1552, __PRETTY_FUNCTION__))
1552 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1552, __PRETTY_FUNCTION__))
;
1553 FromType = S.Context.getPointerType(FromType);
1554 }
1555
1556 // Check that we've computed the proper type after overload resolution.
1557 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1559, __PRETTY_FUNCTION__))
1558 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1559, __PRETTY_FUNCTION__))
1559 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 1559, __PRETTY_FUNCTION__))
;
1560 } else {
1561 return false;
1562 }
1563 }
1564 // Lvalue-to-rvalue conversion (C++11 4.1):
1565 // A glvalue (3.10) of a non-function, non-array type T can
1566 // be converted to a prvalue.
1567 bool argIsLValue = From->isGLValue();
1568 if (argIsLValue &&
1569 !FromType->isFunctionType() && !FromType->isArrayType() &&
1570 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1571 SCS.First = ICK_Lvalue_To_Rvalue;
1572
1573 // C11 6.3.2.1p2:
1574 // ... if the lvalue has atomic type, the value has the non-atomic version
1575 // of the type of the lvalue ...
1576 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1577 FromType = Atomic->getValueType();
1578
1579 // If T is a non-class type, the type of the rvalue is the
1580 // cv-unqualified version of T. Otherwise, the type of the rvalue
1581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1582 // just strip the qualifiers because they don't matter.
1583 FromType = FromType.getUnqualifiedType();
1584 } else if (FromType->isArrayType()) {
1585 // Array-to-pointer conversion (C++ 4.2)
1586 SCS.First = ICK_Array_To_Pointer;
1587
1588 // An lvalue or rvalue of type "array of N T" or "array of unknown
1589 // bound of T" can be converted to an rvalue of type "pointer to
1590 // T" (C++ 4.2p1).
1591 FromType = S.Context.getArrayDecayedType(FromType);
1592
1593 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1594 // This conversion is deprecated in C++03 (D.4)
1595 SCS.DeprecatedStringLiteralToCharPtr = true;
1596
1597 // For the purpose of ranking in overload resolution
1598 // (13.3.3.1.1), this conversion is considered an
1599 // array-to-pointer conversion followed by a qualification
1600 // conversion (4.4). (C++ 4.2p2)
1601 SCS.Second = ICK_Identity;
1602 SCS.Third = ICK_Qualification;
1603 SCS.QualificationIncludesObjCLifetime = false;
1604 SCS.setAllToTypes(FromType);
1605 return true;
1606 }
1607 } else if (FromType->isFunctionType() && argIsLValue) {
1608 // Function-to-pointer conversion (C++ 4.3).
1609 SCS.First = ICK_Function_To_Pointer;
1610
1611 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1612 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1613 if (!S.checkAddressOfFunctionIsAvailable(FD))
1614 return false;
1615
1616 // An lvalue of function type T can be converted to an rvalue of
1617 // type "pointer to T." The result is a pointer to the
1618 // function. (C++ 4.3p1).
1619 FromType = S.Context.getPointerType(FromType);
1620 } else {
1621 // We don't require any conversions for the first step.
1622 SCS.First = ICK_Identity;
1623 }
1624 SCS.setToType(0, FromType);
1625
1626 // The second conversion can be an integral promotion, floating
1627 // point promotion, integral conversion, floating point conversion,
1628 // floating-integral conversion, pointer conversion,
1629 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1630 // For overloading in C, this can also be a "compatible-type"
1631 // conversion.
1632 bool IncompatibleObjC = false;
1633 ImplicitConversionKind SecondICK = ICK_Identity;
1634 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1635 // The unqualified versions of the types are the same: there's no
1636 // conversion to do.
1637 SCS.Second = ICK_Identity;
1638 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1639 // Integral promotion (C++ 4.5).
1640 SCS.Second = ICK_Integral_Promotion;
1641 FromType = ToType.getUnqualifiedType();
1642 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1643 // Floating point promotion (C++ 4.6).
1644 SCS.Second = ICK_Floating_Promotion;
1645 FromType = ToType.getUnqualifiedType();
1646 } else if (S.IsComplexPromotion(FromType, ToType)) {
1647 // Complex promotion (Clang extension)
1648 SCS.Second = ICK_Complex_Promotion;
1649 FromType = ToType.getUnqualifiedType();
1650 } else if (ToType->isBooleanType() &&
1651 (FromType->isArithmeticType() ||
1652 FromType->isAnyPointerType() ||
1653 FromType->isBlockPointerType() ||
1654 FromType->isMemberPointerType() ||
1655 FromType->isNullPtrType())) {
1656 // Boolean conversions (C++ 4.12).
1657 SCS.Second = ICK_Boolean_Conversion;
1658 FromType = S.Context.BoolTy;
1659 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1660 ToType->isIntegralType(S.Context)) {
1661 // Integral conversions (C++ 4.7).
1662 SCS.Second = ICK_Integral_Conversion;
1663 FromType = ToType.getUnqualifiedType();
1664 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1665 // Complex conversions (C99 6.3.1.6)
1666 SCS.Second = ICK_Complex_Conversion;
1667 FromType = ToType.getUnqualifiedType();
1668 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1669 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1670 // Complex-real conversions (C99 6.3.1.7)
1671 SCS.Second = ICK_Complex_Real;
1672 FromType = ToType.getUnqualifiedType();
1673 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1674 // Floating point conversions (C++ 4.8).
1675 SCS.Second = ICK_Floating_Conversion;
1676 FromType = ToType.getUnqualifiedType();
1677 } else if ((FromType->isRealFloatingType() &&
1678 ToType->isIntegralType(S.Context)) ||
1679 (FromType->isIntegralOrUnscopedEnumerationType() &&
1680 ToType->isRealFloatingType())) {
1681 // Floating-integral conversions (C++ 4.9).
1682 SCS.Second = ICK_Floating_Integral;
1683 FromType = ToType.getUnqualifiedType();
1684 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1685 SCS.Second = ICK_Block_Pointer_Conversion;
1686 } else if (AllowObjCWritebackConversion &&
1687 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1688 SCS.Second = ICK_Writeback_Conversion;
1689 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1690 FromType, IncompatibleObjC)) {
1691 // Pointer conversions (C++ 4.10).
1692 SCS.Second = ICK_Pointer_Conversion;
1693 SCS.IncompatibleObjC = IncompatibleObjC;
1694 FromType = FromType.getUnqualifiedType();
1695 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1696 InOverloadResolution, FromType)) {
1697 // Pointer to member conversions (4.11).
1698 SCS.Second = ICK_Pointer_Member;
1699 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1700 SCS.Second = SecondICK;
1701 FromType = ToType.getUnqualifiedType();
1702 } else if (!S.getLangOpts().CPlusPlus &&
1703 S.Context.typesAreCompatible(ToType, FromType)) {
1704 // Compatible conversions (Clang extension for C function overloading)
1705 SCS.Second = ICK_Compatible_Conversion;
1706 FromType = ToType.getUnqualifiedType();
1707 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1708 // Treat a conversion that strips "noreturn" as an identity conversion.
1709 SCS.Second = ICK_NoReturn_Adjustment;
1710 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1711 InOverloadResolution,
1712 SCS, CStyle)) {
1713 SCS.Second = ICK_TransparentUnionConversion;
1714 FromType = ToType;
1715 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1716 CStyle)) {
1717 // tryAtomicConversion has updated the standard conversion sequence
1718 // appropriately.
1719 return true;
1720 } else if (ToType->isEventT() &&
1721 From->isIntegerConstantExpr(S.getASTContext()) &&
1722 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1723 SCS.Second = ICK_Zero_Event_Conversion;
1724 FromType = ToType;
1725 } else {
1726 // No second conversion required.
1727 SCS.Second = ICK_Identity;
1728 }
1729 SCS.setToType(1, FromType);
1730
1731 QualType CanonFrom;
1732 QualType CanonTo;
1733 // The third conversion can be a qualification conversion (C++ 4p1).
1734 bool ObjCLifetimeConversion;
1735 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1736 ObjCLifetimeConversion)) {
1737 SCS.Third = ICK_Qualification;
1738 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1739 FromType = ToType;
1740 CanonFrom = S.Context.getCanonicalType(FromType);
1741 CanonTo = S.Context.getCanonicalType(ToType);
1742 } else {
1743 // No conversion required
1744 SCS.Third = ICK_Identity;
1745
1746 // C++ [over.best.ics]p6:
1747 // [...] Any difference in top-level cv-qualification is
1748 // subsumed by the initialization itself and does not constitute
1749 // a conversion. [...]
1750 CanonFrom = S.Context.getCanonicalType(FromType);
1751 CanonTo = S.Context.getCanonicalType(ToType);
1752 if (CanonFrom.getLocalUnqualifiedType()
1753 == CanonTo.getLocalUnqualifiedType() &&
1754 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1755 FromType = ToType;
1756 CanonFrom = CanonTo;
1757 }
1758 }
1759 SCS.setToType(2, FromType);
1760
1761 if (CanonFrom == CanonTo)
1762 return true;
1763
1764 // If we have not converted the argument type to the parameter type,
1765 // this is a bad conversion sequence, unless we're resolving an overload in C.
1766 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1767 return false;
1768
1769 ExprResult ER = ExprResult{From};
1770 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1771 /*Diagnose=*/false,
1772 /*DiagnoseCFAudited=*/false,
1773 /*ConvertRHS=*/false);
1774 if (Conv != Sema::Compatible)
1775 return false;
1776
1777 SCS.setAllToTypes(ToType);
1778 // We need to set all three because we want this conversion to rank terribly,
1779 // and we don't know what conversions it may overlap with.
1780 SCS.First = ICK_C_Only_Conversion;
1781 SCS.Second = ICK_C_Only_Conversion;
1782 SCS.Third = ICK_C_Only_Conversion;
1783 return true;
1784}
1785
1786static bool
1787IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1788 QualType &ToType,
1789 bool InOverloadResolution,
1790 StandardConversionSequence &SCS,
1791 bool CStyle) {
1792
1793 const RecordType *UT = ToType->getAsUnionType();
1794 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1795 return false;
1796 // The field to initialize within the transparent union.
1797 RecordDecl *UD = UT->getDecl();
1798 // It's compatible if the expression matches any of the fields.
1799 for (const auto *it : UD->fields()) {
1800 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1801 CStyle, /*ObjCWritebackConversion=*/false)) {
1802 ToType = it->getType();
1803 return true;
1804 }
1805 }
1806 return false;
1807}
1808
1809/// IsIntegralPromotion - Determines whether the conversion from the
1810/// expression From (whose potentially-adjusted type is FromType) to
1811/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1812/// sets PromotedType to the promoted type.
1813bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1814 const BuiltinType *To = ToType->getAs<BuiltinType>();
1815 // All integers are built-in.
1816 if (!To) {
1817 return false;
1818 }
1819
1820 // An rvalue of type char, signed char, unsigned char, short int, or
1821 // unsigned short int can be converted to an rvalue of type int if
1822 // int can represent all the values of the source type; otherwise,
1823 // the source rvalue can be converted to an rvalue of type unsigned
1824 // int (C++ 4.5p1).
1825 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1826 !FromType->isEnumeralType()) {
1827 if (// We can promote any signed, promotable integer type to an int
1828 (FromType->isSignedIntegerType() ||
1829 // We can promote any unsigned integer type whose size is
1830 // less than int to an int.
1831 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1832 return To->getKind() == BuiltinType::Int;
1833 }
1834
1835 return To->getKind() == BuiltinType::UInt;
1836 }
1837
1838 // C++11 [conv.prom]p3:
1839 // A prvalue of an unscoped enumeration type whose underlying type is not
1840 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1841 // following types that can represent all the values of the enumeration
1842 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1843 // unsigned int, long int, unsigned long int, long long int, or unsigned
1844 // long long int. If none of the types in that list can represent all the
1845 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1846 // type can be converted to an rvalue a prvalue of the extended integer type
1847 // with lowest integer conversion rank (4.13) greater than the rank of long
1848 // long in which all the values of the enumeration can be represented. If
1849 // there are two such extended types, the signed one is chosen.
1850 // C++11 [conv.prom]p4:
1851 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1852 // can be converted to a prvalue of its underlying type. Moreover, if
1853 // integral promotion can be applied to its underlying type, a prvalue of an
1854 // unscoped enumeration type whose underlying type is fixed can also be
1855 // converted to a prvalue of the promoted underlying type.
1856 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1857 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1858 // provided for a scoped enumeration.
1859 if (FromEnumType->getDecl()->isScoped())
1860 return false;
1861
1862 // We can perform an integral promotion to the underlying type of the enum,
1863 // even if that's not the promoted type. Note that the check for promoting
1864 // the underlying type is based on the type alone, and does not consider
1865 // the bitfield-ness of the actual source expression.
1866 if (FromEnumType->getDecl()->isFixed()) {
1867 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1868 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1869 IsIntegralPromotion(nullptr, Underlying, ToType);
1870 }
1871
1872 // We have already pre-calculated the promotion type, so this is trivial.
1873 if (ToType->isIntegerType() &&
1874 isCompleteType(From->getLocStart(), FromType))
1875 return Context.hasSameUnqualifiedType(
1876 ToType, FromEnumType->getDecl()->getPromotionType());
1877 }
1878
1879 // C++0x [conv.prom]p2:
1880 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1881 // to an rvalue a prvalue of the first of the following types that can
1882 // represent all the values of its underlying type: int, unsigned int,
1883 // long int, unsigned long int, long long int, or unsigned long long int.
1884 // If none of the types in that list can represent all the values of its
1885 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1886 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1887 // type.
1888 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1889 ToType->isIntegerType()) {
1890 // Determine whether the type we're converting from is signed or
1891 // unsigned.
1892 bool FromIsSigned = FromType->isSignedIntegerType();
1893 uint64_t FromSize = Context.getTypeSize(FromType);
1894
1895 // The types we'll try to promote to, in the appropriate
1896 // order. Try each of these types.
1897 QualType PromoteTypes[6] = {
1898 Context.IntTy, Context.UnsignedIntTy,
1899 Context.LongTy, Context.UnsignedLongTy ,
1900 Context.LongLongTy, Context.UnsignedLongLongTy
1901 };
1902 for (int Idx = 0; Idx < 6; ++Idx) {
1903 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1904 if (FromSize < ToSize ||
1905 (FromSize == ToSize &&
1906 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1907 // We found the type that we can promote to. If this is the
1908 // type we wanted, we have a promotion. Otherwise, no
1909 // promotion.
1910 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1911 }
1912 }
1913 }
1914
1915 // An rvalue for an integral bit-field (9.6) can be converted to an
1916 // rvalue of type int if int can represent all the values of the
1917 // bit-field; otherwise, it can be converted to unsigned int if
1918 // unsigned int can represent all the values of the bit-field. If
1919 // the bit-field is larger yet, no integral promotion applies to
1920 // it. If the bit-field has an enumerated type, it is treated as any
1921 // other value of that type for promotion purposes (C++ 4.5p3).
1922 // FIXME: We should delay checking of bit-fields until we actually perform the
1923 // conversion.
1924 if (From) {
1925 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1926 llvm::APSInt BitWidth;
1927 if (FromType->isIntegralType(Context) &&
1928 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1929 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1930 ToSize = Context.getTypeSize(ToType);
1931
1932 // Are we promoting to an int from a bitfield that fits in an int?
1933 if (BitWidth < ToSize ||
1934 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1935 return To->getKind() == BuiltinType::Int;
1936 }
1937
1938 // Are we promoting to an unsigned int from an unsigned bitfield
1939 // that fits into an unsigned int?
1940 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1941 return To->getKind() == BuiltinType::UInt;
1942 }
1943
1944 return false;
1945 }
1946 }
1947 }
1948
1949 // An rvalue of type bool can be converted to an rvalue of type int,
1950 // with false becoming zero and true becoming one (C++ 4.5p4).
1951 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1952 return true;
1953 }
1954
1955 return false;
1956}
1957
1958/// IsFloatingPointPromotion - Determines whether the conversion from
1959/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1960/// returns true and sets PromotedType to the promoted type.
1961bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1962 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1963 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1964 /// An rvalue of type float can be converted to an rvalue of type
1965 /// double. (C++ 4.6p1).
1966 if (FromBuiltin->getKind() == BuiltinType::Float &&
1967 ToBuiltin->getKind() == BuiltinType::Double)
1968 return true;
1969
1970 // C99 6.3.1.5p1:
1971 // When a float is promoted to double or long double, or a
1972 // double is promoted to long double [...].
1973 if (!getLangOpts().CPlusPlus &&
1974 (FromBuiltin->getKind() == BuiltinType::Float ||
1975 FromBuiltin->getKind() == BuiltinType::Double) &&
1976 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1977 return true;
1978
1979 // Half can be promoted to float.
1980 if (!getLangOpts().NativeHalfType &&
1981 FromBuiltin->getKind() == BuiltinType::Half &&
1982 ToBuiltin->getKind() == BuiltinType::Float)
1983 return true;
1984 }
1985
1986 return false;
1987}
1988
1989/// \brief Determine if a conversion is a complex promotion.
1990///
1991/// A complex promotion is defined as a complex -> complex conversion
1992/// where the conversion between the underlying real types is a
1993/// floating-point or integral promotion.
1994bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1995 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1996 if (!FromComplex)
1997 return false;
1998
1999 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2000 if (!ToComplex)
2001 return false;
2002
2003 return IsFloatingPointPromotion(FromComplex->getElementType(),
2004 ToComplex->getElementType()) ||
2005 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2006 ToComplex->getElementType());
2007}
2008
2009/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2010/// the pointer type FromPtr to a pointer to type ToPointee, with the
2011/// same type qualifiers as FromPtr has on its pointee type. ToType,
2012/// if non-empty, will be a pointer to ToType that may or may not have
2013/// the right set of qualifiers on its pointee.
2014///
2015static QualType
2016BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2017 QualType ToPointee, QualType ToType,
2018 ASTContext &Context,
2019 bool StripObjCLifetime = false) {
2020 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2022, __PRETTY_FUNCTION__))
2021 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2022, __PRETTY_FUNCTION__))
2022 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2022, __PRETTY_FUNCTION__))
;
2023
2024 /// Conversions to 'id' subsume cv-qualifier conversions.
2025 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2026 return ToType.getUnqualifiedType();
2027
2028 QualType CanonFromPointee
2029 = Context.getCanonicalType(FromPtr->getPointeeType());
2030 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2031 Qualifiers Quals = CanonFromPointee.getQualifiers();
2032
2033 if (StripObjCLifetime)
2034 Quals.removeObjCLifetime();
2035
2036 // Exact qualifier match -> return the pointer type we're converting to.
2037 if (CanonToPointee.getLocalQualifiers() == Quals) {
2038 // ToType is exactly what we need. Return it.
2039 if (!ToType.isNull())
2040 return ToType.getUnqualifiedType();
2041
2042 // Build a pointer to ToPointee. It has the right qualifiers
2043 // already.
2044 if (isa<ObjCObjectPointerType>(ToType))
2045 return Context.getObjCObjectPointerType(ToPointee);
2046 return Context.getPointerType(ToPointee);
2047 }
2048
2049 // Just build a canonical type that has the right qualifiers.
2050 QualType QualifiedCanonToPointee
2051 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2052
2053 if (isa<ObjCObjectPointerType>(ToType))
2054 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2055 return Context.getPointerType(QualifiedCanonToPointee);
2056}
2057
2058static bool isNullPointerConstantForConversion(Expr *Expr,
2059 bool InOverloadResolution,
2060 ASTContext &Context) {
2061 // Handle value-dependent integral null pointer constants correctly.
2062 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2063 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2064 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2065 return !InOverloadResolution;
2066
2067 return Expr->isNullPointerConstant(Context,
2068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2069 : Expr::NPC_ValueDependentIsNull);
2070}
2071
2072/// IsPointerConversion - Determines whether the conversion of the
2073/// expression From, which has the (possibly adjusted) type FromType,
2074/// can be converted to the type ToType via a pointer conversion (C++
2075/// 4.10). If so, returns true and places the converted type (that
2076/// might differ from ToType in its cv-qualifiers at some level) into
2077/// ConvertedType.
2078///
2079/// This routine also supports conversions to and from block pointers
2080/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2081/// pointers to interfaces. FIXME: Once we've determined the
2082/// appropriate overloading rules for Objective-C, we may want to
2083/// split the Objective-C checks into a different routine; however,
2084/// GCC seems to consider all of these conversions to be pointer
2085/// conversions, so for now they live here. IncompatibleObjC will be
2086/// set if the conversion is an allowed Objective-C conversion that
2087/// should result in a warning.
2088bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2089 bool InOverloadResolution,
2090 QualType& ConvertedType,
2091 bool &IncompatibleObjC) {
2092 IncompatibleObjC = false;
2093 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2094 IncompatibleObjC))
2095 return true;
2096
2097 // Conversion from a null pointer constant to any Objective-C pointer type.
2098 if (ToType->isObjCObjectPointerType() &&
2099 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2100 ConvertedType = ToType;
2101 return true;
2102 }
2103
2104 // Blocks: Block pointers can be converted to void*.
2105 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2106 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2107 ConvertedType = ToType;
2108 return true;
2109 }
2110 // Blocks: A null pointer constant can be converted to a block
2111 // pointer type.
2112 if (ToType->isBlockPointerType() &&
2113 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2114 ConvertedType = ToType;
2115 return true;
2116 }
2117
2118 // If the left-hand-side is nullptr_t, the right side can be a null
2119 // pointer constant.
2120 if (ToType->isNullPtrType() &&
2121 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2122 ConvertedType = ToType;
2123 return true;
2124 }
2125
2126 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2127 if (!ToTypePtr)
2128 return false;
2129
2130 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2131 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2132 ConvertedType = ToType;
2133 return true;
2134 }
2135
2136 // Beyond this point, both types need to be pointers
2137 // , including objective-c pointers.
2138 QualType ToPointeeType = ToTypePtr->getPointeeType();
2139 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2140 !getLangOpts().ObjCAutoRefCount) {
2141 ConvertedType = BuildSimilarlyQualifiedPointerType(
2142 FromType->getAs<ObjCObjectPointerType>(),
2143 ToPointeeType,
2144 ToType, Context);
2145 return true;
2146 }
2147 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2148 if (!FromTypePtr)
2149 return false;
2150
2151 QualType FromPointeeType = FromTypePtr->getPointeeType();
2152
2153 // If the unqualified pointee types are the same, this can't be a
2154 // pointer conversion, so don't do all of the work below.
2155 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2156 return false;
2157
2158 // An rvalue of type "pointer to cv T," where T is an object type,
2159 // can be converted to an rvalue of type "pointer to cv void" (C++
2160 // 4.10p2).
2161 if (FromPointeeType->isIncompleteOrObjectType() &&
2162 ToPointeeType->isVoidType()) {
2163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2164 ToPointeeType,
2165 ToType, Context,
2166 /*StripObjCLifetime=*/true);
2167 return true;
2168 }
2169
2170 // MSVC allows implicit function to void* type conversion.
2171 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2172 ToPointeeType->isVoidType()) {
2173 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2174 ToPointeeType,
2175 ToType, Context);
2176 return true;
2177 }
2178
2179 // When we're overloading in C, we allow a special kind of pointer
2180 // conversion for compatible-but-not-identical pointee types.
2181 if (!getLangOpts().CPlusPlus &&
2182 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2183 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2184 ToPointeeType,
2185 ToType, Context);
2186 return true;
2187 }
2188
2189 // C++ [conv.ptr]p3:
2190 //
2191 // An rvalue of type "pointer to cv D," where D is a class type,
2192 // can be converted to an rvalue of type "pointer to cv B," where
2193 // B is a base class (clause 10) of D. If B is an inaccessible
2194 // (clause 11) or ambiguous (10.2) base class of D, a program that
2195 // necessitates this conversion is ill-formed. The result of the
2196 // conversion is a pointer to the base class sub-object of the
2197 // derived class object. The null pointer value is converted to
2198 // the null pointer value of the destination type.
2199 //
2200 // Note that we do not check for ambiguity or inaccessibility
2201 // here. That is handled by CheckPointerConversion.
2202 if (getLangOpts().CPlusPlus &&
2203 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2204 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2205 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2206 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2207 ToPointeeType,
2208 ToType, Context);
2209 return true;
2210 }
2211
2212 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2213 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2214 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2215 ToPointeeType,
2216 ToType, Context);
2217 return true;
2218 }
2219
2220 return false;
2221}
2222
2223/// \brief Adopt the given qualifiers for the given type.
2224static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2225 Qualifiers TQs = T.getQualifiers();
2226
2227 // Check whether qualifiers already match.
2228 if (TQs == Qs)
2229 return T;
2230
2231 if (Qs.compatiblyIncludes(TQs))
2232 return Context.getQualifiedType(T, Qs);
2233
2234 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2235}
2236
2237/// isObjCPointerConversion - Determines whether this is an
2238/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2239/// with the same arguments and return values.
2240bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2241 QualType& ConvertedType,
2242 bool &IncompatibleObjC) {
2243 if (!getLangOpts().ObjC1)
2244 return false;
2245
2246 // The set of qualifiers on the type we're converting from.
2247 Qualifiers FromQualifiers = FromType.getQualifiers();
2248
2249 // First, we handle all conversions on ObjC object pointer types.
2250 const ObjCObjectPointerType* ToObjCPtr =
2251 ToType->getAs<ObjCObjectPointerType>();
2252 const ObjCObjectPointerType *FromObjCPtr =
2253 FromType->getAs<ObjCObjectPointerType>();
2254
2255 if (ToObjCPtr && FromObjCPtr) {
2256 // If the pointee types are the same (ignoring qualifications),
2257 // then this is not a pointer conversion.
2258 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2259 FromObjCPtr->getPointeeType()))
2260 return false;
2261
2262 // Conversion between Objective-C pointers.
2263 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2264 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2265 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2266 if (getLangOpts().CPlusPlus && LHS && RHS &&
2267 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2268 FromObjCPtr->getPointeeType()))
2269 return false;
2270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2271 ToObjCPtr->getPointeeType(),
2272 ToType, Context);
2273 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2274 return true;
2275 }
2276
2277 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2278 // Okay: this is some kind of implicit downcast of Objective-C
2279 // interfaces, which is permitted. However, we're going to
2280 // complain about it.
2281 IncompatibleObjC = true;
2282 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2283 ToObjCPtr->getPointeeType(),
2284 ToType, Context);
2285 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2286 return true;
2287 }
2288 }
2289 // Beyond this point, both types need to be C pointers or block pointers.
2290 QualType ToPointeeType;
2291 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2292 ToPointeeType = ToCPtr->getPointeeType();
2293 else if (const BlockPointerType *ToBlockPtr =
2294 ToType->getAs<BlockPointerType>()) {
2295 // Objective C++: We're able to convert from a pointer to any object
2296 // to a block pointer type.
2297 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2298 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2299 return true;
2300 }
2301 ToPointeeType = ToBlockPtr->getPointeeType();
2302 }
2303 else if (FromType->getAs<BlockPointerType>() &&
2304 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2305 // Objective C++: We're able to convert from a block pointer type to a
2306 // pointer to any object.
2307 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2308 return true;
2309 }
2310 else
2311 return false;
2312
2313 QualType FromPointeeType;
2314 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2315 FromPointeeType = FromCPtr->getPointeeType();
2316 else if (const BlockPointerType *FromBlockPtr =
2317 FromType->getAs<BlockPointerType>())
2318 FromPointeeType = FromBlockPtr->getPointeeType();
2319 else
2320 return false;
2321
2322 // If we have pointers to pointers, recursively check whether this
2323 // is an Objective-C conversion.
2324 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2325 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2326 IncompatibleObjC)) {
2327 // We always complain about this conversion.
2328 IncompatibleObjC = true;
2329 ConvertedType = Context.getPointerType(ConvertedType);
2330 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2331 return true;
2332 }
2333 // Allow conversion of pointee being objective-c pointer to another one;
2334 // as in I* to id.
2335 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2336 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2337 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2338 IncompatibleObjC)) {
2339
2340 ConvertedType = Context.getPointerType(ConvertedType);
2341 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2342 return true;
2343 }
2344
2345 // If we have pointers to functions or blocks, check whether the only
2346 // differences in the argument and result types are in Objective-C
2347 // pointer conversions. If so, we permit the conversion (but
2348 // complain about it).
2349 const FunctionProtoType *FromFunctionType
2350 = FromPointeeType->getAs<FunctionProtoType>();
2351 const FunctionProtoType *ToFunctionType
2352 = ToPointeeType->getAs<FunctionProtoType>();
2353 if (FromFunctionType && ToFunctionType) {
2354 // If the function types are exactly the same, this isn't an
2355 // Objective-C pointer conversion.
2356 if (Context.getCanonicalType(FromPointeeType)
2357 == Context.getCanonicalType(ToPointeeType))
2358 return false;
2359
2360 // Perform the quick checks that will tell us whether these
2361 // function types are obviously different.
2362 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2363 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2364 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2365 return false;
2366
2367 bool HasObjCConversion = false;
2368 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2369 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2370 // Okay, the types match exactly. Nothing to do.
2371 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2372 ToFunctionType->getReturnType(),
2373 ConvertedType, IncompatibleObjC)) {
2374 // Okay, we have an Objective-C pointer conversion.
2375 HasObjCConversion = true;
2376 } else {
2377 // Function types are too different. Abort.
2378 return false;
2379 }
2380
2381 // Check argument types.
2382 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2383 ArgIdx != NumArgs; ++ArgIdx) {
2384 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2385 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2386 if (Context.getCanonicalType(FromArgType)
2387 == Context.getCanonicalType(ToArgType)) {
2388 // Okay, the types match exactly. Nothing to do.
2389 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2390 ConvertedType, IncompatibleObjC)) {
2391 // Okay, we have an Objective-C pointer conversion.
2392 HasObjCConversion = true;
2393 } else {
2394 // Argument types are too different. Abort.
2395 return false;
2396 }
2397 }
2398
2399 if (HasObjCConversion) {
2400 // We had an Objective-C conversion. Allow this pointer
2401 // conversion, but complain about it.
2402 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2403 IncompatibleObjC = true;
2404 return true;
2405 }
2406 }
2407
2408 return false;
2409}
2410
2411/// \brief Determine whether this is an Objective-C writeback conversion,
2412/// used for parameter passing when performing automatic reference counting.
2413///
2414/// \param FromType The type we're converting form.
2415///
2416/// \param ToType The type we're converting to.
2417///
2418/// \param ConvertedType The type that will be produced after applying
2419/// this conversion.
2420bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2421 QualType &ConvertedType) {
2422 if (!getLangOpts().ObjCAutoRefCount ||
2423 Context.hasSameUnqualifiedType(FromType, ToType))
2424 return false;
2425
2426 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2427 QualType ToPointee;
2428 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2429 ToPointee = ToPointer->getPointeeType();
2430 else
2431 return false;
2432
2433 Qualifiers ToQuals = ToPointee.getQualifiers();
2434 if (!ToPointee->isObjCLifetimeType() ||
2435 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2436 !ToQuals.withoutObjCLifetime().empty())
2437 return false;
2438
2439 // Argument must be a pointer to __strong to __weak.
2440 QualType FromPointee;
2441 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2442 FromPointee = FromPointer->getPointeeType();
2443 else
2444 return false;
2445
2446 Qualifiers FromQuals = FromPointee.getQualifiers();
2447 if (!FromPointee->isObjCLifetimeType() ||
2448 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2449 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2450 return false;
2451
2452 // Make sure that we have compatible qualifiers.
2453 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2454 if (!ToQuals.compatiblyIncludes(FromQuals))
2455 return false;
2456
2457 // Remove qualifiers from the pointee type we're converting from; they
2458 // aren't used in the compatibility check belong, and we'll be adding back
2459 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2460 FromPointee = FromPointee.getUnqualifiedType();
2461
2462 // The unqualified form of the pointee types must be compatible.
2463 ToPointee = ToPointee.getUnqualifiedType();
2464 bool IncompatibleObjC;
2465 if (Context.typesAreCompatible(FromPointee, ToPointee))
2466 FromPointee = ToPointee;
2467 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2468 IncompatibleObjC))
2469 return false;
2470
2471 /// \brief Construct the type we're converting to, which is a pointer to
2472 /// __autoreleasing pointee.
2473 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2474 ConvertedType = Context.getPointerType(FromPointee);
2475 return true;
2476}
2477
2478bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2479 QualType& ConvertedType) {
2480 QualType ToPointeeType;
2481 if (const BlockPointerType *ToBlockPtr =
2482 ToType->getAs<BlockPointerType>())
2483 ToPointeeType = ToBlockPtr->getPointeeType();
2484 else
2485 return false;
2486
2487 QualType FromPointeeType;
2488 if (const BlockPointerType *FromBlockPtr =
2489 FromType->getAs<BlockPointerType>())
2490 FromPointeeType = FromBlockPtr->getPointeeType();
2491 else
2492 return false;
2493 // We have pointer to blocks, check whether the only
2494 // differences in the argument and result types are in Objective-C
2495 // pointer conversions. If so, we permit the conversion.
2496
2497 const FunctionProtoType *FromFunctionType
2498 = FromPointeeType->getAs<FunctionProtoType>();
2499 const FunctionProtoType *ToFunctionType
2500 = ToPointeeType->getAs<FunctionProtoType>();
2501
2502 if (!FromFunctionType || !ToFunctionType)
2503 return false;
2504
2505 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2506 return true;
2507
2508 // Perform the quick checks that will tell us whether these
2509 // function types are obviously different.
2510 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2511 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2512 return false;
2513
2514 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2515 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2516 if (FromEInfo != ToEInfo)
2517 return false;
2518
2519 bool IncompatibleObjC = false;
2520 if (Context.hasSameType(FromFunctionType->getReturnType(),
2521 ToFunctionType->getReturnType())) {
2522 // Okay, the types match exactly. Nothing to do.
2523 } else {
2524 QualType RHS = FromFunctionType->getReturnType();
2525 QualType LHS = ToFunctionType->getReturnType();
2526 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2527 !RHS.hasQualifiers() && LHS.hasQualifiers())
2528 LHS = LHS.getUnqualifiedType();
2529
2530 if (Context.hasSameType(RHS,LHS)) {
2531 // OK exact match.
2532 } else if (isObjCPointerConversion(RHS, LHS,
2533 ConvertedType, IncompatibleObjC)) {
2534 if (IncompatibleObjC)
2535 return false;
2536 // Okay, we have an Objective-C pointer conversion.
2537 }
2538 else
2539 return false;
2540 }
2541
2542 // Check argument types.
2543 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2544 ArgIdx != NumArgs; ++ArgIdx) {
2545 IncompatibleObjC = false;
2546 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2547 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2548 if (Context.hasSameType(FromArgType, ToArgType)) {
2549 // Okay, the types match exactly. Nothing to do.
2550 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2551 ConvertedType, IncompatibleObjC)) {
2552 if (IncompatibleObjC)
2553 return false;
2554 // Okay, we have an Objective-C pointer conversion.
2555 } else
2556 // Argument types are too different. Abort.
2557 return false;
2558 }
2559 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2560 ToFunctionType))
2561 return false;
2562
2563 ConvertedType = ToType;
2564 return true;
2565}
2566
2567enum {
2568 ft_default,
2569 ft_different_class,
2570 ft_parameter_arity,
2571 ft_parameter_mismatch,
2572 ft_return_type,
2573 ft_qualifer_mismatch
2574};
2575
2576/// Attempts to get the FunctionProtoType from a Type. Handles
2577/// MemberFunctionPointers properly.
2578static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2579 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2580 return FPT;
2581
2582 if (auto *MPT = FromType->getAs<MemberPointerType>())
2583 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2584
2585 return nullptr;
2586}
2587
2588/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2589/// function types. Catches different number of parameter, mismatch in
2590/// parameter types, and different return types.
2591void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2592 QualType FromType, QualType ToType) {
2593 // If either type is not valid, include no extra info.
2594 if (FromType.isNull() || ToType.isNull()) {
2595 PDiag << ft_default;
2596 return;
2597 }
2598
2599 // Get the function type from the pointers.
2600 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2601 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2602 *ToMember = ToType->getAs<MemberPointerType>();
2603 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2604 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2605 << QualType(FromMember->getClass(), 0);
2606 return;
2607 }
2608 FromType = FromMember->getPointeeType();
2609 ToType = ToMember->getPointeeType();
2610 }
2611
2612 if (FromType->isPointerType())
2613 FromType = FromType->getPointeeType();
2614 if (ToType->isPointerType())
2615 ToType = ToType->getPointeeType();
2616
2617 // Remove references.
2618 FromType = FromType.getNonReferenceType();
2619 ToType = ToType.getNonReferenceType();
2620
2621 // Don't print extra info for non-specialized template functions.
2622 if (FromType->isInstantiationDependentType() &&
2623 !FromType->getAs<TemplateSpecializationType>()) {
2624 PDiag << ft_default;
2625 return;
2626 }
2627
2628 // No extra info for same types.
2629 if (Context.hasSameType(FromType, ToType)) {
2630 PDiag << ft_default;
2631 return;
2632 }
2633
2634 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2635 *ToFunction = tryGetFunctionProtoType(ToType);
2636
2637 // Both types need to be function types.
2638 if (!FromFunction || !ToFunction) {
2639 PDiag << ft_default;
2640 return;
2641 }
2642
2643 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2644 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2645 << FromFunction->getNumParams();
2646 return;
2647 }
2648
2649 // Handle different parameter types.
2650 unsigned ArgPos;
2651 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2652 PDiag << ft_parameter_mismatch << ArgPos + 1
2653 << ToFunction->getParamType(ArgPos)
2654 << FromFunction->getParamType(ArgPos);
2655 return;
2656 }
2657
2658 // Handle different return type.
2659 if (!Context.hasSameType(FromFunction->getReturnType(),
2660 ToFunction->getReturnType())) {
2661 PDiag << ft_return_type << ToFunction->getReturnType()
2662 << FromFunction->getReturnType();
2663 return;
2664 }
2665
2666 unsigned FromQuals = FromFunction->getTypeQuals(),
2667 ToQuals = ToFunction->getTypeQuals();
2668 if (FromQuals != ToQuals) {
2669 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2670 return;
2671 }
2672
2673 // Unable to find a difference, so add no extra info.
2674 PDiag << ft_default;
2675}
2676
2677/// FunctionParamTypesAreEqual - This routine checks two function proto types
2678/// for equality of their argument types. Caller has already checked that
2679/// they have same number of arguments. If the parameters are different,
2680/// ArgPos will have the parameter index of the first different parameter.
2681bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2682 const FunctionProtoType *NewType,
2683 unsigned *ArgPos) {
2684 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2685 N = NewType->param_type_begin(),
2686 E = OldType->param_type_end();
2687 O && (O != E); ++O, ++N) {
2688 if (!Context.hasSameType(O->getUnqualifiedType(),
2689 N->getUnqualifiedType())) {
2690 if (ArgPos)
2691 *ArgPos = O - OldType->param_type_begin();
2692 return false;
2693 }
2694 }
2695 return true;
2696}
2697
2698/// CheckPointerConversion - Check the pointer conversion from the
2699/// expression From to the type ToType. This routine checks for
2700/// ambiguous or inaccessible derived-to-base pointer
2701/// conversions for which IsPointerConversion has already returned
2702/// true. It returns true and produces a diagnostic if there was an
2703/// error, or returns false otherwise.
2704bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2705 CastKind &Kind,
2706 CXXCastPath& BasePath,
2707 bool IgnoreBaseAccess,
2708 bool Diagnose) {
2709 QualType FromType = From->getType();
2710 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2711
2712 Kind = CK_BitCast;
2713
2714 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2715 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2716 Expr::NPCK_ZeroExpression) {
2717 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2718 DiagRuntimeBehavior(From->getExprLoc(), From,
2719 PDiag(diag::warn_impcast_bool_to_null_pointer)
2720 << ToType << From->getSourceRange());
2721 else if (!isUnevaluatedContext())
2722 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2723 << ToType << From->getSourceRange();
2724 }
2725 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2726 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2727 QualType FromPointeeType = FromPtrType->getPointeeType(),
2728 ToPointeeType = ToPtrType->getPointeeType();
2729
2730 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2731 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2732 // We must have a derived-to-base conversion. Check an
2733 // ambiguous or inaccessible conversion.
2734 unsigned InaccessibleID = 0;
2735 unsigned AmbigiousID = 0;
2736 if (Diagnose) {
2737 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2738 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2739 }
2740 if (CheckDerivedToBaseConversion(
2741 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2742 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2743 &BasePath, IgnoreBaseAccess))
2744 return true;
2745
2746 // The conversion was successful.
2747 Kind = CK_DerivedToBase;
2748 }
2749
2750 if (Diagnose && !IsCStyleOrFunctionalCast &&
2751 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2752 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2753, __PRETTY_FUNCTION__))
2753 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2753, __PRETTY_FUNCTION__))
;
2754 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2755 << From->getSourceRange();
2756 }
2757 }
2758 } else if (const ObjCObjectPointerType *ToPtrType =
2759 ToType->getAs<ObjCObjectPointerType>()) {
2760 if (const ObjCObjectPointerType *FromPtrType =
2761 FromType->getAs<ObjCObjectPointerType>()) {
2762 // Objective-C++ conversions are always okay.
2763 // FIXME: We should have a different class of conversions for the
2764 // Objective-C++ implicit conversions.
2765 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2766 return false;
2767 } else if (FromType->isBlockPointerType()) {
2768 Kind = CK_BlockPointerToObjCPointerCast;
2769 } else {
2770 Kind = CK_CPointerToObjCPointerCast;
2771 }
2772 } else if (ToType->isBlockPointerType()) {
2773 if (!FromType->isBlockPointerType())
2774 Kind = CK_AnyPointerToBlockPointerCast;
2775 }
2776
2777 // We shouldn't fall into this case unless it's valid for other
2778 // reasons.
2779 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2780 Kind = CK_NullToPointer;
2781
2782 return false;
2783}
2784
2785/// IsMemberPointerConversion - Determines whether the conversion of the
2786/// expression From, which has the (possibly adjusted) type FromType, can be
2787/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2788/// If so, returns true and places the converted type (that might differ from
2789/// ToType in its cv-qualifiers at some level) into ConvertedType.
2790bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2791 QualType ToType,
2792 bool InOverloadResolution,
2793 QualType &ConvertedType) {
2794 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2795 if (!ToTypePtr)
2796 return false;
2797
2798 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2799 if (From->isNullPointerConstant(Context,
2800 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2801 : Expr::NPC_ValueDependentIsNull)) {
2802 ConvertedType = ToType;
2803 return true;
2804 }
2805
2806 // Otherwise, both types have to be member pointers.
2807 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2808 if (!FromTypePtr)
2809 return false;
2810
2811 // A pointer to member of B can be converted to a pointer to member of D,
2812 // where D is derived from B (C++ 4.11p2).
2813 QualType FromClass(FromTypePtr->getClass(), 0);
2814 QualType ToClass(ToTypePtr->getClass(), 0);
2815
2816 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2817 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2818 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2819 ToClass.getTypePtr());
2820 return true;
2821 }
2822
2823 return false;
2824}
2825
2826/// CheckMemberPointerConversion - Check the member pointer conversion from the
2827/// expression From to the type ToType. This routine checks for ambiguous or
2828/// virtual or inaccessible base-to-derived member pointer conversions
2829/// for which IsMemberPointerConversion has already returned true. It returns
2830/// true and produces a diagnostic if there was an error, or returns false
2831/// otherwise.
2832bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2833 CastKind &Kind,
2834 CXXCastPath &BasePath,
2835 bool IgnoreBaseAccess) {
2836 QualType FromType = From->getType();
2837 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2838 if (!FromPtrType) {
2839 // This must be a null pointer to member pointer conversion
2840 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2842, __PRETTY_FUNCTION__))
2841 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2842, __PRETTY_FUNCTION__))
2842 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2842, __PRETTY_FUNCTION__))
;
2843 Kind = CK_NullToMemberPointer;
2844 return false;
2845 }
2846
2847 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2848 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2849, __PRETTY_FUNCTION__))
2849 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2849, __PRETTY_FUNCTION__))
;
2850
2851 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2852 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2853
2854 // FIXME: What about dependent types?
2855 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2855, __PRETTY_FUNCTION__))
;
2856 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2856, __PRETTY_FUNCTION__))
;
2857
2858 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2859 /*DetectVirtual=*/true);
2860 bool DerivationOkay =
2861 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2862 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2863, __PRETTY_FUNCTION__))
2863 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 2863, __PRETTY_FUNCTION__))
;
2864 (void)DerivationOkay;
2865
2866 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2867 getUnqualifiedType())) {
2868 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2869 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2870 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2871 return true;
2872 }
2873
2874 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2875 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2876 << FromClass << ToClass << QualType(VBase, 0)
2877 << From->getSourceRange();
2878 return true;
2879 }
2880
2881 if (!IgnoreBaseAccess)
2882 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2883 Paths.front(),
2884 diag::err_downcast_from_inaccessible_base);
2885
2886 // Must be a base to derived member conversion.
2887 BuildBasePathArray(Paths, BasePath);
2888 Kind = CK_BaseToDerivedMemberPointer;
2889 return false;
2890}
2891
2892/// Determine whether the lifetime conversion between the two given
2893/// qualifiers sets is nontrivial.
2894static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2895 Qualifiers ToQuals) {
2896 // Converting anything to const __unsafe_unretained is trivial.
2897 if (ToQuals.hasConst() &&
2898 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2899 return false;
2900
2901 return true;
2902}
2903
2904/// IsQualificationConversion - Determines whether the conversion from
2905/// an rvalue of type FromType to ToType is a qualification conversion
2906/// (C++ 4.4).
2907///
2908/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2909/// when the qualification conversion involves a change in the Objective-C
2910/// object lifetime.
2911bool
2912Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2913 bool CStyle, bool &ObjCLifetimeConversion) {
2914 FromType = Context.getCanonicalType(FromType);
2915 ToType = Context.getCanonicalType(ToType);
2916 ObjCLifetimeConversion = false;
2917
2918 // If FromType and ToType are the same type, this is not a
2919 // qualification conversion.
2920 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2921 return false;
2922
2923 // (C++ 4.4p4):
2924 // A conversion can add cv-qualifiers at levels other than the first
2925 // in multi-level pointers, subject to the following rules: [...]
2926 bool PreviousToQualsIncludeConst = true;
2927 bool UnwrappedAnyPointer = false;
2928 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2929 // Within each iteration of the loop, we check the qualifiers to
2930 // determine if this still looks like a qualification
2931 // conversion. Then, if all is well, we unwrap one more level of
2932 // pointers or pointers-to-members and do it all again
2933 // until there are no more pointers or pointers-to-members left to
2934 // unwrap.
2935 UnwrappedAnyPointer = true;
2936
2937 Qualifiers FromQuals = FromType.getQualifiers();
2938 Qualifiers ToQuals = ToType.getQualifiers();
2939
2940 // Objective-C ARC:
2941 // Check Objective-C lifetime conversions.
2942 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2943 UnwrappedAnyPointer) {
2944 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2945 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2946 ObjCLifetimeConversion = true;
2947 FromQuals.removeObjCLifetime();
2948 ToQuals.removeObjCLifetime();
2949 } else {
2950 // Qualification conversions cannot cast between different
2951 // Objective-C lifetime qualifiers.
2952 return false;
2953 }
2954 }
2955
2956 // Allow addition/removal of GC attributes but not changing GC attributes.
2957 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2958 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2959 FromQuals.removeObjCGCAttr();
2960 ToQuals.removeObjCGCAttr();
2961 }
2962
2963 // -- for every j > 0, if const is in cv 1,j then const is in cv
2964 // 2,j, and similarly for volatile.
2965 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2966 return false;
2967
2968 // -- if the cv 1,j and cv 2,j are different, then const is in
2969 // every cv for 0 < k < j.
2970 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2971 && !PreviousToQualsIncludeConst)
2972 return false;
2973
2974 // Keep track of whether all prior cv-qualifiers in the "to" type
2975 // include const.
2976 PreviousToQualsIncludeConst
2977 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2978 }
2979
2980 // We are left with FromType and ToType being the pointee types
2981 // after unwrapping the original FromType and ToType the same number
2982 // of types. If we unwrapped any pointers, and if FromType and
2983 // ToType have the same unqualified type (since we checked
2984 // qualifiers above), then this is a qualification conversion.
2985 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2986}
2987
2988/// \brief - Determine whether this is a conversion from a scalar type to an
2989/// atomic type.
2990///
2991/// If successful, updates \c SCS's second and third steps in the conversion
2992/// sequence to finish the conversion.
2993static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2994 bool InOverloadResolution,
2995 StandardConversionSequence &SCS,
2996 bool CStyle) {
2997 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2998 if (!ToAtomic)
2999 return false;
3000
3001 StandardConversionSequence InnerSCS;
3002 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3003 InOverloadResolution, InnerSCS,
3004 CStyle, /*AllowObjCWritebackConversion=*/false))
3005 return false;
3006
3007 SCS.Second = InnerSCS.Second;
3008 SCS.setToType(1, InnerSCS.getToType(1));
3009 SCS.Third = InnerSCS.Third;
3010 SCS.QualificationIncludesObjCLifetime
3011 = InnerSCS.QualificationIncludesObjCLifetime;
3012 SCS.setToType(2, InnerSCS.getToType(2));
3013 return true;
3014}
3015
3016static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3017 CXXConstructorDecl *Constructor,
3018 QualType Type) {
3019 const FunctionProtoType *CtorType =
3020 Constructor->getType()->getAs<FunctionProtoType>();
3021 if (CtorType->getNumParams() > 0) {
3022 QualType FirstArg = CtorType->getParamType(0);
3023 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3024 return true;
3025 }
3026 return false;
3027}
3028
3029static OverloadingResult
3030IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3031 CXXRecordDecl *To,
3032 UserDefinedConversionSequence &User,
3033 OverloadCandidateSet &CandidateSet,
3034 bool AllowExplicit) {
3035 DeclContext::lookup_result R = S.LookupConstructors(To);
3036 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3037 Con != ConEnd; ++Con) {
3038 NamedDecl *D = *Con;
3039 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3040
3041 // Find the constructor (which may be a template).
3042 CXXConstructorDecl *Constructor = nullptr;
3043 FunctionTemplateDecl *ConstructorTmpl
3044 = dyn_cast<FunctionTemplateDecl>(D);
3045 if (ConstructorTmpl)
3046 Constructor
3047 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3048 else
3049 Constructor = cast<CXXConstructorDecl>(D);
3050
3051 bool Usable = !Constructor->isInvalidDecl() &&
3052 S.isInitListConstructor(Constructor) &&
3053 (AllowExplicit || !Constructor->isExplicit());
3054 if (Usable) {
3055 // If the first argument is (a reference to) the target type,
3056 // suppress conversions.
3057 bool SuppressUserConversions =
3058 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
3059 if (ConstructorTmpl)
3060 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3061 /*ExplicitArgs*/ nullptr,
3062 From, CandidateSet,
3063 SuppressUserConversions);
3064 else
3065 S.AddOverloadCandidate(Constructor, FoundDecl,
3066 From, CandidateSet,
3067 SuppressUserConversions);
3068 }
3069 }
3070
3071 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3072
3073 OverloadCandidateSet::iterator Best;
3074 switch (auto Result =
3075 CandidateSet.BestViableFunction(S, From->getLocStart(),
3076 Best, true)) {
3077 case OR_Deleted:
3078 case OR_Success: {
3079 // Record the standard conversion we used and the conversion function.
3080 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3081 QualType ThisType = Constructor->getThisType(S.Context);
3082 // Initializer lists don't have conversions as such.
3083 User.Before.setAsIdentityConversion();
3084 User.HadMultipleCandidates = HadMultipleCandidates;
3085 User.ConversionFunction = Constructor;
3086 User.FoundConversionFunction = Best->FoundDecl;
3087 User.After.setAsIdentityConversion();
3088 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3089 User.After.setAllToTypes(ToType);
3090 return Result;
3091 }
3092
3093 case OR_No_Viable_Function:
3094 return OR_No_Viable_Function;
3095 case OR_Ambiguous:
3096 return OR_Ambiguous;
3097 }
3098
3099 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 3099)
;
3100}
3101
3102/// Determines whether there is a user-defined conversion sequence
3103/// (C++ [over.ics.user]) that converts expression From to the type
3104/// ToType. If such a conversion exists, User will contain the
3105/// user-defined conversion sequence that performs such a conversion
3106/// and this routine will return true. Otherwise, this routine returns
3107/// false and User is unspecified.
3108///
3109/// \param AllowExplicit true if the conversion should consider C++0x
3110/// "explicit" conversion functions as well as non-explicit conversion
3111/// functions (C++0x [class.conv.fct]p2).
3112///
3113/// \param AllowObjCConversionOnExplicit true if the conversion should
3114/// allow an extra Objective-C pointer conversion on uses of explicit
3115/// constructors. Requires \c AllowExplicit to also be set.
3116static OverloadingResult
3117IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3118 UserDefinedConversionSequence &User,
3119 OverloadCandidateSet &CandidateSet,
3120 bool AllowExplicit,
3121 bool AllowObjCConversionOnExplicit) {
3122 assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 3122, __PRETTY_FUNCTION__))
;
3123
3124 // Whether we will only visit constructors.
3125 bool ConstructorsOnly = false;
3126
3127 // If the type we are conversion to is a class type, enumerate its
3128 // constructors.
3129 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3130 // C++ [over.match.ctor]p1:
3131 // When objects of class type are direct-initialized (8.5), or
3132 // copy-initialized from an expression of the same or a
3133 // derived class type (8.5), overload resolution selects the
3134 // constructor. [...] For copy-initialization, the candidate
3135 // functions are all the converting constructors (12.3.1) of
3136 // that class. The argument list is the expression-list within
3137 // the parentheses of the initializer.
3138 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3139 (From->getType()->getAs<RecordType>() &&
3140 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3141 ConstructorsOnly = true;
3142
3143 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3144 // We're not going to find any constructors.
3145 } else if (CXXRecordDecl *ToRecordDecl
3146 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3147
3148 Expr **Args = &From;
3149 unsigned NumArgs = 1;
3150 bool ListInitializing = false;
3151 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3152 // But first, see if there is an init-list-constructor that will work.
3153 OverloadingResult Result = IsInitializerListConstructorConversion(
3154 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3155 if (Result != OR_No_Viable_Function)
3156 return Result;
3157 // Never mind.
3158 CandidateSet.clear();
3159
3160 // If we're list-initializing, we pass the individual elements as
3161 // arguments, not the entire list.
3162 Args = InitList->getInits();
3163 NumArgs = InitList->getNumInits();
3164 ListInitializing = true;
3165 }
3166
3167 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3168 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3169 Con != ConEnd; ++Con) {
3170 NamedDecl *D = *Con;
3171 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3172
3173 // Find the constructor (which may be a template).
3174 CXXConstructorDecl *Constructor = nullptr;
3175 FunctionTemplateDecl *ConstructorTmpl
3176 = dyn_cast<FunctionTemplateDecl>(D);
3177 if (ConstructorTmpl)
3178 Constructor
3179 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3180 else
3181 Constructor = cast<CXXConstructorDecl>(D);
3182
3183 bool Usable = !Constructor->isInvalidDecl();
3184 if (ListInitializing)
3185 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3186 else
3187 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3188 if (Usable) {
3189 bool SuppressUserConversions = !ConstructorsOnly;
3190 if (SuppressUserConversions && ListInitializing) {
3191 SuppressUserConversions = false;
3192 if (NumArgs == 1) {
3193 // If the first argument is (a reference to) the target type,
3194 // suppress conversions.
3195 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3196 S.Context, Constructor, ToType);
3197 }
3198 }
3199 if (ConstructorTmpl)
3200 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3201 /*ExplicitArgs*/ nullptr,
3202 llvm::makeArrayRef(Args, NumArgs),
3203 CandidateSet, SuppressUserConversions);
3204 else
3205 // Allow one user-defined conversion when user specifies a
3206 // From->ToType conversion via an static cast (c-style, etc).
3207 S.AddOverloadCandidate(Constructor, FoundDecl,
3208 llvm::makeArrayRef(Args, NumArgs),
3209 CandidateSet, SuppressUserConversions);
3210 }
3211 }
3212 }
3213 }
3214
3215 // Enumerate conversion functions, if we're allowed to.
3216 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3217 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3218 // No conversion functions from incomplete types.
3219 } else if (const RecordType *FromRecordType
3220 = From->getType()->getAs<RecordType>()) {
3221 if (CXXRecordDecl *FromRecordDecl
3222 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3223 // Add all of the conversion functions as candidates.
3224 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3225 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3226 DeclAccessPair FoundDecl = I.getPair();
3227 NamedDecl *D = FoundDecl.getDecl();
3228 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3229 if (isa<UsingShadowDecl>(D))
3230 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3231
3232 CXXConversionDecl *Conv;
3233 FunctionTemplateDecl *ConvTemplate;
3234 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3235 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3236 else
3237 Conv = cast<CXXConversionDecl>(D);
3238
3239 if (AllowExplicit || !Conv->isExplicit()) {
3240 if (ConvTemplate)
3241 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3242 ActingContext, From, ToType,
3243 CandidateSet,
3244 AllowObjCConversionOnExplicit);
3245 else
3246 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3247 From, ToType, CandidateSet,
3248 AllowObjCConversionOnExplicit);
3249 }
3250 }
3251 }
3252 }
3253
3254 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3255
3256 OverloadCandidateSet::iterator Best;
3257 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3258 Best, true)) {
3259 case OR_Success:
3260 case OR_Deleted:
3261 // Record the standard conversion we used and the conversion function.
3262 if (CXXConstructorDecl *Constructor
3263 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3264 // C++ [over.ics.user]p1:
3265 // If the user-defined conversion is specified by a
3266 // constructor (12.3.1), the initial standard conversion
3267 // sequence converts the source type to the type required by
3268 // the argument of the constructor.
3269 //
3270 QualType ThisType = Constructor->getThisType(S.Context);
3271 if (isa<InitListExpr>(From)) {
3272 // Initializer lists don't have conversions as such.
3273 User.Before.setAsIdentityConversion();
3274 } else {
3275 if (Best->Conversions[0].isEllipsis())
3276 User.EllipsisConversion = true;
3277 else {
3278 User.Before = Best->Conversions[0].Standard;
3279 User.EllipsisConversion = false;
3280 }
3281 }
3282 User.HadMultipleCandidates = HadMultipleCandidates;
3283 User.ConversionFunction = Constructor;
3284 User.FoundConversionFunction = Best->FoundDecl;
3285 User.After.setAsIdentityConversion();
3286 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3287 User.After.setAllToTypes(ToType);
3288 return Result;
3289 }
3290 if (CXXConversionDecl *Conversion
3291 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3292 // C++ [over.ics.user]p1:
3293 //
3294 // [...] If the user-defined conversion is specified by a
3295 // conversion function (12.3.2), the initial standard
3296 // conversion sequence converts the source type to the
3297 // implicit object parameter of the conversion function.
3298 User.Before = Best->Conversions[0].Standard;
3299 User.HadMultipleCandidates = HadMultipleCandidates;
3300 User.ConversionFunction = Conversion;
3301 User.FoundConversionFunction = Best->FoundDecl;
3302 User.EllipsisConversion = false;
3303
3304 // C++ [over.ics.user]p2:
3305 // The second standard conversion sequence converts the
3306 // result of the user-defined conversion to the target type
3307 // for the sequence. Since an implicit conversion sequence
3308 // is an initialization, the special rules for
3309 // initialization by user-defined conversion apply when
3310 // selecting the best user-defined conversion for a
3311 // user-defined conversion sequence (see 13.3.3 and
3312 // 13.3.3.1).
3313 User.After = Best->FinalConversion;
3314 return Result;
3315 }
3316 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 3316)
;
3317
3318 case OR_No_Viable_Function:
3319 return OR_No_Viable_Function;
3320
3321 case OR_Ambiguous:
3322 return OR_Ambiguous;
3323 }
3324
3325 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 3325)
;
3326}
3327
3328bool
3329Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3330 ImplicitConversionSequence ICS;
3331 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3332 OverloadCandidateSet::CSK_Normal);
3333 OverloadingResult OvResult =
3334 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3335 CandidateSet, false, false);
3336 if (OvResult == OR_Ambiguous)
3337 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3338 << From->getType() << ToType << From->getSourceRange();
3339 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3340 if (!RequireCompleteType(From->getLocStart(), ToType,
3341 diag::err_typecheck_nonviable_condition_incomplete,
3342 From->getType(), From->getSourceRange()))
3343 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3344 << false << From->getType() << From->getSourceRange() << ToType;
3345 } else
3346 return false;
3347 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3348 return true;
3349}
3350
3351/// \brief Compare the user-defined conversion functions or constructors
3352/// of two user-defined conversion sequences to determine whether any ordering
3353/// is possible.
3354static ImplicitConversionSequence::CompareKind
3355compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3356 FunctionDecl *Function2) {
3357 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3358 return ImplicitConversionSequence::Indistinguishable;
3359
3360 // Objective-C++:
3361 // If both conversion functions are implicitly-declared conversions from
3362 // a lambda closure type to a function pointer and a block pointer,
3363 // respectively, always prefer the conversion to a function pointer,
3364 // because the function pointer is more lightweight and is more likely
3365 // to keep code working.
3366 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3367 if (!Conv1)
3368 return ImplicitConversionSequence::Indistinguishable;
3369
3370 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3371 if (!Conv2)
3372 return ImplicitConversionSequence::Indistinguishable;
3373
3374 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3375 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3376 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3377 if (Block1 != Block2)
3378 return Block1 ? ImplicitConversionSequence::Worse
3379 : ImplicitConversionSequence::Better;
3380 }
3381
3382 return ImplicitConversionSequence::Indistinguishable;
3383}
3384
3385static bool hasDeprecatedStringLiteralToCharPtrConversion(
3386 const ImplicitConversionSequence &ICS) {
3387 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3388 (ICS.isUserDefined() &&
3389 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3390}
3391
3392/// CompareImplicitConversionSequences - Compare two implicit
3393/// conversion sequences to determine whether one is better than the
3394/// other or if they are indistinguishable (C++ 13.3.3.2).
3395static ImplicitConversionSequence::CompareKind
3396CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3397 const ImplicitConversionSequence& ICS1,
3398 const ImplicitConversionSequence& ICS2)
3399{
3400 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3401 // conversion sequences (as defined in 13.3.3.1)
3402 // -- a standard conversion sequence (13.3.3.1.1) is a better
3403 // conversion sequence than a user-defined conversion sequence or
3404 // an ellipsis conversion sequence, and
3405 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3406 // conversion sequence than an ellipsis conversion sequence
3407 // (13.3.3.1.3).
3408 //
3409 // C++0x [over.best.ics]p10:
3410 // For the purpose of ranking implicit conversion sequences as
3411 // described in 13.3.3.2, the ambiguous conversion sequence is
3412 // treated as a user-defined sequence that is indistinguishable
3413 // from any other user-defined conversion sequence.
3414
3415 // String literal to 'char *' conversion has been deprecated in C++03. It has
3416 // been removed from C++11. We still accept this conversion, if it happens at
3417 // the best viable function. Otherwise, this conversion is considered worse
3418 // than ellipsis conversion. Consider this as an extension; this is not in the
3419 // standard. For example:
3420 //
3421 // int &f(...); // #1
3422 // void f(char*); // #2
3423 // void g() { int &r = f("foo"); }
3424 //
3425 // In C++03, we pick #2 as the best viable function.
3426 // In C++11, we pick #1 as the best viable function, because ellipsis
3427 // conversion is better than string-literal to char* conversion (since there
3428 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3429 // convert arguments, #2 would be the best viable function in C++11.
3430 // If the best viable function has this conversion, a warning will be issued
3431 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3432
3433 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3434 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3435 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3436 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3437 ? ImplicitConversionSequence::Worse
3438 : ImplicitConversionSequence::Better;
3439
3440 if (ICS1.getKindRank() < ICS2.getKindRank())
3441 return ImplicitConversionSequence::Better;
3442 if (ICS2.getKindRank() < ICS1.getKindRank())
3443 return ImplicitConversionSequence::Worse;
3444
3445 // The following checks require both conversion sequences to be of
3446 // the same kind.
3447 if (ICS1.getKind() != ICS2.getKind())
3448 return ImplicitConversionSequence::Indistinguishable;
3449
3450 ImplicitConversionSequence::CompareKind Result =
3451 ImplicitConversionSequence::Indistinguishable;
3452
3453 // Two implicit conversion sequences of the same form are
3454 // indistinguishable conversion sequences unless one of the
3455 // following rules apply: (C++ 13.3.3.2p3):
3456
3457 // List-initialization sequence L1 is a better conversion sequence than
3458 // list-initialization sequence L2 if:
3459 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3460 // if not that,
3461 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3462 // and N1 is smaller than N2.,
3463 // even if one of the other rules in this paragraph would otherwise apply.
3464 if (!ICS1.isBad()) {
3465 if (ICS1.isStdInitializerListElement() &&
3466 !ICS2.isStdInitializerListElement())
3467 return ImplicitConversionSequence::Better;
3468 if (!ICS1.isStdInitializerListElement() &&
3469 ICS2.isStdInitializerListElement())
3470 return ImplicitConversionSequence::Worse;
3471 }
3472
3473 if (ICS1.isStandard())
3474 // Standard conversion sequence S1 is a better conversion sequence than
3475 // standard conversion sequence S2 if [...]
3476 Result = CompareStandardConversionSequences(S, Loc,
3477 ICS1.Standard, ICS2.Standard);
3478 else if (ICS1.isUserDefined()) {
3479 // User-defined conversion sequence U1 is a better conversion
3480 // sequence than another user-defined conversion sequence U2 if
3481 // they contain the same user-defined conversion function or
3482 // constructor and if the second standard conversion sequence of
3483 // U1 is better than the second standard conversion sequence of
3484 // U2 (C++ 13.3.3.2p3).
3485 if (ICS1.UserDefined.ConversionFunction ==
3486 ICS2.UserDefined.ConversionFunction)
3487 Result = CompareStandardConversionSequences(S, Loc,
3488 ICS1.UserDefined.After,
3489 ICS2.UserDefined.After);
3490 else
3491 Result = compareConversionFunctions(S,
3492 ICS1.UserDefined.ConversionFunction,
3493 ICS2.UserDefined.ConversionFunction);
3494 }
3495
3496 return Result;
3497}
3498
3499static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3500 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3501 Qualifiers Quals;
3502 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3503 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3504 }
3505
3506 return Context.hasSameUnqualifiedType(T1, T2);
3507}
3508
3509// Per 13.3.3.2p3, compare the given standard conversion sequences to
3510// determine if one is a proper subset of the other.
3511static ImplicitConversionSequence::CompareKind
3512compareStandardConversionSubsets(ASTContext &Context,
3513 const StandardConversionSequence& SCS1,
3514 const StandardConversionSequence& SCS2) {
3515 ImplicitConversionSequence::CompareKind Result
3516 = ImplicitConversionSequence::Indistinguishable;
3517
3518 // the identity conversion sequence is considered to be a subsequence of
3519 // any non-identity conversion sequence
3520 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3521 return ImplicitConversionSequence::Better;
3522 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3523 return ImplicitConversionSequence::Worse;
3524
3525 if (SCS1.Second != SCS2.Second) {
3526 if (SCS1.Second == ICK_Identity)
3527 Result = ImplicitConversionSequence::Better;
3528 else if (SCS2.Second == ICK_Identity)
3529 Result = ImplicitConversionSequence::Worse;
3530 else
3531 return ImplicitConversionSequence::Indistinguishable;
3532 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3533 return ImplicitConversionSequence::Indistinguishable;
3534
3535 if (SCS1.Third == SCS2.Third) {
3536 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3537 : ImplicitConversionSequence::Indistinguishable;
3538 }
3539
3540 if (SCS1.Third == ICK_Identity)
3541 return Result == ImplicitConversionSequence::Worse
3542 ? ImplicitConversionSequence::Indistinguishable
3543 : ImplicitConversionSequence::Better;
3544
3545 if (SCS2.Third == ICK_Identity)
3546 return Result == ImplicitConversionSequence::Better
3547 ? ImplicitConversionSequence::Indistinguishable
3548 : ImplicitConversionSequence::Worse;
3549
3550 return ImplicitConversionSequence::Indistinguishable;
3551}
3552
3553/// \brief Determine whether one of the given reference bindings is better
3554/// than the other based on what kind of bindings they are.
3555static bool
3556isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3557 const StandardConversionSequence &SCS2) {
3558 // C++0x [over.ics.rank]p3b4:
3559 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3560 // implicit object parameter of a non-static member function declared
3561 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3562 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3563 // lvalue reference to a function lvalue and S2 binds an rvalue
3564 // reference*.
3565 //
3566 // FIXME: Rvalue references. We're going rogue with the above edits,
3567 // because the semantics in the current C++0x working paper (N3225 at the
3568 // time of this writing) break the standard definition of std::forward
3569 // and std::reference_wrapper when dealing with references to functions.
3570 // Proposed wording changes submitted to CWG for consideration.
3571 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3572 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3573 return false;
3574
3575 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3576 SCS2.IsLvalueReference) ||
3577 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3578 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3579}
3580
3581/// CompareStandardConversionSequences - Compare two standard
3582/// conversion sequences to determine whether one is better than the
3583/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3584static ImplicitConversionSequence::CompareKind
3585CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3586 const StandardConversionSequence& SCS1,
3587 const StandardConversionSequence& SCS2)
3588{
3589 // Standard conversion sequence S1 is a better conversion sequence
3590 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3591
3592 // -- S1 is a proper subsequence of S2 (comparing the conversion
3593 // sequences in the canonical form defined by 13.3.3.1.1,
3594 // excluding any Lvalue Transformation; the identity conversion
3595 // sequence is considered to be a subsequence of any
3596 // non-identity conversion sequence) or, if not that,
3597 if (ImplicitConversionSequence::CompareKind CK
3598 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3599 return CK;
3600
3601 // -- the rank of S1 is better than the rank of S2 (by the rules
3602 // defined below), or, if not that,
3603 ImplicitConversionRank Rank1 = SCS1.getRank();
3604 ImplicitConversionRank Rank2 = SCS2.getRank();
3605 if (Rank1 < Rank2)
3606 return ImplicitConversionSequence::Better;
3607 else if (Rank2 < Rank1)
3608 return ImplicitConversionSequence::Worse;
3609
3610 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3611 // are indistinguishable unless one of the following rules
3612 // applies:
3613
3614 // A conversion that is not a conversion of a pointer, or
3615 // pointer to member, to bool is better than another conversion
3616 // that is such a conversion.
3617 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3618 return SCS2.isPointerConversionToBool()
3619 ? ImplicitConversionSequence::Better
3620 : ImplicitConversionSequence::Worse;
3621
3622 // C++ [over.ics.rank]p4b2:
3623 //
3624 // If class B is derived directly or indirectly from class A,
3625 // conversion of B* to A* is better than conversion of B* to
3626 // void*, and conversion of A* to void* is better than conversion
3627 // of B* to void*.
3628 bool SCS1ConvertsToVoid
3629 = SCS1.isPointerConversionToVoidPointer(S.Context);
3630 bool SCS2ConvertsToVoid
3631 = SCS2.isPointerConversionToVoidPointer(S.Context);
3632 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3633 // Exactly one of the conversion sequences is a conversion to
3634 // a void pointer; it's the worse conversion.
3635 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3636 : ImplicitConversionSequence::Worse;
3637 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3638 // Neither conversion sequence converts to a void pointer; compare
3639 // their derived-to-base conversions.
3640 if (ImplicitConversionSequence::CompareKind DerivedCK
3641 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3642 return DerivedCK;
3643 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3644 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3645 // Both conversion sequences are conversions to void
3646 // pointers. Compare the source types to determine if there's an
3647 // inheritance relationship in their sources.
3648 QualType FromType1 = SCS1.getFromType();
3649 QualType FromType2 = SCS2.getFromType();
3650
3651 // Adjust the types we're converting from via the array-to-pointer
3652 // conversion, if we need to.
3653 if (SCS1.First == ICK_Array_To_Pointer)
3654 FromType1 = S.Context.getArrayDecayedType(FromType1);
3655 if (SCS2.First == ICK_Array_To_Pointer)
3656 FromType2 = S.Context.getArrayDecayedType(FromType2);
3657
3658 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3659 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3660
3661 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3662 return ImplicitConversionSequence::Better;
3663 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3664 return ImplicitConversionSequence::Worse;
3665
3666 // Objective-C++: If one interface is more specific than the
3667 // other, it is the better one.
3668 const ObjCObjectPointerType* FromObjCPtr1
3669 = FromType1->getAs<ObjCObjectPointerType>();
3670 const ObjCObjectPointerType* FromObjCPtr2
3671 = FromType2->getAs<ObjCObjectPointerType>();
3672 if (FromObjCPtr1 && FromObjCPtr2) {
3673 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3674 FromObjCPtr2);
3675 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3676 FromObjCPtr1);
3677 if (AssignLeft != AssignRight) {
3678 return AssignLeft? ImplicitConversionSequence::Better
3679 : ImplicitConversionSequence::Worse;
3680 }
3681 }
3682 }
3683
3684 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3685 // bullet 3).
3686 if (ImplicitConversionSequence::CompareKind QualCK
3687 = CompareQualificationConversions(S, SCS1, SCS2))
3688 return QualCK;
3689
3690 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3691 // Check for a better reference binding based on the kind of bindings.
3692 if (isBetterReferenceBindingKind(SCS1, SCS2))
3693 return ImplicitConversionSequence::Better;
3694 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3695 return ImplicitConversionSequence::Worse;
3696
3697 // C++ [over.ics.rank]p3b4:
3698 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3699 // which the references refer are the same type except for
3700 // top-level cv-qualifiers, and the type to which the reference
3701 // initialized by S2 refers is more cv-qualified than the type
3702 // to which the reference initialized by S1 refers.
3703 QualType T1 = SCS1.getToType(2);
3704 QualType T2 = SCS2.getToType(2);
3705 T1 = S.Context.getCanonicalType(T1);
3706 T2 = S.Context.getCanonicalType(T2);
3707 Qualifiers T1Quals, T2Quals;
3708 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3709 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3710 if (UnqualT1 == UnqualT2) {
3711 // Objective-C++ ARC: If the references refer to objects with different
3712 // lifetimes, prefer bindings that don't change lifetime.
3713 if (SCS1.ObjCLifetimeConversionBinding !=
3714 SCS2.ObjCLifetimeConversionBinding) {
3715 return SCS1.ObjCLifetimeConversionBinding
3716 ? ImplicitConversionSequence::Worse
3717 : ImplicitConversionSequence::Better;
3718 }
3719
3720 // If the type is an array type, promote the element qualifiers to the
3721 // type for comparison.
3722 if (isa<ArrayType>(T1) && T1Quals)
3723 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3724 if (isa<ArrayType>(T2) && T2Quals)
3725 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3726 if (T2.isMoreQualifiedThan(T1))
3727 return ImplicitConversionSequence::Better;
3728 else if (T1.isMoreQualifiedThan(T2))
3729 return ImplicitConversionSequence::Worse;
3730 }
3731 }
3732
3733 // In Microsoft mode, prefer an integral conversion to a
3734 // floating-to-integral conversion if the integral conversion
3735 // is between types of the same size.
3736 // For example:
3737 // void f(float);
3738 // void f(int);
3739 // int main {
3740 // long a;
3741 // f(a);
3742 // }
3743 // Here, MSVC will call f(int) instead of generating a compile error
3744 // as clang will do in standard mode.
3745 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3746 SCS2.Second == ICK_Floating_Integral &&
3747 S.Context.getTypeSize(SCS1.getFromType()) ==
3748 S.Context.getTypeSize(SCS1.getToType(2)))
3749 return ImplicitConversionSequence::Better;
3750
3751 return ImplicitConversionSequence::Indistinguishable;
3752}
3753
3754/// CompareQualificationConversions - Compares two standard conversion
3755/// sequences to determine whether they can be ranked based on their
3756/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3757static ImplicitConversionSequence::CompareKind
3758CompareQualificationConversions(Sema &S,
3759 const StandardConversionSequence& SCS1,
3760 const StandardConversionSequence& SCS2) {
3761 // C++ 13.3.3.2p3:
3762 // -- S1 and S2 differ only in their qualification conversion and
3763 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3764 // cv-qualification signature of type T1 is a proper subset of
3765 // the cv-qualification signature of type T2, and S1 is not the
3766 // deprecated string literal array-to-pointer conversion (4.2).
3767 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3768 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3769 return ImplicitConversionSequence::Indistinguishable;
3770
3771 // FIXME: the example in the standard doesn't use a qualification
3772 // conversion (!)
3773 QualType T1 = SCS1.getToType(2);
3774 QualType T2 = SCS2.getToType(2);
3775 T1 = S.Context.getCanonicalType(T1);
3776 T2 = S.Context.getCanonicalType(T2);
3777 Qualifiers T1Quals, T2Quals;
3778 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3779 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3780
3781 // If the types are the same, we won't learn anything by unwrapped
3782 // them.
3783 if (UnqualT1 == UnqualT2)
3784 return ImplicitConversionSequence::Indistinguishable;
3785
3786 // If the type is an array type, promote the element qualifiers to the type
3787 // for comparison.
3788 if (isa<ArrayType>(T1) && T1Quals)
3789 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3790 if (isa<ArrayType>(T2) && T2Quals)
3791 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3792
3793 ImplicitConversionSequence::CompareKind Result
3794 = ImplicitConversionSequence::Indistinguishable;
3795
3796 // Objective-C++ ARC:
3797 // Prefer qualification conversions not involving a change in lifetime
3798 // to qualification conversions that do not change lifetime.
3799 if (SCS1.QualificationIncludesObjCLifetime !=
3800 SCS2.QualificationIncludesObjCLifetime) {
3801 Result = SCS1.QualificationIncludesObjCLifetime
3802 ? ImplicitConversionSequence::Worse
3803 : ImplicitConversionSequence::Better;
3804 }
3805
3806 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3807 // Within each iteration of the loop, we check the qualifiers to
3808 // determine if this still looks like a qualification
3809 // conversion. Then, if all is well, we unwrap one more level of
3810 // pointers or pointers-to-members and do it all again
3811 // until there are no more pointers or pointers-to-members left
3812 // to unwrap. This essentially mimics what
3813 // IsQualificationConversion does, but here we're checking for a
3814 // strict subset of qualifiers.
3815 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3816 // The qualifiers are the same, so this doesn't tell us anything
3817 // about how the sequences rank.
3818 ;
3819 else if (T2.isMoreQualifiedThan(T1)) {
3820 // T1 has fewer qualifiers, so it could be the better sequence.
3821 if (Result == ImplicitConversionSequence::Worse)
3822 // Neither has qualifiers that are a subset of the other's
3823 // qualifiers.
3824 return ImplicitConversionSequence::Indistinguishable;
3825
3826 Result = ImplicitConversionSequence::Better;
3827 } else if (T1.isMoreQualifiedThan(T2)) {
3828 // T2 has fewer qualifiers, so it could be the better sequence.
3829 if (Result == ImplicitConversionSequence::Better)
3830 // Neither has qualifiers that are a subset of the other's
3831 // qualifiers.
3832 return ImplicitConversionSequence::Indistinguishable;
3833
3834 Result = ImplicitConversionSequence::Worse;
3835 } else {
3836 // Qualifiers are disjoint.
3837 return ImplicitConversionSequence::Indistinguishable;
3838 }
3839
3840 // If the types after this point are equivalent, we're done.
3841 if (S.Context.hasSameUnqualifiedType(T1, T2))
3842 break;
3843 }
3844
3845 // Check that the winning standard conversion sequence isn't using
3846 // the deprecated string literal array to pointer conversion.
3847 switch (Result) {
3848 case ImplicitConversionSequence::Better:
3849 if (SCS1.DeprecatedStringLiteralToCharPtr)
3850 Result = ImplicitConversionSequence::Indistinguishable;
3851 break;
3852
3853 case ImplicitConversionSequence::Indistinguishable:
3854 break;
3855
3856 case ImplicitConversionSequence::Worse:
3857 if (SCS2.DeprecatedStringLiteralToCharPtr)
3858 Result = ImplicitConversionSequence::Indistinguishable;
3859 break;
3860 }
3861
3862 return Result;
3863}
3864
3865/// CompareDerivedToBaseConversions - Compares two standard conversion
3866/// sequences to determine whether they can be ranked based on their
3867/// various kinds of derived-to-base conversions (C++
3868/// [over.ics.rank]p4b3). As part of these checks, we also look at
3869/// conversions between Objective-C interface types.
3870static ImplicitConversionSequence::CompareKind
3871CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3872 const StandardConversionSequence& SCS1,
3873 const StandardConversionSequence& SCS2) {
3874 QualType FromType1 = SCS1.getFromType();
3875 QualType ToType1 = SCS1.getToType(1);
3876 QualType FromType2 = SCS2.getFromType();
3877 QualType ToType2 = SCS2.getToType(1);
3878
3879 // Adjust the types we're converting from via the array-to-pointer
3880 // conversion, if we need to.
3881 if (SCS1.First == ICK_Array_To_Pointer)
3882 FromType1 = S.Context.getArrayDecayedType(FromType1);
3883 if (SCS2.First == ICK_Array_To_Pointer)
3884 FromType2 = S.Context.getArrayDecayedType(FromType2);
3885
3886 // Canonicalize all of the types.
3887 FromType1 = S.Context.getCanonicalType(FromType1);
3888 ToType1 = S.Context.getCanonicalType(ToType1);
3889 FromType2 = S.Context.getCanonicalType(FromType2);
3890 ToType2 = S.Context.getCanonicalType(ToType2);
3891
3892 // C++ [over.ics.rank]p4b3:
3893 //
3894 // If class B is derived directly or indirectly from class A and
3895 // class C is derived directly or indirectly from B,
3896 //
3897 // Compare based on pointer conversions.
3898 if (SCS1.Second == ICK_Pointer_Conversion &&
3899 SCS2.Second == ICK_Pointer_Conversion &&
3900 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3901 FromType1->isPointerType() && FromType2->isPointerType() &&
3902 ToType1->isPointerType() && ToType2->isPointerType()) {
3903 QualType FromPointee1
3904 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3905 QualType ToPointee1
3906 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3907 QualType FromPointee2
3908 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3909 QualType ToPointee2
3910 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3911
3912 // -- conversion of C* to B* is better than conversion of C* to A*,
3913 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3914 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3915 return ImplicitConversionSequence::Better;
3916 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3917 return ImplicitConversionSequence::Worse;
3918 }
3919
3920 // -- conversion of B* to A* is better than conversion of C* to A*,
3921 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3922 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3923 return ImplicitConversionSequence::Better;
3924 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3925 return ImplicitConversionSequence::Worse;
3926 }
3927 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3928 SCS2.Second == ICK_Pointer_Conversion) {
3929 const ObjCObjectPointerType *FromPtr1
3930 = FromType1->getAs<ObjCObjectPointerType>();
3931 const ObjCObjectPointerType *FromPtr2
3932 = FromType2->getAs<ObjCObjectPointerType>();
3933 const ObjCObjectPointerType *ToPtr1
3934 = ToType1->getAs<ObjCObjectPointerType>();
3935 const ObjCObjectPointerType *ToPtr2
3936 = ToType2->getAs<ObjCObjectPointerType>();
3937
3938 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3939 // Apply the same conversion ranking rules for Objective-C pointer types
3940 // that we do for C++ pointers to class types. However, we employ the
3941 // Objective-C pseudo-subtyping relationship used for assignment of
3942 // Objective-C pointer types.
3943 bool FromAssignLeft
3944 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3945 bool FromAssignRight
3946 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3947 bool ToAssignLeft
3948 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3949 bool ToAssignRight
3950 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3951
3952 // A conversion to an a non-id object pointer type or qualified 'id'
3953 // type is better than a conversion to 'id'.
3954 if (ToPtr1->isObjCIdType() &&
3955 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3956 return ImplicitConversionSequence::Worse;
3957 if (ToPtr2->isObjCIdType() &&
3958 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3959 return ImplicitConversionSequence::Better;
3960
3961 // A conversion to a non-id object pointer type is better than a
3962 // conversion to a qualified 'id' type
3963 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3964 return ImplicitConversionSequence::Worse;
3965 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3966 return ImplicitConversionSequence::Better;
3967
3968 // A conversion to an a non-Class object pointer type or qualified 'Class'
3969 // type is better than a conversion to 'Class'.
3970 if (ToPtr1->isObjCClassType() &&
3971 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3972 return ImplicitConversionSequence::Worse;
3973 if (ToPtr2->isObjCClassType() &&
3974 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3975 return ImplicitConversionSequence::Better;
3976
3977 // A conversion to a non-Class object pointer type is better than a
3978 // conversion to a qualified 'Class' type.
3979 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3980 return ImplicitConversionSequence::Worse;
3981 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3982 return ImplicitConversionSequence::Better;
3983
3984 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3985 if (S.Context.hasSameType(FromType1, FromType2) &&
3986 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3987 (ToAssignLeft != ToAssignRight))
3988 return ToAssignLeft? ImplicitConversionSequence::Worse
3989 : ImplicitConversionSequence::Better;
3990
3991 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3992 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3993 (FromAssignLeft != FromAssignRight))
3994 return FromAssignLeft? ImplicitConversionSequence::Better
3995 : ImplicitConversionSequence::Worse;
3996 }
3997 }
3998
3999 // Ranking of member-pointer types.
4000 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4001 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4002 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4003 const MemberPointerType * FromMemPointer1 =
4004 FromType1->getAs<MemberPointerType>();
4005 const MemberPointerType * ToMemPointer1 =
4006 ToType1->getAs<MemberPointerType>();
4007 const MemberPointerType * FromMemPointer2 =
4008 FromType2->getAs<MemberPointerType>();
4009 const MemberPointerType * ToMemPointer2 =
4010 ToType2->getAs<MemberPointerType>();
4011 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4012 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4013 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4014 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4015 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4016 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4017 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4018 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4019 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4020 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4021 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4022 return ImplicitConversionSequence::Worse;
4023 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4024 return ImplicitConversionSequence::Better;
4025 }
4026 // conversion of B::* to C::* is better than conversion of A::* to C::*
4027 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4028 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4029 return ImplicitConversionSequence::Better;
4030 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4031 return ImplicitConversionSequence::Worse;
4032 }
4033 }
4034
4035 if (SCS1.Second == ICK_Derived_To_Base) {
4036 // -- conversion of C to B is better than conversion of C to A,
4037 // -- binding of an expression of type C to a reference of type
4038 // B& is better than binding an expression of type C to a
4039 // reference of type A&,
4040 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4041 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4042 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4043 return ImplicitConversionSequence::Better;
4044 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4045 return ImplicitConversionSequence::Worse;
4046 }
4047
4048 // -- conversion of B to A is better than conversion of C to A.
4049 // -- binding of an expression of type B to a reference of type
4050 // A& is better than binding an expression of type C to a
4051 // reference of type A&,
4052 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4053 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4054 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4055 return ImplicitConversionSequence::Better;
4056 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4057 return ImplicitConversionSequence::Worse;
4058 }
4059 }
4060
4061 return ImplicitConversionSequence::Indistinguishable;
4062}
4063
4064/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4065/// C++ class.
4066static bool isTypeValid(QualType T) {
4067 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4068 return !Record->isInvalidDecl();
4069
4070 return true;
4071}
4072
4073/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4074/// determine whether they are reference-related,
4075/// reference-compatible, reference-compatible with added
4076/// qualification, or incompatible, for use in C++ initialization by
4077/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4078/// type, and the first type (T1) is the pointee type of the reference
4079/// type being initialized.
4080Sema::ReferenceCompareResult
4081Sema::CompareReferenceRelationship(SourceLocation Loc,
4082 QualType OrigT1, QualType OrigT2,
4083 bool &DerivedToBase,
4084 bool &ObjCConversion,
4085 bool &ObjCLifetimeConversion) {
4086 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4087, __PRETTY_FUNCTION__))
4087 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4087, __PRETTY_FUNCTION__))
;
4088 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4088, __PRETTY_FUNCTION__))
;
4089
4090 QualType T1 = Context.getCanonicalType(OrigT1);
4091 QualType T2 = Context.getCanonicalType(OrigT2);
4092 Qualifiers T1Quals, T2Quals;
4093 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4094 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4095
4096 // C++ [dcl.init.ref]p4:
4097 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4098 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4099 // T1 is a base class of T2.
4100 DerivedToBase = false;
4101 ObjCConversion = false;
4102 ObjCLifetimeConversion = false;
4103 if (UnqualT1 == UnqualT2) {
4104 // Nothing to do.
4105 } else if (isCompleteType(Loc, OrigT2) &&
4106 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4107 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4108 DerivedToBase = true;
4109 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4110 UnqualT2->isObjCObjectOrInterfaceType() &&
4111 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4112 ObjCConversion = true;
4113 else
4114 return Ref_Incompatible;
4115
4116 // At this point, we know that T1 and T2 are reference-related (at
4117 // least).
4118
4119 // If the type is an array type, promote the element qualifiers to the type
4120 // for comparison.
4121 if (isa<ArrayType>(T1) && T1Quals)
4122 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4123 if (isa<ArrayType>(T2) && T2Quals)
4124 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4125
4126 // C++ [dcl.init.ref]p4:
4127 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4128 // reference-related to T2 and cv1 is the same cv-qualification
4129 // as, or greater cv-qualification than, cv2. For purposes of
4130 // overload resolution, cases for which cv1 is greater
4131 // cv-qualification than cv2 are identified as
4132 // reference-compatible with added qualification (see 13.3.3.2).
4133 //
4134 // Note that we also require equivalence of Objective-C GC and address-space
4135 // qualifiers when performing these computations, so that e.g., an int in
4136 // address space 1 is not reference-compatible with an int in address
4137 // space 2.
4138 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4139 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4140 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4141 ObjCLifetimeConversion = true;
4142
4143 T1Quals.removeObjCLifetime();
4144 T2Quals.removeObjCLifetime();
4145 }
4146
4147 if (T1Quals == T2Quals)
4148 return Ref_Compatible;
4149 else if (T1Quals.compatiblyIncludes(T2Quals))
4150 return Ref_Compatible_With_Added_Qualification;
4151 else
4152 return Ref_Related;
4153}
4154
4155/// \brief Look for a user-defined conversion to an value reference-compatible
4156/// with DeclType. Return true if something definite is found.
4157static bool
4158FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4159 QualType DeclType, SourceLocation DeclLoc,
4160 Expr *Init, QualType T2, bool AllowRvalues,
4161 bool AllowExplicit) {
4162 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4162, __PRETTY_FUNCTION__))
;
4163 CXXRecordDecl *T2RecordDecl
4164 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4165
4166 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4167 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4168 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4169 NamedDecl *D = *I;
4170 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4171 if (isa<UsingShadowDecl>(D))
4172 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4173
4174 FunctionTemplateDecl *ConvTemplate
4175 = dyn_cast<FunctionTemplateDecl>(D);
4176 CXXConversionDecl *Conv;
4177 if (ConvTemplate)
4178 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4179 else
4180 Conv = cast<CXXConversionDecl>(D);
4181
4182 // If this is an explicit conversion, and we're not allowed to consider
4183 // explicit conversions, skip it.
4184 if (!AllowExplicit && Conv->isExplicit())
4185 continue;
4186
4187 if (AllowRvalues) {
4188 bool DerivedToBase = false;
4189 bool ObjCConversion = false;
4190 bool ObjCLifetimeConversion = false;
4191
4192 // If we are initializing an rvalue reference, don't permit conversion
4193 // functions that return lvalues.
4194 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4195 const ReferenceType *RefType
4196 = Conv->getConversionType()->getAs<LValueReferenceType>();
4197 if (RefType && !RefType->getPointeeType()->isFunctionType())
4198 continue;
4199 }
4200
4201 if (!ConvTemplate &&
4202 S.CompareReferenceRelationship(
4203 DeclLoc,
4204 Conv->getConversionType().getNonReferenceType()
4205 .getUnqualifiedType(),
4206 DeclType.getNonReferenceType().getUnqualifiedType(),
4207 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4208 Sema::Ref_Incompatible)
4209 continue;
4210 } else {
4211 // If the conversion function doesn't return a reference type,
4212 // it can't be considered for this conversion. An rvalue reference
4213 // is only acceptable if its referencee is a function type.
4214
4215 const ReferenceType *RefType =
4216 Conv->getConversionType()->getAs<ReferenceType>();
4217 if (!RefType ||
4218 (!RefType->isLValueReferenceType() &&
4219 !RefType->getPointeeType()->isFunctionType()))
4220 continue;
4221 }
4222
4223 if (ConvTemplate)
4224 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4225 Init, DeclType, CandidateSet,
4226 /*AllowObjCConversionOnExplicit=*/false);
4227 else
4228 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4229 DeclType, CandidateSet,
4230 /*AllowObjCConversionOnExplicit=*/false);
4231 }
4232
4233 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4234
4235 OverloadCandidateSet::iterator Best;
4236 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4237 case OR_Success:
4238 // C++ [over.ics.ref]p1:
4239 //
4240 // [...] If the parameter binds directly to the result of
4241 // applying a conversion function to the argument
4242 // expression, the implicit conversion sequence is a
4243 // user-defined conversion sequence (13.3.3.1.2), with the
4244 // second standard conversion sequence either an identity
4245 // conversion or, if the conversion function returns an
4246 // entity of a type that is a derived class of the parameter
4247 // type, a derived-to-base Conversion.
4248 if (!Best->FinalConversion.DirectBinding)
4249 return false;
4250
4251 ICS.setUserDefined();
4252 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4253 ICS.UserDefined.After = Best->FinalConversion;
4254 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4255 ICS.UserDefined.ConversionFunction = Best->Function;
4256 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4257 ICS.UserDefined.EllipsisConversion = false;
4258 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4260, __PRETTY_FUNCTION__))
4259 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4260, __PRETTY_FUNCTION__))
4260 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4260, __PRETTY_FUNCTION__))
;
4261 return true;
4262
4263 case OR_Ambiguous:
4264 ICS.setAmbiguous();
4265 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4266 Cand != CandidateSet.end(); ++Cand)
4267 if (Cand->Viable)
4268 ICS.Ambiguous.addConversion(Cand->Function);
4269 return true;
4270
4271 case OR_No_Viable_Function:
4272 case OR_Deleted:
4273 // There was no suitable conversion, or we found a deleted
4274 // conversion; continue with other checks.
4275 return false;
4276 }
4277
4278 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4278)
;
4279}
4280
4281/// \brief Compute an implicit conversion sequence for reference
4282/// initialization.
4283static ImplicitConversionSequence
4284TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4285 SourceLocation DeclLoc,
4286 bool SuppressUserConversions,
4287 bool AllowExplicit) {
4288 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4288, __PRETTY_FUNCTION__))
;
4289
4290 // Most paths end in a failed conversion.
4291 ImplicitConversionSequence ICS;
4292 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4293
4294 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4295 QualType T2 = Init->getType();
4296
4297 // If the initializer is the address of an overloaded function, try
4298 // to resolve the overloaded function. If all goes well, T2 is the
4299 // type of the resulting function.
4300 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4301 DeclAccessPair Found;
4302 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4303 false, Found))
4304 T2 = Fn->getType();
4305 }
4306
4307 // Compute some basic properties of the types and the initializer.
4308 bool isRValRef = DeclType->isRValueReferenceType();
4309 bool DerivedToBase = false;
4310 bool ObjCConversion = false;
4311 bool ObjCLifetimeConversion = false;
4312 Expr::Classification InitCategory = Init->Classify(S.Context);
4313 Sema::ReferenceCompareResult RefRelationship
4314 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4315 ObjCConversion, ObjCLifetimeConversion);
4316
4317
4318 // C++0x [dcl.init.ref]p5:
4319 // A reference to type "cv1 T1" is initialized by an expression
4320 // of type "cv2 T2" as follows:
4321
4322 // -- If reference is an lvalue reference and the initializer expression
4323 if (!isRValRef) {
4324 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4325 // reference-compatible with "cv2 T2," or
4326 //
4327 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4328 if (InitCategory.isLValue() &&
4329 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4330 // C++ [over.ics.ref]p1:
4331 // When a parameter of reference type binds directly (8.5.3)
4332 // to an argument expression, the implicit conversion sequence
4333 // is the identity conversion, unless the argument expression
4334 // has a type that is a derived class of the parameter type,
4335 // in which case the implicit conversion sequence is a
4336 // derived-to-base Conversion (13.3.3.1).
4337 ICS.setStandard();
4338 ICS.Standard.First = ICK_Identity;
4339 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4340 : ObjCConversion? ICK_Compatible_Conversion
4341 : ICK_Identity;
4342 ICS.Standard.Third = ICK_Identity;
4343 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4344 ICS.Standard.setToType(0, T2);
4345 ICS.Standard.setToType(1, T1);
4346 ICS.Standard.setToType(2, T1);
4347 ICS.Standard.ReferenceBinding = true;
4348 ICS.Standard.DirectBinding = true;
4349 ICS.Standard.IsLvalueReference = !isRValRef;
4350 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4351 ICS.Standard.BindsToRvalue = false;
4352 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4353 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4354 ICS.Standard.CopyConstructor = nullptr;
4355 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4356
4357 // Nothing more to do: the inaccessibility/ambiguity check for
4358 // derived-to-base conversions is suppressed when we're
4359 // computing the implicit conversion sequence (C++
4360 // [over.best.ics]p2).
4361 return ICS;
4362 }
4363
4364 // -- has a class type (i.e., T2 is a class type), where T1 is
4365 // not reference-related to T2, and can be implicitly
4366 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4367 // is reference-compatible with "cv3 T3" 92) (this
4368 // conversion is selected by enumerating the applicable
4369 // conversion functions (13.3.1.6) and choosing the best
4370 // one through overload resolution (13.3)),
4371 if (!SuppressUserConversions && T2->isRecordType() &&
4372 S.isCompleteType(DeclLoc, T2) &&
4373 RefRelationship == Sema::Ref_Incompatible) {
4374 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4375 Init, T2, /*AllowRvalues=*/false,
4376 AllowExplicit))
4377 return ICS;
4378 }
4379 }
4380
4381 // -- Otherwise, the reference shall be an lvalue reference to a
4382 // non-volatile const type (i.e., cv1 shall be const), or the reference
4383 // shall be an rvalue reference.
4384 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4385 return ICS;
4386
4387 // -- If the initializer expression
4388 //
4389 // -- is an xvalue, class prvalue, array prvalue or function
4390 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4391 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4392 (InitCategory.isXValue() ||
4393 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4394 (InitCategory.isLValue() && T2->isFunctionType()))) {
4395 ICS.setStandard();
4396 ICS.Standard.First = ICK_Identity;
4397 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4398 : ObjCConversion? ICK_Compatible_Conversion
4399 : ICK_Identity;
4400 ICS.Standard.Third = ICK_Identity;
4401 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4402 ICS.Standard.setToType(0, T2);
4403 ICS.Standard.setToType(1, T1);
4404 ICS.Standard.setToType(2, T1);
4405 ICS.Standard.ReferenceBinding = true;
4406 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4407 // binding unless we're binding to a class prvalue.
4408 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4409 // allow the use of rvalue references in C++98/03 for the benefit of
4410 // standard library implementors; therefore, we need the xvalue check here.
4411 ICS.Standard.DirectBinding =
4412 S.getLangOpts().CPlusPlus11 ||
4413 !(InitCategory.isPRValue() || T2->isRecordType());
4414 ICS.Standard.IsLvalueReference = !isRValRef;
4415 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4416 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4417 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4418 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4419 ICS.Standard.CopyConstructor = nullptr;
4420 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4421 return ICS;
4422 }
4423
4424 // -- has a class type (i.e., T2 is a class type), where T1 is not
4425 // reference-related to T2, and can be implicitly converted to
4426 // an xvalue, class prvalue, or function lvalue of type
4427 // "cv3 T3", where "cv1 T1" is reference-compatible with
4428 // "cv3 T3",
4429 //
4430 // then the reference is bound to the value of the initializer
4431 // expression in the first case and to the result of the conversion
4432 // in the second case (or, in either case, to an appropriate base
4433 // class subobject).
4434 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4435 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4436 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4437 Init, T2, /*AllowRvalues=*/true,
4438 AllowExplicit)) {
4439 // In the second case, if the reference is an rvalue reference
4440 // and the second standard conversion sequence of the
4441 // user-defined conversion sequence includes an lvalue-to-rvalue
4442 // conversion, the program is ill-formed.
4443 if (ICS.isUserDefined() && isRValRef &&
4444 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4445 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4446
4447 return ICS;
4448 }
4449
4450 // A temporary of function type cannot be created; don't even try.
4451 if (T1->isFunctionType())
4452 return ICS;
4453
4454 // -- Otherwise, a temporary of type "cv1 T1" is created and
4455 // initialized from the initializer expression using the
4456 // rules for a non-reference copy initialization (8.5). The
4457 // reference is then bound to the temporary. If T1 is
4458 // reference-related to T2, cv1 must be the same
4459 // cv-qualification as, or greater cv-qualification than,
4460 // cv2; otherwise, the program is ill-formed.
4461 if (RefRelationship == Sema::Ref_Related) {
4462 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4463 // we would be reference-compatible or reference-compatible with
4464 // added qualification. But that wasn't the case, so the reference
4465 // initialization fails.
4466 //
4467 // Note that we only want to check address spaces and cvr-qualifiers here.
4468 // ObjC GC and lifetime qualifiers aren't important.
4469 Qualifiers T1Quals = T1.getQualifiers();
4470 Qualifiers T2Quals = T2.getQualifiers();
4471 T1Quals.removeObjCGCAttr();
4472 T1Quals.removeObjCLifetime();
4473 T2Quals.removeObjCGCAttr();
4474 T2Quals.removeObjCLifetime();
4475 if (!T1Quals.compatiblyIncludes(T2Quals))
4476 return ICS;
4477 }
4478
4479 // If at least one of the types is a class type, the types are not
4480 // related, and we aren't allowed any user conversions, the
4481 // reference binding fails. This case is important for breaking
4482 // recursion, since TryImplicitConversion below will attempt to
4483 // create a temporary through the use of a copy constructor.
4484 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4485 (T1->isRecordType() || T2->isRecordType()))
4486 return ICS;
4487
4488 // If T1 is reference-related to T2 and the reference is an rvalue
4489 // reference, the initializer expression shall not be an lvalue.
4490 if (RefRelationship >= Sema::Ref_Related &&
4491 isRValRef && Init->Classify(S.Context).isLValue())
4492 return ICS;
4493
4494 // C++ [over.ics.ref]p2:
4495 // When a parameter of reference type is not bound directly to
4496 // an argument expression, the conversion sequence is the one
4497 // required to convert the argument expression to the
4498 // underlying type of the reference according to
4499 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4500 // to copy-initializing a temporary of the underlying type with
4501 // the argument expression. Any difference in top-level
4502 // cv-qualification is subsumed by the initialization itself
4503 // and does not constitute a conversion.
4504 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4505 /*AllowExplicit=*/false,
4506 /*InOverloadResolution=*/false,
4507 /*CStyle=*/false,
4508 /*AllowObjCWritebackConversion=*/false,
4509 /*AllowObjCConversionOnExplicit=*/false);
4510
4511 // Of course, that's still a reference binding.
4512 if (ICS.isStandard()) {
4513 ICS.Standard.ReferenceBinding = true;
4514 ICS.Standard.IsLvalueReference = !isRValRef;
4515 ICS.Standard.BindsToFunctionLvalue = false;
4516 ICS.Standard.BindsToRvalue = true;
4517 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4518 ICS.Standard.ObjCLifetimeConversionBinding = false;
4519 } else if (ICS.isUserDefined()) {
4520 const ReferenceType *LValRefType =
4521 ICS.UserDefined.ConversionFunction->getReturnType()
4522 ->getAs<LValueReferenceType>();
4523
4524 // C++ [over.ics.ref]p3:
4525 // Except for an implicit object parameter, for which see 13.3.1, a
4526 // standard conversion sequence cannot be formed if it requires [...]
4527 // binding an rvalue reference to an lvalue other than a function
4528 // lvalue.
4529 // Note that the function case is not possible here.
4530 if (DeclType->isRValueReferenceType() && LValRefType) {
4531 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4532 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4533 // reference to an rvalue!
4534 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4535 return ICS;
4536 }
4537
4538 ICS.UserDefined.Before.setAsIdentityConversion();
4539 ICS.UserDefined.After.ReferenceBinding = true;
4540 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4541 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4542 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4543 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4544 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4545 }
4546
4547 return ICS;
4548}
4549
4550static ImplicitConversionSequence
4551TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4552 bool SuppressUserConversions,
4553 bool InOverloadResolution,
4554 bool AllowObjCWritebackConversion,
4555 bool AllowExplicit = false);
4556
4557/// TryListConversion - Try to copy-initialize a value of type ToType from the
4558/// initializer list From.
4559static ImplicitConversionSequence
4560TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4561 bool SuppressUserConversions,
4562 bool InOverloadResolution,
4563 bool AllowObjCWritebackConversion) {
4564 // C++11 [over.ics.list]p1:
4565 // When an argument is an initializer list, it is not an expression and
4566 // special rules apply for converting it to a parameter type.
4567
4568 ImplicitConversionSequence Result;
4569 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4570
4571 // We need a complete type for what follows. Incomplete types can never be
4572 // initialized from init lists.
4573 if (!S.isCompleteType(From->getLocStart(), ToType))
4574 return Result;
4575
4576 // Per DR1467:
4577 // If the parameter type is a class X and the initializer list has a single
4578 // element of type cv U, where U is X or a class derived from X, the
4579 // implicit conversion sequence is the one required to convert the element
4580 // to the parameter type.
4581 //
4582 // Otherwise, if the parameter type is a character array [... ]
4583 // and the initializer list has a single element that is an
4584 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4585 // implicit conversion sequence is the identity conversion.
4586 if (From->getNumInits() == 1) {
4587 if (ToType->isRecordType()) {
4588 QualType InitType = From->getInit(0)->getType();
4589 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4590 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4591 return TryCopyInitialization(S, From->getInit(0), ToType,
4592 SuppressUserConversions,
4593 InOverloadResolution,
4594 AllowObjCWritebackConversion);
4595 }
4596 // FIXME: Check the other conditions here: array of character type,
4597 // initializer is a string literal.
4598 if (ToType->isArrayType()) {
4599 InitializedEntity Entity =
4600 InitializedEntity::InitializeParameter(S.Context, ToType,
4601 /*Consumed=*/false);
4602 if (S.CanPerformCopyInitialization(Entity, From)) {
4603 Result.setStandard();
4604 Result.Standard.setAsIdentityConversion();
4605 Result.Standard.setFromType(ToType);
4606 Result.Standard.setAllToTypes(ToType);
4607 return Result;
4608 }
4609 }
4610 }
4611
4612 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4613 // C++11 [over.ics.list]p2:
4614 // If the parameter type is std::initializer_list<X> or "array of X" and
4615 // all the elements can be implicitly converted to X, the implicit
4616 // conversion sequence is the worst conversion necessary to convert an
4617 // element of the list to X.
4618 //
4619 // C++14 [over.ics.list]p3:
4620 // Otherwise, if the parameter type is "array of N X", if the initializer
4621 // list has exactly N elements or if it has fewer than N elements and X is
4622 // default-constructible, and if all the elements of the initializer list
4623 // can be implicitly converted to X, the implicit conversion sequence is
4624 // the worst conversion necessary to convert an element of the list to X.
4625 //
4626 // FIXME: We're missing a lot of these checks.
4627 bool toStdInitializerList = false;
4628 QualType X;
4629 if (ToType->isArrayType())
4630 X = S.Context.getAsArrayType(ToType)->getElementType();
4631 else
4632 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4633 if (!X.isNull()) {
4634 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4635 Expr *Init = From->getInit(i);
4636 ImplicitConversionSequence ICS =
4637 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4638 InOverloadResolution,
4639 AllowObjCWritebackConversion);
4640 // If a single element isn't convertible, fail.
4641 if (ICS.isBad()) {
4642 Result = ICS;
4643 break;
4644 }
4645 // Otherwise, look for the worst conversion.
4646 if (Result.isBad() ||
4647 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4648 Result) ==
4649 ImplicitConversionSequence::Worse)
4650 Result = ICS;
4651 }
4652
4653 // For an empty list, we won't have computed any conversion sequence.
4654 // Introduce the identity conversion sequence.
4655 if (From->getNumInits() == 0) {
4656 Result.setStandard();
4657 Result.Standard.setAsIdentityConversion();
4658 Result.Standard.setFromType(ToType);
4659 Result.Standard.setAllToTypes(ToType);
4660 }
4661
4662 Result.setStdInitializerListElement(toStdInitializerList);
4663 return Result;
4664 }
4665
4666 // C++14 [over.ics.list]p4:
4667 // C++11 [over.ics.list]p3:
4668 // Otherwise, if the parameter is a non-aggregate class X and overload
4669 // resolution chooses a single best constructor [...] the implicit
4670 // conversion sequence is a user-defined conversion sequence. If multiple
4671 // constructors are viable but none is better than the others, the
4672 // implicit conversion sequence is a user-defined conversion sequence.
4673 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4674 // This function can deal with initializer lists.
4675 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4676 /*AllowExplicit=*/false,
4677 InOverloadResolution, /*CStyle=*/false,
4678 AllowObjCWritebackConversion,
4679 /*AllowObjCConversionOnExplicit=*/false);
4680 }
4681
4682 // C++14 [over.ics.list]p5:
4683 // C++11 [over.ics.list]p4:
4684 // Otherwise, if the parameter has an aggregate type which can be
4685 // initialized from the initializer list [...] the implicit conversion
4686 // sequence is a user-defined conversion sequence.
4687 if (ToType->isAggregateType()) {
4688 // Type is an aggregate, argument is an init list. At this point it comes
4689 // down to checking whether the initialization works.
4690 // FIXME: Find out whether this parameter is consumed or not.
4691 InitializedEntity Entity =
4692 InitializedEntity::InitializeParameter(S.Context, ToType,
4693 /*Consumed=*/false);
4694 if (S.CanPerformCopyInitialization(Entity, From)) {
4695 Result.setUserDefined();
4696 Result.UserDefined.Before.setAsIdentityConversion();
4697 // Initializer lists don't have a type.
4698 Result.UserDefined.Before.setFromType(QualType());
4699 Result.UserDefined.Before.setAllToTypes(QualType());
4700
4701 Result.UserDefined.After.setAsIdentityConversion();
4702 Result.UserDefined.After.setFromType(ToType);
4703 Result.UserDefined.After.setAllToTypes(ToType);
4704 Result.UserDefined.ConversionFunction = nullptr;
4705 }
4706 return Result;
4707 }
4708
4709 // C++14 [over.ics.list]p6:
4710 // C++11 [over.ics.list]p5:
4711 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4712 if (ToType->isReferenceType()) {
4713 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4714 // mention initializer lists in any way. So we go by what list-
4715 // initialization would do and try to extrapolate from that.
4716
4717 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4718
4719 // If the initializer list has a single element that is reference-related
4720 // to the parameter type, we initialize the reference from that.
4721 if (From->getNumInits() == 1) {
4722 Expr *Init = From->getInit(0);
4723
4724 QualType T2 = Init->getType();
4725
4726 // If the initializer is the address of an overloaded function, try
4727 // to resolve the overloaded function. If all goes well, T2 is the
4728 // type of the resulting function.
4729 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4730 DeclAccessPair Found;
4731 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4732 Init, ToType, false, Found))
4733 T2 = Fn->getType();
4734 }
4735
4736 // Compute some basic properties of the types and the initializer.
4737 bool dummy1 = false;
4738 bool dummy2 = false;
4739 bool dummy3 = false;
4740 Sema::ReferenceCompareResult RefRelationship
4741 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4742 dummy2, dummy3);
4743
4744 if (RefRelationship >= Sema::Ref_Related) {
4745 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4746 SuppressUserConversions,
4747 /*AllowExplicit=*/false);
4748 }
4749 }
4750
4751 // Otherwise, we bind the reference to a temporary created from the
4752 // initializer list.
4753 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4754 InOverloadResolution,
4755 AllowObjCWritebackConversion);
4756 if (Result.isFailure())
4757 return Result;
4758 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4759, __PRETTY_FUNCTION__))
4759 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4759, __PRETTY_FUNCTION__))
;
4760
4761 // Can we even bind to a temporary?
4762 if (ToType->isRValueReferenceType() ||
4763 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4764 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4765 Result.UserDefined.After;
4766 SCS.ReferenceBinding = true;
4767 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4768 SCS.BindsToRvalue = true;
4769 SCS.BindsToFunctionLvalue = false;
4770 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4771 SCS.ObjCLifetimeConversionBinding = false;
4772 } else
4773 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4774 From, ToType);
4775 return Result;
4776 }
4777
4778 // C++14 [over.ics.list]p7:
4779 // C++11 [over.ics.list]p6:
4780 // Otherwise, if the parameter type is not a class:
4781 if (!ToType->isRecordType()) {
4782 // - if the initializer list has one element that is not itself an
4783 // initializer list, the implicit conversion sequence is the one
4784 // required to convert the element to the parameter type.
4785 unsigned NumInits = From->getNumInits();
4786 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4787 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4788 SuppressUserConversions,
4789 InOverloadResolution,
4790 AllowObjCWritebackConversion);
4791 // - if the initializer list has no elements, the implicit conversion
4792 // sequence is the identity conversion.
4793 else if (NumInits == 0) {
4794 Result.setStandard();
4795 Result.Standard.setAsIdentityConversion();
4796 Result.Standard.setFromType(ToType);
4797 Result.Standard.setAllToTypes(ToType);
4798 }
4799 return Result;
4800 }
4801
4802 // C++14 [over.ics.list]p8:
4803 // C++11 [over.ics.list]p7:
4804 // In all cases other than those enumerated above, no conversion is possible
4805 return Result;
4806}
4807
4808/// TryCopyInitialization - Try to copy-initialize a value of type
4809/// ToType from the expression From. Return the implicit conversion
4810/// sequence required to pass this argument, which may be a bad
4811/// conversion sequence (meaning that the argument cannot be passed to
4812/// a parameter of this type). If @p SuppressUserConversions, then we
4813/// do not permit any user-defined conversion sequences.
4814static ImplicitConversionSequence
4815TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4816 bool SuppressUserConversions,
4817 bool InOverloadResolution,
4818 bool AllowObjCWritebackConversion,
4819 bool AllowExplicit) {
4820 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4821 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4822 InOverloadResolution,AllowObjCWritebackConversion);
4823
4824 if (ToType->isReferenceType())
4825 return TryReferenceInit(S, From, ToType,
4826 /*FIXME:*/From->getLocStart(),
4827 SuppressUserConversions,
4828 AllowExplicit);
4829
4830 return TryImplicitConversion(S, From, ToType,
4831 SuppressUserConversions,
4832 /*AllowExplicit=*/false,
4833 InOverloadResolution,
4834 /*CStyle=*/false,
4835 AllowObjCWritebackConversion,
4836 /*AllowObjCConversionOnExplicit=*/false);
4837}
4838
4839static bool TryCopyInitialization(const CanQualType FromQTy,
4840 const CanQualType ToQTy,
4841 Sema &S,
4842 SourceLocation Loc,
4843 ExprValueKind FromVK) {
4844 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4845 ImplicitConversionSequence ICS =
4846 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4847
4848 return !ICS.isBad();
4849}
4850
4851/// TryObjectArgumentInitialization - Try to initialize the object
4852/// parameter of the given member function (@c Method) from the
4853/// expression @p From.
4854static ImplicitConversionSequence
4855TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4856 Expr::Classification FromClassification,
4857 CXXMethodDecl *Method,
4858 CXXRecordDecl *ActingContext) {
4859 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4860 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4861 // const volatile object.
4862 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4863 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4864 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4865
4866 // Set up the conversion sequence as a "bad" conversion, to allow us
4867 // to exit early.
4868 ImplicitConversionSequence ICS;
4869
4870 // We need to have an object of class type.
4871 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4872 FromType = PT->getPointeeType();
4873
4874 // When we had a pointer, it's implicitly dereferenced, so we
4875 // better have an lvalue.
4876 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4876, __PRETTY_FUNCTION__))
;
4877 }
4878
4879 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 4879, __PRETTY_FUNCTION__))
;
4880
4881 // C++0x [over.match.funcs]p4:
4882 // For non-static member functions, the type of the implicit object
4883 // parameter is
4884 //
4885 // - "lvalue reference to cv X" for functions declared without a
4886 // ref-qualifier or with the & ref-qualifier
4887 // - "rvalue reference to cv X" for functions declared with the &&
4888 // ref-qualifier
4889 //
4890 // where X is the class of which the function is a member and cv is the
4891 // cv-qualification on the member function declaration.
4892 //
4893 // However, when finding an implicit conversion sequence for the argument, we
4894 // are not allowed to create temporaries or perform user-defined conversions
4895 // (C++ [over.match.funcs]p5). We perform a simplified version of
4896 // reference binding here, that allows class rvalues to bind to
4897 // non-constant references.
4898
4899 // First check the qualifiers.
4900 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4901 if (ImplicitParamType.getCVRQualifiers()
4902 != FromTypeCanon.getLocalCVRQualifiers() &&
4903 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4904 ICS.setBad(BadConversionSequence::bad_qualifiers,
4905 FromType, ImplicitParamType);
4906 return ICS;
4907 }
4908
4909 // Check that we have either the same type or a derived type. It
4910 // affects the conversion rank.
4911 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4912 ImplicitConversionKind SecondKind;
4913 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4914 SecondKind = ICK_Identity;
4915 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4916 SecondKind = ICK_Derived_To_Base;
4917 else {
4918 ICS.setBad(BadConversionSequence::unrelated_class,
4919 FromType, ImplicitParamType);
4920 return ICS;
4921 }
4922
4923 // Check the ref-qualifier.
4924 switch (Method->getRefQualifier()) {
4925 case RQ_None:
4926 // Do nothing; we don't care about lvalueness or rvalueness.
4927 break;
4928
4929 case RQ_LValue:
4930 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4931 // non-const lvalue reference cannot bind to an rvalue
4932 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4933 ImplicitParamType);
4934 return ICS;
4935 }
4936 break;
4937
4938 case RQ_RValue:
4939 if (!FromClassification.isRValue()) {
4940 // rvalue reference cannot bind to an lvalue
4941 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4942 ImplicitParamType);
4943 return ICS;
4944 }
4945 break;
4946 }
4947
4948 // Success. Mark this as a reference binding.
4949 ICS.setStandard();
4950 ICS.Standard.setAsIdentityConversion();
4951 ICS.Standard.Second = SecondKind;
4952 ICS.Standard.setFromType(FromType);
4953 ICS.Standard.setAllToTypes(ImplicitParamType);
4954 ICS.Standard.ReferenceBinding = true;
4955 ICS.Standard.DirectBinding = true;
4956 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4957 ICS.Standard.BindsToFunctionLvalue = false;
4958 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4959 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4960 = (Method->getRefQualifier() == RQ_None);
4961 return ICS;
4962}
4963
4964/// PerformObjectArgumentInitialization - Perform initialization of
4965/// the implicit object parameter for the given Method with the given
4966/// expression.
4967ExprResult
4968Sema::PerformObjectArgumentInitialization(Expr *From,
4969 NestedNameSpecifier *Qualifier,
4970 NamedDecl *FoundDecl,
4971 CXXMethodDecl *Method) {
4972 QualType FromRecordType, DestType;
4973 QualType ImplicitParamRecordType =
4974 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4975
4976 Expr::Classification FromClassification;
4977 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4978 FromRecordType = PT->getPointeeType();
4979 DestType = Method->getThisType(Context);
4980 FromClassification = Expr::Classification::makeSimpleLValue();
4981 } else {
4982 FromRecordType = From->getType();
4983 DestType = ImplicitParamRecordType;
4984 FromClassification = From->Classify(Context);
4985 }
4986
4987 // Note that we always use the true parent context when performing
4988 // the actual argument initialization.
4989 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4990 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4991 Method->getParent());
4992 if (ICS.isBad()) {
4993 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4994 Qualifiers FromQs = FromRecordType.getQualifiers();
4995 Qualifiers ToQs = DestType.getQualifiers();
4996 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4997 if (CVR) {
4998 Diag(From->getLocStart(),
4999 diag::err_member_function_call_bad_cvr)
5000 << Method->getDeclName() << FromRecordType << (CVR - 1)
5001 << From->getSourceRange();
5002 Diag(Method->getLocation(), diag::note_previous_decl)
5003 << Method->getDeclName();
5004 return ExprError();
5005 }
5006 }
5007
5008 return Diag(From->getLocStart(),
5009 diag::err_implicit_object_parameter_init)
5010 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5011 }
5012
5013 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5014 ExprResult FromRes =
5015 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5016 if (FromRes.isInvalid())
5017 return ExprError();
5018 From = FromRes.get();
5019 }
5020
5021 if (!Context.hasSameType(From->getType(), DestType))
5022 From = ImpCastExprToType(From, DestType, CK_NoOp,
5023 From->getValueKind()).get();
5024 return From;
5025}
5026
5027/// TryContextuallyConvertToBool - Attempt to contextually convert the
5028/// expression From to bool (C++0x [conv]p3).
5029static ImplicitConversionSequence
5030TryContextuallyConvertToBool(Sema &S, Expr *From) {
5031 return TryImplicitConversion(S, From, S.Context.BoolTy,
5032 /*SuppressUserConversions=*/false,
5033 /*AllowExplicit=*/true,
5034 /*InOverloadResolution=*/false,
5035 /*CStyle=*/false,
5036 /*AllowObjCWritebackConversion=*/false,
5037 /*AllowObjCConversionOnExplicit=*/false);
5038}
5039
5040/// PerformContextuallyConvertToBool - Perform a contextual conversion
5041/// of the expression From to bool (C++0x [conv]p3).
5042ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5043 if (checkPlaceholderForOverload(*this, From))
5044 return ExprError();
5045
5046 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5047 if (!ICS.isBad())
5048 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5049
5050 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5051 return Diag(From->getLocStart(),
5052 diag::err_typecheck_bool_condition)
5053 << From->getType() << From->getSourceRange();
5054 return ExprError();
5055}
5056
5057/// Check that the specified conversion is permitted in a converted constant
5058/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5059/// is acceptable.
5060static bool CheckConvertedConstantConversions(Sema &S,
5061 StandardConversionSequence &SCS) {
5062 // Since we know that the target type is an integral or unscoped enumeration
5063 // type, most conversion kinds are impossible. All possible First and Third
5064 // conversions are fine.
5065 switch (SCS.Second) {
5066 case ICK_Identity:
5067 case ICK_NoReturn_Adjustment:
5068 case ICK_Integral_Promotion:
5069 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5070 return true;
5071
5072 case ICK_Boolean_Conversion:
5073 // Conversion from an integral or unscoped enumeration type to bool is
5074 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5075 // conversion, so we allow it in a converted constant expression.
5076 //
5077 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5078 // a lot of popular code. We should at least add a warning for this
5079 // (non-conforming) extension.
5080 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5081 SCS.getToType(2)->isBooleanType();
5082
5083 case ICK_Pointer_Conversion:
5084 case ICK_Pointer_Member:
5085 // C++1z: null pointer conversions and null member pointer conversions are
5086 // only permitted if the source type is std::nullptr_t.
5087 return SCS.getFromType()->isNullPtrType();
5088
5089 case ICK_Floating_Promotion:
5090 case ICK_Complex_Promotion:
5091 case ICK_Floating_Conversion:
5092 case ICK_Complex_Conversion:
5093 case ICK_Floating_Integral:
5094 case ICK_Compatible_Conversion:
5095 case ICK_Derived_To_Base:
5096 case ICK_Vector_Conversion:
5097 case ICK_Vector_Splat:
5098 case ICK_Complex_Real:
5099 case ICK_Block_Pointer_Conversion:
5100 case ICK_TransparentUnionConversion:
5101 case ICK_Writeback_Conversion:
5102 case ICK_Zero_Event_Conversion:
5103 case ICK_C_Only_Conversion:
5104 return false;
5105
5106 case ICK_Lvalue_To_Rvalue:
5107 case ICK_Array_To_Pointer:
5108 case ICK_Function_To_Pointer:
5109 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5109)
;
5110
5111 case ICK_Qualification:
5112 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5112)
;
5113
5114 case ICK_Num_Conversion_Kinds:
5115 break;
5116 }
5117
5118 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5118)
;
5119}
5120
5121/// CheckConvertedConstantExpression - Check that the expression From is a
5122/// converted constant expression of type T, perform the conversion and produce
5123/// the converted expression, per C++11 [expr.const]p3.
5124static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5125 QualType T, APValue &Value,
5126 Sema::CCEKind CCE,
5127 bool RequireInt) {
5128 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5129, __PRETTY_FUNCTION__))
5129 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5129, __PRETTY_FUNCTION__))
;
5130
5131 if (checkPlaceholderForOverload(S, From))
5132 return ExprError();
5133
5134 // C++1z [expr.const]p3:
5135 // A converted constant expression of type T is an expression,
5136 // implicitly converted to type T, where the converted
5137 // expression is a constant expression and the implicit conversion
5138 // sequence contains only [... list of conversions ...].
5139 ImplicitConversionSequence ICS =
5140 TryCopyInitialization(S, From, T,
5141 /*SuppressUserConversions=*/false,
5142 /*InOverloadResolution=*/false,
5143 /*AllowObjcWritebackConversion=*/false,
5144 /*AllowExplicit=*/false);
5145 StandardConversionSequence *SCS = nullptr;
5146 switch (ICS.getKind()) {
5147 case ImplicitConversionSequence::StandardConversion:
5148 SCS = &ICS.Standard;
5149 break;
5150 case ImplicitConversionSequence::UserDefinedConversion:
5151 // We are converting to a non-class type, so the Before sequence
5152 // must be trivial.
5153 SCS = &ICS.UserDefined.After;
5154 break;
5155 case ImplicitConversionSequence::AmbiguousConversion:
5156 case ImplicitConversionSequence::BadConversion:
5157 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5158 return S.Diag(From->getLocStart(),
5159 diag::err_typecheck_converted_constant_expression)
5160 << From->getType() << From->getSourceRange() << T;
5161 return ExprError();
5162
5163 case ImplicitConversionSequence::EllipsisConversion:
5164 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5164)
;
5165 }
5166
5167 // Check that we would only use permitted conversions.
5168 if (!CheckConvertedConstantConversions(S, *SCS)) {
5169 return S.Diag(From->getLocStart(),
5170 diag::err_typecheck_converted_constant_expression_disallowed)
5171 << From->getType() << From->getSourceRange() << T;
5172 }
5173 // [...] and where the reference binding (if any) binds directly.
5174 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5175 return S.Diag(From->getLocStart(),
5176 diag::err_typecheck_converted_constant_expression_indirect)
5177 << From->getType() << From->getSourceRange() << T;
5178 }
5179
5180 ExprResult Result =
5181 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5182 if (Result.isInvalid())
5183 return Result;
5184
5185 // Check for a narrowing implicit conversion.
5186 APValue PreNarrowingValue;
5187 QualType PreNarrowingType;
5188 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5189 PreNarrowingType)) {
5190 case NK_Variable_Narrowing:
5191 // Implicit conversion to a narrower type, and the value is not a constant
5192 // expression. We'll diagnose this in a moment.
5193 case NK_Not_Narrowing:
5194 break;
5195
5196 case NK_Constant_Narrowing:
5197 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5198 << CCE << /*Constant*/1
5199 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5200 break;
5201
5202 case NK_Type_Narrowing:
5203 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5204 << CCE << /*Constant*/0 << From->getType() << T;
5205 break;
5206 }
5207
5208 // Check the expression is a constant expression.
5209 SmallVector<PartialDiagnosticAt, 8> Notes;
5210 Expr::EvalResult Eval;
5211 Eval.Diag = &Notes;
5212
5213 if ((T->isReferenceType()
5214 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5215 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5216 (RequireInt && !Eval.Val.isInt())) {
5217 // The expression can't be folded, so we can't keep it at this position in
5218 // the AST.
5219 Result = ExprError();
5220 } else {
5221 Value = Eval.Val;
5222
5223 if (Notes.empty()) {
5224 // It's a constant expression.
5225 return Result;
5226 }
5227 }
5228
5229 // It's not a constant expression. Produce an appropriate diagnostic.
5230 if (Notes.size() == 1 &&
5231 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5232 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5233 else {
5234 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5235 << CCE << From->getSourceRange();
5236 for (unsigned I = 0; I < Notes.size(); ++I)
5237 S.Diag(Notes[I].first, Notes[I].second);
5238 }
5239 return ExprError();
5240}
5241
5242ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5243 APValue &Value, CCEKind CCE) {
5244 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5245}
5246
5247ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5248 llvm::APSInt &Value,
5249 CCEKind CCE) {
5250 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5250, __PRETTY_FUNCTION__))
;
5251
5252 APValue V;
5253 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5254 if (!R.isInvalid())
5255 Value = V.getInt();
5256 return R;
5257}
5258
5259
5260/// dropPointerConversions - If the given standard conversion sequence
5261/// involves any pointer conversions, remove them. This may change
5262/// the result type of the conversion sequence.
5263static void dropPointerConversion(StandardConversionSequence &SCS) {
5264 if (SCS.Second == ICK_Pointer_Conversion) {
5265 SCS.Second = ICK_Identity;
5266 SCS.Third = ICK_Identity;
5267 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5268 }
5269}
5270
5271/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5272/// convert the expression From to an Objective-C pointer type.
5273static ImplicitConversionSequence
5274TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5275 // Do an implicit conversion to 'id'.
5276 QualType Ty = S.Context.getObjCIdType();
5277 ImplicitConversionSequence ICS
5278 = TryImplicitConversion(S, From, Ty,
5279 // FIXME: Are these flags correct?
5280 /*SuppressUserConversions=*/false,
5281 /*AllowExplicit=*/true,
5282 /*InOverloadResolution=*/false,
5283 /*CStyle=*/false,
5284 /*AllowObjCWritebackConversion=*/false,
5285 /*AllowObjCConversionOnExplicit=*/true);
5286
5287 // Strip off any final conversions to 'id'.
5288 switch (ICS.getKind()) {
5289 case ImplicitConversionSequence::BadConversion:
5290 case ImplicitConversionSequence::AmbiguousConversion:
5291 case ImplicitConversionSequence::EllipsisConversion:
5292 break;
5293
5294 case ImplicitConversionSequence::UserDefinedConversion:
5295 dropPointerConversion(ICS.UserDefined.After);
5296 break;
5297
5298 case ImplicitConversionSequence::StandardConversion:
5299 dropPointerConversion(ICS.Standard);
5300 break;
5301 }
5302
5303 return ICS;
5304}
5305
5306/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5307/// conversion of the expression From to an Objective-C pointer type.
5308ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5309 if (checkPlaceholderForOverload(*this, From))
5310 return ExprError();
5311
5312 QualType Ty = Context.getObjCIdType();
5313 ImplicitConversionSequence ICS =
5314 TryContextuallyConvertToObjCPointer(*this, From);
5315 if (!ICS.isBad())
5316 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5317 return ExprError();
5318}
5319
5320/// Determine whether the provided type is an integral type, or an enumeration
5321/// type of a permitted flavor.
5322bool Sema::ICEConvertDiagnoser::match(QualType T) {
5323 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5324 : T->isIntegralOrUnscopedEnumerationType();
5325}
5326
5327static ExprResult
5328diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5329 Sema::ContextualImplicitConverter &Converter,
5330 QualType T, UnresolvedSetImpl &ViableConversions) {
5331
5332 if (Converter.Suppress)
5333 return ExprError();
5334
5335 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5336 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5337 CXXConversionDecl *Conv =
5338 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5339 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5340 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5341 }
5342 return From;
5343}
5344
5345static bool
5346diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5347 Sema::ContextualImplicitConverter &Converter,
5348 QualType T, bool HadMultipleCandidates,
5349 UnresolvedSetImpl &ExplicitConversions) {
5350 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5351 DeclAccessPair Found = ExplicitConversions[0];
5352 CXXConversionDecl *Conversion =
5353 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5354
5355 // The user probably meant to invoke the given explicit
5356 // conversion; use it.
5357 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5358 std::string TypeStr;
5359 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5360
5361 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5362 << FixItHint::CreateInsertion(From->getLocStart(),
5363 "static_cast<" + TypeStr + ">(")
5364 << FixItHint::CreateInsertion(
5365 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5366 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5367
5368 // If we aren't in a SFINAE context, build a call to the
5369 // explicit conversion function.
5370 if (SemaRef.isSFINAEContext())
5371 return true;
5372
5373 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5374 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5375 HadMultipleCandidates);
5376 if (Result.isInvalid())
5377 return true;
5378 // Record usage of conversion in an implicit cast.
5379 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5380 CK_UserDefinedConversion, Result.get(),
5381 nullptr, Result.get()->getValueKind());
5382 }
5383 return false;
5384}
5385
5386static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5387 Sema::ContextualImplicitConverter &Converter,
5388 QualType T, bool HadMultipleCandidates,
5389 DeclAccessPair &Found) {
5390 CXXConversionDecl *Conversion =
5391 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5392 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5393
5394 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5395 if (!Converter.SuppressConversion) {
5396 if (SemaRef.isSFINAEContext())
5397 return true;
5398
5399 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5400 << From->getSourceRange();
5401 }
5402
5403 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5404 HadMultipleCandidates);
5405 if (Result.isInvalid())
5406 return true;
5407 // Record usage of conversion in an implicit cast.
5408 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5409 CK_UserDefinedConversion, Result.get(),
5410 nullptr, Result.get()->getValueKind());
5411 return false;
5412}
5413
5414static ExprResult finishContextualImplicitConversion(
5415 Sema &SemaRef, SourceLocation Loc, Expr *From,
5416 Sema::ContextualImplicitConverter &Converter) {
5417 if (!Converter.match(From->getType()) && !Converter.Suppress)
5418 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5419 << From->getSourceRange();
5420
5421 return SemaRef.DefaultLvalueConversion(From);
5422}
5423
5424static void
5425collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5426 UnresolvedSetImpl &ViableConversions,
5427 OverloadCandidateSet &CandidateSet) {
5428 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5429 DeclAccessPair FoundDecl = ViableConversions[I];
5430 NamedDecl *D = FoundDecl.getDecl();
5431 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5432 if (isa<UsingShadowDecl>(D))
5433 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5434
5435 CXXConversionDecl *Conv;
5436 FunctionTemplateDecl *ConvTemplate;
5437 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5438 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5439 else
5440 Conv = cast<CXXConversionDecl>(D);
5441
5442 if (ConvTemplate)
5443 SemaRef.AddTemplateConversionCandidate(
5444 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5445 /*AllowObjCConversionOnExplicit=*/false);
5446 else
5447 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5448 ToType, CandidateSet,
5449 /*AllowObjCConversionOnExplicit=*/false);
5450 }
5451}
5452
5453/// \brief Attempt to convert the given expression to a type which is accepted
5454/// by the given converter.
5455///
5456/// This routine will attempt to convert an expression of class type to a
5457/// type accepted by the specified converter. In C++11 and before, the class
5458/// must have a single non-explicit conversion function converting to a matching
5459/// type. In C++1y, there can be multiple such conversion functions, but only
5460/// one target type.
5461///
5462/// \param Loc The source location of the construct that requires the
5463/// conversion.
5464///
5465/// \param From The expression we're converting from.
5466///
5467/// \param Converter Used to control and diagnose the conversion process.
5468///
5469/// \returns The expression, converted to an integral or enumeration type if
5470/// successful.
5471ExprResult Sema::PerformContextualImplicitConversion(
5472 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5473 // We can't perform any more checking for type-dependent expressions.
5474 if (From->isTypeDependent())
5475 return From;
5476
5477 // Process placeholders immediately.
5478 if (From->hasPlaceholderType()) {
5479 ExprResult result = CheckPlaceholderExpr(From);
5480 if (result.isInvalid())
5481 return result;
5482 From = result.get();
5483 }
5484
5485 // If the expression already has a matching type, we're golden.
5486 QualType T = From->getType();
5487 if (Converter.match(T))
5488 return DefaultLvalueConversion(From);
5489
5490 // FIXME: Check for missing '()' if T is a function type?
5491
5492 // We can only perform contextual implicit conversions on objects of class
5493 // type.
5494 const RecordType *RecordTy = T->getAs<RecordType>();
5495 if (!RecordTy || !getLangOpts().CPlusPlus) {
5496 if (!Converter.Suppress)
5497 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5498 return From;
5499 }
5500
5501 // We must have a complete class type.
5502 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5503 ContextualImplicitConverter &Converter;
5504 Expr *From;
5505
5506 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5507 : Converter(Converter), From(From) {}
5508
5509 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5510 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5511 }
5512 } IncompleteDiagnoser(Converter, From);
5513
5514 if (Converter.Suppress ? !isCompleteType(Loc, T)
5515 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5516 return From;
5517
5518 // Look for a conversion to an integral or enumeration type.
5519 UnresolvedSet<4>
5520 ViableConversions; // These are *potentially* viable in C++1y.
5521 UnresolvedSet<4> ExplicitConversions;
5522 const auto &Conversions =
5523 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5524
5525 bool HadMultipleCandidates =
5526 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5527
5528 // To check that there is only one target type, in C++1y:
5529 QualType ToType;
5530 bool HasUniqueTargetType = true;
5531
5532 // Collect explicit or viable (potentially in C++1y) conversions.
5533 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5534 NamedDecl *D = (*I)->getUnderlyingDecl();
5535 CXXConversionDecl *Conversion;
5536 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5537 if (ConvTemplate) {
5538 if (getLangOpts().CPlusPlus14)
5539 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5540 else
5541 continue; // C++11 does not consider conversion operator templates(?).
5542 } else
5543 Conversion = cast<CXXConversionDecl>(D);
5544
5545 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5547, __PRETTY_FUNCTION__))
5546 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5547, __PRETTY_FUNCTION__))
5547 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5547, __PRETTY_FUNCTION__))
;
5548
5549 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5550 if (Converter.match(CurToType) || ConvTemplate) {
5551
5552 if (Conversion->isExplicit()) {
5553 // FIXME: For C++1y, do we need this restriction?
5554 // cf. diagnoseNoViableConversion()
5555 if (!ConvTemplate)
5556 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5557 } else {
5558 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5559 if (ToType.isNull())
5560 ToType = CurToType.getUnqualifiedType();
5561 else if (HasUniqueTargetType &&
5562 (CurToType.getUnqualifiedType() != ToType))
5563 HasUniqueTargetType = false;
5564 }
5565 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5566 }
5567 }
5568 }
5569
5570 if (getLangOpts().CPlusPlus14) {
5571 // C++1y [conv]p6:
5572 // ... An expression e of class type E appearing in such a context
5573 // is said to be contextually implicitly converted to a specified
5574 // type T and is well-formed if and only if e can be implicitly
5575 // converted to a type T that is determined as follows: E is searched
5576 // for conversion functions whose return type is cv T or reference to
5577 // cv T such that T is allowed by the context. There shall be
5578 // exactly one such T.
5579
5580 // If no unique T is found:
5581 if (ToType.isNull()) {
5582 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5583 HadMultipleCandidates,
5584 ExplicitConversions))
5585 return ExprError();
5586 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5587 }
5588
5589 // If more than one unique Ts are found:
5590 if (!HasUniqueTargetType)
5591 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5592 ViableConversions);
5593
5594 // If one unique T is found:
5595 // First, build a candidate set from the previously recorded
5596 // potentially viable conversions.
5597 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5598 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5599 CandidateSet);
5600
5601 // Then, perform overload resolution over the candidate set.
5602 OverloadCandidateSet::iterator Best;
5603 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5604 case OR_Success: {
5605 // Apply this conversion.
5606 DeclAccessPair Found =
5607 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5608 if (recordConversion(*this, Loc, From, Converter, T,
5609 HadMultipleCandidates, Found))
5610 return ExprError();
5611 break;
5612 }
5613 case OR_Ambiguous:
5614 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5615 ViableConversions);
5616 case OR_No_Viable_Function:
5617 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5618 HadMultipleCandidates,
5619 ExplicitConversions))
5620 return ExprError();
5621 // fall through 'OR_Deleted' case.
5622 case OR_Deleted:
5623 // We'll complain below about a non-integral condition type.
5624 break;
5625 }
5626 } else {
5627 switch (ViableConversions.size()) {
5628 case 0: {
5629 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5630 HadMultipleCandidates,
5631 ExplicitConversions))
5632 return ExprError();
5633
5634 // We'll complain below about a non-integral condition type.
5635 break;
5636 }
5637 case 1: {
5638 // Apply this conversion.
5639 DeclAccessPair Found = ViableConversions[0];
5640 if (recordConversion(*this, Loc, From, Converter, T,
5641 HadMultipleCandidates, Found))
5642 return ExprError();
5643 break;
5644 }
5645 default:
5646 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5647 ViableConversions);
5648 }
5649 }
5650
5651 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5652}
5653
5654/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5655/// an acceptable non-member overloaded operator for a call whose
5656/// arguments have types T1 (and, if non-empty, T2). This routine
5657/// implements the check in C++ [over.match.oper]p3b2 concerning
5658/// enumeration types.
5659static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5660 FunctionDecl *Fn,
5661 ArrayRef<Expr *> Args) {
5662 QualType T1 = Args[0]->getType();
5663 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5664
5665 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5666 return true;
5667
5668 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5669 return true;
5670
5671 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5672 if (Proto->getNumParams() < 1)
5673 return false;
5674
5675 if (T1->isEnumeralType()) {
5676 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5677 if (Context.hasSameUnqualifiedType(T1, ArgType))
5678 return true;
5679 }
5680
5681 if (Proto->getNumParams() < 2)
5682 return false;
5683
5684 if (!T2.isNull() && T2->isEnumeralType()) {
5685 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5686 if (Context.hasSameUnqualifiedType(T2, ArgType))
5687 return true;
5688 }
5689
5690 return false;
5691}
5692
5693/// AddOverloadCandidate - Adds the given function to the set of
5694/// candidate functions, using the given function call arguments. If
5695/// @p SuppressUserConversions, then don't allow user-defined
5696/// conversions via constructors or conversion operators.
5697///
5698/// \param PartialOverloading true if we are performing "partial" overloading
5699/// based on an incomplete set of function arguments. This feature is used by
5700/// code completion.
5701void
5702Sema::AddOverloadCandidate(FunctionDecl *Function,
5703 DeclAccessPair FoundDecl,
5704 ArrayRef<Expr *> Args,
5705 OverloadCandidateSet &CandidateSet,
5706 bool SuppressUserConversions,
5707 bool PartialOverloading,
5708 bool AllowExplicit) {
5709 const FunctionProtoType *Proto
5710 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5711 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5711, __PRETTY_FUNCTION__))
;
5712 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5713, __PRETTY_FUNCTION__))
5713 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5713, __PRETTY_FUNCTION__))
;
5714
5715 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5716 if (!isa<CXXConstructorDecl>(Method)) {
5717 // If we get here, it's because we're calling a member function
5718 // that is named without a member access expression (e.g.,
5719 // "this->f") that was either written explicitly or created
5720 // implicitly. This can happen with a qualified call to a member
5721 // function, e.g., X::f(). We use an empty type for the implied
5722 // object argument (C++ [over.call.func]p3), and the acting context
5723 // is irrelevant.
5724 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5725 QualType(), Expr::Classification::makeSimpleLValue(),
5726 Args, CandidateSet, SuppressUserConversions,
5727 PartialOverloading);
5728 return;
5729 }
5730 // We treat a constructor like a non-member function, since its object
5731 // argument doesn't participate in overload resolution.
5732 }
5733
5734 if (!CandidateSet.isNewCandidate(Function))
5735 return;
5736
5737 // C++ [over.match.oper]p3:
5738 // if no operand has a class type, only those non-member functions in the
5739 // lookup set that have a first parameter of type T1 or "reference to
5740 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5741 // is a right operand) a second parameter of type T2 or "reference to
5742 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5743 // candidate functions.
5744 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5745 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5746 return;
5747
5748 // C++11 [class.copy]p11: [DR1402]
5749 // A defaulted move constructor that is defined as deleted is ignored by
5750 // overload resolution.
5751 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5752 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5753 Constructor->isMoveConstructor())
5754 return;
5755
5756 // Overload resolution is always an unevaluated context.
5757 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5758
5759 // Add this candidate
5760 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5761 Candidate.FoundDecl = FoundDecl;
5762 Candidate.Function = Function;
5763 Candidate.Viable = true;
5764 Candidate.IsSurrogate = false;
5765 Candidate.IgnoreObjectArgument = false;
5766 Candidate.ExplicitCallArguments = Args.size();
5767
5768 if (Constructor) {
5769 // C++ [class.copy]p3:
5770 // A member function template is never instantiated to perform the copy
5771 // of a class object to an object of its class type.
5772 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5773 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5774 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5775 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5776 ClassType))) {
5777 Candidate.Viable = false;
5778 Candidate.FailureKind = ovl_fail_illegal_constructor;
5779 return;
5780 }
5781 }
5782
5783 unsigned NumParams = Proto->getNumParams();
5784
5785 // (C++ 13.3.2p2): A candidate function having fewer than m
5786 // parameters is viable only if it has an ellipsis in its parameter
5787 // list (8.3.5).
5788 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5789 !Proto->isVariadic()) {
5790 Candidate.Viable = false;
5791 Candidate.FailureKind = ovl_fail_too_many_arguments;
5792 return;
5793 }
5794
5795 // (C++ 13.3.2p2): A candidate function having more than m parameters
5796 // is viable only if the (m+1)st parameter has a default argument
5797 // (8.3.6). For the purposes of overload resolution, the
5798 // parameter list is truncated on the right, so that there are
5799 // exactly m parameters.
5800 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5801 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5802 // Not enough arguments.
5803 Candidate.Viable = false;
5804 Candidate.FailureKind = ovl_fail_too_few_arguments;
5805 return;
5806 }
5807
5808 // (CUDA B.1): Check for invalid calls between targets.
5809 if (getLangOpts().CUDA)
5810 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5811 // Skip the check for callers that are implicit members, because in this
5812 // case we may not yet know what the member's target is; the target is
5813 // inferred for the member automatically, based on the bases and fields of
5814 // the class.
5815 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5816 Candidate.Viable = false;
5817 Candidate.FailureKind = ovl_fail_bad_target;
5818 return;
5819 }
5820
5821 // Determine the implicit conversion sequences for each of the
5822 // arguments.
5823 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5824 if (ArgIdx < NumParams) {
5825 // (C++ 13.3.2p3): for F to be a viable function, there shall
5826 // exist for each argument an implicit conversion sequence
5827 // (13.3.3.1) that converts that argument to the corresponding
5828 // parameter of F.
5829 QualType ParamType = Proto->getParamType(ArgIdx);
5830 Candidate.Conversions[ArgIdx]
5831 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5832 SuppressUserConversions,
5833 /*InOverloadResolution=*/true,
5834 /*AllowObjCWritebackConversion=*/
5835 getLangOpts().ObjCAutoRefCount,
5836 AllowExplicit);
5837 if (Candidate.Conversions[ArgIdx].isBad()) {
5838 Candidate.Viable = false;
5839 Candidate.FailureKind = ovl_fail_bad_conversion;
5840 return;
5841 }
5842 } else {
5843 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5844 // argument for which there is no corresponding parameter is
5845 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5846 Candidate.Conversions[ArgIdx].setEllipsis();
5847 }
5848 }
5849
5850 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5851 Candidate.Viable = false;
5852 Candidate.FailureKind = ovl_fail_enable_if;
5853 Candidate.DeductionFailure.Data = FailedAttr;
5854 return;
5855 }
5856}
5857
5858ObjCMethodDecl *
5859Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5860 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5861 if (Methods.size() <= 1)
5862 return nullptr;
5863
5864 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5865 bool Match = true;
5866 ObjCMethodDecl *Method = Methods[b];
5867 unsigned NumNamedArgs = Sel.getNumArgs();
5868 // Method might have more arguments than selector indicates. This is due
5869 // to addition of c-style arguments in method.
5870 if (Method->param_size() > NumNamedArgs)
5871 NumNamedArgs = Method->param_size();
5872 if (Args.size() < NumNamedArgs)
5873 continue;
5874
5875 for (unsigned i = 0; i < NumNamedArgs; i++) {
5876 // We can't do any type-checking on a type-dependent argument.
5877 if (Args[i]->isTypeDependent()) {
5878 Match = false;
5879 break;
5880 }
5881
5882 ParmVarDecl *param = Method->parameters()[i];
5883 Expr *argExpr = Args[i];
5884 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 5884, __PRETTY_FUNCTION__))
;
5885
5886 // Strip the unbridged-cast placeholder expression off unless it's
5887 // a consumed argument.
5888 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5889 !param->hasAttr<CFConsumedAttr>())
5890 argExpr = stripARCUnbridgedCast(argExpr);
5891
5892 // If the parameter is __unknown_anytype, move on to the next method.
5893 if (param->getType() == Context.UnknownAnyTy) {
5894 Match = false;
5895 break;
5896 }
5897
5898 ImplicitConversionSequence ConversionState
5899 = TryCopyInitialization(*this, argExpr, param->getType(),
5900 /*SuppressUserConversions*/false,
5901 /*InOverloadResolution=*/true,
5902 /*AllowObjCWritebackConversion=*/
5903 getLangOpts().ObjCAutoRefCount,
5904 /*AllowExplicit*/false);
5905 if (ConversionState.isBad()) {
5906 Match = false;
5907 break;
5908 }
5909 }
5910 // Promote additional arguments to variadic methods.
5911 if (Match && Method->isVariadic()) {
5912 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5913 if (Args[i]->isTypeDependent()) {
5914 Match = false;
5915 break;
5916 }
5917 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5918 nullptr);
5919 if (Arg.isInvalid()) {
5920 Match = false;
5921 break;
5922 }
5923 }
5924 } else {
5925 // Check for extra arguments to non-variadic methods.
5926 if (Args.size() != NumNamedArgs)
5927 Match = false;
5928 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5929 // Special case when selectors have no argument. In this case, select
5930 // one with the most general result type of 'id'.
5931 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5932 QualType ReturnT = Methods[b]->getReturnType();
5933 if (ReturnT->isObjCIdType())
5934 return Methods[b];
5935 }
5936 }
5937 }
5938
5939 if (Match)
5940 return Method;
5941 }
5942 return nullptr;
5943}
5944
5945// specific_attr_iterator iterates over enable_if attributes in reverse, and
5946// enable_if is order-sensitive. As a result, we need to reverse things
5947// sometimes. Size of 4 elements is arbitrary.
5948static SmallVector<EnableIfAttr *, 4>
5949getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5950 SmallVector<EnableIfAttr *, 4> Result;
5951 if (!Function->hasAttrs())
5952 return Result;
5953
5954 const auto &FuncAttrs = Function->getAttrs();
5955 for (Attr *Attr : FuncAttrs)
5956 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5957 Result.push_back(EnableIf);
5958
5959 std::reverse(Result.begin(), Result.end());
5960 return Result;
5961}
5962
5963EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5964 bool MissingImplicitThis) {
5965 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5966 if (EnableIfAttrs.empty())
5967 return nullptr;
5968
5969 SFINAETrap Trap(*this);
5970 SmallVector<Expr *, 16> ConvertedArgs;
5971 bool InitializationFailed = false;
5972 bool ContainsValueDependentExpr = false;
5973
5974 // Convert the arguments.
5975 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5976 ExprResult R;
5977 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5978 !cast<CXXMethodDecl>(Function)->isStatic() &&
5979 !isa<CXXConstructorDecl>(Function)) {
5980 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5981 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5982 Method, Method);
5983 } else {
5984 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5985 Context, Function->getParamDecl(I)),
5986 SourceLocation(), Args[I]);
5987 }
5988
5989 if (R.isInvalid()) {
5990 InitializationFailed = true;
5991 break;
5992 }
5993
5994 ContainsValueDependentExpr |= R.get()->isValueDependent();
5995 ConvertedArgs.push_back(R.get());
5996 }
5997
5998 if (InitializationFailed || Trap.hasErrorOccurred())
5999 return EnableIfAttrs[0];
6000
6001 // Push default arguments if needed.
6002 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6003 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6004 ParmVarDecl *P = Function->getParamDecl(i);
6005 ExprResult R = PerformCopyInitialization(
6006 InitializedEntity::InitializeParameter(Context,
6007 Function->getParamDecl(i)),
6008 SourceLocation(),
6009 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6010 : P->getDefaultArg());
6011 if (R.isInvalid()) {
6012 InitializationFailed = true;
6013 break;
6014 }
6015 ContainsValueDependentExpr |= R.get()->isValueDependent();
6016 ConvertedArgs.push_back(R.get());
6017 }
6018
6019 if (InitializationFailed || Trap.hasErrorOccurred())
6020 return EnableIfAttrs[0];
6021 }
6022
6023 for (auto *EIA : EnableIfAttrs) {
6024 APValue Result;
6025 if (EIA->getCond()->isValueDependent()) {
6026 // Don't even try now, we'll examine it after instantiation.
6027 continue;
6028 }
6029
6030 if (!EIA->getCond()->EvaluateWithSubstitution(
6031 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6032 if (!ContainsValueDependentExpr)
6033 return EIA;
6034 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
6035 return EIA;
6036 }
6037 }
6038 return nullptr;
6039}
6040
6041/// \brief Add all of the function declarations in the given function set to
6042/// the overload candidate set.
6043void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6044 ArrayRef<Expr *> Args,
6045 OverloadCandidateSet& CandidateSet,
6046 TemplateArgumentListInfo *ExplicitTemplateArgs,
6047 bool SuppressUserConversions,
6048 bool PartialOverloading) {
6049 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6050 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6051 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6052 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6053 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6054 cast<CXXMethodDecl>(FD)->getParent(),
6055 Args[0]->getType(), Args[0]->Classify(Context),
6056 Args.slice(1), CandidateSet,
6057 SuppressUserConversions, PartialOverloading);
6058 else
6059 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6060 SuppressUserConversions, PartialOverloading);
6061 } else {
6062 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6063 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6064 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6065 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6066 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6067 ExplicitTemplateArgs,
6068 Args[0]->getType(),
6069 Args[0]->Classify(Context), Args.slice(1),
6070 CandidateSet, SuppressUserConversions,
6071 PartialOverloading);
6072 else
6073 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6074 ExplicitTemplateArgs, Args,
6075 CandidateSet, SuppressUserConversions,
6076 PartialOverloading);
6077 }
6078 }
6079}
6080
6081/// AddMethodCandidate - Adds a named decl (which is some kind of
6082/// method) as a method candidate to the given overload set.
6083void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6084 QualType ObjectType,
6085 Expr::Classification ObjectClassification,
6086 ArrayRef<Expr *> Args,
6087 OverloadCandidateSet& CandidateSet,
6088 bool SuppressUserConversions) {
6089 NamedDecl *Decl = FoundDecl.getDecl();
6090 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6091
6092 if (isa<UsingShadowDecl>(Decl))
6093 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6094
6095 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6096 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6097, __PRETTY_FUNCTION__))
6097 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6097, __PRETTY_FUNCTION__))
;
6098 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6099 /*ExplicitArgs*/ nullptr,
6100 ObjectType, ObjectClassification,
6101 Args, CandidateSet,
6102 SuppressUserConversions);
6103 } else {
6104 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6105 ObjectType, ObjectClassification,
6106 Args,
6107 CandidateSet, SuppressUserConversions);
6108 }
6109}
6110
6111/// AddMethodCandidate - Adds the given C++ member function to the set
6112/// of candidate functions, using the given function call arguments
6113/// and the object argument (@c Object). For example, in a call
6114/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6115/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6116/// allow user-defined conversions via constructors or conversion
6117/// operators.
6118void
6119Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6120 CXXRecordDecl *ActingContext, QualType ObjectType,
6121 Expr::Classification ObjectClassification,
6122 ArrayRef<Expr *> Args,
6123 OverloadCandidateSet &CandidateSet,
6124 bool SuppressUserConversions,
6125 bool PartialOverloading) {
6126 const FunctionProtoType *Proto
6127 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6128 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6128, __PRETTY_FUNCTION__))
;
6129 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6130, __PRETTY_FUNCTION__))
6130 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6130, __PRETTY_FUNCTION__))
;
6131
6132 if (!CandidateSet.isNewCandidate(Method))
6133 return;
6134
6135 // C++11 [class.copy]p23: [DR1402]
6136 // A defaulted move assignment operator that is defined as deleted is
6137 // ignored by overload resolution.
6138 if (Method->isDefaulted() && Method->isDeleted() &&
6139 Method->isMoveAssignmentOperator())
6140 return;
6141
6142 // Overload resolution is always an unevaluated context.
6143 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6144
6145 // Add this candidate
6146 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6147 Candidate.FoundDecl = FoundDecl;
6148 Candidate.Function = Method;
6149 Candidate.IsSurrogate = false;
6150 Candidate.IgnoreObjectArgument = false;
6151 Candidate.ExplicitCallArguments = Args.size();
6152
6153 unsigned NumParams = Proto->getNumParams();
6154
6155 // (C++ 13.3.2p2): A candidate function having fewer than m
6156 // parameters is viable only if it has an ellipsis in its parameter
6157 // list (8.3.5).
6158 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6159 !Proto->isVariadic()) {
6160 Candidate.Viable = false;
6161 Candidate.FailureKind = ovl_fail_too_many_arguments;
6162 return;
6163 }
6164
6165 // (C++ 13.3.2p2): A candidate function having more than m parameters
6166 // is viable only if the (m+1)st parameter has a default argument
6167 // (8.3.6). For the purposes of overload resolution, the
6168 // parameter list is truncated on the right, so that there are
6169 // exactly m parameters.
6170 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6171 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6172 // Not enough arguments.
6173 Candidate.Viable = false;
6174 Candidate.FailureKind = ovl_fail_too_few_arguments;
6175 return;
6176 }
6177
6178 Candidate.Viable = true;
6179
6180 if (Method->isStatic() || ObjectType.isNull())
6181 // The implicit object argument is ignored.
6182 Candidate.IgnoreObjectArgument = true;
6183 else {
6184 // Determine the implicit conversion sequence for the object
6185 // parameter.
6186 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6187 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6188 Method, ActingContext);
6189 if (Candidate.Conversions[0].isBad()) {
6190 Candidate.Viable = false;
6191 Candidate.FailureKind = ovl_fail_bad_conversion;
6192 return;
6193 }
6194 }
6195
6196 // (CUDA B.1): Check for invalid calls between targets.
6197 if (getLangOpts().CUDA)
6198 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6199 if (CheckCUDATarget(Caller, Method)) {
6200 Candidate.Viable = false;
6201 Candidate.FailureKind = ovl_fail_bad_target;
6202 return;
6203 }
6204
6205 // Determine the implicit conversion sequences for each of the
6206 // arguments.
6207 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6208 if (ArgIdx < NumParams) {
6209 // (C++ 13.3.2p3): for F to be a viable function, there shall
6210 // exist for each argument an implicit conversion sequence
6211 // (13.3.3.1) that converts that argument to the corresponding
6212 // parameter of F.
6213 QualType ParamType = Proto->getParamType(ArgIdx);
6214 Candidate.Conversions[ArgIdx + 1]
6215 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6216 SuppressUserConversions,
6217 /*InOverloadResolution=*/true,
6218 /*AllowObjCWritebackConversion=*/
6219 getLangOpts().ObjCAutoRefCount);
6220 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6221 Candidate.Viable = false;
6222 Candidate.FailureKind = ovl_fail_bad_conversion;
6223 return;
6224 }
6225 } else {
6226 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6227 // argument for which there is no corresponding parameter is
6228 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6229 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6230 }
6231 }
6232
6233 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6234 Candidate.Viable = false;
6235 Candidate.FailureKind = ovl_fail_enable_if;
6236 Candidate.DeductionFailure.Data = FailedAttr;
6237 return;
6238 }
6239}
6240
6241/// \brief Add a C++ member function template as a candidate to the candidate
6242/// set, using template argument deduction to produce an appropriate member
6243/// function template specialization.
6244void
6245Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6246 DeclAccessPair FoundDecl,
6247 CXXRecordDecl *ActingContext,
6248 TemplateArgumentListInfo *ExplicitTemplateArgs,
6249 QualType ObjectType,
6250 Expr::Classification ObjectClassification,
6251 ArrayRef<Expr *> Args,
6252 OverloadCandidateSet& CandidateSet,
6253 bool SuppressUserConversions,
6254 bool PartialOverloading) {
6255 if (!CandidateSet.isNewCandidate(MethodTmpl))
6256 return;
6257
6258 // C++ [over.match.funcs]p7:
6259 // In each case where a candidate is a function template, candidate
6260 // function template specializations are generated using template argument
6261 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6262 // candidate functions in the usual way.113) A given name can refer to one
6263 // or more function templates and also to a set of overloaded non-template
6264 // functions. In such a case, the candidate functions generated from each
6265 // function template are combined with the set of non-template candidate
6266 // functions.
6267 TemplateDeductionInfo Info(CandidateSet.getLocation());
6268 FunctionDecl *Specialization = nullptr;
6269 if (TemplateDeductionResult Result
6270 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6271 Specialization, Info, PartialOverloading)) {
6272 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6273 Candidate.FoundDecl = FoundDecl;
6274 Candidate.Function = MethodTmpl->getTemplatedDecl();
6275 Candidate.Viable = false;
6276 Candidate.FailureKind = ovl_fail_bad_deduction;
6277 Candidate.IsSurrogate = false;
6278 Candidate.IgnoreObjectArgument = false;
6279 Candidate.ExplicitCallArguments = Args.size();
6280 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6281 Info);
6282 return;
6283 }
6284
6285 // Add the function template specialization produced by template argument
6286 // deduction as a candidate.
6287 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6287, __PRETTY_FUNCTION__))
;
6288 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6289, __PRETTY_FUNCTION__))
6289 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6289, __PRETTY_FUNCTION__))
;
6290 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6291 ActingContext, ObjectType, ObjectClassification, Args,
6292 CandidateSet, SuppressUserConversions, PartialOverloading);
6293}
6294
6295/// \brief Add a C++ function template specialization as a candidate
6296/// in the candidate set, using template argument deduction to produce
6297/// an appropriate function template specialization.
6298void
6299Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6300 DeclAccessPair FoundDecl,
6301 TemplateArgumentListInfo *ExplicitTemplateArgs,
6302 ArrayRef<Expr *> Args,
6303 OverloadCandidateSet& CandidateSet,
6304 bool SuppressUserConversions,
6305 bool PartialOverloading) {
6306 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6307 return;
6308
6309 // C++ [over.match.funcs]p7:
6310 // In each case where a candidate is a function template, candidate
6311 // function template specializations are generated using template argument
6312 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6313 // candidate functions in the usual way.113) A given name can refer to one
6314 // or more function templates and also to a set of overloaded non-template
6315 // functions. In such a case, the candidate functions generated from each
6316 // function template are combined with the set of non-template candidate
6317 // functions.
6318 TemplateDeductionInfo Info(CandidateSet.getLocation());
6319 FunctionDecl *Specialization = nullptr;
6320 if (TemplateDeductionResult Result
6321 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6322 Specialization, Info, PartialOverloading)) {
6323 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6324 Candidate.FoundDecl = FoundDecl;
6325 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6326 Candidate.Viable = false;
6327 Candidate.FailureKind = ovl_fail_bad_deduction;
6328 Candidate.IsSurrogate = false;
6329 Candidate.IgnoreObjectArgument = false;
6330 Candidate.ExplicitCallArguments = Args.size();
6331 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6332 Info);
6333 return;
6334 }
6335
6336 // Add the function template specialization produced by template argument
6337 // deduction as a candidate.
6338 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6338, __PRETTY_FUNCTION__))
;
6339 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6340 SuppressUserConversions, PartialOverloading);
6341}
6342
6343/// Determine whether this is an allowable conversion from the result
6344/// of an explicit conversion operator to the expected type, per C++
6345/// [over.match.conv]p1 and [over.match.ref]p1.
6346///
6347/// \param ConvType The return type of the conversion function.
6348///
6349/// \param ToType The type we are converting to.
6350///
6351/// \param AllowObjCPointerConversion Allow a conversion from one
6352/// Objective-C pointer to another.
6353///
6354/// \returns true if the conversion is allowable, false otherwise.
6355static bool isAllowableExplicitConversion(Sema &S,
6356 QualType ConvType, QualType ToType,
6357 bool AllowObjCPointerConversion) {
6358 QualType ToNonRefType = ToType.getNonReferenceType();
6359
6360 // Easy case: the types are the same.
6361 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6362 return true;
6363
6364 // Allow qualification conversions.
6365 bool ObjCLifetimeConversion;
6366 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6367 ObjCLifetimeConversion))
6368 return true;
6369
6370 // If we're not allowed to consider Objective-C pointer conversions,
6371 // we're done.
6372 if (!AllowObjCPointerConversion)
6373 return false;
6374
6375 // Is this an Objective-C pointer conversion?
6376 bool IncompatibleObjC = false;
6377 QualType ConvertedType;
6378 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6379 IncompatibleObjC);
6380}
6381
6382/// AddConversionCandidate - Add a C++ conversion function as a
6383/// candidate in the candidate set (C++ [over.match.conv],
6384/// C++ [over.match.copy]). From is the expression we're converting from,
6385/// and ToType is the type that we're eventually trying to convert to
6386/// (which may or may not be the same type as the type that the
6387/// conversion function produces).
6388void
6389Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6390 DeclAccessPair FoundDecl,
6391 CXXRecordDecl *ActingContext,
6392 Expr *From, QualType ToType,
6393 OverloadCandidateSet& CandidateSet,
6394 bool AllowObjCConversionOnExplicit) {
6395 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6396, __PRETTY_FUNCTION__))
6396 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6396, __PRETTY_FUNCTION__))
;
6397 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6398 if (!CandidateSet.isNewCandidate(Conversion))
6399 return;
6400
6401 // If the conversion function has an undeduced return type, trigger its
6402 // deduction now.
6403 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6404 if (DeduceReturnType(Conversion, From->getExprLoc()))
6405 return;
6406 ConvType = Conversion->getConversionType().getNonReferenceType();
6407 }
6408
6409 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6410 // operator is only a candidate if its return type is the target type or
6411 // can be converted to the target type with a qualification conversion.
6412 if (Conversion->isExplicit() &&
6413 !isAllowableExplicitConversion(*this, ConvType, ToType,
6414 AllowObjCConversionOnExplicit))
6415 return;
6416
6417 // Overload resolution is always an unevaluated context.
6418 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6419
6420 // Add this candidate
6421 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6422 Candidate.FoundDecl = FoundDecl;
6423 Candidate.Function = Conversion;
6424 Candidate.IsSurrogate = false;
6425 Candidate.IgnoreObjectArgument = false;
6426 Candidate.FinalConversion.setAsIdentityConversion();
6427 Candidate.FinalConversion.setFromType(ConvType);
6428 Candidate.FinalConversion.setAllToTypes(ToType);
6429 Candidate.Viable = true;
6430 Candidate.ExplicitCallArguments = 1;
6431
6432 // C++ [over.match.funcs]p4:
6433 // For conversion functions, the function is considered to be a member of
6434 // the class of the implicit implied object argument for the purpose of
6435 // defining the type of the implicit object parameter.
6436 //
6437 // Determine the implicit conversion sequence for the implicit
6438 // object parameter.
6439 QualType ImplicitParamType = From->getType();
6440 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6441 ImplicitParamType = FromPtrType->getPointeeType();
6442 CXXRecordDecl *ConversionContext
6443 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6444
6445 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6446 *this, CandidateSet.getLocation(), From->getType(),
6447 From->Classify(Context), Conversion, ConversionContext);
6448
6449 if (Candidate.Conversions[0].isBad()) {
6450 Candidate.Viable = false;
6451 Candidate.FailureKind = ovl_fail_bad_conversion;
6452 return;
6453 }
6454
6455 // We won't go through a user-defined type conversion function to convert a
6456 // derived to base as such conversions are given Conversion Rank. They only
6457 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6458 QualType FromCanon
6459 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6460 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6461 if (FromCanon == ToCanon ||
6462 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6463 Candidate.Viable = false;
6464 Candidate.FailureKind = ovl_fail_trivial_conversion;
6465 return;
6466 }
6467
6468 // To determine what the conversion from the result of calling the
6469 // conversion function to the type we're eventually trying to
6470 // convert to (ToType), we need to synthesize a call to the
6471 // conversion function and attempt copy initialization from it. This
6472 // makes sure that we get the right semantics with respect to
6473 // lvalues/rvalues and the type. Fortunately, we can allocate this
6474 // call on the stack and we don't need its arguments to be
6475 // well-formed.
6476 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6477 VK_LValue, From->getLocStart());
6478 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6479 Context.getPointerType(Conversion->getType()),
6480 CK_FunctionToPointerDecay,
6481 &ConversionRef, VK_RValue);
6482
6483 QualType ConversionType = Conversion->getConversionType();
6484 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6485 Candidate.Viable = false;
6486 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6487 return;
6488 }
6489
6490 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6491
6492 // Note that it is safe to allocate CallExpr on the stack here because
6493 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6494 // allocator).
6495 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6496 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6497 From->getLocStart());
6498 ImplicitConversionSequence ICS =
6499 TryCopyInitialization(*this, &Call, ToType,
6500 /*SuppressUserConversions=*/true,
6501 /*InOverloadResolution=*/false,
6502 /*AllowObjCWritebackConversion=*/false);
6503
6504 switch (ICS.getKind()) {
6505 case ImplicitConversionSequence::StandardConversion:
6506 Candidate.FinalConversion = ICS.Standard;
6507
6508 // C++ [over.ics.user]p3:
6509 // If the user-defined conversion is specified by a specialization of a
6510 // conversion function template, the second standard conversion sequence
6511 // shall have exact match rank.
6512 if (Conversion->getPrimaryTemplate() &&
6513 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6514 Candidate.Viable = false;
6515 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6516 return;
6517 }
6518
6519 // C++0x [dcl.init.ref]p5:
6520 // In the second case, if the reference is an rvalue reference and
6521 // the second standard conversion sequence of the user-defined
6522 // conversion sequence includes an lvalue-to-rvalue conversion, the
6523 // program is ill-formed.
6524 if (ToType->isRValueReferenceType() &&
6525 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6526 Candidate.Viable = false;
6527 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6528 return;
6529 }
6530 break;
6531
6532 case ImplicitConversionSequence::BadConversion:
6533 Candidate.Viable = false;
6534 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6535 return;
6536
6537 default:
6538 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6539)
6539 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6539)
;
6540 }
6541
6542 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6543 Candidate.Viable = false;
6544 Candidate.FailureKind = ovl_fail_enable_if;
6545 Candidate.DeductionFailure.Data = FailedAttr;
6546 return;
6547 }
6548}
6549
6550/// \brief Adds a conversion function template specialization
6551/// candidate to the overload set, using template argument deduction
6552/// to deduce the template arguments of the conversion function
6553/// template from the type that we are converting to (C++
6554/// [temp.deduct.conv]).
6555void
6556Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6557 DeclAccessPair FoundDecl,
6558 CXXRecordDecl *ActingDC,
6559 Expr *From, QualType ToType,
6560 OverloadCandidateSet &CandidateSet,
6561 bool AllowObjCConversionOnExplicit) {
6562 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6563, __PRETTY_FUNCTION__))
6563 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6563, __PRETTY_FUNCTION__))
;
6564
6565 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6566 return;
6567
6568 TemplateDeductionInfo Info(CandidateSet.getLocation());
6569 CXXConversionDecl *Specialization = nullptr;
6570 if (TemplateDeductionResult Result
6571 = DeduceTemplateArguments(FunctionTemplate, ToType,
6572 Specialization, Info)) {
6573 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6574 Candidate.FoundDecl = FoundDecl;
6575 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6576 Candidate.Viable = false;
6577 Candidate.FailureKind = ovl_fail_bad_deduction;
6578 Candidate.IsSurrogate = false;
6579 Candidate.IgnoreObjectArgument = false;
6580 Candidate.ExplicitCallArguments = 1;
6581 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6582 Info);
6583 return;
6584 }
6585
6586 // Add the conversion function template specialization produced by
6587 // template argument deduction as a candidate.
6588 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6588, __PRETTY_FUNCTION__))
;
6589 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6590 CandidateSet, AllowObjCConversionOnExplicit);
6591}
6592
6593/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6594/// converts the given @c Object to a function pointer via the
6595/// conversion function @c Conversion, and then attempts to call it
6596/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6597/// the type of function that we'll eventually be calling.
6598void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6599 DeclAccessPair FoundDecl,
6600 CXXRecordDecl *ActingContext,
6601 const FunctionProtoType *Proto,
6602 Expr *Object,
6603 ArrayRef<Expr *> Args,
6604 OverloadCandidateSet& CandidateSet) {
6605 if (!CandidateSet.isNewCandidate(Conversion))
6606 return;
6607
6608 // Overload resolution is always an unevaluated context.
6609 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6610
6611 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6612 Candidate.FoundDecl = FoundDecl;
6613 Candidate.Function = nullptr;
6614 Candidate.Surrogate = Conversion;
6615 Candidate.Viable = true;
6616 Candidate.IsSurrogate = true;
6617 Candidate.IgnoreObjectArgument = false;
6618 Candidate.ExplicitCallArguments = Args.size();
6619
6620 // Determine the implicit conversion sequence for the implicit
6621 // object parameter.
6622 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6623 *this, CandidateSet.getLocation(), Object->getType(),
6624 Object->Classify(Context), Conversion, ActingContext);
6625 if (ObjectInit.isBad()) {
6626 Candidate.Viable = false;
6627 Candidate.FailureKind = ovl_fail_bad_conversion;
6628 Candidate.Conversions[0] = ObjectInit;
6629 return;
6630 }
6631
6632 // The first conversion is actually a user-defined conversion whose
6633 // first conversion is ObjectInit's standard conversion (which is
6634 // effectively a reference binding). Record it as such.
6635 Candidate.Conversions[0].setUserDefined();
6636 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6637 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6638 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6639 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6640 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6641 Candidate.Conversions[0].UserDefined.After
6642 = Candidate.Conversions[0].UserDefined.Before;
6643 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6644
6645 // Find the
6646 unsigned NumParams = Proto->getNumParams();
6647
6648 // (C++ 13.3.2p2): A candidate function having fewer than m
6649 // parameters is viable only if it has an ellipsis in its parameter
6650 // list (8.3.5).
6651 if (Args.size() > NumParams && !Proto->isVariadic()) {
6652 Candidate.Viable = false;
6653 Candidate.FailureKind = ovl_fail_too_many_arguments;
6654 return;
6655 }
6656
6657 // Function types don't have any default arguments, so just check if
6658 // we have enough arguments.
6659 if (Args.size() < NumParams) {
6660 // Not enough arguments.
6661 Candidate.Viable = false;
6662 Candidate.FailureKind = ovl_fail_too_few_arguments;
6663 return;
6664 }
6665
6666 // Determine the implicit conversion sequences for each of the
6667 // arguments.
6668 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6669 if (ArgIdx < NumParams) {
6670 // (C++ 13.3.2p3): for F to be a viable function, there shall
6671 // exist for each argument an implicit conversion sequence
6672 // (13.3.3.1) that converts that argument to the corresponding
6673 // parameter of F.
6674 QualType ParamType = Proto->getParamType(ArgIdx);
6675 Candidate.Conversions[ArgIdx + 1]
6676 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6677 /*SuppressUserConversions=*/false,
6678 /*InOverloadResolution=*/false,
6679 /*AllowObjCWritebackConversion=*/
6680 getLangOpts().ObjCAutoRefCount);
6681 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6682 Candidate.Viable = false;
6683 Candidate.FailureKind = ovl_fail_bad_conversion;
6684 return;
6685 }
6686 } else {
6687 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6688 // argument for which there is no corresponding parameter is
6689 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6690 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6691 }
6692 }
6693
6694 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6695 Candidate.Viable = false;
6696 Candidate.FailureKind = ovl_fail_enable_if;
6697 Candidate.DeductionFailure.Data = FailedAttr;
6698 return;
6699 }
6700}
6701
6702/// \brief Add overload candidates for overloaded operators that are
6703/// member functions.
6704///
6705/// Add the overloaded operator candidates that are member functions
6706/// for the operator Op that was used in an operator expression such
6707/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6708/// CandidateSet will store the added overload candidates. (C++
6709/// [over.match.oper]).
6710void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6711 SourceLocation OpLoc,
6712 ArrayRef<Expr *> Args,
6713 OverloadCandidateSet& CandidateSet,
6714 SourceRange OpRange) {
6715 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6716
6717 // C++ [over.match.oper]p3:
6718 // For a unary operator @ with an operand of a type whose
6719 // cv-unqualified version is T1, and for a binary operator @ with
6720 // a left operand of a type whose cv-unqualified version is T1 and
6721 // a right operand of a type whose cv-unqualified version is T2,
6722 // three sets of candidate functions, designated member
6723 // candidates, non-member candidates and built-in candidates, are
6724 // constructed as follows:
6725 QualType T1 = Args[0]->getType();
6726
6727 // -- If T1 is a complete class type or a class currently being
6728 // defined, the set of member candidates is the result of the
6729 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6730 // the set of member candidates is empty.
6731 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6732 // Complete the type if it can be completed.
6733 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6734 return;
6735 // If the type is neither complete nor being defined, bail out now.
6736 if (!T1Rec->getDecl()->getDefinition())
6737 return;
6738
6739 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6740 LookupQualifiedName(Operators, T1Rec->getDecl());
6741 Operators.suppressDiagnostics();
6742
6743 for (LookupResult::iterator Oper = Operators.begin(),
6744 OperEnd = Operators.end();
6745 Oper != OperEnd;
6746 ++Oper)
6747 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6748 Args[0]->Classify(Context),
6749 Args.slice(1),
6750 CandidateSet,
6751 /* SuppressUserConversions = */ false);
6752 }
6753}
6754
6755/// AddBuiltinCandidate - Add a candidate for a built-in
6756/// operator. ResultTy and ParamTys are the result and parameter types
6757/// of the built-in candidate, respectively. Args and NumArgs are the
6758/// arguments being passed to the candidate. IsAssignmentOperator
6759/// should be true when this built-in candidate is an assignment
6760/// operator. NumContextualBoolArguments is the number of arguments
6761/// (at the beginning of the argument list) that will be contextually
6762/// converted to bool.
6763void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6764 ArrayRef<Expr *> Args,
6765 OverloadCandidateSet& CandidateSet,
6766 bool IsAssignmentOperator,
6767 unsigned NumContextualBoolArguments) {
6768 // Overload resolution is always an unevaluated context.
6769 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6770
6771 // Add this candidate
6772 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6773 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6774 Candidate.Function = nullptr;
6775 Candidate.IsSurrogate = false;
6776 Candidate.IgnoreObjectArgument = false;
6777 Candidate.BuiltinTypes.ResultTy = ResultTy;
6778 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6779 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6780
6781 // Determine the implicit conversion sequences for each of the
6782 // arguments.
6783 Candidate.Viable = true;
6784 Candidate.ExplicitCallArguments = Args.size();
6785 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6786 // C++ [over.match.oper]p4:
6787 // For the built-in assignment operators, conversions of the
6788 // left operand are restricted as follows:
6789 // -- no temporaries are introduced to hold the left operand, and
6790 // -- no user-defined conversions are applied to the left
6791 // operand to achieve a type match with the left-most
6792 // parameter of a built-in candidate.
6793 //
6794 // We block these conversions by turning off user-defined
6795 // conversions, since that is the only way that initialization of
6796 // a reference to a non-class type can occur from something that
6797 // is not of the same type.
6798 if (ArgIdx < NumContextualBoolArguments) {
6799 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6800, __PRETTY_FUNCTION__))
6800 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6800, __PRETTY_FUNCTION__))
;
6801 Candidate.Conversions[ArgIdx]
6802 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6803 } else {
6804 Candidate.Conversions[ArgIdx]
6805 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6806 ArgIdx == 0 && IsAssignmentOperator,
6807 /*InOverloadResolution=*/false,
6808 /*AllowObjCWritebackConversion=*/
6809 getLangOpts().ObjCAutoRefCount);
6810 }
6811 if (Candidate.Conversions[ArgIdx].isBad()) {
6812 Candidate.Viable = false;
6813 Candidate.FailureKind = ovl_fail_bad_conversion;
6814 break;
6815 }
6816 }
6817}
6818
6819namespace {
6820
6821/// BuiltinCandidateTypeSet - A set of types that will be used for the
6822/// candidate operator functions for built-in operators (C++
6823/// [over.built]). The types are separated into pointer types and
6824/// enumeration types.
6825class BuiltinCandidateTypeSet {
6826 /// TypeSet - A set of types.
6827 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6828 llvm::SmallPtrSet<QualType, 8>> TypeSet;
6829
6830 /// PointerTypes - The set of pointer types that will be used in the
6831 /// built-in candidates.
6832 TypeSet PointerTypes;
6833
6834 /// MemberPointerTypes - The set of member pointer types that will be
6835 /// used in the built-in candidates.
6836 TypeSet MemberPointerTypes;
6837
6838 /// EnumerationTypes - The set of enumeration types that will be
6839 /// used in the built-in candidates.
6840 TypeSet EnumerationTypes;
6841
6842 /// \brief The set of vector types that will be used in the built-in
6843 /// candidates.
6844 TypeSet VectorTypes;
6845
6846 /// \brief A flag indicating non-record types are viable candidates
6847 bool HasNonRecordTypes;
6848
6849 /// \brief A flag indicating whether either arithmetic or enumeration types
6850 /// were present in the candidate set.
6851 bool HasArithmeticOrEnumeralTypes;
6852
6853 /// \brief A flag indicating whether the nullptr type was present in the
6854 /// candidate set.
6855 bool HasNullPtrType;
6856
6857 /// Sema - The semantic analysis instance where we are building the
6858 /// candidate type set.
6859 Sema &SemaRef;
6860
6861 /// Context - The AST context in which we will build the type sets.
6862 ASTContext &Context;
6863
6864 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6865 const Qualifiers &VisibleQuals);
6866 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6867
6868public:
6869 /// iterator - Iterates through the types that are part of the set.
6870 typedef TypeSet::iterator iterator;
6871
6872 BuiltinCandidateTypeSet(Sema &SemaRef)
6873 : HasNonRecordTypes(false),
6874 HasArithmeticOrEnumeralTypes(false),
6875 HasNullPtrType(false),
6876 SemaRef(SemaRef),
6877 Context(SemaRef.Context) { }
6878
6879 void AddTypesConvertedFrom(QualType Ty,
6880 SourceLocation Loc,
6881 bool AllowUserConversions,
6882 bool AllowExplicitConversions,
6883 const Qualifiers &VisibleTypeConversionsQuals);
6884
6885 /// pointer_begin - First pointer type found;
6886 iterator pointer_begin() { return PointerTypes.begin(); }
6887
6888 /// pointer_end - Past the last pointer type found;
6889 iterator pointer_end() { return PointerTypes.end(); }
6890
6891 /// member_pointer_begin - First member pointer type found;
6892 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6893
6894 /// member_pointer_end - Past the last member pointer type found;
6895 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6896
6897 /// enumeration_begin - First enumeration type found;
6898 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6899
6900 /// enumeration_end - Past the last enumeration type found;
6901 iterator enumeration_end() { return EnumerationTypes.end(); }
6902
6903 iterator vector_begin() { return VectorTypes.begin(); }
6904 iterator vector_end() { return VectorTypes.end(); }
6905
6906 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6907 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6908 bool hasNullPtrType() const { return HasNullPtrType; }
6909};
6910
6911} // end anonymous namespace
6912
6913/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6914/// the set of pointer types along with any more-qualified variants of
6915/// that type. For example, if @p Ty is "int const *", this routine
6916/// will add "int const *", "int const volatile *", "int const
6917/// restrict *", and "int const volatile restrict *" to the set of
6918/// pointer types. Returns true if the add of @p Ty itself succeeded,
6919/// false otherwise.
6920///
6921/// FIXME: what to do about extended qualifiers?
6922bool
6923BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6924 const Qualifiers &VisibleQuals) {
6925
6926 // Insert this type.
6927 if (!PointerTypes.insert(Ty))
6928 return false;
6929
6930 QualType PointeeTy;
6931 const PointerType *PointerTy = Ty->getAs<PointerType>();
6932 bool buildObjCPtr = false;
6933 if (!PointerTy) {
6934 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6935 PointeeTy = PTy->getPointeeType();
6936 buildObjCPtr = true;
6937 } else {
6938 PointeeTy = PointerTy->getPointeeType();
6939 }
6940
6941 // Don't add qualified variants of arrays. For one, they're not allowed
6942 // (the qualifier would sink to the element type), and for another, the
6943 // only overload situation where it matters is subscript or pointer +- int,
6944 // and those shouldn't have qualifier variants anyway.
6945 if (PointeeTy->isArrayType())
6946 return true;
6947
6948 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6949 bool hasVolatile = VisibleQuals.hasVolatile();
6950 bool hasRestrict = VisibleQuals.hasRestrict();
6951
6952 // Iterate through all strict supersets of BaseCVR.
6953 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6954 if ((CVR | BaseCVR) != CVR) continue;
6955 // Skip over volatile if no volatile found anywhere in the types.
6956 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6957
6958 // Skip over restrict if no restrict found anywhere in the types, or if
6959 // the type cannot be restrict-qualified.
6960 if ((CVR & Qualifiers::Restrict) &&
6961 (!hasRestrict ||
6962 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6963 continue;
6964
6965 // Build qualified pointee type.
6966 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6967
6968 // Build qualified pointer type.
6969 QualType QPointerTy;
6970 if (!buildObjCPtr)
6971 QPointerTy = Context.getPointerType(QPointeeTy);
6972 else
6973 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6974
6975 // Insert qualified pointer type.
6976 PointerTypes.insert(QPointerTy);
6977 }
6978
6979 return true;
6980}
6981
6982/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6983/// to the set of pointer types along with any more-qualified variants of
6984/// that type. For example, if @p Ty is "int const *", this routine
6985/// will add "int const *", "int const volatile *", "int const
6986/// restrict *", and "int const volatile restrict *" to the set of
6987/// pointer types. Returns true if the add of @p Ty itself succeeded,
6988/// false otherwise.
6989///
6990/// FIXME: what to do about extended qualifiers?
6991bool
6992BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6993 QualType Ty) {
6994 // Insert this type.
6995 if (!MemberPointerTypes.insert(Ty))
6996 return false;
6997
6998 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6999 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 6999, __PRETTY_FUNCTION__))
;
7000
7001 QualType PointeeTy = PointerTy->getPointeeType();
7002 // Don't add qualified variants of arrays. For one, they're not allowed
7003 // (the qualifier would sink to the element type), and for another, the
7004 // only overload situation where it matters is subscript or pointer +- int,
7005 // and those shouldn't have qualifier variants anyway.
7006 if (PointeeTy->isArrayType())
7007 return true;
7008 const Type *ClassTy = PointerTy->getClass();
7009
7010 // Iterate through all strict supersets of the pointee type's CVR
7011 // qualifiers.
7012 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7013 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7014 if ((CVR | BaseCVR) != CVR) continue;
7015
7016 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7017 MemberPointerTypes.insert(
7018 Context.getMemberPointerType(QPointeeTy, ClassTy));
7019 }
7020
7021 return true;
7022}
7023
7024/// AddTypesConvertedFrom - Add each of the types to which the type @p
7025/// Ty can be implicit converted to the given set of @p Types. We're
7026/// primarily interested in pointer types and enumeration types. We also
7027/// take member pointer types, for the conditional operator.
7028/// AllowUserConversions is true if we should look at the conversion
7029/// functions of a class type, and AllowExplicitConversions if we
7030/// should also include the explicit conversion functions of a class
7031/// type.
7032void
7033BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7034 SourceLocation Loc,
7035 bool AllowUserConversions,
7036 bool AllowExplicitConversions,
7037 const Qualifiers &VisibleQuals) {
7038 // Only deal with canonical types.
7039 Ty = Context.getCanonicalType(Ty);
7040
7041 // Look through reference types; they aren't part of the type of an
7042 // expression for the purposes of conversions.
7043 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7044 Ty = RefTy->getPointeeType();
7045
7046 // If we're dealing with an array type, decay to the pointer.
7047 if (Ty->isArrayType())
7048 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7049
7050 // Otherwise, we don't care about qualifiers on the type.
7051 Ty = Ty.getLocalUnqualifiedType();
7052
7053 // Flag if we ever add a non-record type.
7054 const RecordType *TyRec = Ty->getAs<RecordType>();
7055 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7056
7057 // Flag if we encounter an arithmetic type.
7058 HasArithmeticOrEnumeralTypes =
7059 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7060
7061 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7062 PointerTypes.insert(Ty);
7063 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7064 // Insert our type, and its more-qualified variants, into the set
7065 // of types.
7066 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7067 return;
7068 } else if (Ty->isMemberPointerType()) {
7069 // Member pointers are far easier, since the pointee can't be converted.
7070 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7071 return;
7072 } else if (Ty->isEnumeralType()) {
7073 HasArithmeticOrEnumeralTypes = true;
7074 EnumerationTypes.insert(Ty);
7075 } else if (Ty->isVectorType()) {
7076 // We treat vector types as arithmetic types in many contexts as an
7077 // extension.
7078 HasArithmeticOrEnumeralTypes = true;
7079 VectorTypes.insert(Ty);
7080 } else if (Ty->isNullPtrType()) {
7081 HasNullPtrType = true;
7082 } else if (AllowUserConversions && TyRec) {
7083 // No conversion functions in incomplete types.
7084 if (!SemaRef.isCompleteType(Loc, Ty))
7085 return;
7086
7087 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7088 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7089 if (isa<UsingShadowDecl>(D))
7090 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7091
7092 // Skip conversion function templates; they don't tell us anything
7093 // about which builtin types we can convert to.
7094 if (isa<FunctionTemplateDecl>(D))
7095 continue;
7096
7097 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7098 if (AllowExplicitConversions || !Conv->isExplicit()) {
7099 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7100 VisibleQuals);
7101 }
7102 }
7103 }
7104}
7105
7106/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7107/// the volatile- and non-volatile-qualified assignment operators for the
7108/// given type to the candidate set.
7109static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7110 QualType T,
7111 ArrayRef<Expr *> Args,
7112 OverloadCandidateSet &CandidateSet) {
7113 QualType ParamTypes[2];
7114
7115 // T& operator=(T&, T)
7116 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7117 ParamTypes[1] = T;
7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7119 /*IsAssignmentOperator=*/true);
7120
7121 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7122 // volatile T& operator=(volatile T&, T)
7123 ParamTypes[0]
7124 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7125 ParamTypes[1] = T;
7126 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7127 /*IsAssignmentOperator=*/true);
7128 }
7129}
7130
7131/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7132/// if any, found in visible type conversion functions found in ArgExpr's type.
7133static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7134 Qualifiers VRQuals;
7135 const RecordType *TyRec;
7136 if (const MemberPointerType *RHSMPType =
7137 ArgExpr->getType()->getAs<MemberPointerType>())
7138 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7139 else
7140 TyRec = ArgExpr->getType()->getAs<RecordType>();
7141 if (!TyRec) {
7142 // Just to be safe, assume the worst case.
7143 VRQuals.addVolatile();
7144 VRQuals.addRestrict();
7145 return VRQuals;
7146 }
7147
7148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7149 if (!ClassDecl->hasDefinition())
7150 return VRQuals;
7151
7152 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7153 if (isa<UsingShadowDecl>(D))
7154 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7155 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7156 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7157 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7158 CanTy = ResTypeRef->getPointeeType();
7159 // Need to go down the pointer/mempointer chain and add qualifiers
7160 // as see them.
7161 bool done = false;
7162 while (!done) {
7163 if (CanTy.isRestrictQualified())
7164 VRQuals.addRestrict();
7165 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7166 CanTy = ResTypePtr->getPointeeType();
7167 else if (const MemberPointerType *ResTypeMPtr =
7168 CanTy->getAs<MemberPointerType>())
7169 CanTy = ResTypeMPtr->getPointeeType();
7170 else
7171 done = true;
7172 if (CanTy.isVolatileQualified())
7173 VRQuals.addVolatile();
7174 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7175 return VRQuals;
7176 }
7177 }
7178 }
7179 return VRQuals;
7180}
7181
7182namespace {
7183
7184/// \brief Helper class to manage the addition of builtin operator overload
7185/// candidates. It provides shared state and utility methods used throughout
7186/// the process, as well as a helper method to add each group of builtin
7187/// operator overloads from the standard to a candidate set.
7188class BuiltinOperatorOverloadBuilder {
7189 // Common instance state available to all overload candidate addition methods.
7190 Sema &S;
7191 ArrayRef<Expr *> Args;
7192 Qualifiers VisibleTypeConversionsQuals;
7193 bool HasArithmeticOrEnumeralCandidateType;
7194 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7195 OverloadCandidateSet &CandidateSet;
7196
7197 // Define some constants used to index and iterate over the arithemetic types
7198 // provided via the getArithmeticType() method below.
7199 // The "promoted arithmetic types" are the arithmetic
7200 // types are that preserved by promotion (C++ [over.built]p2).
7201 static const unsigned FirstIntegralType = 3;
7202 static const unsigned LastIntegralType = 20;
7203 static const unsigned FirstPromotedIntegralType = 3,
7204 LastPromotedIntegralType = 11;
7205 static const unsigned FirstPromotedArithmeticType = 0,
7206 LastPromotedArithmeticType = 11;
7207 static const unsigned NumArithmeticTypes = 20;
7208
7209 /// \brief Get the canonical type for a given arithmetic type index.
7210 CanQualType getArithmeticType(unsigned index) {
7211 assert(index < NumArithmeticTypes)((index < NumArithmeticTypes) ? static_cast<void> (0
) : __assert_fail ("index < NumArithmeticTypes", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7211, __PRETTY_FUNCTION__))
;
7212 static CanQualType ASTContext::* const
7213 ArithmeticTypes[NumArithmeticTypes] = {
7214 // Start of promoted types.
7215 &ASTContext::FloatTy,
7216 &ASTContext::DoubleTy,
7217 &ASTContext::LongDoubleTy,
7218
7219 // Start of integral types.
7220 &ASTContext::IntTy,
7221 &ASTContext::LongTy,
7222 &ASTContext::LongLongTy,
7223 &ASTContext::Int128Ty,
7224 &ASTContext::UnsignedIntTy,
7225 &ASTContext::UnsignedLongTy,
7226 &ASTContext::UnsignedLongLongTy,
7227 &ASTContext::UnsignedInt128Ty,
7228 // End of promoted types.
7229
7230 &ASTContext::BoolTy,
7231 &ASTContext::CharTy,
7232 &ASTContext::WCharTy,
7233 &ASTContext::Char16Ty,
7234 &ASTContext::Char32Ty,
7235 &ASTContext::SignedCharTy,
7236 &ASTContext::ShortTy,
7237 &ASTContext::UnsignedCharTy,
7238 &ASTContext::UnsignedShortTy,
7239 // End of integral types.
7240 // FIXME: What about complex? What about half?
7241 };
7242 return S.Context.*ArithmeticTypes[index];
7243 }
7244
7245 /// \brief Gets the canonical type resulting from the usual arithemetic
7246 /// converions for the given arithmetic types.
7247 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7248 // Accelerator table for performing the usual arithmetic conversions.
7249 // The rules are basically:
7250 // - if either is floating-point, use the wider floating-point
7251 // - if same signedness, use the higher rank
7252 // - if same size, use unsigned of the higher rank
7253 // - use the larger type
7254 // These rules, together with the axiom that higher ranks are
7255 // never smaller, are sufficient to precompute all of these results
7256 // *except* when dealing with signed types of higher rank.
7257 // (we could precompute SLL x UI for all known platforms, but it's
7258 // better not to make any assumptions).
7259 // We assume that int128 has a higher rank than long long on all platforms.
7260 enum PromotedType {
7261 Dep=-1,
7262 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7263 };
7264 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7265 [LastPromotedArithmeticType] = {
7266/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7267/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7268/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7269/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7270/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7271/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7272/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7273/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7274/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7275/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7276/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7277 };
7278
7279 assert(L < LastPromotedArithmeticType)((L < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("L < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7279, __PRETTY_FUNCTION__))
;
7280 assert(R < LastPromotedArithmeticType)((R < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("R < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7280, __PRETTY_FUNCTION__))
;
7281 int Idx = ConversionsTable[L][R];
7282
7283 // Fast path: the table gives us a concrete answer.
7284 if (Idx != Dep) return getArithmeticType(Idx);
7285
7286 // Slow path: we need to compare widths.
7287 // An invariant is that the signed type has higher rank.
7288 CanQualType LT = getArithmeticType(L),
7289 RT = getArithmeticType(R);
7290 unsigned LW = S.Context.getIntWidth(LT),
7291 RW = S.Context.getIntWidth(RT);
7292
7293 // If they're different widths, use the signed type.
7294 if (LW > RW) return LT;
7295 else if (LW < RW) return RT;
7296
7297 // Otherwise, use the unsigned type of the signed type's rank.
7298 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7299 assert(L == SLL || R == SLL)((L == SLL || R == SLL) ? static_cast<void> (0) : __assert_fail
("L == SLL || R == SLL", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7299, __PRETTY_FUNCTION__))
;
7300 return S.Context.UnsignedLongLongTy;
7301 }
7302
7303 /// \brief Helper method to factor out the common pattern of adding overloads
7304 /// for '++' and '--' builtin operators.
7305 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7306 bool HasVolatile,
7307 bool HasRestrict) {
7308 QualType ParamTypes[2] = {
7309 S.Context.getLValueReferenceType(CandidateTy),
7310 S.Context.IntTy
7311 };
7312
7313 // Non-volatile version.
7314 if (Args.size() == 1)
7315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7316 else
7317 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7318
7319 // Use a heuristic to reduce number of builtin candidates in the set:
7320 // add volatile version only if there are conversions to a volatile type.
7321 if (HasVolatile) {
7322 ParamTypes[0] =
7323 S.Context.getLValueReferenceType(
7324 S.Context.getVolatileType(CandidateTy));
7325 if (Args.size() == 1)
7326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7327 else
7328 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7329 }
7330
7331 // Add restrict version only if there are conversions to a restrict type
7332 // and our candidate type is a non-restrict-qualified pointer.
7333 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7334 !CandidateTy.isRestrictQualified()) {
7335 ParamTypes[0]
7336 = S.Context.getLValueReferenceType(
7337 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7338 if (Args.size() == 1)
7339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7340 else
7341 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7342
7343 if (HasVolatile) {
7344 ParamTypes[0]
7345 = S.Context.getLValueReferenceType(
7346 S.Context.getCVRQualifiedType(CandidateTy,
7347 (Qualifiers::Volatile |
7348 Qualifiers::Restrict)));
7349 if (Args.size() == 1)
7350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7351 else
7352 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7353 }
7354 }
7355
7356 }
7357
7358public:
7359 BuiltinOperatorOverloadBuilder(
7360 Sema &S, ArrayRef<Expr *> Args,
7361 Qualifiers VisibleTypeConversionsQuals,
7362 bool HasArithmeticOrEnumeralCandidateType,
7363 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7364 OverloadCandidateSet &CandidateSet)
7365 : S(S), Args(Args),
7366 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7367 HasArithmeticOrEnumeralCandidateType(
7368 HasArithmeticOrEnumeralCandidateType),
7369 CandidateTypes(CandidateTypes),
7370 CandidateSet(CandidateSet) {
7371 // Validate some of our static helper constants in debug builds.
7372 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7373, __PRETTY_FUNCTION__))
7373 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7373, __PRETTY_FUNCTION__))
;
7374 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
7375 == 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
7376 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
;
7377 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7379, __PRETTY_FUNCTION__))
7378 == 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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7379, __PRETTY_FUNCTION__))
7379 "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-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7379, __PRETTY_FUNCTION__))
;
7380 assert(getArithmeticType(LastPromotedArithmeticType - 1)((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7382, __PRETTY_FUNCTION__))
7381 == S.Context.UnsignedInt128Ty &&((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7382, __PRETTY_FUNCTION__))
7382 "Invalid last promoted arithmetic type")((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 7382, __PRETTY_FUNCTION__))
;
7383 }
7384
7385 // C++ [over.built]p3:
7386 //
7387 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7388 // is either volatile or empty, there exist candidate operator
7389 // functions of the form
7390 //
7391 // VQ T& operator++(VQ T&);
7392 // T operator++(VQ T&, int);
7393 //
7394 // C++ [over.built]p4:
7395 //
7396 // For every pair (T, VQ), where T is an arithmetic type other
7397 // than bool, and VQ is either volatile or empty, there exist
7398 // candidate operator functions of the form
7399 //
7400 // VQ T& operator--(VQ T&);
7401 // T operator--(VQ T&, int);
7402 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7403 if (!HasArithmeticOrEnumeralCandidateType)
7404 return;
7405
7406 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7407 Arith < NumArithmeticTypes; ++Arith) {
7408 addPlusPlusMinusMinusStyleOverloads(
7409 getArithmeticType(Arith),
7410 VisibleTypeConversionsQuals.hasVolatile(),
7411 VisibleTypeConversionsQuals.hasRestrict());
7412 }
7413 }
7414
7415 // C++ [over.built]p5:
7416 //
7417 // For every pair (T, VQ), where T is a cv-qualified or
7418 // cv-unqualified object type, and VQ is either volatile or
7419 // empty, there exist candidate operator functions of the form
7420 //
7421 // T*VQ& operator++(T*VQ&);
7422 // T*VQ& operator--(T*VQ&);
7423 // T* operator++(T*VQ&, int);
7424 // T* operator--(T*VQ&, int);
7425 void addPlusPlusMinusMinusPointerOverloads() {
7426 for (BuiltinCandidateTypeSet::iterator
7427 Ptr = CandidateTypes[0].pointer_begin(),
7428 PtrEnd = CandidateTypes[0].pointer_end();
7429 Ptr != PtrEnd; ++Ptr) {
7430 // Skip pointer types that aren't pointers to object types.
7431 if (!(*Ptr)->getPointeeType()->isObjectType())
7432 continue;
7433
7434 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7435 (!(*Ptr).isVolatileQualified() &&
7436 VisibleTypeConversionsQuals.hasVolatile()),
7437 (!(*Ptr).isRestrictQualified() &&
7438 VisibleTypeConversionsQuals.hasRestrict()));
7439 }
7440 }
7441
7442 // C++ [over.built]p6:
7443 // For every cv-qualified or cv-unqualified object type T, there
7444 // exist candidate operator functions of the form
7445 //
7446 // T& operator*(T*);
7447 //
7448 // C++ [over.built]p7:
7449 // For every function type T that does not have cv-qualifiers or a
7450 // ref-qualifier, there exist candidate operator functions of the form
7451 // T& operator*(T*);
7452 void addUnaryStarPointerOverloads() {
7453 for (BuiltinCandidateTypeSet::iterator
7454 Ptr = CandidateTypes[0].pointer_begin(),
7455 PtrEnd = CandidateTypes[0].pointer_end();
7456 Ptr != PtrEnd; ++Ptr) {
7457 QualType ParamTy = *Ptr;
7458 QualType PointeeTy = ParamTy->getPointeeType();
7459 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7460 continue;
7461
7462 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7463 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7464 continue;
7465
7466 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7467 &ParamTy, Args, CandidateSet);
7468 }
7469 }
7470
7471 // C++ [over.built]p9:
7472 // For every promoted arithmetic type T, there exist candidate
7473 // operator functions of the form
7474 //
7475 // T operator+(T);
7476 // T operator-(T);
7477 void addUnaryPlusOrMinusArithmeticOverloads() {
7478 if (!HasArithmeticOrEnumeralCandidateType)
7479 return;
7480
7481 for (unsigned Arith = FirstPromotedArithmeticType;
7482 Arith < LastPromotedArithmeticType; ++Arith) {
7483 QualType ArithTy = getArithmeticType(Arith);
7484 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7485 }
7486
7487 // Extension: We also add these operators for vector types.
7488 for (BuiltinCandidateTypeSet::iterator
7489 Vec = CandidateTypes[0].vector_begin(),
7490 VecEnd = CandidateTypes[0].vector_end();
7491 Vec != VecEnd; ++Vec) {
7492 QualType VecTy = *Vec;
7493 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7494 }
7495 }
7496
7497 // C++ [over.built]p8:
7498 // For every type T, there exist candidate operator functions of
7499 // the form
7500 //
7501 // T* operator+(T*);
7502 void addUnaryPlusPointerOverloads() {
7503 for (BuiltinCandidateTypeSet::iterator
7504 Ptr = CandidateTypes[0].pointer_begin(),
7505 PtrEnd = CandidateTypes[0].pointer_end();
7506 Ptr != PtrEnd; ++Ptr) {
7507 QualType ParamTy = *Ptr;
7508 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7509 }
7510 }
7511
7512 // C++ [over.built]p10:
7513 // For every promoted integral type T, there exist candidate
7514 // operator functions of the form
7515 //
7516 // T operator~(T);
7517 void addUnaryTildePromotedIntegralOverloads() {
7518 if (!HasArithmeticOrEnumeralCandidateType)
7519 return;
7520
7521 for (unsigned Int = FirstPromotedIntegralType;
7522 Int < LastPromotedIntegralType; ++Int) {
7523 QualType IntTy = getArithmeticType(Int);
7524 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7525 }
7526
7527 // Extension: We also add this operator for vector types.
7528 for (BuiltinCandidateTypeSet::iterator
7529 Vec = CandidateTypes[0].vector_begin(),
7530 VecEnd = CandidateTypes[0].vector_end();
7531 Vec != VecEnd; ++Vec) {
7532 QualType VecTy = *Vec;
7533 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7534 }
7535 }
7536
7537 // C++ [over.match.oper]p16:
7538 // For every pointer to member type T, there exist candidate operator
7539 // functions of the form
7540 //
7541 // bool operator==(T,T);
7542 // bool operator!=(T,T);
7543 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7544 /// Set of (canonical) types that we've already handled.
7545 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7546
7547 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7548 for (BuiltinCandidateTypeSet::iterator
7549 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7550 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7551 MemPtr != MemPtrEnd;
7552 ++MemPtr) {
7553 // Don't add the same builtin candidate twice.
7554 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7555 continue;
7556
7557 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7558 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7559 }
7560 }
7561 }
7562
7563 // C++ [over.built]p15:
7564 //
7565 // For every T, where T is an enumeration type, a pointer type, or
7566 // std::nullptr_t, there exist candidate operator functions of the form
7567 //
7568 // bool operator<(T, T);
7569 // bool operator>(T, T);
7570 // bool operator<=(T, T);
7571 // bool operator>=(T, T);
7572 // bool operator==(T, T);
7573 // bool operator!=(T, T);
7574 void addRelationalPointerOrEnumeralOverloads() {
7575 // C++ [over.match.oper]p3:
7576 // [...]the built-in candidates include all of the candidate operator
7577 // functions defined in 13.6 that, compared to the given operator, [...]
7578 // do not have the same parameter-type-list as any non-template non-member
7579 // candidate.
7580 //
7581 // Note that in practice, this only affects enumeration types because there
7582 // aren't any built-in candidates of record type, and a user-defined operator
7583 // must have an operand of record or enumeration type. Also, the only other
7584 // overloaded operator with enumeration arguments, operator=,
7585 // cannot be overloaded for enumeration types, so this is the only place
7586 // where we must suppress candidates like this.
7587 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7588 UserDefinedBinaryOperators;
7589
7590 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7591 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7592 CandidateTypes[ArgIdx].enumeration_end()) {
7593 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7594 CEnd = CandidateSet.end();
7595 C != CEnd; ++C) {
7596 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7597 continue;
7598
7599 if (C->Function->isFunctionTemplateSpecialization())
7600 continue;
7601
7602 QualType FirstParamType =
7603 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7604 QualType SecondParamType =
7605 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7606
7607 // Skip if either parameter isn't of enumeral type.
7608 if (!FirstParamType->isEnumeralType() ||
7609 !SecondParamType->isEnumeralType())
7610 continue;
7611
7612 // Add this operator to the set of known user-defined operators.
7613 UserDefinedBinaryOperators.insert(
7614 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7615 S.Context.getCanonicalType(SecondParamType)));
7616 }
7617 }
7618 }
7619
7620 /// Set of (canonical) types that we've already handled.
7621 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7622
7623 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7624 for (BuiltinCandidateTypeSet::iterator
7625 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7626 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7627 Ptr != PtrEnd; ++Ptr) {
7628 // Don't add the same builtin candidate twice.
7629 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7630 continue;
7631
7632 QualType ParamTypes[2] = { *Ptr, *Ptr };
7633 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7634 }
7635 for (BuiltinCandidateTypeSet::iterator
7636 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7637 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7638 Enum != EnumEnd; ++Enum) {
7639 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7640
7641 // Don't add the same builtin candidate twice, or if a user defined
7642 // candidate exists.
7643 if (!AddedTypes.insert(CanonType).second ||
7644 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7645 CanonType)))
7646 continue;
7647
7648 QualType ParamTypes[2] = { *Enum, *Enum };
7649 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7650 }
7651
7652 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7653 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7654 if (AddedTypes.insert(NullPtrTy).second &&
7655 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7656 NullPtrTy))) {
7657 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7658 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7659 CandidateSet);
7660 }
7661 }
7662 }
7663 }
7664
7665 // C++ [over.built]p13:
7666 //
7667 // For every cv-qualified or cv-unqualified object type T
7668 // there exist candidate operator functions of the form
7669 //
7670 // T* operator+(T*, ptrdiff_t);
7671 // T& operator[](T*, ptrdiff_t); [BELOW]
7672 // T* operator-(T*, ptrdiff_t);
7673 // T* operator+(ptrdiff_t, T*);
7674 // T& operator[](ptrdiff_t, T*); [BELOW]
7675 //
7676 // C++ [over.built]p14:
7677 //
7678 // For every T, where T is a pointer to object type, there
7679 // exist candidate operator functions of the form
7680 //
7681 // ptrdiff_t operator-(T, T);
7682 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7683 /// Set of (canonical) types that we've already handled.
7684 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7685
7686 for (int Arg = 0; Arg < 2; ++Arg) {
7687 QualType AsymmetricParamTypes[2] = {
7688 S.Context.getPointerDiffType(),
7689 S.Context.getPointerDiffType(),
7690 };
7691 for (BuiltinCandidateTypeSet::iterator
7692 Ptr = CandidateTypes[Arg].pointer_begin(),
7693 PtrEnd = CandidateTypes[Arg].pointer_end();
7694 Ptr != PtrEnd; ++Ptr) {
7695 QualType PointeeTy = (*Ptr)->getPointeeType();
7696 if (!PointeeTy->isObjectType())
7697 continue;
7698
7699 AsymmetricParamTypes[Arg] = *Ptr;
7700 if (Arg == 0 || Op == OO_Plus) {
7701 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7702 // T* operator+(ptrdiff_t, T*);
7703 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7704 }
7705 if (Op == OO_Minus) {
7706 // ptrdiff_t operator-(T, T);
7707 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7708 continue;
7709
7710 QualType ParamTypes[2] = { *Ptr, *Ptr };
7711 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7712 Args, CandidateSet);
7713 }
7714 }
7715 }
7716 }
7717
7718 // C++ [over.built]p12:
7719 //
7720 // For every pair of promoted arithmetic types L and R, there
7721 // exist candidate operator functions of the form
7722 //
7723 // LR operator*(L, R);
7724 // LR operator/(L, R);
7725 // LR operator+(L, R);
7726 // LR operator-(L, R);
7727 // bool operator<(L, R);
7728 // bool operator>(L, R);
7729 // bool operator<=(L, R);
7730 // bool operator>=(L, R);
7731 // bool operator==(L, R);
7732 // bool operator!=(L, R);
7733 //
7734 // where LR is the result of the usual arithmetic conversions
7735 // between types L and R.
7736 //
7737 // C++ [over.built]p24:
7738 //
7739 // For every pair of promoted arithmetic types L and R, there exist
7740 // candidate operator functions of the form
7741 //
7742 // LR operator?(bool, L, R);
7743 //
7744 // where LR is the result of the usual arithmetic conversions
7745 // between types L and R.
7746 // Our candidates ignore the first parameter.
7747 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7748 if (!HasArithmeticOrEnumeralCandidateType)
7749 return;
7750
7751 for (unsigned Left = FirstPromotedArithmeticType;
7752 Left < LastPromotedArithmeticType; ++Left) {
7753 for (unsigned Right = FirstPromotedArithmeticType;
7754 Right < LastPromotedArithmeticType; ++Right) {
7755 QualType LandR[2] = { getArithmeticType(Left),
7756 getArithmeticType(Right) };
7757 QualType Result =
7758 isComparison ? S.Context.BoolTy
7759 : getUsualArithmeticConversions(Left, Right);
7760 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7761 }
7762 }
7763
7764 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7765 // conditional operator for vector types.
7766 for (BuiltinCandidateTypeSet::iterator
7767 Vec1 = CandidateTypes[0].vector_begin(),
7768 Vec1End = CandidateTypes[0].vector_end();
7769 Vec1 != Vec1End; ++Vec1) {
7770 for (BuiltinCandidateTypeSet::iterator
7771 Vec2 = CandidateTypes[1].vector_begin(),
7772 Vec2End = CandidateTypes[1].vector_end();
7773 Vec2 != Vec2End; ++Vec2) {
7774 QualType LandR[2] = { *Vec1, *Vec2 };
7775 QualType Result = S.Context.BoolTy;
7776 if (!isComparison) {
7777 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7778 Result = *Vec1;
7779 else
7780 Result = *Vec2;
7781 }
7782
7783 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7784 }
7785 }
7786 }
7787
7788 // C++ [over.built]p17:
7789 //
7790 // For every pair of promoted integral types L and R, there
7791 // exist candidate operator functions of the form
7792 //
7793 // LR operator%(L, R);
7794 // LR operator&(L, R);
7795 // LR operator^(L, R);
7796 // LR operator|(L, R);
7797 // L operator<<(L, R);
7798 // L operator>>(L, R);
7799 //
7800 // where LR is the result of the usual arithmetic conversions
7801 // between types L and R.
7802 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7803 if (!HasArithmeticOrEnumeralCandidateType)
7804 return;
7805
7806 for (unsigned Left = FirstPromotedIntegralType;
7807 Left < LastPromotedIntegralType; ++Left) {
7808 for (unsigned Right = FirstPromotedIntegralType;
7809 Right < LastPromotedIntegralType; ++Right) {
7810 QualType LandR[2] = { getArithmeticType(Left),
7811 getArithmeticType(Right) };
7812 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7813 ? LandR[0]
7814 : getUsualArithmeticConversions(Left, Right);
7815 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7816 }
7817 }
7818 }
7819
7820 // C++ [over.built]p20:
7821 //
7822 // For every pair (T, VQ), where T is an enumeration or
7823 // pointer to member type and VQ is either volatile or
7824 // empty, there exist candidate operator functions of the form
7825 //
7826 // VQ T& operator=(VQ T&, T);
7827 void addAssignmentMemberPointerOrEnumeralOverloads() {
7828 /// Set of (canonical) types that we've already handled.
7829 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7830
7831 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7832 for (BuiltinCandidateTypeSet::iterator
7833 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7834 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7835 Enum != EnumEnd; ++Enum) {
7836 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7837 continue;
7838
7839 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7840 }
7841
7842 for (BuiltinCandidateTypeSet::iterator
7843 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7844 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7845 MemPtr != MemPtrEnd; ++MemPtr) {
7846 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7847 continue;
7848
7849 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7850 }
7851 }
7852 }
7853
7854 // C++ [over.built]p19:
7855 //
7856 // For every pair (T, VQ), where T is any type and VQ is either
7857 // volatile or empty, there exist candidate operator functions
7858 // of the form
7859 //
7860 // T*VQ& operator=(T*VQ&, T*);
7861 //
7862 // C++ [over.built]p21:
7863 //
7864 // For every pair (T, VQ), where T is a cv-qualified or
7865 // cv-unqualified object type and VQ is either volatile or
7866 // empty, there exist candidate operator functions of the form
7867 //
7868 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7869 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7870 void addAssignmentPointerOverloads(bool isEqualOp) {
7871 /// Set of (canonical) types that we've already handled.
7872 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7873
7874 for (BuiltinCandidateTypeSet::iterator
7875 Ptr = CandidateTypes[0].pointer_begin(),
7876 PtrEnd = CandidateTypes[0].pointer_end();
7877 Ptr != PtrEnd; ++Ptr) {
7878 // If this is operator=, keep track of the builtin candidates we added.
7879 if (isEqualOp)
7880 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7881 else if (!(*Ptr)->getPointeeType()->isObjectType())
7882 continue;
7883
7884 // non-volatile version
7885 QualType ParamTypes[2] = {
7886 S.Context.getLValueReferenceType(*Ptr),
7887 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7888 };
7889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7890 /*IsAssigmentOperator=*/ isEqualOp);
7891
7892 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7893 VisibleTypeConversionsQuals.hasVolatile();
7894 if (NeedVolatile) {
7895 // volatile version
7896 ParamTypes[0] =
7897 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7898 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7899 /*IsAssigmentOperator=*/isEqualOp);
7900 }
7901
7902 if (!(*Ptr).isRestrictQualified() &&
7903 VisibleTypeConversionsQuals.hasRestrict()) {
7904 // restrict version
7905 ParamTypes[0]
7906 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7907 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7908 /*IsAssigmentOperator=*/isEqualOp);
7909
7910 if (NeedVolatile) {
7911 // volatile restrict version
7912 ParamTypes[0]
7913 = S.Context.getLValueReferenceType(
7914 S.Context.getCVRQualifiedType(*Ptr,
7915 (Qualifiers::Volatile |
7916 Qualifiers::Restrict)));
7917 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7918 /*IsAssigmentOperator=*/isEqualOp);
7919 }
7920 }
7921 }
7922
7923 if (isEqualOp) {
7924 for (BuiltinCandidateTypeSet::iterator
7925 Ptr = CandidateTypes[1].pointer_begin(),
7926 PtrEnd = CandidateTypes[1].pointer_end();
7927 Ptr != PtrEnd; ++Ptr) {
7928 // Make sure we don't add the same candidate twice.
7929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7930 continue;
7931
7932 QualType ParamTypes[2] = {
7933 S.Context.getLValueReferenceType(*Ptr),
7934 *Ptr,
7935 };
7936
7937 // non-volatile version
7938 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7939 /*IsAssigmentOperator=*/true);
7940
7941 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7942 VisibleTypeConversionsQuals.hasVolatile();
7943 if (NeedVolatile) {
7944 // volatile version
7945 ParamTypes[0] =
7946 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7947 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7948 /*IsAssigmentOperator=*/true);
7949 }
7950
7951 if (!(*Ptr).isRestrictQualified() &&
7952 VisibleTypeConversionsQuals.hasRestrict()) {
7953 // restrict version
7954 ParamTypes[0]
7955 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7956 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7957 /*IsAssigmentOperator=*/true);
7958
7959 if (NeedVolatile) {
7960 // volatile restrict version
7961 ParamTypes[0]
7962 = S.Context.getLValueReferenceType(
7963 S.Context.getCVRQualifiedType(*Ptr,
7964 (Qualifiers::Volatile |
7965 Qualifiers::Restrict)));
7966 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7967 /*IsAssigmentOperator=*/true);
7968 }
7969 }
7970 }
7971 }
7972 }
7973
7974 // C++ [over.built]p18:
7975 //
7976 // For every triple (L, VQ, R), where L is an arithmetic type,
7977 // VQ is either volatile or empty, and R is a promoted
7978 // arithmetic type, there exist candidate operator functions of
7979 // the form
7980 //
7981 // VQ L& operator=(VQ L&, R);
7982 // VQ L& operator*=(VQ L&, R);
7983 // VQ L& operator/=(VQ L&, R);
7984 // VQ L& operator+=(VQ L&, R);
7985 // VQ L& operator-=(VQ L&, R);
7986 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7987 if (!HasArithmeticOrEnumeralCandidateType)
7988 return;
7989
7990 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7991 for (unsigned Right = FirstPromotedArithmeticType;
7992 Right < LastPromotedArithmeticType; ++Right) {
7993 QualType ParamTypes[2];
7994 ParamTypes[1] = getArithmeticType(Right);
7995
7996 // Add this built-in operator as a candidate (VQ is empty).
7997 ParamTypes[0] =
7998 S.Context.getLValueReferenceType(getArithmeticType(Left));
7999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8000 /*IsAssigmentOperator=*/isEqualOp);
8001
8002 // Add this built-in operator as a candidate (VQ is 'volatile').
8003 if (VisibleTypeConversionsQuals.hasVolatile()) {
8004 ParamTypes[0] =
8005 S.Context.getVolatileType(getArithmeticType(Left));
8006 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8007 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8008 /*IsAssigmentOperator=*/isEqualOp);
8009 }
8010 }
8011 }
8012
8013 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8014 for (BuiltinCandidateTypeSet::iterator
8015 Vec1 = CandidateTypes[0].vector_begin(),
8016 Vec1End = CandidateTypes[0].vector_end();
8017 Vec1 != Vec1End; ++Vec1) {
8018 for (BuiltinCandidateTypeSet::iterator
8019 Vec2 = CandidateTypes[1].vector_begin(),
8020 Vec2End = CandidateTypes[1].vector_end();
8021 Vec2 != Vec2End; ++Vec2) {
8022 QualType ParamTypes[2];
8023 ParamTypes[1] = *Vec2;
8024 // Add this built-in operator as a candidate (VQ is empty).
8025 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8026 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8027 /*IsAssigmentOperator=*/isEqualOp);
8028
8029 // Add this built-in operator as a candidate (VQ is 'volatile').
8030 if (VisibleTypeConversionsQuals.hasVolatile()) {
8031 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8032 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8033 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8034 /*IsAssigmentOperator=*/isEqualOp);
8035 }
8036 }
8037 }
8038 }
8039
8040 // C++ [over.built]p22:
8041 //
8042 // For every triple (L, VQ, R), where L is an integral type, VQ
8043 // is either volatile or empty, and R is a promoted integral
8044 // type, there exist candidate operator functions of the form
8045 //
8046 // VQ L& operator%=(VQ L&, R);
8047 // VQ L& operator<<=(VQ L&, R);
8048 // VQ L& operator>>=(VQ L&, R);
8049 // VQ L& operator&=(VQ L&, R);
8050 // VQ L& operator^=(VQ L&, R);
8051 // VQ L& operator|=(VQ L&, R);
8052 void addAssignmentIntegralOverloads() {
8053 if (!HasArithmeticOrEnumeralCandidateType)
8054 return;
8055
8056 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8057 for (unsigned Right = FirstPromotedIntegralType;
8058 Right < LastPromotedIntegralType; ++Right) {
8059 QualType ParamTypes[2];
8060 ParamTypes[1] = getArithmeticType(Right);
8061
8062 // Add this built-in operator as a candidate (VQ is empty).
8063 ParamTypes[0] =
8064 S.Context.getLValueReferenceType(getArithmeticType(Left));
8065 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8066 if (VisibleTypeConversionsQuals.hasVolatile()) {
8067 // Add this built-in operator as a candidate (VQ is 'volatile').
8068 ParamTypes[0] = getArithmeticType(Left);
8069 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8070 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8071 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8072 }
8073 }
8074 }
8075 }
8076
8077 // C++ [over.operator]p23:
8078 //
8079 // There also exist candidate operator functions of the form
8080 //
8081 // bool operator!(bool);
8082 // bool operator&&(bool, bool);
8083 // bool operator||(bool, bool);
8084 void addExclaimOverload() {
8085 QualType ParamTy = S.Context.BoolTy;
8086 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8087 /*IsAssignmentOperator=*/false,
8088 /*NumContextualBoolArguments=*/1);
8089 }
8090 void addAmpAmpOrPipePipeOverload() {
8091 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8092 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8093 /*IsAssignmentOperator=*/false,
8094 /*NumContextualBoolArguments=*/2);
8095 }
8096
8097 // C++ [over.built]p13:
8098 //
8099 // For every cv-qualified or cv-unqualified object type T there
8100 // exist candidate operator functions of the form
8101 //
8102 // T* operator+(T*, ptrdiff_t); [ABOVE]
8103 // T& operator[](T*, ptrdiff_t);
8104 // T* operator-(T*, ptrdiff_t); [ABOVE]
8105 // T* operator+(ptrdiff_t, T*); [ABOVE]
8106 // T& operator[](ptrdiff_t, T*);
8107 void addSubscriptOverloads() {
8108 for (BuiltinCandidateTypeSet::iterator
8109 Ptr = CandidateTypes[0].pointer_begin(),
8110 PtrEnd = CandidateTypes[0].pointer_end();
8111 Ptr != PtrEnd; ++Ptr) {
8112 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8113 QualType PointeeType = (*Ptr)->getPointeeType();
8114 if (!PointeeType->isObjectType())
8115 continue;
8116
8117 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8118
8119 // T& operator[](T*, ptrdiff_t)
8120 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8121 }
8122
8123 for (BuiltinCandidateTypeSet::iterator
8124 Ptr = CandidateTypes[1].pointer_begin(),
8125 PtrEnd = CandidateTypes[1].pointer_end();
8126 Ptr != PtrEnd; ++Ptr) {
8127 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8128 QualType PointeeType = (*Ptr)->getPointeeType();
8129 if (!PointeeType->isObjectType())
8130 continue;
8131
8132 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8133
8134 // T& operator[](ptrdiff_t, T*)
8135 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8136 }
8137 }
8138
8139 // C++ [over.built]p11:
8140 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8141 // C1 is the same type as C2 or is a derived class of C2, T is an object
8142 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8143 // there exist candidate operator functions of the form
8144 //
8145 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8146 //
8147 // where CV12 is the union of CV1 and CV2.
8148 void addArrowStarOverloads() {
8149 for (BuiltinCandidateTypeSet::iterator
8150 Ptr = CandidateTypes[0].pointer_begin(),
8151 PtrEnd = CandidateTypes[0].pointer_end();
8152 Ptr != PtrEnd; ++Ptr) {
8153 QualType C1Ty = (*Ptr);
8154 QualType C1;
8155 QualifierCollector Q1;
8156 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8157 if (!isa<RecordType>(C1))
8158 continue;
8159 // heuristic to reduce number of builtin candidates in the set.
8160 // Add volatile/restrict version only if there are conversions to a
8161 // volatile/restrict type.
8162 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8163 continue;
8164 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8165 continue;
8166 for (BuiltinCandidateTypeSet::iterator
8167 MemPtr = CandidateTypes[1].member_pointer_begin(),
8168 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8169 MemPtr != MemPtrEnd; ++MemPtr) {
8170 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8171 QualType C2 = QualType(mptr->getClass(), 0);
8172 C2 = C2.getUnqualifiedType();
8173 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8174 break;
8175 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8176 // build CV12 T&
8177 QualType T = mptr->getPointeeType();
8178 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8179 T.isVolatileQualified())
8180 continue;
8181 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8182 T.isRestrictQualified())
8183 continue;
8184 T = Q1.apply(S.Context, T);
8185 QualType ResultTy = S.Context.getLValueReferenceType(T);
8186 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8187 }
8188 }
8189 }
8190
8191 // Note that we don't consider the first argument, since it has been
8192 // contextually converted to bool long ago. The candidates below are
8193 // therefore added as binary.
8194 //
8195 // C++ [over.built]p25:
8196 // For every type T, where T is a pointer, pointer-to-member, or scoped
8197 // enumeration type, there exist candidate operator functions of the form
8198 //
8199 // T operator?(bool, T, T);
8200 //
8201 void addConditionalOperatorOverloads() {
8202 /// Set of (canonical) types that we've already handled.
8203 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8204
8205 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8206 for (BuiltinCandidateTypeSet::iterator
8207 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8208 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8209 Ptr != PtrEnd; ++Ptr) {
8210 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8211 continue;
8212
8213 QualType ParamTypes[2] = { *Ptr, *Ptr };
8214 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8215 }
8216
8217 for (BuiltinCandidateTypeSet::iterator
8218 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8219 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8220 MemPtr != MemPtrEnd; ++MemPtr) {
8221 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8222 continue;
8223
8224 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8225 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8226 }
8227
8228 if (S.getLangOpts().CPlusPlus11) {
8229 for (BuiltinCandidateTypeSet::iterator
8230 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8231 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8232 Enum != EnumEnd; ++Enum) {
8233 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8234 continue;
8235
8236 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8237 continue;
8238
8239 QualType ParamTypes[2] = { *Enum, *Enum };
8240 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8241 }
8242 }
8243 }
8244 }
8245};
8246
8247} // end anonymous namespace
8248
8249/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8250/// operator overloads to the candidate set (C++ [over.built]), based
8251/// on the operator @p Op and the arguments given. For example, if the
8252/// operator is a binary '+', this routine might add "int
8253/// operator+(int, int)" to cover integer addition.
8254void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8255 SourceLocation OpLoc,
8256 ArrayRef<Expr *> Args,
8257 OverloadCandidateSet &CandidateSet) {
8258 // Find all of the types that the arguments can convert to, but only
8259 // if the operator we're looking at has built-in operator candidates
8260 // that make use of these types. Also record whether we encounter non-record
8261 // candidate types or either arithmetic or enumeral candidate types.
8262 Qualifiers VisibleTypeConversionsQuals;
8263 VisibleTypeConversionsQuals.addConst();
8264 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8265 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8266
8267 bool HasNonRecordCandidateType = false;
8268 bool HasArithmeticOrEnumeralCandidateType = false;
8269 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8270 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8271 CandidateTypes.emplace_back(*this);
8272 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8273 OpLoc,
8274 true,
8275 (Op == OO_Exclaim ||
8276 Op == OO_AmpAmp ||
8277 Op == OO_PipePipe),
8278 VisibleTypeConversionsQuals);
8279 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8280 CandidateTypes[ArgIdx].hasNonRecordTypes();
8281 HasArithmeticOrEnumeralCandidateType =
8282 HasArithmeticOrEnumeralCandidateType ||
8283 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8284 }
8285
8286 // Exit early when no non-record types have been added to the candidate set
8287 // for any of the arguments to the operator.
8288 //
8289 // We can't exit early for !, ||, or &&, since there we have always have
8290 // 'bool' overloads.
8291 if (!HasNonRecordCandidateType &&
8292 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8293 return;
8294
8295 // Setup an object to manage the common state for building overloads.
8296 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8297 VisibleTypeConversionsQuals,
8298 HasArithmeticOrEnumeralCandidateType,
8299 CandidateTypes, CandidateSet);
8300
8301 // Dispatch over the operation to add in only those overloads which apply.
8302 switch (Op) {
8303 case OO_None:
8304 case NUM_OVERLOADED_OPERATORS:
8305 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8305)
;
8306
8307 case OO_New:
8308 case OO_Delete:
8309 case OO_Array_New:
8310 case OO_Array_Delete:
8311 case OO_Call:
8312 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8313)
8313 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8313)
;
8314
8315 case OO_Comma:
8316 case OO_Arrow:
8317 case OO_Coawait:
8318 // C++ [over.match.oper]p3:
8319 // -- For the operator ',', the unary operator '&', the
8320 // operator '->', or the operator 'co_await', the
8321 // built-in candidates set is empty.
8322 break;
8323
8324 case OO_Plus: // '+' is either unary or binary
8325 if (Args.size() == 1)
8326 OpBuilder.addUnaryPlusPointerOverloads();
8327 // Fall through.
8328
8329 case OO_Minus: // '-' is either unary or binary
8330 if (Args.size() == 1) {
8331 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8332 } else {
8333 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8334 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8335 }
8336 break;
8337
8338 case OO_Star: // '*' is either unary or binary
8339 if (Args.size() == 1)
8340 OpBuilder.addUnaryStarPointerOverloads();
8341 else
8342 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8343 break;
8344
8345 case OO_Slash:
8346 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8347 break;
8348
8349 case OO_PlusPlus:
8350 case OO_MinusMinus:
8351 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8352 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8353 break;
8354
8355 case OO_EqualEqual:
8356 case OO_ExclaimEqual:
8357 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8358 // Fall through.
8359
8360 case OO_Less:
8361 case OO_Greater:
8362 case OO_LessEqual:
8363 case OO_GreaterEqual:
8364 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8365 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8366 break;
8367
8368 case OO_Percent:
8369 case OO_Caret:
8370 case OO_Pipe:
8371 case OO_LessLess:
8372 case OO_GreaterGreater:
8373 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8374 break;
8375
8376 case OO_Amp: // '&' is either unary or binary
8377 if (Args.size() == 1)
8378 // C++ [over.match.oper]p3:
8379 // -- For the operator ',', the unary operator '&', or the
8380 // operator '->', the built-in candidates set is empty.
8381 break;
8382
8383 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8384 break;
8385
8386 case OO_Tilde:
8387 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8388 break;
8389
8390 case OO_Equal:
8391 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8392 // Fall through.
8393
8394 case OO_PlusEqual:
8395 case OO_MinusEqual:
8396 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8397 // Fall through.
8398
8399 case OO_StarEqual:
8400 case OO_SlashEqual:
8401 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8402 break;
8403
8404 case OO_PercentEqual:
8405 case OO_LessLessEqual:
8406 case OO_GreaterGreaterEqual:
8407 case OO_AmpEqual:
8408 case OO_CaretEqual:
8409 case OO_PipeEqual:
8410 OpBuilder.addAssignmentIntegralOverloads();
8411 break;
8412
8413 case OO_Exclaim:
8414 OpBuilder.addExclaimOverload();
8415 break;
8416
8417 case OO_AmpAmp:
8418 case OO_PipePipe:
8419 OpBuilder.addAmpAmpOrPipePipeOverload();
8420 break;
8421
8422 case OO_Subscript:
8423 OpBuilder.addSubscriptOverloads();
8424 break;
8425
8426 case OO_ArrowStar:
8427 OpBuilder.addArrowStarOverloads();
8428 break;
8429
8430 case OO_Conditional:
8431 OpBuilder.addConditionalOperatorOverloads();
8432 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8433 break;
8434 }
8435}
8436
8437/// \brief Add function candidates found via argument-dependent lookup
8438/// to the set of overloading candidates.
8439///
8440/// This routine performs argument-dependent name lookup based on the
8441/// given function name (which may also be an operator name) and adds
8442/// all of the overload candidates found by ADL to the overload
8443/// candidate set (C++ [basic.lookup.argdep]).
8444void
8445Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8446 SourceLocation Loc,
8447 ArrayRef<Expr *> Args,
8448 TemplateArgumentListInfo *ExplicitTemplateArgs,
8449 OverloadCandidateSet& CandidateSet,
8450 bool PartialOverloading) {
8451 ADLResult Fns;
8452
8453 // FIXME: This approach for uniquing ADL results (and removing
8454 // redundant candidates from the set) relies on pointer-equality,
8455 // which means we need to key off the canonical decl. However,
8456 // always going back to the canonical decl might not get us the
8457 // right set of default arguments. What default arguments are
8458 // we supposed to consider on ADL candidates, anyway?
8459
8460 // FIXME: Pass in the explicit template arguments?
8461 ArgumentDependentLookup(Name, Loc, Args, Fns);
8462
8463 // Erase all of the candidates we already knew about.
8464 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8465 CandEnd = CandidateSet.end();
8466 Cand != CandEnd; ++Cand)
8467 if (Cand->Function) {
8468 Fns.erase(Cand->Function);
8469 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8470 Fns.erase(FunTmpl);
8471 }
8472
8473 // For each of the ADL candidates we found, add it to the overload
8474 // set.
8475 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8476 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8477 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8478 if (ExplicitTemplateArgs)
8479 continue;
8480
8481 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8482 PartialOverloading);
8483 } else
8484 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8485 FoundDecl, ExplicitTemplateArgs,
8486 Args, CandidateSet, PartialOverloading);
8487 }
8488}
8489
8490// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8491// Cand2 for overloading. This function assumes that all of the enable_if attrs
8492// on Cand1 and Cand2 have conditions that evaluate to true.
8493//
8494// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8495// Cand1's first N enable_if attributes have precisely the same conditions as
8496// Cand2's first N enable_if attributes (where N = the number of enable_if
8497// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8498static bool hasBetterEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8499 const FunctionDecl *Cand2) {
8500
8501 // FIXME: The next several lines are just
8502 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8503 // instead of reverse order which is how they're stored in the AST.
8504 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8505 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8506
8507 // Candidate 1 is better if it has strictly more attributes and
8508 // the common sequence is identical.
8509 if (Cand1Attrs.size() <= Cand2Attrs.size())
8510 return false;
8511
8512 auto Cand1I = Cand1Attrs.begin();
8513 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8514 for (auto &Cand2A : Cand2Attrs) {
8515 Cand1ID.clear();
8516 Cand2ID.clear();
8517
8518 auto &Cand1A = *Cand1I++;
8519 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8520 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8521 if (Cand1ID != Cand2ID)
8522 return false;
8523 }
8524
8525 return true;
8526}
8527
8528/// isBetterOverloadCandidate - Determines whether the first overload
8529/// candidate is a better candidate than the second (C++ 13.3.3p1).
8530bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8531 const OverloadCandidate &Cand2,
8532 SourceLocation Loc,
8533 bool UserDefinedConversion) {
8534 // Define viable functions to be better candidates than non-viable
8535 // functions.
8536 if (!Cand2.Viable)
8537 return Cand1.Viable;
8538 else if (!Cand1.Viable)
8539 return false;
8540
8541 // C++ [over.match.best]p1:
8542 //
8543 // -- if F is a static member function, ICS1(F) is defined such
8544 // that ICS1(F) is neither better nor worse than ICS1(G) for
8545 // any function G, and, symmetrically, ICS1(G) is neither
8546 // better nor worse than ICS1(F).
8547 unsigned StartArg = 0;
8548 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8549 StartArg = 1;
8550
8551 // C++ [over.match.best]p1:
8552 // A viable function F1 is defined to be a better function than another
8553 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8554 // conversion sequence than ICSi(F2), and then...
8555 unsigned NumArgs = Cand1.NumConversions;
8556 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch")((Cand2.NumConversions == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.NumConversions == NumArgs && \"Overload candidate mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8556, __PRETTY_FUNCTION__))
;
8557 bool HasBetterConversion = false;
8558 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8559 switch (CompareImplicitConversionSequences(S, Loc,
8560 Cand1.Conversions[ArgIdx],
8561 Cand2.Conversions[ArgIdx])) {
8562 case ImplicitConversionSequence::Better:
8563 // Cand1 has a better conversion sequence.
8564 HasBetterConversion = true;
8565 break;
8566
8567 case ImplicitConversionSequence::Worse:
8568 // Cand1 can't be better than Cand2.
8569 return false;
8570
8571 case ImplicitConversionSequence::Indistinguishable:
8572 // Do nothing.
8573 break;
8574 }
8575 }
8576
8577 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8578 // ICSj(F2), or, if not that,
8579 if (HasBetterConversion)
8580 return true;
8581
8582 // -- the context is an initialization by user-defined conversion
8583 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8584 // from the return type of F1 to the destination type (i.e.,
8585 // the type of the entity being initialized) is a better
8586 // conversion sequence than the standard conversion sequence
8587 // from the return type of F2 to the destination type.
8588 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8589 isa<CXXConversionDecl>(Cand1.Function) &&
8590 isa<CXXConversionDecl>(Cand2.Function)) {
8591 // First check whether we prefer one of the conversion functions over the
8592 // other. This only distinguishes the results in non-standard, extension
8593 // cases such as the conversion from a lambda closure type to a function
8594 // pointer or block.
8595 ImplicitConversionSequence::CompareKind Result =
8596 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8597 if (Result == ImplicitConversionSequence::Indistinguishable)
8598 Result = CompareStandardConversionSequences(S, Loc,
8599 Cand1.FinalConversion,
8600 Cand2.FinalConversion);
8601
8602 if (Result != ImplicitConversionSequence::Indistinguishable)
8603 return Result == ImplicitConversionSequence::Better;
8604
8605 // FIXME: Compare kind of reference binding if conversion functions
8606 // convert to a reference type used in direct reference binding, per
8607 // C++14 [over.match.best]p1 section 2 bullet 3.
8608 }
8609
8610 // -- F1 is a non-template function and F2 is a function template
8611 // specialization, or, if not that,
8612 bool Cand1IsSpecialization = Cand1.Function &&
8613 Cand1.Function->getPrimaryTemplate();
8614 bool Cand2IsSpecialization = Cand2.Function &&
8615 Cand2.Function->getPrimaryTemplate();
8616 if (Cand1IsSpecialization != Cand2IsSpecialization)
8617 return Cand2IsSpecialization;
8618
8619 // -- F1 and F2 are function template specializations, and the function
8620 // template for F1 is more specialized than the template for F2
8621 // according to the partial ordering rules described in 14.5.5.2, or,
8622 // if not that,
8623 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8624 if (FunctionTemplateDecl *BetterTemplate
8625 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8626 Cand2.Function->getPrimaryTemplate(),
8627 Loc,
8628 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8629 : TPOC_Call,
8630 Cand1.ExplicitCallArguments,
8631 Cand2.ExplicitCallArguments))
8632 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8633 }
8634
8635 // Check for enable_if value-based overload resolution.
8636 if (Cand1.Function && Cand2.Function &&
8637 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8638 Cand2.Function->hasAttr<EnableIfAttr>()))
8639 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8640
8641 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8642 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8643 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8644 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8645 }
8646
8647 bool HasPS1 = Cand1.Function != nullptr &&
8648 functionHasPassObjectSizeParams(Cand1.Function);
8649 bool HasPS2 = Cand2.Function != nullptr &&
8650 functionHasPassObjectSizeParams(Cand2.Function);
8651 return HasPS1 != HasPS2 && HasPS1;
8652}
8653
8654/// Determine whether two declarations are "equivalent" for the purposes of
8655/// name lookup and overload resolution. This applies when the same internal/no
8656/// linkage entity is defined by two modules (probably by textually including
8657/// the same header). In such a case, we don't consider the declarations to
8658/// declare the same entity, but we also don't want lookups with both
8659/// declarations visible to be ambiguous in some cases (this happens when using
8660/// a modularized libstdc++).
8661bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8662 const NamedDecl *B) {
8663 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8664 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8665 if (!VA || !VB)
8666 return false;
8667
8668 // The declarations must be declaring the same name as an internal linkage
8669 // entity in different modules.
8670 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8671 VB->getDeclContext()->getRedeclContext()) ||
8672 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8673 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8674 VA->isExternallyVisible() || VB->isExternallyVisible())
8675 return false;
8676
8677 // Check that the declarations appear to be equivalent.
8678 //
8679 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8680 // For constants and functions, we should check the initializer or body is
8681 // the same. For non-constant variables, we shouldn't allow it at all.
8682 if (Context.hasSameType(VA->getType(), VB->getType()))
8683 return true;
8684
8685 // Enum constants within unnamed enumerations will have different types, but
8686 // may still be similar enough to be interchangeable for our purposes.
8687 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8688 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8689 // Only handle anonymous enums. If the enumerations were named and
8690 // equivalent, they would have been merged to the same type.
8691 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8692 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8693 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8694 !Context.hasSameType(EnumA->getIntegerType(),
8695 EnumB->getIntegerType()))
8696 return false;
8697 // Allow this only if the value is the same for both enumerators.
8698 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8699 }
8700 }
8701
8702 // Nothing else is sufficiently similar.
8703 return false;
8704}
8705
8706void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8707 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8708 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8709
8710 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8711 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8712 << !M << (M ? M->getFullModuleName() : "");
8713
8714 for (auto *E : Equiv) {
8715 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8716 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8717 << !M << (M ? M->getFullModuleName() : "");
8718 }
8719}
8720
8721/// \brief Computes the best viable function (C++ 13.3.3)
8722/// within an overload candidate set.
8723///
8724/// \param Loc The location of the function name (or operator symbol) for
8725/// which overload resolution occurs.
8726///
8727/// \param Best If overload resolution was successful or found a deleted
8728/// function, \p Best points to the candidate function found.
8729///
8730/// \returns The result of overload resolution.
8731OverloadingResult
8732OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8733 iterator &Best,
8734 bool UserDefinedConversion) {
8735 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8736 std::transform(begin(), end(), std::back_inserter(Candidates),
8737 [](OverloadCandidate &Cand) { return &Cand; });
8738
8739 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8740 // but accepted by both clang and NVCC. However during a particular
8741 // compilation mode only one call variant is viable. We need to
8742 // exclude non-viable overload candidates from consideration based
8743 // only on their host/device attributes. Specifically, if one
8744 // candidate call is WrongSide and the other is SameSide, we ignore
8745 // the WrongSide candidate.
8746 if (S.getLangOpts().CUDA) {
8747 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8748 bool ContainsSameSideCandidate =
8749 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8750 return Cand->Function &&
8751 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8752 Sema::CFP_SameSide;
8753 });
8754 if (ContainsSameSideCandidate) {
8755 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8756 return Cand->Function &&
8757 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8758 Sema::CFP_WrongSide;
8759 };
8760 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8761 IsWrongSideCandidate),
8762 Candidates.end());
8763 }
8764 }
8765
8766 // Find the best viable function.
8767 Best = end();
8768 for (auto *Cand : Candidates)
8769 if (Cand->Viable)
8770 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8771 UserDefinedConversion))
8772 Best = Cand;
8773
8774 // If we didn't find any viable functions, abort.
8775 if (Best == end())
8776 return OR_No_Viable_Function;
8777
8778 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8779
8780 // Make sure that this function is better than every other viable
8781 // function. If not, we have an ambiguity.
8782 for (auto *Cand : Candidates) {
8783 if (Cand->Viable &&
8784 Cand != Best &&
8785 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8786 UserDefinedConversion)) {
8787 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8788 Cand->Function)) {
8789 EquivalentCands.push_back(Cand->Function);
8790 continue;
8791 }
8792
8793 Best = end();
8794 return OR_Ambiguous;
8795 }
8796 }
8797
8798 // Best is the best viable function.
8799 if (Best->Function &&
8800 (Best->Function->isDeleted() ||
8801 S.isFunctionConsideredUnavailable(Best->Function)))
8802 return OR_Deleted;
8803
8804 if (!EquivalentCands.empty())
8805 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8806 EquivalentCands);
8807
8808 return OR_Success;
8809}
8810
8811namespace {
8812
8813enum OverloadCandidateKind {
8814 oc_function,
8815 oc_method,
8816 oc_constructor,
8817 oc_function_template,
8818 oc_method_template,
8819 oc_constructor_template,
8820 oc_implicit_default_constructor,
8821 oc_implicit_copy_constructor,
8822 oc_implicit_move_constructor,
8823 oc_implicit_copy_assignment,
8824 oc_implicit_move_assignment,
8825 oc_implicit_inherited_constructor
8826};
8827
8828OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8829 FunctionDecl *Fn,
8830 std::string &Description) {
8831 bool isTemplate = false;
8832
8833 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8834 isTemplate = true;
8835 Description = S.getTemplateArgumentBindingsText(
8836 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8837 }
8838
8839 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8840 if (!Ctor->isImplicit())
8841 return isTemplate ? oc_constructor_template : oc_constructor;
8842
8843 if (Ctor->getInheritedConstructor())
8844 return oc_implicit_inherited_constructor;
8845
8846 if (Ctor->isDefaultConstructor())
8847 return oc_implicit_default_constructor;
8848
8849 if (Ctor->isMoveConstructor())
8850 return oc_implicit_move_constructor;
8851
8852 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8853, __PRETTY_FUNCTION__))
8853 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8853, __PRETTY_FUNCTION__))
;
8854 return oc_implicit_copy_constructor;
8855 }
8856
8857 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8858 // This actually gets spelled 'candidate function' for now, but
8859 // it doesn't hurt to split it out.
8860 if (!Meth->isImplicit())
8861 return isTemplate ? oc_method_template : oc_method;
8862
8863 if (Meth->isMoveAssignmentOperator())
8864 return oc_implicit_move_assignment;
8865
8866 if (Meth->isCopyAssignmentOperator())
8867 return oc_implicit_copy_assignment;
8868
8869 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8869, __PRETTY_FUNCTION__))
;
8870 return oc_method;
8871 }
8872
8873 return isTemplate ? oc_function_template : oc_function;
8874}
8875
8876void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8877 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8878 if (!Ctor) return;
8879
8880 Ctor = Ctor->getInheritedConstructor();
8881 if (!Ctor) return;
8882
8883 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8884}
8885
8886} // end anonymous namespace
8887
8888static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8889 const FunctionDecl *FD) {
8890 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8891 bool AlwaysTrue;
8892 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8893 return false;
8894 if (!AlwaysTrue)
8895 return false;
8896 }
8897 return true;
8898}
8899
8900/// \brief Returns true if we can take the address of the function.
8901///
8902/// \param Complain - If true, we'll emit a diagnostic
8903/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8904/// we in overload resolution?
8905/// \param Loc - The location of the statement we're complaining about. Ignored
8906/// if we're not complaining, or if we're in overload resolution.
8907static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8908 bool Complain,
8909 bool InOverloadResolution,
8910 SourceLocation Loc) {
8911 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8912 if (Complain) {
8913 if (InOverloadResolution)
8914 S.Diag(FD->getLocStart(),
8915 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8916 else
8917 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8918 }
8919 return false;
8920 }
8921
8922 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8923 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8924 if (I == FD->param_end())
8925 return true;
8926
8927 if (Complain) {
8928 // Add one to ParamNo because it's user-facing
8929 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8930 if (InOverloadResolution)
8931 S.Diag(FD->getLocation(),
8932 diag::note_ovl_candidate_has_pass_object_size_params)
8933 << ParamNo;
8934 else
8935 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8936 << FD << ParamNo;
8937 }
8938 return false;
8939}
8940
8941static bool checkAddressOfCandidateIsAvailable(Sema &S,
8942 const FunctionDecl *FD) {
8943 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8944 /*InOverloadResolution=*/true,
8945 /*Loc=*/SourceLocation());
8946}
8947
8948bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8949 bool Complain,
8950 SourceLocation Loc) {
8951 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8952 /*InOverloadResolution=*/false,
8953 Loc);
8954}
8955
8956// Notes the location of an overload candidate.
8957void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8958 bool TakingAddress) {
8959 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8960 return;
8961
8962 std::string FnDesc;
8963 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8964 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8965 << (unsigned) K << FnDesc;
8966
8967 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8968 Diag(Fn->getLocation(), PD);
8969 MaybeEmitInheritedConstructorNote(*this, Fn);
8970}
8971
8972// Notes the location of all overload candidates designated through
8973// OverloadedExpr
8974void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8975 bool TakingAddress) {
8976 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 8976, __PRETTY_FUNCTION__))
;
8977
8978 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8979 OverloadExpr *OvlExpr = Ovl.Expression;
8980
8981 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8982 IEnd = OvlExpr->decls_end();
8983 I != IEnd; ++I) {
8984 if (FunctionTemplateDecl *FunTmpl =
8985 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8986 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8987 TakingAddress);
8988 } else if (FunctionDecl *Fun
8989 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8990 NoteOverloadCandidate(Fun, DestType, TakingAddress);
8991 }
8992 }
8993}
8994
8995/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8996/// "lead" diagnostic; it will be given two arguments, the source and
8997/// target types of the conversion.
8998void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8999 Sema &S,
9000 SourceLocation CaretLoc,
9001 const PartialDiagnostic &PDiag) const {
9002 S.Diag(CaretLoc, PDiag)
9003 << Ambiguous.getFromType() << Ambiguous.getToType();
9004 // FIXME: The note limiting machinery is borrowed from
9005 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9006 // refactoring here.
9007 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9008 unsigned CandsShown = 0;
9009 AmbiguousConversionSequence::const_iterator I, E;
9010 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9011 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9012 break;
9013 ++CandsShown;
9014 S.NoteOverloadCandidate(*I);
9015 }
9016 if (I != E)
9017 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9018}
9019
9020static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9021 unsigned I, bool TakingCandidateAddress) {
9022 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9023 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9023, __PRETTY_FUNCTION__))
;
9024 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9024, __PRETTY_FUNCTION__))
;
9025 FunctionDecl *Fn = Cand->Function;
9026
9027 // There's a conversion slot for the object argument if this is a
9028 // non-constructor method. Note that 'I' corresponds the
9029 // conversion-slot index.
9030 bool isObjectArgument = false;
9031 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9032 if (I == 0)
9033 isObjectArgument = true;
9034 else
9035 I--;
9036 }
9037
9038 std::string FnDesc;
9039 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9040
9041 Expr *FromExpr = Conv.Bad.FromExpr;
1
'FromExpr' initialized here
9042 QualType FromTy = Conv.Bad.getFromType();
9043 QualType ToTy = Conv.Bad.getToType();
9044
9045 if (FromTy == S.Context.OverloadTy) {
2
Taking false branch
9046 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9046, __PRETTY_FUNCTION__))
;
9047 Expr *E = FromExpr->IgnoreParens();
9048 if (isa<UnaryOperator>(E))
9049 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9050 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9051
9052 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9053 << (unsigned) FnKind << FnDesc
9054 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9055 << ToTy << Name << I+1;
9056 MaybeEmitInheritedConstructorNote(S, Fn);
9057 return;
9058 }
9059
9060 // Do some hand-waving analysis to see if the non-viability is due
9061 // to a qualifier mismatch.
9062 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9063 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9064 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
3
Taking false branch
9065 CToTy = RT->getPointeeType();
9066 else {
9067 // TODO: detect and diagnose the full richness of const mismatches.
9068 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4
Taking false branch
9069 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9070 CFromTy = FromPT->getPointeeType();
9071 CToTy = ToPT->getPointeeType();
9072 }
9073 }
9074
9075 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9076 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9077 Qualifiers FromQs = CFromTy.getQualifiers();
9078 Qualifiers ToQs = CToTy.getQualifiers();
9079
9080 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9082 << (unsigned) FnKind << FnDesc
9083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9084 << FromTy
9085 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9086 << (unsigned) isObjectArgument << I+1;
9087 MaybeEmitInheritedConstructorNote(S, Fn);
9088 return;
9089 }
9090
9091 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9093 << (unsigned) FnKind << FnDesc
9094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9095 << FromTy
9096 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9097 << (unsigned) isObjectArgument << I+1;
9098 MaybeEmitInheritedConstructorNote(S, Fn);
9099 return;
9100 }
9101
9102 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9104 << (unsigned) FnKind << FnDesc
9105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9106 << FromTy
9107 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9108 << (unsigned) isObjectArgument << I+1;
9109 MaybeEmitInheritedConstructorNote(S, Fn);
9110 return;
9111 }
9112
9113 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9114 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9114, __PRETTY_FUNCTION__))
;
9115
9116 if (isObjectArgument) {
9117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9118 << (unsigned) FnKind << FnDesc
9119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9120 << FromTy << (CVR - 1);
9121 } else {
9122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9123 << (unsigned) FnKind << FnDesc
9124 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9125 << FromTy << (CVR - 1) << I+1;
9126 }
9127 MaybeEmitInheritedConstructorNote(S, Fn);
9128 return;
9129 }
9130
9131 // Special diagnostic for failure to convert an initializer list, since
9132 // telling the user that it has type void is not useful.
9133 if (FromExpr && isa<InitListExpr>(FromExpr)) {
5
Assuming pointer value is null
9134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9135 << (unsigned) FnKind << FnDesc
9136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9137 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9138 MaybeEmitInheritedConstructorNote(S, Fn);
9139 return;
9140 }
9141
9142 // Diagnose references or pointers to incomplete types differently,
9143 // since it's far from impossible that the incompleteness triggered
9144 // the failure.
9145 QualType TempFromTy = FromTy.getNonReferenceType();
9146 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6
Assuming 'PTy' is null
7
Taking false branch
9147 TempFromTy = PTy->getPointeeType();
9148 if (TempFromTy->isIncompleteType()) {
8
Taking false branch
9149 // Emit the generic diagnostic and, optionally, add the hints to it.
9150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9151 << (unsigned) FnKind << FnDesc
9152 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9153 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9154 << (unsigned) (Cand->Fix.Kind);
9155
9156 MaybeEmitInheritedConstructorNote(S, Fn);
9157 return;
9158 }
9159
9160 // Diagnose base -> derived pointer conversions.
9161 unsigned BaseToDerivedConversion = 0;
9162 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9
Assuming 'FromPtrTy' is null
10
Taking false branch
9163 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9164 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9165 FromPtrTy->getPointeeType()) &&
9166 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9167 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9168 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9169 FromPtrTy->getPointeeType()))
9170 BaseToDerivedConversion = 1;
9171 }
9172 } else if (const ObjCObjectPointerType *FromPtrTy
11
Assuming 'FromPtrTy' is null
12
Taking false branch
9173 = FromTy->getAs<ObjCObjectPointerType>()) {
9174 if (const ObjCObjectPointerType *ToPtrTy
9175 = ToTy->getAs<ObjCObjectPointerType>())
9176 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9177 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9178 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9179 FromPtrTy->getPointeeType()) &&
9180 FromIface->isSuperClassOf(ToIface))
9181 BaseToDerivedConversion = 2;
9182 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
13
Assuming 'ToRefTy' is non-null
14
Taking true branch
9183 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9184 !FromTy->isIncompleteType() &&
9185 !ToRefTy->getPointeeType()->isIncompleteType() &&
9186 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9187 BaseToDerivedConversion = 3;
9188 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
15
Called C++ object pointer is null
9189 ToTy.getNonReferenceType().getCanonicalType() ==
9190 FromTy.getNonReferenceType().getCanonicalType()) {
9191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9192 << (unsigned) FnKind << FnDesc
9193 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9194 << (unsigned) isObjectArgument << I + 1;
9195 MaybeEmitInheritedConstructorNote(S, Fn);
9196 return;
9197 }
9198 }
9199
9200 if (BaseToDerivedConversion) {
9201 S.Diag(Fn->getLocation(),
9202 diag::note_ovl_candidate_bad_base_to_derived_conv)
9203 << (unsigned) FnKind << FnDesc
9204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9205 << (BaseToDerivedConversion - 1)
9206 << FromTy << ToTy << I+1;
9207 MaybeEmitInheritedConstructorNote(S, Fn);
9208 return;
9209 }
9210
9211 if (isa<ObjCObjectPointerType>(CFromTy) &&
9212 isa<PointerType>(CToTy)) {
9213 Qualifiers FromQs = CFromTy.getQualifiers();
9214 Qualifiers ToQs = CToTy.getQualifiers();
9215 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9216 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9217 << (unsigned) FnKind << FnDesc
9218 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9219 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9220 MaybeEmitInheritedConstructorNote(S, Fn);
9221 return;
9222 }
9223 }
9224
9225 if (TakingCandidateAddress &&
9226 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9227 return;
9228
9229 // Emit the generic diagnostic and, optionally, add the hints to it.
9230 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9231 FDiag << (unsigned) FnKind << FnDesc
9232 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9233 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9234 << (unsigned) (Cand->Fix.Kind);
9235
9236 // If we can fix the conversion, suggest the FixIts.
9237 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9238 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9239 FDiag << *HI;
9240 S.Diag(Fn->getLocation(), FDiag);
9241
9242 MaybeEmitInheritedConstructorNote(S, Fn);
9243}
9244
9245/// Additional arity mismatch diagnosis specific to a function overload
9246/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9247/// over a candidate in any candidate set.
9248static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9249 unsigned NumArgs) {
9250 FunctionDecl *Fn = Cand->Function;
9251 unsigned MinParams = Fn->getMinRequiredArguments();
9252
9253 // With invalid overloaded operators, it's possible that we think we
9254 // have an arity mismatch when in fact it looks like we have the
9255 // right number of arguments, because only overloaded operators have
9256 // the weird behavior of overloading member and non-member functions.
9257 // Just don't report anything.
9258 if (Fn->isInvalidDecl() &&
9259 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9260 return true;
9261
9262 if (NumArgs < MinParams) {
9263 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9265, __PRETTY_FUNCTION__))
9264 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9265, __PRETTY_FUNCTION__))
9265 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9265, __PRETTY_FUNCTION__))
;
9266 } else {
9267 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9269, __PRETTY_FUNCTION__))
9268 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9269, __PRETTY_FUNCTION__))
9269 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9269, __PRETTY_FUNCTION__))
;
9270 }
9271
9272 return false;
9273}
9274
9275/// General arity mismatch diagnosis over a candidate in a candidate set.
9276static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
9277 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280, __PRETTY_FUNCTION__))
9278 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280, __PRETTY_FUNCTION__))
9279 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280, __PRETTY_FUNCTION__))
9280 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280, __PRETTY_FUNCTION__))
;
9281
9282 FunctionDecl *Fn = cast<FunctionDecl>(D);
9283
9284 // TODO: treat calls to a missing default constructor as a special case
9285 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9286 unsigned MinParams = Fn->getMinRequiredArguments();
9287
9288 // at least / at most / exactly
9289 unsigned mode, modeCount;
9290 if (NumFormalArgs < MinParams) {
9291 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9292 FnTy->isTemplateVariadic())
9293 mode = 0; // "at least"
9294 else
9295 mode = 2; // "exactly"
9296 modeCount = MinParams;
9297 } else {
9298 if (MinParams != FnTy->getNumParams())
9299 mode = 1; // "at most"
9300 else
9301 mode = 2; // "exactly"
9302 modeCount = FnTy->getNumParams();
9303 }
9304
9305 std::string Description;
9306 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9307
9308 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9310 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9311 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9312 else
9313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9314 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9315 << mode << modeCount << NumFormalArgs;
9316 MaybeEmitInheritedConstructorNote(S, Fn);
9317}
9318
9319/// Arity mismatch diagnosis specific to a function overload candidate.
9320static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9321 unsigned NumFormalArgs) {
9322 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9323 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9324}
9325
9326static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9327 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9328 return TD;
9329 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9330)
9330 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9330)
;
9331}
9332
9333/// Diagnose a failed template-argument deduction.
9334static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9335 DeductionFailureInfo &DeductionFailure,
9336 unsigned NumArgs,
9337 bool TakingCandidateAddress) {
9338 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9339 NamedDecl *ParamD;
9340 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9341 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9342 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9343 switch (DeductionFailure.Result) {
9344 case Sema::TDK_Success:
9345 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9345)
;
9346
9347 case Sema::TDK_Incomplete: {
9348 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9348, __PRETTY_FUNCTION__))
;
9349 S.Diag(Templated->getLocation(),
9350 diag::note_ovl_candidate_incomplete_deduction)
9351 << ParamD->getDeclName();
9352 MaybeEmitInheritedConstructorNote(S, Templated);
9353 return;
9354 }
9355
9356 case Sema::TDK_Underqualified: {
9357 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9357, __PRETTY_FUNCTION__))
;
9358 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9359
9360 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9361
9362 // Param will have been canonicalized, but it should just be a
9363 // qualified version of ParamD, so move the qualifiers to that.
9364 QualifierCollector Qs;
9365 Qs.strip(Param);
9366 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9367 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9367, __PRETTY_FUNCTION__))
;
9368
9369 // Arg has also been canonicalized, but there's nothing we can do
9370 // about that. It also doesn't matter as much, because it won't
9371 // have any template parameters in it (because deduction isn't
9372 // done on dependent types).
9373 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9374
9375 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9376 << ParamD->getDeclName() << Arg << NonCanonParam;
9377 MaybeEmitInheritedConstructorNote(S, Templated);
9378 return;
9379 }
9380
9381 case Sema::TDK_Inconsistent: {
9382 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9382, __PRETTY_FUNCTION__))
;
9383 int which = 0;
9384 if (isa<TemplateTypeParmDecl>(ParamD))
9385 which = 0;
9386 else if (isa<NonTypeTemplateParmDecl>(ParamD))
9387 which = 1;
9388 else {
9389 which = 2;
9390 }
9391
9392 S.Diag(Templated->getLocation(),
9393 diag::note_ovl_candidate_inconsistent_deduction)
9394 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9395 << *DeductionFailure.getSecondArg();
9396 MaybeEmitInheritedConstructorNote(S, Templated);
9397 return;
9398 }
9399
9400 case Sema::TDK_InvalidExplicitArguments:
9401 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9401, __PRETTY_FUNCTION__))
;
9402 if (ParamD->getDeclName())
9403 S.Diag(Templated->getLocation(),
9404 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9405 << ParamD->getDeclName();
9406 else {
9407 int index = 0;
9408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9409 index = TTP->getIndex();
9410 else if (NonTypeTemplateParmDecl *NTTP
9411 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9412 index = NTTP->getIndex();
9413 else
9414 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9415 S.Diag(Templated->getLocation(),
9416 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9417 << (index + 1);
9418 }
9419 MaybeEmitInheritedConstructorNote(S, Templated);
9420 return;
9421
9422 case Sema::TDK_TooManyArguments:
9423 case Sema::TDK_TooFewArguments:
9424 DiagnoseArityMismatch(S, Templated, NumArgs);
9425 return;
9426
9427 case Sema::TDK_InstantiationDepth:
9428 S.Diag(Templated->getLocation(),
9429 diag::note_ovl_candidate_instantiation_depth);
9430 MaybeEmitInheritedConstructorNote(S, Templated);
9431 return;
9432
9433 case Sema::TDK_SubstitutionFailure: {
9434 // Format the template argument list into the argument string.
9435 SmallString<128> TemplateArgString;
9436 if (TemplateArgumentList *Args =
9437 DeductionFailure.getTemplateArgumentList()) {
9438 TemplateArgString = " ";
9439 TemplateArgString += S.getTemplateArgumentBindingsText(
9440 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9441 }
9442
9443 // If this candidate was disabled by enable_if, say so.
9444 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9445 if (PDiag && PDiag->second.getDiagID() ==
9446 diag::err_typename_nested_not_found_enable_if) {
9447 // FIXME: Use the source range of the condition, and the fully-qualified
9448 // name of the enable_if template. These are both present in PDiag.
9449 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9450 << "'enable_if'" << TemplateArgString;
9451 return;
9452 }
9453
9454 // Format the SFINAE diagnostic into the argument string.
9455 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9456 // formatted message in another diagnostic.
9457 SmallString<128> SFINAEArgString;
9458 SourceRange R;
9459 if (PDiag) {
9460 SFINAEArgString = ": ";
9461 R = SourceRange(PDiag->first, PDiag->first);
9462 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9463 }
9464
9465 S.Diag(Templated->getLocation(),
9466 diag::note_ovl_candidate_substitution_failure)
9467 << TemplateArgString << SFINAEArgString << R;
9468 MaybeEmitInheritedConstructorNote(S, Templated);
9469 return;
9470 }
9471
9472 case Sema::TDK_FailedOverloadResolution: {
9473 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9474 S.Diag(Templated->getLocation(),
9475 diag::note_ovl_candidate_failed_overload_resolution)
9476 << R.Expression->getName();
9477 return;
9478 }
9479
9480 case Sema::TDK_DeducedMismatch: {
9481 // Format the template argument list into the argument string.
9482 SmallString<128> TemplateArgString;
9483 if (TemplateArgumentList *Args =
9484 DeductionFailure.getTemplateArgumentList()) {
9485 TemplateArgString = " ";
9486 TemplateArgString += S.getTemplateArgumentBindingsText(
9487 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9488 }
9489
9490 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9491 << (*DeductionFailure.getCallArgIndex() + 1)
9492 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9493 << TemplateArgString;
9494 break;
9495 }
9496
9497 case Sema::TDK_NonDeducedMismatch: {
9498 // FIXME: Provide a source location to indicate what we couldn't match.
9499 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9500 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9501 if (FirstTA.getKind() == TemplateArgument::Template &&
9502 SecondTA.getKind() == TemplateArgument::Template) {
9503 TemplateName FirstTN = FirstTA.getAsTemplate();
9504 TemplateName SecondTN = SecondTA.getAsTemplate();
9505 if (FirstTN.getKind() == TemplateName::Template &&
9506 SecondTN.getKind() == TemplateName::Template) {
9507 if (FirstTN.getAsTemplateDecl()->getName() ==
9508 SecondTN.getAsTemplateDecl()->getName()) {
9509 // FIXME: This fixes a bad diagnostic where both templates are named
9510 // the same. This particular case is a bit difficult since:
9511 // 1) It is passed as a string to the diagnostic printer.
9512 // 2) The diagnostic printer only attempts to find a better
9513 // name for types, not decls.
9514 // Ideally, this should folded into the diagnostic printer.
9515 S.Diag(Templated->getLocation(),
9516 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9517 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9518 return;
9519 }
9520 }
9521 }
9522
9523 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9524 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9525 return;
9526
9527 // FIXME: For generic lambda parameters, check if the function is a lambda
9528 // call operator, and if so, emit a prettier and more informative
9529 // diagnostic that mentions 'auto' and lambda in addition to
9530 // (or instead of?) the canonical template type parameters.
9531 S.Diag(Templated->getLocation(),
9532 diag::note_ovl_candidate_non_deduced_mismatch)
9533 << FirstTA << SecondTA;
9534 return;
9535 }
9536 // TODO: diagnose these individually, then kill off
9537 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9538 case Sema::TDK_MiscellaneousDeductionFailure:
9539 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9540 MaybeEmitInheritedConstructorNote(S, Templated);
9541 return;
9542 }
9543}
9544
9545/// Diagnose a failed template-argument deduction, for function calls.
9546static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9547 unsigned NumArgs,
9548 bool TakingCandidateAddress) {
9549 unsigned TDK = Cand->DeductionFailure.Result;
9550 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9551 if (CheckArityMismatch(S, Cand, NumArgs))
9552 return;
9553 }
9554 DiagnoseBadDeduction(S, Cand->Function, // pattern
9555 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9556}
9557
9558/// CUDA: diagnose an invalid call across targets.
9559static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9560 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9561 FunctionDecl *Callee = Cand->Function;
9562
9563 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9564 CalleeTarget = S.IdentifyCUDATarget(Callee);
9565
9566 std::string FnDesc;
9567 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9568
9569 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9570 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9571
9572 // This could be an implicit constructor for which we could not infer the
9573 // target due to a collsion. Diagnose that case.
9574 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9575 if (Meth != nullptr && Meth->isImplicit()) {
9576 CXXRecordDecl *ParentClass = Meth->getParent();
9577 Sema::CXXSpecialMember CSM;
9578
9579 switch (FnKind) {
9580 default:
9581 return;
9582 case oc_implicit_default_constructor:
9583 CSM = Sema::CXXDefaultConstructor;
9584 break;
9585 case oc_implicit_copy_constructor:
9586 CSM = Sema::CXXCopyConstructor;
9587 break;
9588 case oc_implicit_move_constructor:
9589 CSM = Sema::CXXMoveConstructor;
9590 break;
9591 case oc_implicit_copy_assignment:
9592 CSM = Sema::CXXCopyAssignment;
9593 break;
9594 case oc_implicit_move_assignment:
9595 CSM = Sema::CXXMoveAssignment;
9596 break;
9597 };
9598
9599 bool ConstRHS = false;
9600 if (Meth->getNumParams()) {
9601 if (const ReferenceType *RT =
9602 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9603 ConstRHS = RT->getPointeeType().isConstQualified();
9604 }
9605 }
9606
9607 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9608 /* ConstRHS */ ConstRHS,
9609 /* Diagnose */ true);
9610 }
9611}
9612
9613static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9614 FunctionDecl *Callee = Cand->Function;
9615 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9616
9617 S.Diag(Callee->getLocation(),
9618 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9619 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9620}
9621
9622/// Generates a 'note' diagnostic for an overload candidate. We've
9623/// already generated a primary error at the call site.
9624///
9625/// It really does need to be a single diagnostic with its caret
9626/// pointed at the candidate declaration. Yes, this creates some
9627/// major challenges of technical writing. Yes, this makes pointing
9628/// out problems with specific arguments quite awkward. It's still
9629/// better than generating twenty screens of text for every failed
9630/// overload.
9631///
9632/// It would be great to be able to express per-candidate problems
9633/// more richly for those diagnostic clients that cared, but we'd
9634/// still have to be just as careful with the default diagnostics.
9635static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9636 unsigned NumArgs,
9637 bool TakingCandidateAddress) {
9638 FunctionDecl *Fn = Cand->Function;
9639
9640 // Note deleted candidates, but only if they're viable.
9641 if (Cand->Viable && (Fn->isDeleted() ||
9642 S.isFunctionConsideredUnavailable(Fn))) {
9643 std::string FnDesc;
9644 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9645
9646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9647 << FnKind << FnDesc
9648 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9649 MaybeEmitInheritedConstructorNote(S, Fn);
9650 return;
9651 }
9652
9653 // We don't really have anything else to say about viable candidates.
9654 if (Cand->Viable) {
9655 S.NoteOverloadCandidate(Fn);
9656 return;
9657 }
9658
9659 switch (Cand->FailureKind) {
9660 case ovl_fail_too_many_arguments:
9661 case ovl_fail_too_few_arguments:
9662 return DiagnoseArityMismatch(S, Cand, NumArgs);
9663
9664 case ovl_fail_bad_deduction:
9665 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
9666
9667 case ovl_fail_illegal_constructor: {
9668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9669 << (Fn->getPrimaryTemplate() ? 1 : 0);
9670 MaybeEmitInheritedConstructorNote(S, Fn);
9671 return;
9672 }
9673
9674 case ovl_fail_trivial_conversion:
9675 case ovl_fail_bad_final_conversion:
9676 case ovl_fail_final_conversion_not_exact:
9677 return S.NoteOverloadCandidate(Fn);
9678
9679 case ovl_fail_bad_conversion: {
9680 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9681 for (unsigned N = Cand->NumConversions; I != N; ++I)
9682 if (Cand->Conversions[I].isBad())
9683 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9684
9685 // FIXME: this currently happens when we're called from SemaInit
9686 // when user-conversion overload fails. Figure out how to handle
9687 // those conditions and diagnose them well.
9688 return S.NoteOverloadCandidate(Fn);
9689 }
9690
9691 case ovl_fail_bad_target:
9692 return DiagnoseBadTarget(S, Cand);
9693
9694 case ovl_fail_enable_if:
9695 return DiagnoseFailedEnableIfAttr(S, Cand);
9696
9697 case ovl_fail_addr_not_available: {
9698 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9699 (void)Available;
9700 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9700, __PRETTY_FUNCTION__))
;
9701 break;
9702 }
9703 }
9704}
9705
9706static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9707 // Desugar the type of the surrogate down to a function type,
9708 // retaining as many typedefs as possible while still showing
9709 // the function type (and, therefore, its parameter types).
9710 QualType FnType = Cand->Surrogate->getConversionType();
9711 bool isLValueReference = false;
9712 bool isRValueReference = false;
9713 bool isPointer = false;
9714 if (const LValueReferenceType *FnTypeRef =
9715 FnType->getAs<LValueReferenceType>()) {
9716 FnType = FnTypeRef->getPointeeType();
9717 isLValueReference = true;
9718 } else if (const RValueReferenceType *FnTypeRef =
9719 FnType->getAs<RValueReferenceType>()) {
9720 FnType = FnTypeRef->getPointeeType();
9721 isRValueReference = true;
9722 }
9723 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9724 FnType = FnTypePtr->getPointeeType();
9725 isPointer = true;
9726 }
9727 // Desugar down to a function type.
9728 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9729 // Reconstruct the pointer/reference as appropriate.
9730 if (isPointer) FnType = S.Context.getPointerType(FnType);
9731 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9732 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9733
9734 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9735 << FnType;
9736 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9737}
9738
9739static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9740 SourceLocation OpLoc,
9741 OverloadCandidate *Cand) {
9742 assert(Cand->NumConversions <= 2 && "builtin operator is not binary")((Cand->NumConversions <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->NumConversions <= 2 && \"builtin operator is not binary\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9742, __PRETTY_FUNCTION__))
;
9743 std::string TypeStr("operator");
9744 TypeStr += Opc;
9745 TypeStr += "(";
9746 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9747 if (Cand->NumConversions == 1) {
9748 TypeStr += ")";
9749 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9750 } else {
9751 TypeStr += ", ";
9752 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9753 TypeStr += ")";
9754 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9755 }
9756}
9757
9758static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9759 OverloadCandidate *Cand) {
9760 unsigned NoOperands = Cand->NumConversions;
9761 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9762 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9763 if (ICS.isBad()) break; // all meaningless after first invalid
9764 if (!ICS.isAmbiguous()) continue;
9765
9766 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9767 S.PDiag(diag::note_ambiguous_type_conversion));
9768 }
9769}
9770
9771static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9772 if (Cand->Function)
9773 return Cand->Function->getLocation();
9774 if (Cand->IsSurrogate)
9775 return Cand->Surrogate->getLocation();
9776 return SourceLocation();
9777}
9778
9779static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9780 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9781 case Sema::TDK_Success:
9782 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9782)
;
9783
9784 case Sema::TDK_Invalid:
9785 case Sema::TDK_Incomplete:
9786 return 1;
9787
9788 case Sema::TDK_Underqualified:
9789 case Sema::TDK_Inconsistent:
9790 return 2;
9791
9792 case Sema::TDK_SubstitutionFailure:
9793 case Sema::TDK_DeducedMismatch:
9794 case Sema::TDK_NonDeducedMismatch:
9795 case Sema::TDK_MiscellaneousDeductionFailure:
9796 return 3;
9797
9798 case Sema::TDK_InstantiationDepth:
9799 case Sema::TDK_FailedOverloadResolution:
9800 return 4;
9801
9802 case Sema::TDK_InvalidExplicitArguments:
9803 return 5;
9804
9805 case Sema::TDK_TooManyArguments:
9806 case Sema::TDK_TooFewArguments:
9807 return 6;
9808 }
9809 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9809)
;
9810}
9811
9812namespace {
9813struct CompareOverloadCandidatesForDisplay {
9814 Sema &S;
9815 SourceLocation Loc;
9816 size_t NumArgs;
9817
9818 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9819 : S(S), NumArgs(nArgs) {}
9820
9821 bool operator()(const OverloadCandidate *L,
9822 const OverloadCandidate *R) {
9823 // Fast-path this check.
9824 if (L == R) return false;
9825
9826 // Order first by viability.
9827 if (L->Viable) {
9828 if (!R->Viable) return true;
9829
9830 // TODO: introduce a tri-valued comparison for overload
9831 // candidates. Would be more worthwhile if we had a sort
9832 // that could exploit it.
9833 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9834 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9835 } else if (R->Viable)
9836 return false;
9837
9838 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9838, __PRETTY_FUNCTION__))
;
9839
9840 // Criteria by which we can sort non-viable candidates:
9841 if (!L->Viable) {
9842 // 1. Arity mismatches come after other candidates.
9843 if (L->FailureKind == ovl_fail_too_many_arguments ||
9844 L->FailureKind == ovl_fail_too_few_arguments) {
9845 if (R->FailureKind == ovl_fail_too_many_arguments ||
9846 R->FailureKind == ovl_fail_too_few_arguments) {
9847 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9848 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9849 if (LDist == RDist) {
9850 if (L->FailureKind == R->FailureKind)
9851 // Sort non-surrogates before surrogates.
9852 return !L->IsSurrogate && R->IsSurrogate;
9853 // Sort candidates requiring fewer parameters than there were
9854 // arguments given after candidates requiring more parameters
9855 // than there were arguments given.
9856 return L->FailureKind == ovl_fail_too_many_arguments;
9857 }
9858 return LDist < RDist;
9859 }
9860 return false;
9861 }
9862 if (R->FailureKind == ovl_fail_too_many_arguments ||
9863 R->FailureKind == ovl_fail_too_few_arguments)
9864 return true;
9865
9866 // 2. Bad conversions come first and are ordered by the number
9867 // of bad conversions and quality of good conversions.
9868 if (L->FailureKind == ovl_fail_bad_conversion) {
9869 if (R->FailureKind != ovl_fail_bad_conversion)
9870 return true;
9871
9872 // The conversion that can be fixed with a smaller number of changes,
9873 // comes first.
9874 unsigned numLFixes = L->Fix.NumConversionsFixed;
9875 unsigned numRFixes = R->Fix.NumConversionsFixed;
9876 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
9877 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
9878 if (numLFixes != numRFixes) {
9879 return numLFixes < numRFixes;
9880 }
9881
9882 // If there's any ordering between the defined conversions...
9883 // FIXME: this might not be transitive.
9884 assert(L->NumConversions == R->NumConversions)((L->NumConversions == R->NumConversions) ? static_cast
<void> (0) : __assert_fail ("L->NumConversions == R->NumConversions"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9884, __PRETTY_FUNCTION__))
;
9885
9886 int leftBetter = 0;
9887 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9888 for (unsigned E = L->NumConversions; I != E; ++I) {
9889 switch (CompareImplicitConversionSequences(S, Loc,
9890 L->Conversions[I],
9891 R->Conversions[I])) {
9892 case ImplicitConversionSequence::Better:
9893 leftBetter++;
9894 break;
9895
9896 case ImplicitConversionSequence::Worse:
9897 leftBetter--;
9898 break;
9899
9900 case ImplicitConversionSequence::Indistinguishable:
9901 break;
9902 }
9903 }
9904 if (leftBetter > 0) return true;
9905 if (leftBetter < 0) return false;
9906
9907 } else if (R->FailureKind == ovl_fail_bad_conversion)
9908 return false;
9909
9910 if (L->FailureKind == ovl_fail_bad_deduction) {
9911 if (R->FailureKind != ovl_fail_bad_deduction)
9912 return true;
9913
9914 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9915 return RankDeductionFailure(L->DeductionFailure)
9916 < RankDeductionFailure(R->DeductionFailure);
9917 } else if (R->FailureKind == ovl_fail_bad_deduction)
9918 return false;
9919
9920 // TODO: others?
9921 }
9922
9923 // Sort everything else by location.
9924 SourceLocation LLoc = GetLocationForCandidate(L);
9925 SourceLocation RLoc = GetLocationForCandidate(R);
9926
9927 // Put candidates without locations (e.g. builtins) at the end.
9928 if (LLoc.isInvalid()) return false;
9929 if (RLoc.isInvalid()) return true;
9930
9931 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9932 }
9933};
9934}
9935
9936/// CompleteNonViableCandidate - Normally, overload resolution only
9937/// computes up to the first. Produces the FixIt set if possible.
9938static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9939 ArrayRef<Expr *> Args) {
9940 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9940, __PRETTY_FUNCTION__))
;
9941
9942 // Don't do anything on failures other than bad conversion.
9943 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9944
9945 // We only want the FixIts if all the arguments can be corrected.
9946 bool Unfixable = false;
9947 // Use a implicit copy initialization to check conversion fixes.
9948 Cand->Fix.setConversionChecker(TryCopyInitialization);
9949
9950 // Skip forward to the first bad conversion.
9951 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9952 unsigned ConvCount = Cand->NumConversions;
9953 while (true) {
9954 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9954, __PRETTY_FUNCTION__))
;
9955 ConvIdx++;
9956 if (Cand->Conversions[ConvIdx - 1].isBad()) {
9957 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9958 break;
9959 }
9960 }
9961
9962 if (ConvIdx == ConvCount)
9963 return;
9964
9965 assert(!Cand->Conversions[ConvIdx].isInitialized() &&((!Cand->Conversions[ConvIdx].isInitialized() && "remaining conversion is initialized?"
) ? static_cast<void> (0) : __assert_fail ("!Cand->Conversions[ConvIdx].isInitialized() && \"remaining conversion is initialized?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9966, __PRETTY_FUNCTION__))
9966 "remaining conversion is initialized?")((!Cand->Conversions[ConvIdx].isInitialized() && "remaining conversion is initialized?"
) ? static_cast<void> (0) : __assert_fail ("!Cand->Conversions[ConvIdx].isInitialized() && \"remaining conversion is initialized?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9966, __PRETTY_FUNCTION__))
;
9967
9968 // FIXME: this should probably be preserved from the overload
9969 // operation somehow.
9970 bool SuppressUserConversions = false;
9971
9972 const FunctionProtoType* Proto;
9973 unsigned ArgIdx = ConvIdx;
9974
9975 if (Cand->IsSurrogate) {
9976 QualType ConvType
9977 = Cand->Surrogate->getConversionType().getNonReferenceType();
9978 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9979 ConvType = ConvPtrType->getPointeeType();
9980 Proto = ConvType->getAs<FunctionProtoType>();
9981 ArgIdx--;
9982 } else if (Cand->Function) {
9983 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9984 if (isa<CXXMethodDecl>(Cand->Function) &&
9985 !isa<CXXConstructorDecl>(Cand->Function))
9986 ArgIdx--;
9987 } else {
9988 // Builtin binary operator with a bad first conversion.
9989 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 9989, __PRETTY_FUNCTION__))
;
9990 for (; ConvIdx != ConvCount; ++ConvIdx)
9991 Cand->Conversions[ConvIdx]
9992 = TryCopyInitialization(S, Args[ConvIdx],
9993 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9994 SuppressUserConversions,
9995 /*InOverloadResolution*/ true,
9996 /*AllowObjCWritebackConversion=*/
9997 S.getLangOpts().ObjCAutoRefCount);
9998 return;
9999 }
10000
10001 // Fill in the rest of the conversions.
10002 unsigned NumParams = Proto->getNumParams();
10003 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10004 if (ArgIdx < NumParams) {
10005 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10006 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10007 /*InOverloadResolution=*/true,
10008 /*AllowObjCWritebackConversion=*/
10009 S.getLangOpts().ObjCAutoRefCount);
10010 // Store the FixIt in the candidate if it exists.
10011 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10012 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10013 }
10014 else
10015 Cand->Conversions[ConvIdx].setEllipsis();
10016 }
10017}
10018
10019/// PrintOverloadCandidates - When overload resolution fails, prints
10020/// diagnostic messages containing the candidates in the candidate
10021/// set.
10022void OverloadCandidateSet::NoteCandidates(Sema &S,
10023 OverloadCandidateDisplayKind OCD,
10024 ArrayRef<Expr *> Args,
10025 StringRef Opc,
10026 SourceLocation OpLoc) {
10027 // Sort the candidates by viability and position. Sorting directly would
10028 // be prohibitive, so we make a set of pointers and sort those.
10029 SmallVector<OverloadCandidate*, 32> Cands;
10030 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10031 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10032 if (Cand->Viable)
10033 Cands.push_back(Cand);
10034 else if (OCD == OCD_AllCandidates) {
10035 CompleteNonViableCandidate(S, Cand, Args);
10036 if (Cand->Function || Cand->IsSurrogate)
10037 Cands.push_back(Cand);
10038 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10039 // want to list every possible builtin candidate.
10040 }
10041 }
10042
10043 std::sort(Cands.begin(), Cands.end(),
10044 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10045
10046 bool ReportedAmbiguousConversions = false;
10047
10048 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10049 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10050 unsigned CandsShown = 0;
10051 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10052 OverloadCandidate *Cand = *I;
10053
10054 // Set an arbitrary limit on the number of candidate functions we'll spam
10055 // the user with. FIXME: This limit should depend on details of the
10056 // candidate list.
10057 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10058 break;
10059 }
10060 ++CandsShown;
10061
10062 if (Cand->Function)
10063 NoteFunctionCandidate(S, Cand, Args.size(),
10064 /*TakingCandidateAddress=*/false);
10065 else if (Cand->IsSurrogate)
10066 NoteSurrogateCandidate(S, Cand);
10067 else {
10068 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10069, __PRETTY_FUNCTION__))
10069 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10069, __PRETTY_FUNCTION__))
;
10070 // Generally we only see ambiguities including viable builtin
10071 // operators if overload resolution got screwed up by an
10072 // ambiguous user-defined conversion.
10073 //
10074 // FIXME: It's quite possible for different conversions to see
10075 // different ambiguities, though.
10076 if (!ReportedAmbiguousConversions) {
10077 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10078 ReportedAmbiguousConversions = true;
10079 }
10080
10081 // If this is a viable builtin, print it.
10082 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10083 }
10084 }
10085
10086 if (I != E)
10087 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10088}
10089
10090static SourceLocation
10091GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10092 return Cand->Specialization ? Cand->Specialization->getLocation()
10093 : SourceLocation();
10094}
10095
10096namespace {
10097struct CompareTemplateSpecCandidatesForDisplay {
10098 Sema &S;
10099 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10100
10101 bool operator()(const TemplateSpecCandidate *L,
10102 const TemplateSpecCandidate *R) {
10103 // Fast-path this check.
10104 if (L == R)
10105 return false;
10106
10107 // Assuming that both candidates are not matches...
10108
10109 // Sort by the ranking of deduction failures.
10110 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10111 return RankDeductionFailure(L->DeductionFailure) <
10112 RankDeductionFailure(R->DeductionFailure);
10113
10114 // Sort everything else by location.
10115 SourceLocation LLoc = GetLocationForCandidate(L);
10116 SourceLocation RLoc = GetLocationForCandidate(R);
10117
10118 // Put candidates without locations (e.g. builtins) at the end.
10119 if (LLoc.isInvalid())
10120 return false;
10121 if (RLoc.isInvalid())
10122 return true;
10123
10124 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10125 }
10126};
10127}
10128
10129/// Diagnose a template argument deduction failure.
10130/// We are treating these failures as overload failures due to bad
10131/// deductions.
10132void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10133 bool ForTakingAddress) {
10134 DiagnoseBadDeduction(S, Specialization, // pattern
10135 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10136}
10137
10138void TemplateSpecCandidateSet::destroyCandidates() {
10139 for (iterator i = begin(), e = end(); i != e; ++i) {
10140 i->DeductionFailure.Destroy();
10141 }
10142}
10143
10144void TemplateSpecCandidateSet::clear() {
10145 destroyCandidates();
10146 Candidates.clear();
10147}
10148
10149/// NoteCandidates - When no template specialization match is found, prints
10150/// diagnostic messages containing the non-matching specializations that form
10151/// the candidate set.
10152/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10153/// OCD == OCD_AllCandidates and Cand->Viable == false.
10154void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10155 // Sort the candidates by position (assuming no candidate is a match).
10156 // Sorting directly would be prohibitive, so we make a set of pointers
10157 // and sort those.
10158 SmallVector<TemplateSpecCandidate *, 32> Cands;
10159 Cands.reserve(size());
10160 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10161 if (Cand->Specialization)
10162 Cands.push_back(Cand);
10163 // Otherwise, this is a non-matching builtin candidate. We do not,
10164 // in general, want to list every possible builtin candidate.
10165 }
10166
10167 std::sort(Cands.begin(), Cands.end(),
10168 CompareTemplateSpecCandidatesForDisplay(S));
10169
10170 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10171 // for generalization purposes (?).
10172 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10173
10174 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10175 unsigned CandsShown = 0;
10176 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10177 TemplateSpecCandidate *Cand = *I;
10178
10179 // Set an arbitrary limit on the number of candidates we'll spam
10180 // the user with. FIXME: This limit should depend on details of the
10181 // candidate list.
10182 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10183 break;
10184 ++CandsShown;
10185
10186 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10187, __PRETTY_FUNCTION__))
10187 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10187, __PRETTY_FUNCTION__))
;
10188 Cand->NoteDeductionFailure(S, ForTakingAddress);
10189 }
10190
10191 if (I != E)
10192 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10193}
10194
10195// [PossiblyAFunctionType] --> [Return]
10196// NonFunctionType --> NonFunctionType
10197// R (A) --> R(A)
10198// R (*)(A) --> R (A)
10199// R (&)(A) --> R (A)
10200// R (S::*)(A) --> R (A)
10201QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10202 QualType Ret = PossiblyAFunctionType;
10203 if (const PointerType *ToTypePtr =
10204 PossiblyAFunctionType->getAs<PointerType>())
10205 Ret = ToTypePtr->getPointeeType();
10206 else if (const ReferenceType *ToTypeRef =
10207 PossiblyAFunctionType->getAs<ReferenceType>())
10208 Ret = ToTypeRef->getPointeeType();
10209 else if (const MemberPointerType *MemTypePtr =
10210 PossiblyAFunctionType->getAs<MemberPointerType>())
10211 Ret = MemTypePtr->getPointeeType();
10212 Ret =
10213 Context.getCanonicalType(Ret).getUnqualifiedType();
10214 return Ret;
10215}
10216
10217namespace {
10218// A helper class to help with address of function resolution
10219// - allows us to avoid passing around all those ugly parameters
10220class AddressOfFunctionResolver {
10221 Sema& S;
10222 Expr* SourceExpr;
10223 const QualType& TargetType;
10224 QualType TargetFunctionType; // Extracted function type from target type
10225
10226 bool Complain;
10227 //DeclAccessPair& ResultFunctionAccessPair;
10228 ASTContext& Context;
10229
10230 bool TargetTypeIsNonStaticMemberFunction;
10231 bool FoundNonTemplateFunction;
10232 bool StaticMemberFunctionFromBoundPointer;
10233 bool HasComplained;
10234
10235 OverloadExpr::FindResult OvlExprInfo;
10236 OverloadExpr *OvlExpr;
10237 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10238 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10239 TemplateSpecCandidateSet FailedCandidates;
10240
10241public:
10242 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10243 const QualType &TargetType, bool Complain)
10244 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10245 Complain(Complain), Context(S.getASTContext()),
10246 TargetTypeIsNonStaticMemberFunction(
10247 !!TargetType->getAs<MemberPointerType>()),
10248 FoundNonTemplateFunction(false),
10249 StaticMemberFunctionFromBoundPointer(false),
10250 HasComplained(false),
10251 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10252 OvlExpr(OvlExprInfo.Expression),
10253 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10254 ExtractUnqualifiedFunctionTypeFromTargetType();
10255
10256 if (TargetFunctionType->isFunctionType()) {
10257 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10258 if (!UME->isImplicitAccess() &&
10259 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10260 StaticMemberFunctionFromBoundPointer = true;
10261 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10262 DeclAccessPair dap;
10263 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10264 OvlExpr, false, &dap)) {
10265 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10266 if (!Method->isStatic()) {
10267 // If the target type is a non-function type and the function found
10268 // is a non-static member function, pretend as if that was the
10269 // target, it's the only possible type to end up with.
10270 TargetTypeIsNonStaticMemberFunction = true;
10271
10272 // And skip adding the function if its not in the proper form.
10273 // We'll diagnose this due to an empty set of functions.
10274 if (!OvlExprInfo.HasFormOfMemberPointer)
10275 return;
10276 }
10277
10278 Matches.push_back(std::make_pair(dap, Fn));
10279 }
10280 return;
10281 }
10282
10283 if (OvlExpr->hasExplicitTemplateArgs())
10284 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10285
10286 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10287 // C++ [over.over]p4:
10288 // If more than one function is selected, [...]
10289 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10290 if (FoundNonTemplateFunction)
10291 EliminateAllTemplateMatches();
10292 else
10293 EliminateAllExceptMostSpecializedTemplate();
10294 }
10295 }
10296
10297 if (S.getLangOpts().CUDA && Matches.size() > 1)
10298 EliminateSuboptimalCudaMatches();
10299 }
10300
10301 bool hasComplained() const { return HasComplained; }
10302
10303private:
10304 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10305 QualType Discard;
10306 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10307 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10308 }
10309
10310 /// \return true if A is considered a better overload candidate for the
10311 /// desired type than B.
10312 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10313 // If A doesn't have exactly the correct type, we don't want to classify it
10314 // as "better" than anything else. This way, the user is required to
10315 // disambiguate for us if there are multiple candidates and no exact match.
10316 return candidateHasExactlyCorrectType(A) &&
10317 (!candidateHasExactlyCorrectType(B) ||
10318 hasBetterEnableIfAttrs(S, A, B));
10319 }
10320
10321 /// \return true if we were able to eliminate all but one overload candidate,
10322 /// false otherwise.
10323 bool eliminiateSuboptimalOverloadCandidates() {
10324 // Same algorithm as overload resolution -- one pass to pick the "best",
10325 // another pass to be sure that nothing is better than the best.
10326 auto Best = Matches.begin();
10327 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10328 if (isBetterCandidate(I->second, Best->second))
10329 Best = I;
10330
10331 const FunctionDecl *BestFn = Best->second;
10332 auto IsBestOrInferiorToBest = [this, BestFn](
10333 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10334 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10335 };
10336
10337 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10338 // option, so we can potentially give the user a better error
10339 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10340 return false;
10341 Matches[0] = *Best;
10342 Matches.resize(1);
10343 return true;
10344 }
10345
10346 bool isTargetTypeAFunction() const {
10347 return TargetFunctionType->isFunctionType();
10348 }
10349
10350 // [ToType] [Return]
10351
10352 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10353 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10354 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10355 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10356 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10357 }
10358
10359 // return true if any matching specializations were found
10360 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10361 const DeclAccessPair& CurAccessFunPair) {
10362 if (CXXMethodDecl *Method
10363 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10364 // Skip non-static function templates when converting to pointer, and
10365 // static when converting to member pointer.
10366 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10367 return false;
10368 }
10369 else if (TargetTypeIsNonStaticMemberFunction)
10370 return false;
10371
10372 // C++ [over.over]p2:
10373 // If the name is a function template, template argument deduction is
10374 // done (14.8.2.2), and if the argument deduction succeeds, the
10375 // resulting template argument list is used to generate a single
10376 // function template specialization, which is added to the set of
10377 // overloaded functions considered.
10378 FunctionDecl *Specialization = nullptr;
10379 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10380 if (Sema::TemplateDeductionResult Result
10381 = S.DeduceTemplateArguments(FunctionTemplate,
10382 &OvlExplicitTemplateArgs,
10383 TargetFunctionType, Specialization,
10384 Info, /*InOverloadResolution=*/true)) {
10385 // Make a note of the failed deduction for diagnostics.
10386 FailedCandidates.addCandidate()
10387 .set(FunctionTemplate->getTemplatedDecl(),
10388 MakeDeductionFailureInfo(Context, Result, Info));
10389 return false;
10390 }
10391
10392 // Template argument deduction ensures that we have an exact match or
10393 // compatible pointer-to-function arguments that would be adjusted by ICS.
10394 // This function template specicalization works.
10395 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10397, __PRETTY_FUNCTION__))
10396 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10397, __PRETTY_FUNCTION__))
10397 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10397, __PRETTY_FUNCTION__))
;
10398
10399 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10400 return false;
10401
10402 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10403 return true;
10404 }
10405
10406 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10407 const DeclAccessPair& CurAccessFunPair) {
10408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10409 // Skip non-static functions when converting to pointer, and static
10410 // when converting to member pointer.
10411 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10412 return false;
10413 }
10414 else if (TargetTypeIsNonStaticMemberFunction)
10415 return false;
10416
10417 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10418 if (S.getLangOpts().CUDA)
10419 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10420 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10421 return false;
10422
10423 // If any candidate has a placeholder return type, trigger its deduction
10424 // now.
10425 if (S.getLangOpts().CPlusPlus14 &&
10426 FunDecl->getReturnType()->isUndeducedType() &&
10427 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10428 HasComplained |= Complain;
10429 return false;
10430 }
10431
10432 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10433 return false;
10434
10435 // If we're in C, we need to support types that aren't exactly identical.
10436 if (!S.getLangOpts().CPlusPlus ||
10437 candidateHasExactlyCorrectType(FunDecl)) {
10438 Matches.push_back(std::make_pair(
10439 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10440 FoundNonTemplateFunction = true;
10441 return true;
10442 }
10443 }
10444
10445 return false;
10446 }
10447
10448 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10449 bool Ret = false;
10450
10451 // If the overload expression doesn't have the form of a pointer to
10452 // member, don't try to convert it to a pointer-to-member type.
10453 if (IsInvalidFormOfPointerToMemberFunction())
10454 return false;
10455
10456 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10457 E = OvlExpr->decls_end();
10458 I != E; ++I) {
10459 // Look through any using declarations to find the underlying function.
10460 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10461
10462 // C++ [over.over]p3:
10463 // Non-member functions and static member functions match
10464 // targets of type "pointer-to-function" or "reference-to-function."
10465 // Nonstatic member functions match targets of
10466 // type "pointer-to-member-function."
10467 // Note that according to DR 247, the containing class does not matter.
10468 if (FunctionTemplateDecl *FunctionTemplate
10469 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10470 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10471 Ret = true;
10472 }
10473 // If we have explicit template arguments supplied, skip non-templates.
10474 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10475 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10476 Ret = true;
10477 }
10478 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10478, __PRETTY_FUNCTION__))
;
10479 return Ret;
10480 }
10481
10482 void EliminateAllExceptMostSpecializedTemplate() {
10483 // [...] and any given function template specialization F1 is
10484 // eliminated if the set contains a second function template
10485 // specialization whose function template is more specialized
10486 // than the function template of F1 according to the partial
10487 // ordering rules of 14.5.5.2.
10488
10489 // The algorithm specified above is quadratic. We instead use a
10490 // two-pass algorithm (similar to the one used to identify the
10491 // best viable function in an overload set) that identifies the
10492 // best function template (if it exists).
10493
10494 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10495 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10496 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10497
10498 // TODO: It looks like FailedCandidates does not serve much purpose
10499 // here, since the no_viable diagnostic has index 0.
10500 UnresolvedSetIterator Result = S.getMostSpecialized(
10501 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10502 SourceExpr->getLocStart(), S.PDiag(),
10503 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10504 .second->getDeclName(),
10505 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10506 Complain, TargetFunctionType);
10507
10508 if (Result != MatchesCopy.end()) {
10509 // Make it the first and only element
10510 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10511 Matches[0].second = cast<FunctionDecl>(*Result);
10512 Matches.resize(1);
10513 } else
10514 HasComplained |= Complain;
10515 }
10516
10517 void EliminateAllTemplateMatches() {
10518 // [...] any function template specializations in the set are
10519 // eliminated if the set also contains a non-template function, [...]
10520 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10521 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10522 ++I;
10523 else {
10524 Matches[I] = Matches[--N];
10525 Matches.resize(N);
10526 }
10527 }
10528 }
10529
10530 void EliminateSuboptimalCudaMatches() {
10531 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10532 }
10533
10534public:
10535 void ComplainNoMatchesFound() const {
10536 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10536, __PRETTY_FUNCTION__))
;
10537 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10538 << OvlExpr->getName() << TargetFunctionType
10539 << OvlExpr->getSourceRange();
10540 if (FailedCandidates.empty())
10541 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10542 /*TakingAddress=*/true);
10543 else {
10544 // We have some deduction failure messages. Use them to diagnose
10545 // the function templates, and diagnose the non-template candidates
10546 // normally.
10547 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10548 IEnd = OvlExpr->decls_end();
10549 I != IEnd; ++I)
10550 if (FunctionDecl *Fun =
10551 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10552 if (!functionHasPassObjectSizeParams(Fun))
10553 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10554 /*TakingAddress=*/true);
10555 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10556 }
10557 }
10558
10559 bool IsInvalidFormOfPointerToMemberFunction() const {
10560 return TargetTypeIsNonStaticMemberFunction &&
10561 !OvlExprInfo.HasFormOfMemberPointer;
10562 }
10563
10564 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10565 // TODO: Should we condition this on whether any functions might
10566 // have matched, or is it more appropriate to do that in callers?
10567 // TODO: a fixit wouldn't hurt.
10568 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10569 << TargetType << OvlExpr->getSourceRange();
10570 }
10571
10572 bool IsStaticMemberFunctionFromBoundPointer() const {
10573 return StaticMemberFunctionFromBoundPointer;
10574 }
10575
10576 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10577 S.Diag(OvlExpr->getLocStart(),
10578 diag::err_invalid_form_pointer_member_function)
10579 << OvlExpr->getSourceRange();
10580 }
10581
10582 void ComplainOfInvalidConversion() const {
10583 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10584 << OvlExpr->getName() << TargetType;
10585 }
10586
10587 void ComplainMultipleMatchesFound() const {
10588 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10588, __PRETTY_FUNCTION__))
;
10589 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10590 << OvlExpr->getName()
10591 << OvlExpr->getSourceRange();
10592 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10593 /*TakingAddress=*/true);
10594 }
10595
10596 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10597
10598 int getNumMatches() const { return Matches.size(); }
10599
10600 FunctionDecl* getMatchingFunctionDecl() const {
10601 if (Matches.size() != 1) return nullptr;
10602 return Matches[0].second;
10603 }
10604
10605 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10606 if (Matches.size() != 1) return nullptr;
10607 return &Matches[0].first;
10608 }
10609};
10610}
10611
10612/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10613/// an overloaded function (C++ [over.over]), where @p From is an
10614/// expression with overloaded function type and @p ToType is the type
10615/// we're trying to resolve to. For example:
10616///
10617/// @code
10618/// int f(double);
10619/// int f(int);
10620///
10621/// int (*pfd)(double) = f; // selects f(double)
10622/// @endcode
10623///
10624/// This routine returns the resulting FunctionDecl if it could be
10625/// resolved, and NULL otherwise. When @p Complain is true, this
10626/// routine will emit diagnostics if there is an error.
10627FunctionDecl *
10628Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10629 QualType TargetType,
10630 bool Complain,
10631 DeclAccessPair &FoundResult,
10632 bool *pHadMultipleCandidates) {
10633 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10633, __PRETTY_FUNCTION__))
;
10634
10635 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10636 Complain);
10637 int NumMatches = Resolver.getNumMatches();
10638 FunctionDecl *Fn = nullptr;
10639 bool ShouldComplain = Complain && !Resolver.hasComplained();
10640 if (NumMatches == 0 && ShouldComplain) {
10641 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10642 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10643 else
10644 Resolver.ComplainNoMatchesFound();
10645 }
10646 else if (NumMatches > 1 && ShouldComplain)
10647 Resolver.ComplainMultipleMatchesFound();
10648 else if (NumMatches == 1) {
10649 Fn = Resolver.getMatchingFunctionDecl();
10650 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10650, __PRETTY_FUNCTION__))
;
10651 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10652 if (Complain) {
10653 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10654 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10655 else
10656 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10657 }
10658 }
10659
10660 if (pHadMultipleCandidates)
10661 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10662 return Fn;
10663}
10664
10665/// \brief Given an expression that refers to an overloaded function, try to
10666/// resolve that function to a single function that can have its address taken.
10667/// This will modify `Pair` iff it returns non-null.
10668///
10669/// This routine can only realistically succeed if all but one candidates in the
10670/// overload set for SrcExpr cannot have their addresses taken.
10671FunctionDecl *
10672Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10673 DeclAccessPair &Pair) {
10674 OverloadExpr::FindResult R = OverloadExpr::find(E);
10675 OverloadExpr *Ovl = R.Expression;
10676 FunctionDecl *Result = nullptr;
10677 DeclAccessPair DAP;
10678 // Don't use the AddressOfResolver because we're specifically looking for
10679 // cases where we have one overload candidate that lacks
10680 // enable_if/pass_object_size/...
10681 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10682 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10683 if (!FD)
10684 return nullptr;
10685
10686 if (!checkAddressOfFunctionIsAvailable(FD))
10687 continue;
10688
10689 // We have more than one result; quit.
10690 if (Result)
10691 return nullptr;
10692 DAP = I.getPair();
10693 Result = FD;
10694 }
10695
10696 if (Result)
10697 Pair = DAP;
10698 return Result;
10699}
10700
10701/// \brief Given an expression that refers to an overloaded function, try to
10702/// resolve that overloaded function expression down to a single function.
10703///
10704/// This routine can only resolve template-ids that refer to a single function
10705/// template, where that template-id refers to a single template whose template
10706/// arguments are either provided by the template-id or have defaults,
10707/// as described in C++0x [temp.arg.explicit]p3.
10708///
10709/// If no template-ids are found, no diagnostics are emitted and NULL is
10710/// returned.
10711FunctionDecl *
10712Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10713 bool Complain,
10714 DeclAccessPair *FoundResult) {
10715 // C++ [over.over]p1:
10716 // [...] [Note: any redundant set of parentheses surrounding the
10717 // overloaded function name is ignored (5.1). ]
10718 // C++ [over.over]p1:
10719 // [...] The overloaded function name can be preceded by the &
10720 // operator.
10721
10722 // If we didn't actually find any template-ids, we're done.
10723 if (!ovl->hasExplicitTemplateArgs())
10724 return nullptr;
10725
10726 TemplateArgumentListInfo ExplicitTemplateArgs;
10727 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10728 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10729
10730 // Look through all of the overloaded functions, searching for one
10731 // whose type matches exactly.
10732 FunctionDecl *Matched = nullptr;
10733 for (UnresolvedSetIterator I = ovl->decls_begin(),
10734 E = ovl->decls_end(); I != E; ++I) {
10735 // C++0x [temp.arg.explicit]p3:
10736 // [...] In contexts where deduction is done and fails, or in contexts
10737 // where deduction is not done, if a template argument list is
10738 // specified and it, along with any default template arguments,
10739 // identifies a single function template specialization, then the
10740 // template-id is an lvalue for the function template specialization.
10741 FunctionTemplateDecl *FunctionTemplate
10742 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10743
10744 // C++ [over.over]p2:
10745 // If the name is a function template, template argument deduction is
10746 // done (14.8.2.2), and if the argument deduction succeeds, the
10747 // resulting template argument list is used to generate a single
10748 // function template specialization, which is added to the set of
10749 // overloaded functions considered.
10750 FunctionDecl *Specialization = nullptr;
10751 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10752 if (TemplateDeductionResult Result
10753 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10754 Specialization, Info,
10755 /*InOverloadResolution=*/true)) {
10756 // Make a note of the failed deduction for diagnostics.
10757 // TODO: Actually use the failed-deduction info?
10758 FailedCandidates.addCandidate()
10759 .set(FunctionTemplate->getTemplatedDecl(),
10760 MakeDeductionFailureInfo(Context, Result, Info));
10761 continue;
10762 }
10763
10764 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10764, __PRETTY_FUNCTION__))
;
10765
10766 // Multiple matches; we can't resolve to a single declaration.
10767 if (Matched) {
10768 if (Complain) {
10769 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10770 << ovl->getName();
10771 NoteAllOverloadCandidates(ovl);
10772 }
10773 return nullptr;
10774 }
10775
10776 Matched = Specialization;
10777 if (FoundResult) *FoundResult = I.getPair();
10778 }
10779
10780 if (Matched && getLangOpts().CPlusPlus14 &&
10781 Matched->getReturnType()->isUndeducedType() &&
10782 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10783 return nullptr;
10784
10785 return Matched;
10786}
10787
10788
10789
10790
10791// Resolve and fix an overloaded expression that can be resolved
10792// because it identifies a single function template specialization.
10793//
10794// Last three arguments should only be supplied if Complain = true
10795//
10796// Return true if it was logically possible to so resolve the
10797// expression, regardless of whether or not it succeeded. Always
10798// returns true if 'complain' is set.
10799bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10800 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10801 bool complain, SourceRange OpRangeForComplaining,
10802 QualType DestTypeForComplaining,
10803 unsigned DiagIDForComplaining) {
10804 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10804, __PRETTY_FUNCTION__))
;
10805
10806 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10807
10808 DeclAccessPair found;
10809 ExprResult SingleFunctionExpression;
10810 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10811 ovl.Expression, /*complain*/ false, &found)) {
10812 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10813 SrcExpr = ExprError();
10814 return true;
10815 }
10816
10817 // It is only correct to resolve to an instance method if we're
10818 // resolving a form that's permitted to be a pointer to member.
10819 // Otherwise we'll end up making a bound member expression, which
10820 // is illegal in all the contexts we resolve like this.
10821 if (!ovl.HasFormOfMemberPointer &&
10822 isa<CXXMethodDecl>(fn) &&
10823 cast<CXXMethodDecl>(fn)->isInstance()) {
10824 if (!complain) return false;
10825
10826 Diag(ovl.Expression->getExprLoc(),
10827 diag::err_bound_member_function)
10828 << 0 << ovl.Expression->getSourceRange();
10829
10830 // TODO: I believe we only end up here if there's a mix of
10831 // static and non-static candidates (otherwise the expression
10832 // would have 'bound member' type, not 'overload' type).
10833 // Ideally we would note which candidate was chosen and why
10834 // the static candidates were rejected.
10835 SrcExpr = ExprError();
10836 return true;
10837 }
10838
10839 // Fix the expression to refer to 'fn'.
10840 SingleFunctionExpression =
10841 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10842
10843 // If desired, do function-to-pointer decay.
10844 if (doFunctionPointerConverion) {
10845 SingleFunctionExpression =
10846 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10847 if (SingleFunctionExpression.isInvalid()) {
10848 SrcExpr = ExprError();
10849 return true;
10850 }
10851 }
10852 }
10853
10854 if (!SingleFunctionExpression.isUsable()) {
10855 if (complain) {
10856 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10857 << ovl.Expression->getName()
10858 << DestTypeForComplaining
10859 << OpRangeForComplaining
10860 << ovl.Expression->getQualifierLoc().getSourceRange();
10861 NoteAllOverloadCandidates(SrcExpr.get());
10862
10863 SrcExpr = ExprError();
10864 return true;
10865 }
10866
10867 return false;
10868 }
10869
10870 SrcExpr = SingleFunctionExpression;
10871 return true;
10872}
10873
10874/// \brief Add a single candidate to the overload set.
10875static void AddOverloadedCallCandidate(Sema &S,
10876 DeclAccessPair FoundDecl,
10877 TemplateArgumentListInfo *ExplicitTemplateArgs,
10878 ArrayRef<Expr *> Args,
10879 OverloadCandidateSet &CandidateSet,
10880 bool PartialOverloading,
10881 bool KnownValid) {
10882 NamedDecl *Callee = FoundDecl.getDecl();
10883 if (isa<UsingShadowDecl>(Callee))
10884 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10885
10886 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10887 if (ExplicitTemplateArgs) {
10888 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10888, __PRETTY_FUNCTION__))
;
10889 return;
10890 }
10891 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10892 /*SuppressUsedConversions=*/false,
10893 PartialOverloading);
10894 return;
10895 }
10896
10897 if (FunctionTemplateDecl *FuncTemplate
10898 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10899 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10900 ExplicitTemplateArgs, Args, CandidateSet,
10901 /*SuppressUsedConversions=*/false,
10902 PartialOverloading);
10903 return;
10904 }
10905
10906 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10906, __PRETTY_FUNCTION__))
;
10907}
10908
10909/// \brief Add the overload candidates named by callee and/or found by argument
10910/// dependent lookup to the given overload set.
10911void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10912 ArrayRef<Expr *> Args,
10913 OverloadCandidateSet &CandidateSet,
10914 bool PartialOverloading) {
10915
10916#ifndef NDEBUG
10917 // Verify that ArgumentDependentLookup is consistent with the rules
10918 // in C++0x [basic.lookup.argdep]p3:
10919 //
10920 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10921 // and let Y be the lookup set produced by argument dependent
10922 // lookup (defined as follows). If X contains
10923 //
10924 // -- a declaration of a class member, or
10925 //
10926 // -- a block-scope function declaration that is not a
10927 // using-declaration, or
10928 //
10929 // -- a declaration that is neither a function or a function
10930 // template
10931 //
10932 // then Y is empty.
10933
10934 if (ULE->requiresADL()) {
10935 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10936 E = ULE->decls_end(); I != E; ++I) {
10937 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10937, __PRETTY_FUNCTION__))
;
10938 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10939, __PRETTY_FUNCTION__))
10939 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10939, __PRETTY_FUNCTION__))
;
10940 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 10940, __PRETTY_FUNCTION__))
;
10941 }
10942 }
10943#endif
10944
10945 // It would be nice to avoid this copy.
10946 TemplateArgumentListInfo TABuffer;
10947 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10948 if (ULE->hasExplicitTemplateArgs()) {
10949 ULE->copyTemplateArgumentsInto(TABuffer);
10950 ExplicitTemplateArgs = &TABuffer;
10951 }
10952
10953 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10954 E = ULE->decls_end(); I != E; ++I)
10955 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10956 CandidateSet, PartialOverloading,
10957 /*KnownValid*/ true);
10958
10959 if (ULE->requiresADL())
10960 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10961 Args, ExplicitTemplateArgs,
10962 CandidateSet, PartialOverloading);
10963}
10964
10965/// Determine whether a declaration with the specified name could be moved into
10966/// a different namespace.
10967static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10968 switch (Name.getCXXOverloadedOperator()) {
10969 case OO_New: case OO_Array_New:
10970 case OO_Delete: case OO_Array_Delete:
10971 return false;
10972
10973 default:
10974 return true;
10975 }
10976}
10977
10978/// Attempt to recover from an ill-formed use of a non-dependent name in a
10979/// template, where the non-dependent name was declared after the template
10980/// was defined. This is common in code written for a compilers which do not
10981/// correctly implement two-stage name lookup.
10982///
10983/// Returns true if a viable candidate was found and a diagnostic was issued.
10984static bool
10985DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10986 const CXXScopeSpec &SS, LookupResult &R,
10987 OverloadCandidateSet::CandidateSetKind CSK,
10988 TemplateArgumentListInfo *ExplicitTemplateArgs,
10989 ArrayRef<Expr *> Args,
10990 bool *DoDiagnoseEmptyLookup = nullptr) {
10991 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10992 return false;
10993
10994 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10995 if (DC->isTransparentContext())
10996 continue;
10997
10998 SemaRef.LookupQualifiedName(R, DC);
10999
11000 if (!R.empty()) {
11001 R.suppressDiagnostics();
11002
11003 if (isa<CXXRecordDecl>(DC)) {
11004 // Don't diagnose names we find in classes; we get much better
11005 // diagnostics for these from DiagnoseEmptyLookup.
11006 R.clear();
11007 if (DoDiagnoseEmptyLookup)
11008 *DoDiagnoseEmptyLookup = true;
11009 return false;
11010 }
11011
11012 OverloadCandidateSet Candidates(FnLoc, CSK);
11013 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11014 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11015 ExplicitTemplateArgs, Args,
11016 Candidates, false, /*KnownValid*/ false);
11017
11018 OverloadCandidateSet::iterator Best;
11019 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11020 // No viable functions. Don't bother the user with notes for functions
11021 // which don't work and shouldn't be found anyway.
11022 R.clear();
11023 return false;
11024 }
11025
11026 // Find the namespaces where ADL would have looked, and suggest
11027 // declaring the function there instead.
11028 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11029 Sema::AssociatedClassSet AssociatedClasses;
11030 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11031 AssociatedNamespaces,
11032 AssociatedClasses);
11033 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11034 if (canBeDeclaredInNamespace(R.getLookupName())) {
11035 DeclContext *Std = SemaRef.getStdNamespace();
11036 for (Sema::AssociatedNamespaceSet::iterator
11037 it = AssociatedNamespaces.begin(),
11038 end = AssociatedNamespaces.end(); it != end; ++it) {
11039 // Never suggest declaring a function within namespace 'std'.
11040 if (Std && Std->Encloses(*it))
11041 continue;
11042
11043 // Never suggest declaring a function within a namespace with a
11044 // reserved name, like __gnu_cxx.
11045 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11046 if (NS &&
11047 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11048 continue;
11049
11050 SuggestedNamespaces.insert(*it);
11051 }
11052 }
11053
11054 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11055 << R.getLookupName();
11056 if (SuggestedNamespaces.empty()) {
11057 SemaRef.Diag(Best->Function->getLocation(),
11058 diag::note_not_found_by_two_phase_lookup)
11059 << R.getLookupName() << 0;
11060 } else if (SuggestedNamespaces.size() == 1) {
11061 SemaRef.Diag(Best->Function->getLocation(),
11062 diag::note_not_found_by_two_phase_lookup)
11063 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11064 } else {
11065 // FIXME: It would be useful to list the associated namespaces here,
11066 // but the diagnostics infrastructure doesn't provide a way to produce
11067 // a localized representation of a list of items.
11068 SemaRef.Diag(Best->Function->getLocation(),
11069 diag::note_not_found_by_two_phase_lookup)
11070 << R.getLookupName() << 2;
11071 }
11072
11073 // Try to recover by calling this function.
11074 return true;
11075 }
11076
11077 R.clear();
11078 }
11079
11080 return false;
11081}
11082
11083/// Attempt to recover from ill-formed use of a non-dependent operator in a
11084/// template, where the non-dependent operator was declared after the template
11085/// was defined.
11086///
11087/// Returns true if a viable candidate was found and a diagnostic was issued.
11088static bool
11089DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11090 SourceLocation OpLoc,
11091 ArrayRef<Expr *> Args) {
11092 DeclarationName OpName =
11093 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11094 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11095 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11096 OverloadCandidateSet::CSK_Operator,
11097 /*ExplicitTemplateArgs=*/nullptr, Args);
11098}
11099
11100namespace {
11101class BuildRecoveryCallExprRAII {
11102 Sema &SemaRef;
11103public:
11104 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11105 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11105, __PRETTY_FUNCTION__))
;
11106 SemaRef.IsBuildingRecoveryCallExpr = true;
11107 }
11108
11109 ~BuildRecoveryCallExprRAII() {
11110 SemaRef.IsBuildingRecoveryCallExpr = false;
11111 }
11112};
11113
11114}
11115
11116static std::unique_ptr<CorrectionCandidateCallback>
11117MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11118 bool HasTemplateArgs, bool AllowTypoCorrection) {
11119 if (!AllowTypoCorrection)
11120 return llvm::make_unique<NoTypoCorrectionCCC>();
11121 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11122 HasTemplateArgs, ME);
11123}
11124
11125/// Attempts to recover from a call where no functions were found.
11126///
11127/// Returns true if new candidates were found.
11128static ExprResult
11129BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11130 UnresolvedLookupExpr *ULE,
11131 SourceLocation LParenLoc,
11132 MutableArrayRef<Expr *> Args,
11133 SourceLocation RParenLoc,
11134 bool EmptyLookup, bool AllowTypoCorrection) {
11135 // Do not try to recover if it is already building a recovery call.
11136 // This stops infinite loops for template instantiations like
11137 //
11138 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11139 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11140 //
11141 if (SemaRef.IsBuildingRecoveryCallExpr)
11142 return ExprError();
11143 BuildRecoveryCallExprRAII RCE(SemaRef);
11144
11145 CXXScopeSpec SS;
11146 SS.Adopt(ULE->getQualifierLoc());
11147 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11148
11149 TemplateArgumentListInfo TABuffer;
11150 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11151 if (ULE->hasExplicitTemplateArgs()) {
11152 ULE->copyTemplateArgumentsInto(TABuffer);
11153 ExplicitTemplateArgs = &TABuffer;
11154 }
11155
11156 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11157 Sema::LookupOrdinaryName);
11158 bool DoDiagnoseEmptyLookup = EmptyLookup;
11159 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11160 OverloadCandidateSet::CSK_Normal,
11161 ExplicitTemplateArgs, Args,
11162 &DoDiagnoseEmptyLookup) &&
11163 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11164 S, SS, R,
11165 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11166 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11167 ExplicitTemplateArgs, Args)))
11168 return ExprError();
11169
11170 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11170, __PRETTY_FUNCTION__))
;
11171
11172 // Build an implicit member call if appropriate. Just drop the
11173 // casts and such from the call, we don't really care.
11174 ExprResult NewFn = ExprError();
11175 if ((*R.begin())->isCXXClassMember())
11176 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11177 ExplicitTemplateArgs, S);
11178 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11179 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11180 ExplicitTemplateArgs);
11181 else
11182 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11183
11184 if (NewFn.isInvalid())
11185 return ExprError();
11186
11187 // This shouldn't cause an infinite loop because we're giving it
11188 // an expression with viable lookup results, which should never
11189 // end up here.
11190 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11191 MultiExprArg(Args.data(), Args.size()),
11192 RParenLoc);
11193}
11194
11195/// \brief Constructs and populates an OverloadedCandidateSet from
11196/// the given function.
11197/// \returns true when an the ExprResult output parameter has been set.
11198bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11199 UnresolvedLookupExpr *ULE,
11200 MultiExprArg Args,
11201 SourceLocation RParenLoc,
11202 OverloadCandidateSet *CandidateSet,
11203 ExprResult *Result) {
11204#ifndef NDEBUG
11205 if (ULE->requiresADL()) {
11206 // To do ADL, we must have found an unqualified name.
11207 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11207, __PRETTY_FUNCTION__))
;
11208
11209 // We don't perform ADL for implicit declarations of builtins.
11210 // Verify that this was correctly set up.
11211 FunctionDecl *F;
11212 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11213 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11214 F->getBuiltinID() && F->isImplicit())
11215 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11215)
;
11216
11217 // We don't perform ADL in C.
11218 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11218, __PRETTY_FUNCTION__))
;
11219 }
11220#endif
11221
11222 UnbridgedCastsSet UnbridgedCasts;
11223 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11224 *Result = ExprError();
11225 return true;
11226 }
11227
11228 // Add the functions denoted by the callee to the set of candidate
11229 // functions, including those from argument-dependent lookup.
11230 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11231
11232 if (getLangOpts().MSVCCompat &&
11233 CurContext->isDependentContext() && !isSFINAEContext() &&
11234 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11235
11236 OverloadCandidateSet::iterator Best;
11237 if (CandidateSet->empty() ||
11238 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11239 OR_No_Viable_Function) {
11240 // In Microsoft mode, if we are inside a template class member function then
11241 // create a type dependent CallExpr. The goal is to postpone name lookup
11242 // to instantiation time to be able to search into type dependent base
11243 // classes.
11244 CallExpr *CE = new (Context) CallExpr(
11245 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11246 CE->setTypeDependent(true);
11247 CE->setValueDependent(true);
11248 CE->setInstantiationDependent(true);
11249 *Result = CE;
11250 return true;
11251 }
11252 }
11253
11254 if (CandidateSet->empty())
11255 return false;
11256
11257 UnbridgedCasts.restore();
11258 return false;
11259}
11260
11261/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11262/// the completed call expression. If overload resolution fails, emits
11263/// diagnostics and returns ExprError()
11264static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11265 UnresolvedLookupExpr *ULE,
11266 SourceLocation LParenLoc,
11267 MultiExprArg Args,
11268 SourceLocation RParenLoc,
11269 Expr *ExecConfig,
11270 OverloadCandidateSet *CandidateSet,
11271 OverloadCandidateSet::iterator *Best,
11272 OverloadingResult OverloadResult,
11273 bool AllowTypoCorrection) {
11274 if (CandidateSet->empty())
11275 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11276 RParenLoc, /*EmptyLookup=*/true,
11277 AllowTypoCorrection);
11278
11279 switch (OverloadResult) {
11280 case OR_Success: {
11281 FunctionDecl *FDecl = (*Best)->Function;
11282 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11283 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11284 return ExprError();
11285 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11286 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11287 ExecConfig);
11288 }
11289
11290 case OR_No_Viable_Function: {
11291 // Try to recover by looking for viable functions which the user might
11292 // have meant to call.
11293 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11294 Args, RParenLoc,
11295 /*EmptyLookup=*/false,
11296 AllowTypoCorrection);
11297 if (!Recovery.isInvalid())
11298 return Recovery;
11299
11300 // If the user passes in a function that we can't take the address of, we
11301 // generally end up emitting really bad error messages. Here, we attempt to
11302 // emit better ones.
11303 for (const Expr *Arg : Args) {
11304 if (!Arg->getType()->isFunctionType())
11305 continue;
11306 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11307 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11308 if (FD &&
11309 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11310 Arg->getExprLoc()))
11311 return ExprError();
11312 }
11313 }
11314
11315 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11316 << ULE->getName() << Fn->getSourceRange();
11317 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11318 break;
11319 }
11320
11321 case OR_Ambiguous:
11322 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11323 << ULE->getName() << Fn->getSourceRange();
11324 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11325 break;
11326
11327 case OR_Deleted: {
11328 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11329 << (*Best)->Function->isDeleted()
11330 << ULE->getName()
11331 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11332 << Fn->getSourceRange();
11333 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11334
11335 // We emitted an error for the unvailable/deleted function call but keep
11336 // the call in the AST.
11337 FunctionDecl *FDecl = (*Best)->Function;
11338 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11339 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11340 ExecConfig);
11341 }
11342 }
11343
11344 // Overload resolution failed.
11345 return ExprError();
11346}
11347
11348static void markUnaddressableCandidatesUnviable(Sema &S,
11349 OverloadCandidateSet &CS) {
11350 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11351 if (I->Viable &&
11352 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11353 I->Viable = false;
11354 I->FailureKind = ovl_fail_addr_not_available;
11355 }
11356 }
11357}
11358
11359/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11360/// (which eventually refers to the declaration Func) and the call
11361/// arguments Args/NumArgs, attempt to resolve the function call down
11362/// to a specific function. If overload resolution succeeds, returns
11363/// the call expression produced by overload resolution.
11364/// Otherwise, emits diagnostics and returns ExprError.
11365ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11366 UnresolvedLookupExpr *ULE,
11367 SourceLocation LParenLoc,
11368 MultiExprArg Args,
11369 SourceLocation RParenLoc,
11370 Expr *ExecConfig,
11371 bool AllowTypoCorrection,
11372 bool CalleesAddressIsTaken) {
11373 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11374 OverloadCandidateSet::CSK_Normal);
11375 ExprResult result;
11376
11377 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11378 &result))
11379 return result;
11380
11381 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11382 // functions that aren't addressible are considered unviable.
11383 if (CalleesAddressIsTaken)
11384 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11385
11386 OverloadCandidateSet::iterator Best;
11387 OverloadingResult OverloadResult =
11388 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11389
11390 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11391 RParenLoc, ExecConfig, &CandidateSet,
11392 &Best, OverloadResult,
11393 AllowTypoCorrection);
11394}
11395
11396static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11397 return Functions.size() > 1 ||
11398 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11399}
11400
11401/// \brief Create a unary operation that may resolve to an overloaded
11402/// operator.
11403///
11404/// \param OpLoc The location of the operator itself (e.g., '*').
11405///
11406/// \param Opc The UnaryOperatorKind that describes this operator.
11407///
11408/// \param Fns The set of non-member functions that will be
11409/// considered by overload resolution. The caller needs to build this
11410/// set based on the context using, e.g.,
11411/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11412/// set should not contain any member functions; those will be added
11413/// by CreateOverloadedUnaryOp().
11414///
11415/// \param Input The input argument.
11416ExprResult
11417Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11418 const UnresolvedSetImpl &Fns,
11419 Expr *Input) {
11420 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11421 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11421, __PRETTY_FUNCTION__))
;
11422 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11423 // TODO: provide better source location info.
11424 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11425
11426 if (checkPlaceholderForOverload(*this, Input))
11427 return ExprError();
11428
11429 Expr *Args[2] = { Input, nullptr };
11430 unsigned NumArgs = 1;
11431
11432 // For post-increment and post-decrement, add the implicit '0' as
11433 // the second argument, so that we know this is a post-increment or
11434 // post-decrement.
11435 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11436 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11437 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11438 SourceLocation());
11439 NumArgs = 2;
11440 }
11441
11442 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11443
11444 if (Input->isTypeDependent()) {
11445 if (Fns.empty())
11446 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11447 VK_RValue, OK_Ordinary, OpLoc);
11448
11449 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11450 UnresolvedLookupExpr *Fn
11451 = UnresolvedLookupExpr::Create(Context, NamingClass,
11452 NestedNameSpecifierLoc(), OpNameInfo,
11453 /*ADL*/ true, IsOverloaded(Fns),
11454 Fns.begin(), Fns.end());
11455 return new (Context)
11456 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11457 VK_RValue, OpLoc, false);
11458 }
11459
11460 // Build an empty overload set.
11461 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11462
11463 // Add the candidates from the given function set.
11464 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11465
11466 // Add operator candidates that are member functions.
11467 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11468
11469 // Add candidates from ADL.
11470 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11471 /*ExplicitTemplateArgs*/nullptr,
11472 CandidateSet);
11473
11474 // Add builtin operator candidates.
11475 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11476
11477 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11478
11479 // Perform overload resolution.
11480 OverloadCandidateSet::iterator Best;
11481 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11482 case OR_Success: {
11483 // We found a built-in operator or an overloaded operator.
11484 FunctionDecl *FnDecl = Best->Function;
11485
11486 if (FnDecl) {
11487 // We matched an overloaded operator. Build a call to that
11488 // operator.
11489
11490 // Convert the arguments.
11491 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11492 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11493
11494 ExprResult InputRes =
11495 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11496 Best->FoundDecl, Method);
11497 if (InputRes.isInvalid())
11498 return ExprError();
11499 Input = InputRes.get();
11500 } else {
11501 // Convert the arguments.
11502 ExprResult InputInit
11503 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11504 Context,
11505 FnDecl->getParamDecl(0)),
11506 SourceLocation(),
11507 Input);
11508 if (InputInit.isInvalid())
11509 return ExprError();
11510 Input = InputInit.get();
11511 }
11512
11513 // Build the actual expression node.
11514 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11515 HadMultipleCandidates, OpLoc);
11516 if (FnExpr.isInvalid())
11517 return ExprError();
11518
11519 // Determine the result type.
11520 QualType ResultTy = FnDecl->getReturnType();
11521 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11522 ResultTy = ResultTy.getNonLValueExprType(Context);
11523
11524 Args[0] = Input;
11525 CallExpr *TheCall =
11526 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11527 ResultTy, VK, OpLoc, false);
11528
11529 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11530 return ExprError();
11531
11532 return MaybeBindToTemporary(TheCall);
11533 } else {
11534 // We matched a built-in operator. Convert the arguments, then
11535 // break out so that we will build the appropriate built-in
11536 // operator node.
11537 ExprResult InputRes =
11538 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11539 Best->Conversions[0], AA_Passing);
11540 if (InputRes.isInvalid())
11541 return ExprError();
11542 Input = InputRes.get();
11543 break;
11544 }
11545 }
11546
11547 case OR_No_Viable_Function:
11548 // This is an erroneous use of an operator which can be overloaded by
11549 // a non-member function. Check for non-member operators which were
11550 // defined too late to be candidates.
11551 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11552 // FIXME: Recover by calling the found function.
11553 return ExprError();
11554
11555 // No viable function; fall through to handling this as a
11556 // built-in operator, which will produce an error message for us.
11557 break;
11558
11559 case OR_Ambiguous:
11560 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11561 << UnaryOperator::getOpcodeStr(Opc)
11562 << Input->getType()
11563 << Input->getSourceRange();
11564 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11565 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11566 return ExprError();
11567
11568 case OR_Deleted:
11569 Diag(OpLoc, diag::err_ovl_deleted_oper)
11570 << Best->Function->isDeleted()
11571 << UnaryOperator::getOpcodeStr(Opc)
11572 << getDeletedOrUnavailableSuffix(Best->Function)
11573 << Input->getSourceRange();
11574 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11575 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11576 return ExprError();
11577 }
11578
11579 // Either we found no viable overloaded operator or we matched a
11580 // built-in operator. In either case, fall through to trying to
11581 // build a built-in operation.
11582 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11583}
11584
11585/// \brief Create a binary operation that may resolve to an overloaded
11586/// operator.
11587///
11588/// \param OpLoc The location of the operator itself (e.g., '+').
11589///
11590/// \param Opc The BinaryOperatorKind that describes this operator.
11591///
11592/// \param Fns The set of non-member functions that will be
11593/// considered by overload resolution. The caller needs to build this
11594/// set based on the context using, e.g.,
11595/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11596/// set should not contain any member functions; those will be added
11597/// by CreateOverloadedBinOp().
11598///
11599/// \param LHS Left-hand argument.
11600/// \param RHS Right-hand argument.
11601ExprResult
11602Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11603 BinaryOperatorKind Opc,
11604 const UnresolvedSetImpl &Fns,
11605 Expr *LHS, Expr *RHS) {
11606 Expr *Args[2] = { LHS, RHS };
11607 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11608
11609 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11610 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11611
11612 // If either side is type-dependent, create an appropriate dependent
11613 // expression.
11614 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11615 if (Fns.empty()) {
11616 // If there are no functions to store, just build a dependent
11617 // BinaryOperator or CompoundAssignment.
11618 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11619 return new (Context) BinaryOperator(
11620 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11621 OpLoc, FPFeatures.fp_contract);
11622
11623 return new (Context) CompoundAssignOperator(
11624 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11625 Context.DependentTy, Context.DependentTy, OpLoc,
11626 FPFeatures.fp_contract);
11627 }
11628
11629 // FIXME: save results of ADL from here?
11630 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11631 // TODO: provide better source location info in DNLoc component.
11632 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11633 UnresolvedLookupExpr *Fn
11634 = UnresolvedLookupExpr::Create(Context, NamingClass,
11635 NestedNameSpecifierLoc(), OpNameInfo,
11636 /*ADL*/ true, IsOverloaded(Fns),
11637 Fns.begin(), Fns.end());
11638 return new (Context)
11639 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11640 VK_RValue, OpLoc, FPFeatures.fp_contract);
11641 }
11642
11643 // Always do placeholder-like conversions on the RHS.
11644 if (checkPlaceholderForOverload(*this, Args[1]))
11645 return ExprError();
11646
11647 // Do placeholder-like conversion on the LHS; note that we should
11648 // not get here with a PseudoObject LHS.
11649 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11649, __PRETTY_FUNCTION__))
;
11650 if (checkPlaceholderForOverload(*this, Args[0]))
11651 return ExprError();
11652
11653 // If this is the assignment operator, we only perform overload resolution
11654 // if the left-hand side is a class or enumeration type. This is actually
11655 // a hack. The standard requires that we do overload resolution between the
11656 // various built-in candidates, but as DR507 points out, this can lead to
11657 // problems. So we do it this way, which pretty much follows what GCC does.
11658 // Note that we go the traditional code path for compound assignment forms.
11659 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11660 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11661
11662 // If this is the .* operator, which is not overloadable, just
11663 // create a built-in binary operator.
11664 if (Opc == BO_PtrMemD)
11665 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11666
11667 // Build an empty overload set.
11668 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11669
11670 // Add the candidates from the given function set.
11671 AddFunctionCandidates(Fns, Args, CandidateSet);
11672
11673 // Add operator candidates that are member functions.
11674 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11675
11676 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11677 // performed for an assignment operator (nor for operator[] nor operator->,
11678 // which don't get here).
11679 if (Opc != BO_Assign)
11680 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11681 /*ExplicitTemplateArgs*/ nullptr,
11682 CandidateSet);
11683
11684 // Add builtin operator candidates.
11685 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11686
11687 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11688
11689 // Perform overload resolution.
11690 OverloadCandidateSet::iterator Best;
11691 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11692 case OR_Success: {
11693 // We found a built-in operator or an overloaded operator.
11694 FunctionDecl *FnDecl = Best->Function;
11695
11696 if (FnDecl) {
11697 // We matched an overloaded operator. Build a call to that
11698 // operator.
11699
11700 // Convert the arguments.
11701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11702 // Best->Access is only meaningful for class members.
11703 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11704
11705 ExprResult Arg1 =
11706 PerformCopyInitialization(
11707 InitializedEntity::InitializeParameter(Context,
11708 FnDecl->getParamDecl(0)),
11709 SourceLocation(), Args[1]);
11710 if (Arg1.isInvalid())
11711 return ExprError();
11712
11713 ExprResult Arg0 =
11714 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11715 Best->FoundDecl, Method);
11716 if (Arg0.isInvalid())
11717 return ExprError();
11718 Args[0] = Arg0.getAs<Expr>();
11719 Args[1] = RHS = Arg1.getAs<Expr>();
11720 } else {
11721 // Convert the arguments.
11722 ExprResult Arg0 = PerformCopyInitialization(
11723 InitializedEntity::InitializeParameter(Context,
11724 FnDecl->getParamDecl(0)),
11725 SourceLocation(), Args[0]);
11726 if (Arg0.isInvalid())
11727 return ExprError();
11728
11729 ExprResult Arg1 =
11730 PerformCopyInitialization(
11731 InitializedEntity::InitializeParameter(Context,
11732 FnDecl->getParamDecl(1)),
11733 SourceLocation(), Args[1]);
11734 if (Arg1.isInvalid())
11735 return ExprError();
11736 Args[0] = LHS = Arg0.getAs<Expr>();
11737 Args[1] = RHS = Arg1.getAs<Expr>();
11738 }
11739
11740 // Build the actual expression node.
11741 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11742 Best->FoundDecl,
11743 HadMultipleCandidates, OpLoc);
11744 if (FnExpr.isInvalid())
11745 return ExprError();
11746
11747 // Determine the result type.
11748 QualType ResultTy = FnDecl->getReturnType();
11749 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11750 ResultTy = ResultTy.getNonLValueExprType(Context);
11751
11752 CXXOperatorCallExpr *TheCall =
11753 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11754 Args, ResultTy, VK, OpLoc,
11755 FPFeatures.fp_contract);
11756
11757 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11758 FnDecl))
11759 return ExprError();
11760
11761 ArrayRef<const Expr *> ArgsArray(Args, 2);
11762 // Cut off the implicit 'this'.
11763 if (isa<CXXMethodDecl>(FnDecl))
11764 ArgsArray = ArgsArray.slice(1);
11765
11766 // Check for a self move.
11767 if (Op == OO_Equal)
11768 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11769
11770 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11771 TheCall->getSourceRange(), VariadicDoesNotApply);
11772
11773 return MaybeBindToTemporary(TheCall);
11774 } else {
11775 // We matched a built-in operator. Convert the arguments, then
11776 // break out so that we will build the appropriate built-in
11777 // operator node.
11778 ExprResult ArgsRes0 =
11779 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11780 Best->Conversions[0], AA_Passing);
11781 if (ArgsRes0.isInvalid())
11782 return ExprError();
11783 Args[0] = ArgsRes0.get();
11784
11785 ExprResult ArgsRes1 =
11786 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11787 Best->Conversions[1], AA_Passing);
11788 if (ArgsRes1.isInvalid())
11789 return ExprError();
11790 Args[1] = ArgsRes1.get();
11791 break;
11792 }
11793 }
11794
11795 case OR_No_Viable_Function: {
11796 // C++ [over.match.oper]p9:
11797 // If the operator is the operator , [...] and there are no
11798 // viable functions, then the operator is assumed to be the
11799 // built-in operator and interpreted according to clause 5.
11800 if (Opc == BO_Comma)
11801 break;
11802
11803 // For class as left operand for assignment or compound assigment
11804 // operator do not fall through to handling in built-in, but report that
11805 // no overloaded assignment operator found
11806 ExprResult Result = ExprError();
11807 if (Args[0]->getType()->isRecordType() &&
11808 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11809 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11810 << BinaryOperator::getOpcodeStr(Opc)
11811 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11812 if (Args[0]->getType()->isIncompleteType()) {
11813 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11814 << Args[0]->getType()
11815 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11816 }
11817 } else {
11818 // This is an erroneous use of an operator which can be overloaded by
11819 // a non-member function. Check for non-member operators which were
11820 // defined too late to be candidates.
11821 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11822 // FIXME: Recover by calling the found function.
11823 return ExprError();
11824
11825 // No viable function; try to create a built-in operation, which will
11826 // produce an error. Then, show the non-viable candidates.
11827 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11828 }
11829 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11830, __PRETTY_FUNCTION__))
11830 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 11830, __PRETTY_FUNCTION__))
;
11831 if (Result.isInvalid())
11832 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11833 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11834 return Result;
11835 }
11836
11837 case OR_Ambiguous:
11838 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11839 << BinaryOperator::getOpcodeStr(Opc)
11840 << Args[0]->getType() << Args[1]->getType()
11841 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11842 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11843 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11844 return ExprError();
11845
11846 case OR_Deleted:
11847 if (isImplicitlyDeleted(Best->Function)) {
11848 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11849 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11850 << Context.getRecordType(Method->getParent())
11851 << getSpecialMember(Method);
11852
11853 // The user probably meant to call this special member. Just
11854 // explain why it's deleted.
11855 NoteDeletedFunction(Method);
11856 return ExprError();
11857 } else {
11858 Diag(OpLoc, diag::err_ovl_deleted_oper)
11859 << Best->Function->isDeleted()
11860 << BinaryOperator::getOpcodeStr(Opc)
11861 << getDeletedOrUnavailableSuffix(Best->Function)
11862 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11863 }
11864 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11865 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11866 return ExprError();
11867 }
11868
11869 // We matched a built-in operator; build it.
11870 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11871}
11872
11873ExprResult
11874Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11875 SourceLocation RLoc,
11876 Expr *Base, Expr *Idx) {
11877 Expr *Args[2] = { Base, Idx };
11878 DeclarationName OpName =
11879 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11880
11881 // If either side is type-dependent, create an appropriate dependent
11882 // expression.
11883 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11884
11885 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11886 // CHECKME: no 'operator' keyword?
11887 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11888 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11889 UnresolvedLookupExpr *Fn
11890 = UnresolvedLookupExpr::Create(Context, NamingClass,
11891 NestedNameSpecifierLoc(), OpNameInfo,
11892 /*ADL*/ true, /*Overloaded*/ false,
11893 UnresolvedSetIterator(),
11894 UnresolvedSetIterator());
11895 // Can't add any actual overloads yet
11896
11897 return new (Context)
11898 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11899 Context.DependentTy, VK_RValue, RLoc, false);
11900 }
11901
11902 // Handle placeholders on both operands.
11903 if (checkPlaceholderForOverload(*this, Args[0]))
11904 return ExprError();
11905 if (checkPlaceholderForOverload(*this, Args[1]))
11906 return ExprError();
11907
11908 // Build an empty overload set.
11909 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11910
11911 // Subscript can only be overloaded as a member function.
11912
11913 // Add operator candidates that are member functions.
11914 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11915
11916 // Add builtin operator candidates.
11917 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11918
11919 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11920
11921 // Perform overload resolution.
11922 OverloadCandidateSet::iterator Best;
11923 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11924 case OR_Success: {
11925 // We found a built-in operator or an overloaded operator.
11926 FunctionDecl *FnDecl = Best->Function;
11927
11928 if (FnDecl) {
11929 // We matched an overloaded operator. Build a call to that
11930 // operator.
11931
11932 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11933
11934 // Convert the arguments.
11935 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11936 ExprResult Arg0 =
11937 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11938 Best->FoundDecl, Method);
11939 if (Arg0.isInvalid())
11940 return ExprError();
11941 Args[0] = Arg0.get();
11942
11943 // Convert the arguments.
11944 ExprResult InputInit
11945 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11946 Context,
11947 FnDecl->getParamDecl(0)),
11948 SourceLocation(),
11949 Args[1]);
11950 if (InputInit.isInvalid())
11951 return ExprError();
11952
11953 Args[1] = InputInit.getAs<Expr>();
11954
11955 // Build the actual expression node.
11956 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11957 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11958 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11959 Best->FoundDecl,
11960 HadMultipleCandidates,
11961 OpLocInfo.getLoc(),
11962 OpLocInfo.getInfo());
11963 if (FnExpr.isInvalid())
11964 return ExprError();
11965
11966 // Determine the result type
11967 QualType ResultTy = FnDecl->getReturnType();
11968 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11969 ResultTy = ResultTy.getNonLValueExprType(Context);
11970
11971 CXXOperatorCallExpr *TheCall =
11972 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11973 FnExpr.get(), Args,
11974 ResultTy, VK, RLoc,
11975 false);
11976
11977 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11978 return ExprError();
11979
11980 return MaybeBindToTemporary(TheCall);
11981 } else {
11982 // We matched a built-in operator. Convert the arguments, then
11983 // break out so that we will build the appropriate built-in
11984 // operator node.
11985 ExprResult ArgsRes0 =
11986 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11987 Best->Conversions[0], AA_Passing);
11988 if (ArgsRes0.isInvalid())
11989 return ExprError();
11990 Args[0] = ArgsRes0.get();
11991
11992 ExprResult ArgsRes1 =
11993 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11994 Best->Conversions[1], AA_Passing);
11995 if (ArgsRes1.isInvalid())
11996 return ExprError();
11997 Args[1] = ArgsRes1.get();
11998
11999 break;
12000 }
12001 }
12002
12003 case OR_No_Viable_Function: {
12004 if (CandidateSet.empty())
12005 Diag(LLoc, diag::err_ovl_no_oper)
12006 << Args[0]->getType() << /*subscript*/ 0
12007 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12008 else
12009 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12010 << Args[0]->getType()
12011 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12012 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12013 "[]", LLoc);
12014 return ExprError();
12015 }
12016
12017 case OR_Ambiguous:
12018 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12019 << "[]"
12020 << Args[0]->getType() << Args[1]->getType()
12021 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12022 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12023 "[]", LLoc);
12024 return ExprError();
12025
12026 case OR_Deleted:
12027 Diag(LLoc, diag::err_ovl_deleted_oper)
12028 << Best->Function->isDeleted() << "[]"
12029 << getDeletedOrUnavailableSuffix(Best->Function)
12030 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12032 "[]", LLoc);
12033 return ExprError();
12034 }
12035
12036 // We matched a built-in operator; build it.
12037 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12038}
12039
12040/// BuildCallToMemberFunction - Build a call to a member
12041/// function. MemExpr is the expression that refers to the member
12042/// function (and includes the object parameter), Args/NumArgs are the
12043/// arguments to the function call (not including the object
12044/// parameter). The caller needs to validate that the member
12045/// expression refers to a non-static member function or an overloaded
12046/// member function.
12047ExprResult
12048Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12049 SourceLocation LParenLoc,
12050 MultiExprArg Args,
12051 SourceLocation RParenLoc) {
12052 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12053, __PRETTY_FUNCTION__))
12053 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12053, __PRETTY_FUNCTION__))
;
12054
12055 // Dig out the member expression. This holds both the object
12056 // argument and the member function we're referring to.
12057 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12058
12059 // Determine whether this is a call to a pointer-to-member function.
12060 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12061 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12061, __PRETTY_FUNCTION__))
;
12062 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12062, __PRETTY_FUNCTION__))
;
12063
12064 QualType fnType =
12065 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12066
12067 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12068 QualType resultType = proto->getCallResultType(Context);
12069 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12070
12071 // Check that the object type isn't more qualified than the
12072 // member function we're calling.
12073 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12074
12075 QualType objectType = op->getLHS()->getType();
12076 if (op->getOpcode() == BO_PtrMemI)
12077 objectType = objectType->castAs<PointerType>()->getPointeeType();
12078 Qualifiers objectQuals = objectType.getQualifiers();
12079
12080 Qualifiers difference = objectQuals - funcQuals;
12081 difference.removeObjCGCAttr();
12082 difference.removeAddressSpace();
12083 if (difference) {
12084 std::string qualsString = difference.getAsString();
12085 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12086 << fnType.getUnqualifiedType()
12087 << qualsString
12088 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12089 }
12090
12091 CXXMemberCallExpr *call
12092 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12093 resultType, valueKind, RParenLoc);
12094
12095 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12096 call, nullptr))
12097 return ExprError();
12098
12099 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12100 return ExprError();
12101
12102 if (CheckOtherCall(call, proto))
12103 return ExprError();
12104
12105 return MaybeBindToTemporary(call);
12106 }
12107
12108 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12109 return new (Context)
12110 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12111
12112 UnbridgedCastsSet UnbridgedCasts;
12113 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12114 return ExprError();
12115
12116 MemberExpr *MemExpr;
12117 CXXMethodDecl *Method = nullptr;
12118 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12119 NestedNameSpecifier *Qualifier = nullptr;
12120 if (isa<MemberExpr>(NakedMemExpr)) {
12121 MemExpr = cast<MemberExpr>(NakedMemExpr);
12122 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12123 FoundDecl = MemExpr->getFoundDecl();
12124 Qualifier = MemExpr->getQualifier();
12125 UnbridgedCasts.restore();
12126 } else {
12127 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12128 Qualifier = UnresExpr->getQualifier();
12129
12130 QualType ObjectType = UnresExpr->getBaseType();
12131 Expr::Classification ObjectClassification
12132 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12133 : UnresExpr->getBase()->Classify(Context);
12134
12135 // Add overload candidates
12136 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12137 OverloadCandidateSet::CSK_Normal);
12138
12139 // FIXME: avoid copy.
12140 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12141 if (UnresExpr->hasExplicitTemplateArgs()) {
12142 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12143 TemplateArgs = &TemplateArgsBuffer;
12144 }
12145
12146 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12147 E = UnresExpr->decls_end(); I != E; ++I) {
12148
12149 NamedDecl *Func = *I;
12150 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12151 if (isa<UsingShadowDecl>(Func))
12152 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12153
12154
12155 // Microsoft supports direct constructor calls.
12156 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12157 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12158 Args, CandidateSet);
12159 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12160 // If explicit template arguments were provided, we can't call a
12161 // non-template member function.
12162 if (TemplateArgs)
12163 continue;
12164
12165 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12166 ObjectClassification, Args, CandidateSet,
12167 /*SuppressUserConversions=*/false);
12168 } else {
12169 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12170 I.getPair(), ActingDC, TemplateArgs,
12171 ObjectType, ObjectClassification,
12172 Args, CandidateSet,
12173 /*SuppressUsedConversions=*/false);
12174 }
12175 }
12176
12177 DeclarationName DeclName = UnresExpr->getMemberName();
12178
12179 UnbridgedCasts.restore();
12180
12181 OverloadCandidateSet::iterator Best;
12182 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12183 Best)) {
12184 case OR_Success:
12185 Method = cast<CXXMethodDecl>(Best->Function);
12186 FoundDecl = Best->FoundDecl;
12187 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12188 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12189 return ExprError();
12190 // If FoundDecl is different from Method (such as if one is a template
12191 // and the other a specialization), make sure DiagnoseUseOfDecl is
12192 // called on both.
12193 // FIXME: This would be more comprehensively addressed by modifying
12194 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12195 // being used.
12196 if (Method != FoundDecl.getDecl() &&
12197 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12198 return ExprError();
12199 break;
12200
12201 case OR_No_Viable_Function:
12202 Diag(UnresExpr->getMemberLoc(),
12203 diag::err_ovl_no_viable_member_function_in_call)
12204 << DeclName << MemExprE->getSourceRange();
12205 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12206 // FIXME: Leaking incoming expressions!
12207 return ExprError();
12208
12209 case OR_Ambiguous:
12210 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12211 << DeclName << MemExprE->getSourceRange();
12212 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12213 // FIXME: Leaking incoming expressions!
12214 return ExprError();
12215
12216 case OR_Deleted:
12217 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12218 << Best->Function->isDeleted()
12219 << DeclName
12220 << getDeletedOrUnavailableSuffix(Best->Function)
12221 << MemExprE->getSourceRange();
12222 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12223 // FIXME: Leaking incoming expressions!
12224 return ExprError();
12225 }
12226
12227 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12228
12229 // If overload resolution picked a static member, build a
12230 // non-member call based on that function.
12231 if (Method->isStatic()) {
12232 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12233 RParenLoc);
12234 }
12235
12236 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12237 }
12238
12239 QualType ResultType = Method->getReturnType();
12240 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12241 ResultType = ResultType.getNonLValueExprType(Context);
12242
12243 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12243, __PRETTY_FUNCTION__))
;
12244 CXXMemberCallExpr *TheCall =
12245 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12246 ResultType, VK, RParenLoc);
12247
12248 // (CUDA B.1): Check for invalid calls between targets.
12249 if (getLangOpts().CUDA) {
12250 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12251 if (CheckCUDATarget(Caller, Method)) {
12252 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12253 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12254 << IdentifyCUDATarget(Caller);
12255 return ExprError();
12256 }
12257 }
12258 }
12259
12260 // Check for a valid return type.
12261 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12262 TheCall, Method))
12263 return ExprError();
12264
12265 // Convert the object argument (for a non-static member function call).
12266 // We only need to do this if there was actually an overload; otherwise
12267 // it was done at lookup.
12268 if (!Method->isStatic()) {
12269 ExprResult ObjectArg =
12270 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12271 FoundDecl, Method);
12272 if (ObjectArg.isInvalid())
12273 return ExprError();
12274 MemExpr->setBase(ObjectArg.get());
12275 }
12276
12277 // Convert the rest of the arguments
12278 const FunctionProtoType *Proto =
12279 Method->getType()->getAs<FunctionProtoType>();
12280 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12281 RParenLoc))
12282 return ExprError();
12283
12284 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12285
12286 if (CheckFunctionCall(Method, TheCall, Proto))
12287 return ExprError();
12288
12289 // In the case the method to call was not selected by the overloading
12290 // resolution process, we still need to handle the enable_if attribute. Do
12291 // that here, so it will not hide previous -- and more relevant -- errors
12292 if (isa<MemberExpr>(NakedMemExpr)) {
12293 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12294 Diag(MemExprE->getLocStart(),
12295 diag::err_ovl_no_viable_member_function_in_call)
12296 << Method << Method->getSourceRange();
12297 Diag(Method->getLocation(),
12298 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12299 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12300 return ExprError();
12301 }
12302 }
12303
12304 if ((isa<CXXConstructorDecl>(CurContext) ||
12305 isa<CXXDestructorDecl>(CurContext)) &&
12306 TheCall->getMethodDecl()->isPure()) {
12307 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12308
12309 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12310 MemExpr->performsVirtualDispatch(getLangOpts())) {
12311 Diag(MemExpr->getLocStart(),
12312 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12313 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12314 << MD->getParent()->getDeclName();
12315
12316 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12317 if (getLangOpts().AppleKext)
12318 Diag(MemExpr->getLocStart(),
12319 diag::note_pure_qualified_call_kext)
12320 << MD->getParent()->getDeclName()
12321 << MD->getDeclName();
12322 }
12323 }
12324
12325 if (CXXDestructorDecl *DD =
12326 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12327 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12328 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12329 getLangOpts().AppleKext;
12330 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12331 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12332 MemExpr->getMemberLoc());
12333 }
12334
12335 return MaybeBindToTemporary(TheCall);
12336}
12337
12338/// BuildCallToObjectOfClassType - Build a call to an object of class
12339/// type (C++ [over.call.object]), which can end up invoking an
12340/// overloaded function call operator (@c operator()) or performing a
12341/// user-defined conversion on the object argument.
12342ExprResult
12343Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12344 SourceLocation LParenLoc,
12345 MultiExprArg Args,
12346 SourceLocation RParenLoc) {
12347 if (checkPlaceholderForOverload(*this, Obj))
12348 return ExprError();
12349 ExprResult Object = Obj;
12350
12351 UnbridgedCastsSet UnbridgedCasts;
12352 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12353 return ExprError();
12354
12355 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12356, __PRETTY_FUNCTION__))
12356 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12356, __PRETTY_FUNCTION__))
;
12357 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12358
12359 // C++ [over.call.object]p1:
12360 // If the primary-expression E in the function call syntax
12361 // evaluates to a class object of type "cv T", then the set of
12362 // candidate functions includes at least the function call
12363 // operators of T. The function call operators of T are obtained by
12364 // ordinary lookup of the name operator() in the context of
12365 // (E).operator().
12366 OverloadCandidateSet CandidateSet(LParenLoc,
12367 OverloadCandidateSet::CSK_Operator);
12368 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12369
12370 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12371 diag::err_incomplete_object_call, Object.get()))
12372 return true;
12373
12374 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12375 LookupQualifiedName(R, Record->getDecl());
12376 R.suppressDiagnostics();
12377
12378 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12379 Oper != OperEnd; ++Oper) {
12380 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12381 Object.get()->Classify(Context),
12382 Args, CandidateSet,
12383 /*SuppressUserConversions=*/ false);
12384 }
12385
12386 // C++ [over.call.object]p2:
12387 // In addition, for each (non-explicit in C++0x) conversion function
12388 // declared in T of the form
12389 //
12390 // operator conversion-type-id () cv-qualifier;
12391 //
12392 // where cv-qualifier is the same cv-qualification as, or a
12393 // greater cv-qualification than, cv, and where conversion-type-id
12394 // denotes the type "pointer to function of (P1,...,Pn) returning
12395 // R", or the type "reference to pointer to function of
12396 // (P1,...,Pn) returning R", or the type "reference to function
12397 // of (P1,...,Pn) returning R", a surrogate call function [...]
12398 // is also considered as a candidate function. Similarly,
12399 // surrogate call functions are added to the set of candidate
12400 // functions for each conversion function declared in an
12401 // accessible base class provided the function is not hidden
12402 // within T by another intervening declaration.
12403 const auto &Conversions =
12404 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12405 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12406 NamedDecl *D = *I;
12407 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12408 if (isa<UsingShadowDecl>(D))
12409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12410
12411 // Skip over templated conversion functions; they aren't
12412 // surrogates.
12413 if (isa<FunctionTemplateDecl>(D))
12414 continue;
12415
12416 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12417 if (!Conv->isExplicit()) {
12418 // Strip the reference type (if any) and then the pointer type (if
12419 // any) to get down to what might be a function type.
12420 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12421 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12422 ConvType = ConvPtrType->getPointeeType();
12423
12424 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12425 {
12426 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12427 Object.get(), Args, CandidateSet);
12428 }
12429 }
12430 }
12431
12432 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12433
12434 // Perform overload resolution.
12435 OverloadCandidateSet::iterator Best;
12436 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12437 Best)) {
12438 case OR_Success:
12439 // Overload resolution succeeded; we'll build the appropriate call
12440 // below.
12441 break;
12442
12443 case OR_No_Viable_Function:
12444 if (CandidateSet.empty())
12445 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12446 << Object.get()->getType() << /*call*/ 1
12447 << Object.get()->getSourceRange();
12448 else
12449 Diag(Object.get()->getLocStart(),
12450 diag::err_ovl_no_viable_object_call)
12451 << Object.get()->getType() << Object.get()->getSourceRange();
12452 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12453 break;
12454
12455 case OR_Ambiguous:
12456 Diag(Object.get()->getLocStart(),
12457 diag::err_ovl_ambiguous_object_call)
12458 << Object.get()->getType() << Object.get()->getSourceRange();
12459 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12460 break;
12461
12462 case OR_Deleted:
12463 Diag(Object.get()->getLocStart(),
12464 diag::err_ovl_deleted_object_call)
12465 << Best->Function->isDeleted()
12466 << Object.get()->getType()
12467 << getDeletedOrUnavailableSuffix(Best->Function)
12468 << Object.get()->getSourceRange();
12469 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12470 break;
12471 }
12472
12473 if (Best == CandidateSet.end())
12474 return true;
12475
12476 UnbridgedCasts.restore();
12477
12478 if (Best->Function == nullptr) {
12479 // Since there is no function declaration, this is one of the
12480 // surrogate candidates. Dig out the conversion function.
12481 CXXConversionDecl *Conv
12482 = cast<CXXConversionDecl>(
12483 Best->Conversions[0].UserDefined.ConversionFunction);
12484
12485 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12486 Best->FoundDecl);
12487 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12488 return ExprError();
12489 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12490, __PRETTY_FUNCTION__))
12490 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12490, __PRETTY_FUNCTION__))
;
12491 // We selected one of the surrogate functions that converts the
12492 // object parameter to a function pointer. Perform the conversion
12493 // on the object argument, then let ActOnCallExpr finish the job.
12494
12495 // Create an implicit member expr to refer to the conversion operator.
12496 // and then call it.
12497 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12498 Conv, HadMultipleCandidates);
12499 if (Call.isInvalid())
12500 return ExprError();
12501 // Record usage of conversion in an implicit cast.
12502 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12503 CK_UserDefinedConversion, Call.get(),
12504 nullptr, VK_RValue);
12505
12506 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12507 }
12508
12509 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12510
12511 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12512 // that calls this method, using Object for the implicit object
12513 // parameter and passing along the remaining arguments.
12514 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12515
12516 // An error diagnostic has already been printed when parsing the declaration.
12517 if (Method->isInvalidDecl())
12518 return ExprError();
12519
12520 const FunctionProtoType *Proto =
12521 Method->getType()->getAs<FunctionProtoType>();
12522
12523 unsigned NumParams = Proto->getNumParams();
12524
12525 DeclarationNameInfo OpLocInfo(
12526 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12527 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12528 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12529 HadMultipleCandidates,
12530 OpLocInfo.getLoc(),
12531 OpLocInfo.getInfo());
12532 if (NewFn.isInvalid())
12533 return true;
12534
12535 // Build the full argument list for the method call (the implicit object
12536 // parameter is placed at the beginning of the list).
12537 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12538 MethodArgs[0] = Object.get();
12539 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12540
12541 // Once we've built TheCall, all of the expressions are properly
12542 // owned.
12543 QualType ResultTy = Method->getReturnType();
12544 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12545 ResultTy = ResultTy.getNonLValueExprType(Context);
12546
12547 CXXOperatorCallExpr *TheCall = new (Context)
12548 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12549 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12550 ResultTy, VK, RParenLoc, false);
12551 MethodArgs.reset();
12552
12553 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12554 return true;
12555
12556 // We may have default arguments. If so, we need to allocate more
12557 // slots in the call for them.
12558 if (Args.size() < NumParams)
12559 TheCall->setNumArgs(Context, NumParams + 1);
12560
12561 bool IsError = false;
12562
12563 // Initialize the implicit object parameter.
12564 ExprResult ObjRes =
12565 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12566 Best->FoundDecl, Method);
12567 if (ObjRes.isInvalid())
12568 IsError = true;
12569 else
12570 Object = ObjRes;
12571 TheCall->setArg(0, Object.get());
12572
12573 // Check the argument types.
12574 for (unsigned i = 0; i != NumParams; i++) {
12575 Expr *Arg;
12576 if (i < Args.size()) {
12577 Arg = Args[i];
12578
12579 // Pass the argument.
12580
12581 ExprResult InputInit
12582 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12583 Context,
12584 Method->getParamDecl(i)),
12585 SourceLocation(), Arg);
12586
12587 IsError |= InputInit.isInvalid();
12588 Arg = InputInit.getAs<Expr>();
12589 } else {
12590 ExprResult DefArg
12591 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12592 if (DefArg.isInvalid()) {
12593 IsError = true;
12594 break;
12595 }
12596
12597 Arg = DefArg.getAs<Expr>();
12598 }
12599
12600 TheCall->setArg(i + 1, Arg);
12601 }
12602
12603 // If this is a variadic call, handle args passed through "...".
12604 if (Proto->isVariadic()) {
12605 // Promote the arguments (C99 6.5.2.2p7).
12606 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12607 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12608 nullptr);
12609 IsError |= Arg.isInvalid();
12610 TheCall->setArg(i + 1, Arg.get());
12611 }
12612 }
12613
12614 if (IsError) return true;
12615
12616 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12617
12618 if (CheckFunctionCall(Method, TheCall, Proto))
12619 return true;
12620
12621 return MaybeBindToTemporary(TheCall);
12622}
12623
12624/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12625/// (if one exists), where @c Base is an expression of class type and
12626/// @c Member is the name of the member we're trying to find.
12627ExprResult
12628Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12629 bool *NoArrowOperatorFound) {
12630 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12631, __PRETTY_FUNCTION__))
12631 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12631, __PRETTY_FUNCTION__))
;
12632
12633 if (checkPlaceholderForOverload(*this, Base))
12634 return ExprError();
12635
12636 SourceLocation Loc = Base->getExprLoc();
12637
12638 // C++ [over.ref]p1:
12639 //
12640 // [...] An expression x->m is interpreted as (x.operator->())->m
12641 // for a class object x of type T if T::operator->() exists and if
12642 // the operator is selected as the best match function by the
12643 // overload resolution mechanism (13.3).
12644 DeclarationName OpName =
12645 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12646 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12647 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12648
12649 if (RequireCompleteType(Loc, Base->getType(),
12650 diag::err_typecheck_incomplete_tag, Base))
12651 return ExprError();
12652
12653 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12654 LookupQualifiedName(R, BaseRecord->getDecl());
12655 R.suppressDiagnostics();
12656
12657 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12658 Oper != OperEnd; ++Oper) {
12659 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12660 None, CandidateSet, /*SuppressUserConversions=*/false);
12661 }
12662
12663 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12664
12665 // Perform overload resolution.
12666 OverloadCandidateSet::iterator Best;
12667 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12668 case OR_Success:
12669 // Overload resolution succeeded; we'll build the call below.
12670 break;
12671
12672 case OR_No_Viable_Function:
12673 if (CandidateSet.empty()) {
12674 QualType BaseType = Base->getType();
12675 if (NoArrowOperatorFound) {
12676 // Report this specific error to the caller instead of emitting a
12677 // diagnostic, as requested.
12678 *NoArrowOperatorFound = true;
12679 return ExprError();
12680 }
12681 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12682 << BaseType << Base->getSourceRange();
12683 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12684 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12685 << FixItHint::CreateReplacement(OpLoc, ".");
12686 }
12687 } else
12688 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12689 << "operator->" << Base->getSourceRange();
12690 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12691 return ExprError();
12692
12693 case OR_Ambiguous:
12694 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12695 << "->" << Base->getType() << Base->getSourceRange();
12696 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12697 return ExprError();
12698
12699 case OR_Deleted:
12700 Diag(OpLoc, diag::err_ovl_deleted_oper)
12701 << Best->Function->isDeleted()
12702 << "->"
12703 << getDeletedOrUnavailableSuffix(Best->Function)
12704 << Base->getSourceRange();
12705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12706 return ExprError();
12707 }
12708
12709 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12710
12711 // Convert the object parameter.
12712 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12713 ExprResult BaseResult =
12714 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12715 Best->FoundDecl, Method);
12716 if (BaseResult.isInvalid())
12717 return ExprError();
12718 Base = BaseResult.get();
12719
12720 // Build the operator call.
12721 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12722 HadMultipleCandidates, OpLoc);
12723 if (FnExpr.isInvalid())
12724 return ExprError();
12725
12726 QualType ResultTy = Method->getReturnType();
12727 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12728 ResultTy = ResultTy.getNonLValueExprType(Context);
12729 CXXOperatorCallExpr *TheCall =
12730 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12731 Base, ResultTy, VK, OpLoc, false);
12732
12733 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12734 return ExprError();
12735
12736 return MaybeBindToTemporary(TheCall);
12737}
12738
12739/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12740/// a literal operator described by the provided lookup results.
12741ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12742 DeclarationNameInfo &SuffixInfo,
12743 ArrayRef<Expr*> Args,
12744 SourceLocation LitEndLoc,
12745 TemplateArgumentListInfo *TemplateArgs) {
12746 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12747
12748 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12749 OverloadCandidateSet::CSK_Normal);
12750 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12751 /*SuppressUserConversions=*/true);
12752
12753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12754
12755 // Perform overload resolution. This will usually be trivial, but might need
12756 // to perform substitutions for a literal operator template.
12757 OverloadCandidateSet::iterator Best;
12758 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12759 case OR_Success:
12760 case OR_Deleted:
12761 break;
12762
12763 case OR_No_Viable_Function:
12764 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12765 << R.getLookupName();
12766 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12767 return ExprError();
12768
12769 case OR_Ambiguous:
12770 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12771 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12772 return ExprError();
12773 }
12774
12775 FunctionDecl *FD = Best->Function;
12776 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12777 HadMultipleCandidates,
12778 SuffixInfo.getLoc(),
12779 SuffixInfo.getInfo());
12780 if (Fn.isInvalid())
12781 return true;
12782
12783 // Check the argument types. This should almost always be a no-op, except
12784 // that array-to-pointer decay is applied to string literals.
12785 Expr *ConvArgs[2];
12786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12787 ExprResult InputInit = PerformCopyInitialization(
12788 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12789 SourceLocation(), Args[ArgIdx]);
12790 if (InputInit.isInvalid())
12791 return true;
12792 ConvArgs[ArgIdx] = InputInit.get();
12793 }
12794
12795 QualType ResultTy = FD->getReturnType();
12796 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12797 ResultTy = ResultTy.getNonLValueExprType(Context);
12798
12799 UserDefinedLiteral *UDL =
12800 new (Context) UserDefinedLiteral(Context, Fn.get(),
12801 llvm::makeArrayRef(ConvArgs, Args.size()),
12802 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12803
12804 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12805 return ExprError();
12806
12807 if (CheckFunctionCall(FD, UDL, nullptr))
12808 return ExprError();
12809
12810 return MaybeBindToTemporary(UDL);
12811}
12812
12813/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12814/// given LookupResult is non-empty, it is assumed to describe a member which
12815/// will be invoked. Otherwise, the function will be found via argument
12816/// dependent lookup.
12817/// CallExpr is set to a valid expression and FRS_Success returned on success,
12818/// otherwise CallExpr is set to ExprError() and some non-success value
12819/// is returned.
12820Sema::ForRangeStatus
12821Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12822 SourceLocation RangeLoc,
12823 const DeclarationNameInfo &NameInfo,
12824 LookupResult &MemberLookup,
12825 OverloadCandidateSet *CandidateSet,
12826 Expr *Range, ExprResult *CallExpr) {
12827 Scope *S = nullptr;
12828
12829 CandidateSet->clear();
12830 if (!MemberLookup.empty()) {
12831 ExprResult MemberRef =
12832 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12833 /*IsPtr=*/false, CXXScopeSpec(),
12834 /*TemplateKWLoc=*/SourceLocation(),
12835 /*FirstQualifierInScope=*/nullptr,
12836 MemberLookup,
12837 /*TemplateArgs=*/nullptr, S);
12838 if (MemberRef.isInvalid()) {
12839 *CallExpr = ExprError();
12840 return FRS_DiagnosticIssued;
12841 }
12842 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12843 if (CallExpr->isInvalid()) {
12844 *CallExpr = ExprError();
12845 return FRS_DiagnosticIssued;
12846 }
12847 } else {
12848 UnresolvedSet<0> FoundNames;
12849 UnresolvedLookupExpr *Fn =
12850 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12851 NestedNameSpecifierLoc(), NameInfo,
12852 /*NeedsADL=*/true, /*Overloaded=*/false,
12853 FoundNames.begin(), FoundNames.end());
12854
12855 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12856 CandidateSet, CallExpr);
12857 if (CandidateSet->empty() || CandidateSetError) {
12858 *CallExpr = ExprError();
12859 return FRS_NoViableFunction;
12860 }
12861 OverloadCandidateSet::iterator Best;
12862 OverloadingResult OverloadResult =
12863 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12864
12865 if (OverloadResult == OR_No_Viable_Function) {
12866 *CallExpr = ExprError();
12867 return FRS_NoViableFunction;
12868 }
12869 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12870 Loc, nullptr, CandidateSet, &Best,
12871 OverloadResult,
12872 /*AllowTypoCorrection=*/false);
12873 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12874 *CallExpr = ExprError();
12875 return FRS_DiagnosticIssued;
12876 }
12877 }
12878 return FRS_Success;
12879}
12880
12881
12882/// FixOverloadedFunctionReference - E is an expression that refers to
12883/// a C++ overloaded function (possibly with some parentheses and
12884/// perhaps a '&' around it). We have resolved the overloaded function
12885/// to the function declaration Fn, so patch up the expression E to
12886/// refer (possibly indirectly) to Fn. Returns the new expr.
12887Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12888 FunctionDecl *Fn) {
12889 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12890 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12891 Found, Fn);
12892 if (SubExpr == PE->getSubExpr())
12893 return PE;
12894
12895 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12896 }
12897
12898 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12899 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12900 Found, Fn);
12901 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12903, __PRETTY_FUNCTION__))
12902 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12903, __PRETTY_FUNCTION__))
12903 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12903, __PRETTY_FUNCTION__))
;
12904 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12904, __PRETTY_FUNCTION__))
;
12905 if (SubExpr == ICE->getSubExpr())
12906 return ICE;
12907
12908 return ImplicitCastExpr::Create(Context, ICE->getType(),
12909 ICE->getCastKind(),
12910 SubExpr, nullptr,
12911 ICE->getValueKind());
12912 }
12913
12914 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12915 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12916, __PRETTY_FUNCTION__))
12916 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12916, __PRETTY_FUNCTION__))
;
12917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12918 if (Method->isStatic()) {
12919 // Do nothing: static member functions aren't any different
12920 // from non-member functions.
12921 } else {
12922 // Fix the subexpression, which really has to be an
12923 // UnresolvedLookupExpr holding an overloaded member function
12924 // or template.
12925 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12926 Found, Fn);
12927 if (SubExpr == UnOp->getSubExpr())
12928 return UnOp;
12929
12930 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12931, __PRETTY_FUNCTION__))
12931 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12931, __PRETTY_FUNCTION__))
;
12932 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12933, __PRETTY_FUNCTION__))
12933 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 12933, __PRETTY_FUNCTION__))
;
12934
12935 // We have taken the address of a pointer to member
12936 // function. Perform the computation here so that we get the
12937 // appropriate pointer to member type.
12938 QualType ClassType
12939 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12940 QualType MemPtrType
12941 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12942
12943 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12944 VK_RValue, OK_Ordinary,
12945 UnOp->getOperatorLoc());
12946 }
12947 }
12948 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12949 Found, Fn);
12950 if (SubExpr == UnOp->getSubExpr())
12951 return UnOp;
12952
12953 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12954 Context.getPointerType(SubExpr->getType()),
12955 VK_RValue, OK_Ordinary,
12956 UnOp->getOperatorLoc());
12957 }
12958
12959 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12960 // FIXME: avoid copy.
12961 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12962 if (ULE->hasExplicitTemplateArgs()) {
12963 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12964 TemplateArgs = &TemplateArgsBuffer;
12965 }
12966
12967 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12968 ULE->getQualifierLoc(),
12969 ULE->getTemplateKeywordLoc(),
12970 Fn,
12971 /*enclosing*/ false, // FIXME?
12972 ULE->getNameLoc(),
12973 Fn->getType(),
12974 VK_LValue,
12975 Found.getDecl(),
12976 TemplateArgs);
12977 MarkDeclRefReferenced(DRE);
12978 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12979 return DRE;
12980 }
12981
12982 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12983 // FIXME: avoid copy.
12984 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12985 if (MemExpr->hasExplicitTemplateArgs()) {
12986 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12987 TemplateArgs = &TemplateArgsBuffer;
12988 }
12989
12990 Expr *Base;
12991
12992 // If we're filling in a static method where we used to have an
12993 // implicit member access, rewrite to a simple decl ref.
12994 if (MemExpr->isImplicitAccess()) {
12995 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12996 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12997 MemExpr->getQualifierLoc(),
12998 MemExpr->getTemplateKeywordLoc(),
12999 Fn,
13000 /*enclosing*/ false,
13001 MemExpr->getMemberLoc(),
13002 Fn->getType(),
13003 VK_LValue,
13004 Found.getDecl(),
13005 TemplateArgs);
13006 MarkDeclRefReferenced(DRE);
13007 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13008 return DRE;
13009 } else {
13010 SourceLocation Loc = MemExpr->getMemberLoc();
13011 if (MemExpr->getQualifier())
13012 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13013 CheckCXXThisCapture(Loc);
13014 Base = new (Context) CXXThisExpr(Loc,
13015 MemExpr->getBaseType(),
13016 /*isImplicit=*/true);
13017 }
13018 } else
13019 Base = MemExpr->getBase();
13020
13021 ExprValueKind valueKind;
13022 QualType type;
13023 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13024 valueKind = VK_LValue;
13025 type = Fn->getType();
13026 } else {
13027 valueKind = VK_RValue;
13028 type = Context.BoundMemberTy;
13029 }
13030
13031 MemberExpr *ME = MemberExpr::Create(
13032 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13033 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13034 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13035 OK_Ordinary);
13036 ME->setHadMultipleCandidates(true);
13037 MarkMemberReferenced(ME);
13038 return ME;
13039 }
13040
13041 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/tmp/buildd/llvm-toolchain-snapshot-3.9~svn267387/tools/clang/lib/Sema/SemaOverload.cpp"
, 13041)
;
13042}
13043
13044ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13045 DeclAccessPair Found,
13046 FunctionDecl *Fn) {
13047 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13048}